teiid SVN: r1899 - trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules.
by teiid-commits@lists.jboss.org
Author: shawkins
Date: 2010-03-04 00:02:09 -0500 (Thu, 04 Mar 2010)
New Revision: 1899
Modified:
trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleMergeVirtual.java
Log:
TEIID-989 adding more aggressive view removal logic with an unrelated order by in the upper frame
Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleMergeVirtual.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleMergeVirtual.java 2010-03-04 03:27:35 UTC (rev 1898)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleMergeVirtual.java 2010-03-04 05:02:09 UTC (rev 1899)
@@ -50,6 +50,7 @@
import com.metamatrix.query.sql.symbol.GroupSymbol;
import com.metamatrix.query.sql.symbol.SingleElementSymbol;
import com.metamatrix.query.sql.util.SymbolMap;
+import com.metamatrix.query.sql.visitor.ElementCollectorVisitor;
import com.metamatrix.query.sql.visitor.FunctionCollectorVisitor;
import com.metamatrix.query.sql.visitor.GroupsUsedByElementsVisitor;
import com.metamatrix.query.sql.visitor.ValueIteratorProviderCollectorVisitor;
@@ -105,14 +106,33 @@
return root;
}
+ SymbolMap symbolMap = (SymbolMap)frame.getProperty(NodeConstants.Info.SYMBOL_MAP);
+
PlanNode sortNode = NodeEditor.findParent(parentProject, NodeConstants.Types.SORT, NodeConstants.Types.SOURCE);
if (sortNode != null && sortNode.hasBooleanProperty(NodeConstants.Info.UNRELATED_SORT)) {
- // the lower group cannot contain DUP_REMOVE, GROUP, UNION
- // or a projected expression for an unrelated sort column (until SQL 2003 sorts are supported).
-
- // for now though the simplification is to just not remove the inline view.
- return root;
+ OrderBy sortOrder = (OrderBy)sortNode.getProperty(NodeConstants.Info.SORT_ORDER);
+ boolean unrelated = false;
+ for (OrderByItem item : sortOrder.getOrderByItems()) {
+ if (!item.isUnrelated()) {
+ continue;
+ }
+ Collection<ElementSymbol> elements = ElementCollectorVisitor.getElements(item.getSymbol(), true);
+ for (ElementSymbol elementSymbol : elements) {
+ if (virtualGroup.equals(elementSymbol.getGroupSymbol())) {
+ unrelated = true;
+ if (!(symbolMap.getMappedExpression(elementSymbol) instanceof ElementSymbol)) {
+ return root;
+ }
+ }
+ }
+ }
+ // the lower frame cannot contain DUP_REMOVE, GROUP, UNION if unrelated
+ if (unrelated && NodeEditor.findNodePreOrder(frame, NodeConstants.Types.DUP_REMOVE, NodeConstants.Types.PROJECT) != null
+ || NodeEditor.findNodePreOrder(frame, NodeConstants.Types.SET_OP, NodeConstants.Types.SOURCE) != null
+ || NodeEditor.findNodePreOrder(frame, NodeConstants.Types.GROUP, NodeConstants.Types.SOURCE) != null) {
+ return root;
+ }
}
//try to remove the virtual layer if we are only doing a simple projection in the following cases:
@@ -138,8 +158,6 @@
groupCols = (List<SingleElementSymbol>)parentGroup.getProperty(NodeConstants.Info.GROUP_COLS);
}
- SymbolMap symbolMap = (SymbolMap)frame.getProperty(NodeConstants.Info.SYMBOL_MAP);
-
if (!checkProjectedSymbols(projectNode, virtualGroup, parentJoin, groupCols, symbolMap, metadata)) {
return root;
}
14 years, 2 months
teiid SVN: r1898 - in trunk/engine/src: test/java/com/metamatrix/query/optimizer/relational and 1 other directory.
by teiid-commits@lists.jboss.org
Author: shawkins
Date: 2010-03-03 22:27:35 -0500 (Wed, 03 Mar 2010)
New Revision: 1898
Modified:
trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/AliasGenerator.java
trunk/engine/src/test/java/com/metamatrix/query/optimizer/relational/TestAliasGenerator.java
Log:
TEIID-1009 fix for the alias generator creating alias symbols in the order by clause
Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/AliasGenerator.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/AliasGenerator.java 2010-03-04 01:56:20 UTC (rev 1897)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/AliasGenerator.java 2010-03-04 03:27:35 UTC (rev 1898)
@@ -31,6 +31,7 @@
import com.metamatrix.query.sql.LanguageVisitor;
import com.metamatrix.query.sql.lang.ExistsCriteria;
import com.metamatrix.query.sql.lang.OrderBy;
+import com.metamatrix.query.sql.lang.OrderByItem;
import com.metamatrix.query.sql.lang.Query;
import com.metamatrix.query.sql.lang.Select;
import com.metamatrix.query.sql.lang.SetQuery;
@@ -328,7 +329,12 @@
public void visit(OrderBy obj) {
//add/correct aliases if necessary
for (int i = 0; i < obj.getVariableCount(); i++) {
- SingleElementSymbol element = obj.getVariable(i);
+ OrderByItem item = obj.getOrderByItems().get(i);
+ SingleElementSymbol element = item.getSymbol();
+ if (item.isUnrelated()) {
+ visitNode(element);
+ continue;
+ }
String name = visitor.namingContext.getElementName(element, false);
if (name != null) {
boolean needsAlias = true;
Modified: trunk/engine/src/test/java/com/metamatrix/query/optimizer/relational/TestAliasGenerator.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/optimizer/relational/TestAliasGenerator.java 2010-03-04 01:56:20 UTC (rev 1897)
+++ trunk/engine/src/test/java/com/metamatrix/query/optimizer/relational/TestAliasGenerator.java 2010-03-04 03:27:35 UTC (rev 1898)
@@ -142,4 +142,10 @@
helpTest(sql, expected, true, FakeMetadataFactory.exampleBQTCached());
}
+ @Test public void testUnrelatedOrderBy1() throws Exception {
+ String sql = "SELECT b.IntKey FROM (select intkey, stringkey from BQT1.SmallA) a, (select intkey, stringkey from BQT1.SmallA) b ORDER BY a.StringKey"; //$NON-NLS-1$
+ String expected = "SELECT v_1.c_0 FROM (SELECT g_0.intkey AS c_0, g_0.stringkey AS c_1 FROM BQT1.SmallA AS g_0) AS v_0, (SELECT g_1.intkey AS c_0, g_1.stringkey AS c_1 FROM BQT1.SmallA AS g_1) AS v_1 ORDER BY v_0.c_1"; //$NON-NLS-1$
+ helpTest(sql, expected, true, FakeMetadataFactory.exampleBQTCached());
+ }
+
}
14 years, 2 months
teiid SVN: r1897 - in branches/JCA: common-internal/src/main/java/com/metamatrix/internal/core/xml and 9 other directories.
by teiid-commits@lists.jboss.org
Author: shawkins
Date: 2010-03-03 20:56:20 -0500 (Wed, 03 Mar 2010)
New Revision: 1897
Removed:
branches/JCA/connector-sdk/src/main/java/com/metamatrix/cdk/ConnectorShell.java
branches/JCA/connector-sdk/src/main/java/com/metamatrix/cdk/ConnectorShellCommandTarget.java
branches/JCA/connector-sdk/src/main/java/com/metamatrix/cdk/QueryCommandTarget.java
branches/JCA/connector-sdk/src/main/java/com/metamatrix/common/classloader/
branches/JCA/connector-sdk/src/main/java/com/metamatrix/core/commandshell/ConnectorResultUtility.java
branches/JCA/connector-sdk/src/main/java/com/metamatrix/core/commandshell/ScriptCommandTarget.java
branches/JCA/connector-sdk/src/main/java/com/metamatrix/core/commandshell/ScriptFileNameStack.java
branches/JCA/connector-sdk/src/main/java/com/metamatrix/core/factory/
branches/JCA/connector-sdk/src/test/java/com/metamatrix/core/commandshell/TestScriptFileNameStack.java
branches/JCA/connector-sdk/src/test/java/com/metamatrix/core/factory/
branches/JCA/test-integration/common/src/test/java/com/metamatrix/cdk/TestConnectorShell.java
branches/JCA/test-integration/common/src/test/java/com/metamatrix/cdk/api/TestConnectorResultUtility.java
Modified:
branches/JCA/common-core/src/main/java/com/metamatrix/core/util/ObjectConverterUtil.java
branches/JCA/common-internal/src/main/java/com/metamatrix/internal/core/xml/JdomHelper.java
branches/JCA/connector-sdk/src/test/java/com/metamatrix/core/commandshell/TestCommand.java
branches/JCA/engine/src/main/java/com/metamatrix/common/buffer/impl/FileStorageManager.java
Log:
TEIID-833 cleaning sdk and prepping for merge
Modified: branches/JCA/common-core/src/main/java/com/metamatrix/core/util/ObjectConverterUtil.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/core/util/ObjectConverterUtil.java 2010-03-04 01:32:54 UTC (rev 1896)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/core/util/ObjectConverterUtil.java 2010-03-04 01:56:20 UTC (rev 1897)
@@ -28,7 +28,6 @@
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
-import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -133,17 +132,17 @@
public static void write(final InputStream is, final File f) throws IOException {
FileOutputStream fio = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(fio);
-
- byte[] buff = new byte[2048];
- int bytesRead;
-
- // Simple read/write loop.
- while (-1 != (bytesRead = is.read(buff, 0, buff.length))) {
- bos.write(buff, 0, bytesRead);
+ try {
+ byte[] buff = new byte[2048];
+ int bytesRead;
+
+ // Simple read/write loop.
+ while (-1 != (bytesRead = is.read(buff, 0, buff.length))) {
+ bos.write(buff, 0, bytesRead);
+ }
+ } finally {
+ bos.close();
}
-
- bos.flush();
- bos.close();
}
public static void write(byte[] data, final String fileName) throws Exception {
@@ -158,16 +157,6 @@
is.close();
}
- public static InputStream convertToInputStream(final File file) {
- try {
- FileInputStream fis = new FileInputStream(file);
- InputStream isContent = new BufferedInputStream(fis);
- return isContent;
- } catch (FileNotFoundException fie) {
- final Object[] params = new Object[]{file.getName()};
- throw new IllegalArgumentException(CorePlugin.Util.getString("ObjectConverterUtil.File_is_not_found_4",params)); //$NON-NLS-1$
- }
- }
/**
* Returns the given bytes as a char array using a given encoding (null means platform default).
*/
Modified: branches/JCA/common-internal/src/main/java/com/metamatrix/internal/core/xml/JdomHelper.java
===================================================================
--- branches/JCA/common-internal/src/main/java/com/metamatrix/internal/core/xml/JdomHelper.java 2010-03-04 01:32:54 UTC (rev 1896)
+++ branches/JCA/common-internal/src/main/java/com/metamatrix/internal/core/xml/JdomHelper.java 2010-03-04 01:56:20 UTC (rev 1897)
@@ -738,22 +738,20 @@
* @throws IOException if there are problems writing to the file.
*/
public static void write( Document doc , String filename, String indent, boolean newlines ) throws IOException {
- if(doc == null){
- ArgCheck.isNotNull(doc,CorePlugin.Util.getString("JdomHelper.The_Document_reference_may_not_be_null_42")); //$NON-NLS-1$
- }
+ ArgCheck.isNotNull(doc,CorePlugin.Util.getString("JdomHelper.The_Document_reference_may_not_be_null_42")); //$NON-NLS-1$
+ ArgCheck.isNotNull(filename,CorePlugin.Util.getString("JdomHelper.The_filename_may_not_be_null_43")); //$NON-NLS-1$
- if(filename == null){
- ArgCheck.isNotNull(filename,CorePlugin.Util.getString("JdomHelper.The_filename_may_not_be_null_43")); //$NON-NLS-1$
- }
-
if(filename.length() == 0){
ArgCheck.isNotZeroLength(filename,CorePlugin.Util.getString("JdomHelper.The_filename_may_not_be_zero-length_44")); //$NON-NLS-1$
}
FileOutputStream out = new FileOutputStream( filename );
- write(doc,out,indent,newlines);
- out.flush();
- out.close();
+ try {
+ write(doc,out,indent,newlines);
+ out.flush();
+ } finally {
+ out.close();
+ }
}
/**
Deleted: branches/JCA/connector-sdk/src/main/java/com/metamatrix/cdk/ConnectorShell.java
===================================================================
--- branches/JCA/connector-sdk/src/main/java/com/metamatrix/cdk/ConnectorShell.java 2010-03-04 01:32:54 UTC (rev 1896)
+++ branches/JCA/connector-sdk/src/main/java/com/metamatrix/cdk/ConnectorShell.java 2010-03-04 01:56:20 UTC (rev 1897)
@@ -1,118 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.cdk;
-
-import com.metamatrix.cdk.api.ConnectorHost;
-import com.metamatrix.core.commandshell.CommandShell;
-
-
-/**
- * Command line utility to execute queries on a connector.
- */
-public class ConnectorShell extends CommandShell {
-
-
-
- public ConnectorShell(ConnectorHost host) {
- super(new ConnectorShellCommandTarget(host));
- }
-
- public ConnectorShell(ConnectorShellCommandTarget target) {
- super(target);
- }
-
- public static void main(String[] args) {
- System.out.println("Starting"); //$NON-NLS-1$
-
- new ConnectorShell(new ConnectorShellCommandTarget()).run(args, DEFAULT_LOG_FILE);
- }
-
- protected boolean showHelpFor(String methodName) {
- return getParameterNamesDirect(methodName) != null;
- }
-
- protected String[] getParameterNames(String methodName) {
- String[] result = getParameterNamesDirect(methodName);
- if (result == null) {
- result = new String[] {};
- }
- return result;
- }
-
- private String[] getParameterNamesDirect(String methodName) {
- if (methodName.equals("select")) { //$NON-NLS-1$
- return new String[] { "query" }; //$NON-NLS-1$
- } else if (methodName.equals("run")) { //$NON-NLS-1$
- return new String[] { "scriptName" }; //$NON-NLS-1$
- } else if (methodName.equals("setProperty")) { //$NON-NLS-1$
- return new String[] { "propertyName", "propertyValue" }; //$NON-NLS-1$ //$NON-NLS-2$
- } else if (methodName.equals("load")) { //$NON-NLS-1$
- return new String[] { "fullyQualifiedConnectorClassName", "pathToVdbFile" }; //$NON-NLS-1$ //$NON-NLS-2$
- } else if (methodName.equals("getProperties")) { //$NON-NLS-1$
- return new String[] {};
- } else if (methodName.equals("delete")) { //$NON-NLS-1$
- return new String[] { "multilineSqlTerminatedWith;" }; //$NON-NLS-1$
- } else if (methodName.equals("insert")) { //$NON-NLS-1$
- return new String[] { "multilineSqlTerminatedWith;" }; //$NON-NLS-1$
- } else if (methodName.equals("help")) { //$NON-NLS-1$
- return new String[] { "" }; //$NON-NLS-1$
- } else if (methodName.equals("update")) { //$NON-NLS-1$
- return new String[] { "multilineSqlTerminatedWith;" }; //$NON-NLS-1$
- } else if (methodName.equals("select")) { //$NON-NLS-1$
- return new String[] { "multilineSqlTerminatedWith;" }; //$NON-NLS-1$
- } else if (methodName.equals("quit")) { //$NON-NLS-1$
- return new String[] { "" }; //$NON-NLS-1$
- } else if (methodName.equals("runScript")) { //$NON-NLS-1$
- return new String[] { "pathToScriptFile", "scriptNameWithinFile" }; //$NON-NLS-1$ //$NON-NLS-2$
- } else if (methodName.equals("loadFromScript")) { //$NON-NLS-1$
- return new String[] { "pathToConfiguratonScript" }; //$NON-NLS-1$
- } else if (methodName.equals("setFailOnError")) { //$NON-NLS-1$
- return new String[] { "boolean" }; //$NON-NLS-1$
- } else if (methodName.equals("setPrintStackOnError")) { //$NON-NLS-1$
- return new String[] { "boolean" }; //$NON-NLS-1$
- } else if (methodName.equals("setSecurityContext")) { //$NON-NLS-1$
- return new String[] { "vdbName", "vdbVersion", "userName" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- } else if (methodName.equals("setScriptFile")) { //$NON-NLS-1$
- return new String[] { "pathToScriptFile" }; //$NON-NLS-1$
- } else if (methodName.equals("runAll")) { //$NON-NLS-1$
- return new String[] {};
- } else if (methodName.equals("setBatchSize")) { //$NON-NLS-1$
- return new String[] { "batchSize" }; //$NON-NLS-1$
- } else if (methodName.equalsIgnoreCase("start")) { //$NON-NLS-1$
- return new String[] {};
- } else if (methodName.equalsIgnoreCase("stop")) { //$NON-NLS-1$
- return new String[] {};
- } else if (methodName.equalsIgnoreCase("loadProperties")) { //$NON-NLS-1$
- return new String[] {"pathToPropertyFile"}; //$NON-NLS-1$
- } else if (methodName.equalsIgnoreCase("createTemplate")) { //$NON-NLS-1$
- return new String[] {"pathToTemplateFile"}; //$NON-NLS-1$
- } else if (methodName.equalsIgnoreCase("createArchive")) { //$NON-NLS-1$
- return new String[] {"pathToArchiveFileName", "pathToCDKFileName", "pathToDirectoryForExtenstionModules"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- } else if (methodName.equalsIgnoreCase("loadArchive")) { //$NON-NLS-1$
- return new String[] {"pathToArchiveFileName", "newConnectorTypeName"}; //$NON-NLS-1$//$NON-NLS-2$
- } else if (methodName.equalsIgnoreCase("exec")) { //$NON-NLS-1$
- return new String[] {"fullyQualifiedProcedureName"}; //$NON-NLS-1$
- }
- return null;
- }
-}
Deleted: branches/JCA/connector-sdk/src/main/java/com/metamatrix/cdk/ConnectorShellCommandTarget.java
===================================================================
--- branches/JCA/connector-sdk/src/main/java/com/metamatrix/cdk/ConnectorShellCommandTarget.java 2010-03-04 01:32:54 UTC (rev 1896)
+++ branches/JCA/connector-sdk/src/main/java/com/metamatrix/cdk/ConnectorShellCommandTarget.java 2010-03-04 01:56:20 UTC (rev 1897)
@@ -1,236 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.cdk;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URLClassLoader;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Properties;
-import java.util.Set;
-
-import org.teiid.connector.api.Connector;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.language.Call;
-import org.teiid.connector.language.Command;
-import org.teiid.connector.language.Select;
-
-import com.metamatrix.cdk.api.ConnectorHost;
-import com.metamatrix.core.MetaMatrixRuntimeException;
-import com.metamatrix.core.commandshell.ConnectorResultUtility;
-import com.metamatrix.core.factory.ComponentLoader;
-
-
-/**
- * Implements the commands supported by the ConnectorShell. Delegates to a ConnectorHost to execute queries.
- */
-public class ConnectorShellCommandTarget extends QueryCommandTarget {
- private static final String MM_JAR_PROTOCOL = "extensionjar"; //$NON-NLS-1$
- private static final String CONNECTOR_CLASSPATH = "ConnectorClassPath"; //$NON-NLS-1$
- private static final String CONNECTOR_CLASS_NAME = "ConnectorClass"; //$NON-NLS-1$
-
- private ConnectorHost connectorHost;
- private Properties connectorProperties = null;
- private Connector connector;
- private String vdbFileName;
- private String connectorClassName = null;
- private URLClassLoader connectorClassLoader = null;
- public ConnectorShellCommandTarget() {
- }
-
- public ConnectorShellCommandTarget(ConnectorHost connectorHost) {
- this.connectorHost = connectorHost;
- }
-
- protected String execute(String query) {
- try {
- Command command = getConnectorHost().getCommand(query);
- String[] columnNames = null;
- if(command instanceof Select) {
- Select iquery = (Select) command;
- columnNames = iquery.getColumnNames();
- } else if (!(command instanceof Call)){
- columnNames = new String[] {"count"}; //$NON-NLS-1$
- }
- List results = getConnectorHost().executeCommand(command);
- return ConnectorResultUtility.resultsToString(results, columnNames);
- } catch (ConnectorException e) {
- throw new MetaMatrixRuntimeException(e);
- }
- }
-
- protected Set getMethodsToIgnore() {
- Set result = new HashSet();
- result.addAll(Arrays.asList( new String[] { "runRep", "setUsePreparedStatement"} )); //$NON-NLS-1$ //$NON-NLS-2$
- return result;
- }
-
- /**
- * Executes the provided script and expects the script to produce a ConnectorHost for executing queries.
- * @param configurationScriptFileName Resource name of the script file to be loaded from the class path.
- */
- public void loadFromScript(String configurationScriptFileName) {
- ComponentLoader loader = new ComponentLoader(this.getClass().getClassLoader(), configurationScriptFileName);
- connectorHost = (ConnectorHost) loader.load("ConnectorHost"); //$NON-NLS-1$
- }
-
- public void load(String connectorClassName, String vdbFileName) throws IllegalAccessException,
- InstantiationException, ClassNotFoundException {
- if (connectorClassLoader == null) {
- Class.forName(connectorClassName); // Just make sure we load the class
- this.connectorProperties = new Properties();
- }
- else {
- connectorClassLoader.loadClass(connectorClassName).newInstance();
- }
- this.vdbFileName = vdbFileName;
- this.connectorClassName = connectorClassName;
- connectorHost = null;
- }
-
-
- public void start() throws IllegalAccessException,
- InstantiationException, ClassNotFoundException, ConnectorException {
- if (connectorHost == null) {
- if (vdbFileName == null) {
- throw new RuntimeException(CdkPlugin.Util.getString("ConnectorShellCommandTarget.Connector_must_be_loaded_before_it_can_be_used._1")); //$NON-NLS-1$
- }
- if (connectorClassLoader == null) {
- connector = (Connector) Class.forName(connectorClassName).newInstance();
- }
- else {
- connector = (Connector) connectorClassLoader.loadClass(connectorClassName).newInstance();
- }
- connectorHost = new ConnectorHost(connector, null, shell.expandFileName(vdbFileName));
- }
- }
-
- public void stop() {
- if (connector != null) {
- connector = null;
- }
- connectorHost = null;
- }
-
- private Properties loadFromPropertiesFile(File propertyFile) {
- Properties props = new Properties();
- InputStream in = null;
- try {
- in = new FileInputStream(propertyFile);
- props.load(in);
- return props;
- } catch (IOException e) {
- throw new RuntimeException(CdkPlugin.Util.getString("ConnectorShellCommandTarget.Cannot_read_from_file__{0}_1", propertyFile)); //$NON-NLS-1$
- } finally {
- try {
- in.close();
- } catch (Exception e) {
- }
- }
- }
-
- public void setFailOnError(boolean failOnError) {
- if (failOnError) {
- shell.turnOffExceptionHandling();
- } else {
- shell.turnOnExceptionHandling();
- }
- }
-
- public void setPrintStackOnError(boolean printStackOnError) {
- shell.setPrintStackTraceOnException(printStackOnError);
- }
-
- public void setSecurityContext(ExecutionContext context) {
- getConnectorHost().setExecutionContext(context);
- }
-
- public void setBatchSize(int batchSize) {
- }
-
- public void setProperty(String propertyName, String propertyValue) {
- if (connectorHost == null) {
- if (connectorProperties == null) {
- connectorProperties = new Properties();
- }
- connectorProperties.put(propertyName, propertyValue);
- } else {
- throw new RuntimeException(CdkPlugin.Util.getString("ConnectorShellCommandTarget.Cannot_set_connector_properties_after_the_connector_is_started._1")); //$NON-NLS-1$
- }
- }
-
- private ConnectorHost getConnectorHost() {
- return connectorHost;
- }
-
- public void createTemplate(String filename) {
- File file = new File(filename);
- if (file.exists()) {
- if (!file.canWrite()) {
- throw new RuntimeException(CdkPlugin.Util.getString("ConnectorShellCommandTarget.Cannot_write_to_file__{0}_3", file)); //$NON-NLS-1$
- }
- } else if (file.getParentFile() == null || file.getParentFile().exists()) {
- try {
- if (!file.createNewFile()) {
- throw new RuntimeException(CdkPlugin.Util.getString("ConnectorShellCommandTarget.Cannot_create_file__{0}_4", file)); //$NON-NLS-1$
- }
- } catch (IOException e) {
- throw new RuntimeException(CdkPlugin.Util.getString("ConnectorShellCommandTarget.Cannot_create_file__{0}_4", file)); //$NON-NLS-1$
- }
- } else {
- throw new RuntimeException(CdkPlugin.Util.getString("ConnectorShellCommandTarget.Cannot_create_file_{0}_because_directory_{1}_does_not_exist._6", file, file.getParentFile())); //$NON-NLS-1$
- }
- FileOutputStream out = null;
- try {
- out = new FileOutputStream(file);
- } catch (FileNotFoundException e) {
- throw new RuntimeException(CdkPlugin.Util.getString("ConnectorShellCommandTarget.Cannot_write_to_file__{0}_3", file)); //$NON-NLS-1$
- }
-
- InputStream template = getClass().getResourceAsStream("Template.cdk"); //$NON-NLS-1$
- int readByte = -1;
- try {
- while((readByte = template.read()) != -1) {
- out.write(readByte);
- }
- } catch (IOException e) {
- throw new RuntimeException(CdkPlugin.Util.getString("ConnectorShellCommandTarget.Cannot_write_to_file__{0}_3", file)); //$NON-NLS-1$
- } finally {
- try {
- template.close();
- } catch (Exception e) {
- }
- try {
- out.close();
- } catch (Exception e) {
- }
- }
- }
-}
Deleted: branches/JCA/connector-sdk/src/main/java/com/metamatrix/cdk/QueryCommandTarget.java
===================================================================
--- branches/JCA/connector-sdk/src/main/java/com/metamatrix/cdk/QueryCommandTarget.java 2010-03-04 01:32:54 UTC (rev 1896)
+++ branches/JCA/connector-sdk/src/main/java/com/metamatrix/cdk/QueryCommandTarget.java 2010-03-04 01:56:20 UTC (rev 1897)
@@ -1,111 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.cdk;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
-import com.metamatrix.core.MetaMatrixRuntimeException;
-import com.metamatrix.core.commandshell.ScriptCommandTarget;
-
-/**
- * Base CommandTarget class for processing SQL queries via the command line.
- */
-abstract public class QueryCommandTarget extends ScriptCommandTarget {
-
- abstract protected String execute(String query);
- protected boolean usePreparedStatement = false;
- protected boolean prepareStmt = false;
- protected Map preparedStmts = new HashMap();
- protected String currentPreparedStmtName = null;
-
- protected String readSql(String commandName, String[] args) {
- StringBuffer query = new StringBuffer();
- StringBuffer firstLine = new StringBuffer();
- firstLine.append(commandName);
- firstLine.append(" "); //$NON-NLS-1$
-
- for (int i = 0; i < args.length; i++) {
- firstLine.append(args[i]);
- firstLine.append(" "); //$NON-NLS-1$
- }
-
- String line = firstLine.toString();
-
- boolean cont = true;
- while (cont) {
- try {
- if (line != null && line.trim().endsWith(";")) { //$NON-NLS-1$
- cont = false;
- line = line.trim();
- line = line.substring(0, line.length() - 1);
- }
- query.append(" "); //$NON-NLS-1$
- query.append(line);
- if (cont) {
- line = shell.getNextCommandLine();
- }
- } catch (IOException e) {
- throw new MetaMatrixRuntimeException(e);
- }
- }
- return query.toString();
- }
-
- public void setUsePreparedStatement(boolean usePreparedStatement) {
- this.usePreparedStatement = usePreparedStatement;
- }
-
- protected String executeSql(String commandName, String[] args) {
- if (!this.usePreparedStatement) {
- prepareStmt = false;
- }
-
- if (prepareStmt) {
- preparedStmts.put(currentPreparedStmtName, readSql(commandName, args));
- return ""; //$NON-NLS-1$
- }
- return execute(readSql(commandName, args));
- }
-
- public String select(String[] args) {
- return executeSql("select", args); //$NON-NLS-1$
- }
-
- public String insert(String[] args) {
- return executeSql("insert", args); //$NON-NLS-1$
- }
-
- public String update(String[] args) {
- return executeSql("update", args); //$NON-NLS-1$
- }
-
- public String delete(String[] args) {
- return executeSql("delete", args); //$NON-NLS-1$
- }
-
- public String exec(String[] args) {
- return executeSql("exec", args); //$NON-NLS-1$
- }
-}
Deleted: branches/JCA/connector-sdk/src/main/java/com/metamatrix/core/commandshell/ConnectorResultUtility.java
===================================================================
--- branches/JCA/connector-sdk/src/main/java/com/metamatrix/core/commandshell/ConnectorResultUtility.java 2010-03-04 01:32:54 UTC (rev 1896)
+++ branches/JCA/connector-sdk/src/main/java/com/metamatrix/core/commandshell/ConnectorResultUtility.java 2010-03-04 01:56:20 UTC (rev 1897)
@@ -1,206 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.core.commandshell;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.StringReader;
-import java.util.Iterator;
-import java.util.List;
-
-import com.metamatrix.core.MetaMatrixRuntimeException;
-import com.metamatrix.core.util.StringUtil;
-
-/**
- * Provides utility methods for manipulating the results of executing commands against a connector.
- */
-public class ConnectorResultUtility {
- private static final String ERROR_MESSAGE_PREFIX = "CompareResults Error: "; //$NON-NLS-1$
- private static final String NULL_STRING = "<null>"; //$NON-NLS-1$
- private static final String COLUMN_SEPARATOR = "\t"; //$NON-NLS-1$
- private static final String NOROWS_STRING = "No rows returned."; //$NON-NLS-1$
-
- /**
- * Converts a List of Lists, where each sub-list is a row of data, into a tab delimited String where each line is
- * a row of data. Each object is converted to a String.
- * @param results a List of Lists of data typcially obtained by executing a command on a connector through the ConnectorHost
- * @return the results converted to a tab delimited String
- */
- public static String resultsToString(List results, String[] columnNames) {
- if (results == null || results.isEmpty()) {
- return NOROWS_STRING;
- }
- StringBuffer result = new StringBuffer();
- int columnIndex = 0;
- for (Iterator iterator = results.iterator(); iterator.hasNext();) {
-
- List row = (List) iterator.next();
- boolean firstColumn = true;
- columnIndex = 0;
- for (Iterator j = row.iterator(); j.hasNext(); columnIndex++) {
- Object next = j.next();
- String value = null;
- if (next == null) {
- value = NULL_STRING;
- } else {
- value = next.toString();
- value = StringUtil.replaceAll(value, "\t", "\\t"); //$NON-NLS-1$ //$NON-NLS-2$
- value = StringUtil.replaceAll(value, "\n", "\\n"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- if (firstColumn) {
- firstColumn = false;
- } else {
- result.append(COLUMN_SEPARATOR);
- }
- result.append(value);
- }
- result.append(StringUtil.LINE_SEPARATOR);
- }
-
- if (columnNames == null || columnNames.length == 0) {
- columnNames = new String[columnIndex];
- for (int i = 0; i < columnIndex; i++) {
- columnNames[i] = "col" + (i+1); //$NON-NLS-1$
- }
- }
- StringBuffer header = new StringBuffer();
- boolean firstValue = true;
- for (int i=0; i < columnNames.length; i++) {
- String label = null;
- if (columnNames[i] == null) {
- label = NULL_STRING;
- } else {
- label = columnNames[i];
-
- int delimiterIndex = columnNames[i].lastIndexOf('.');
- if (delimiterIndex != -1) {
- label = columnNames[i].substring(delimiterIndex + 1);
- }
- }
- if (firstValue) {
- firstValue = false;
- } else {
- header.append(COLUMN_SEPARATOR);
- }
- header.append(label);
- }
- header.append(StringUtil.LINE_SEPARATOR);
- return header.toString() + result.toString();
- }
-
- public static String resultsToString(List results) {
- return resultsToString(results, null);
- }
-
- private static int getRowCount(String text) throws IOException {
- BufferedReader reader = new BufferedReader(new StringReader(text));
- int rowCount = 0;
- String line = reader.readLine();
- while (line != null) {
- rowCount++;
- line = reader.readLine();
- }
- return rowCount;
- }
-
- /**
- * Compares two sets of results to determine if they are identical.
- * The results are in the string form provided by the resultsToString method.
- * @param expected String form of the expected results
- * @param actual String form of the actual results
- * @return null if the String are identical or a description of the first difference if they are different
- */
- public static String compareResultsStrings(String expected, String actual) {
- if (expected.equals(actual)) {
- return null;
- }
- try {
- BufferedReader expectedReader = new BufferedReader(new StringReader(expected));
- BufferedReader actualReader = new BufferedReader(new StringReader(actual));
-
- int expectedRowCount = getRowCount(expected);
- int actualRowCount = getRowCount(actual);
-
- if (expectedRowCount > actualRowCount) {
- return (ERROR_MESSAGE_PREFIX + "Expected " + expectedRowCount + //$NON-NLS-1$
- " records but received only " + actualRowCount); //$NON-NLS-1$
- } else if (actualRowCount > expectedRowCount) {
- // Check also for less records than expected
- return (ERROR_MESSAGE_PREFIX + "Expected " + expectedRowCount + //$NON-NLS-1$
- " records but received " + actualRowCount); //$NON-NLS-1$
- }
-
- String expectedLine = expectedReader.readLine();
- int rowIndex = 0;
- while (expectedLine != null) {
- String actualLine = actualReader.readLine();
-
- List actualRow = StringUtil.split(actualLine, COLUMN_SEPARATOR);
- List expectedRow = StringUtil.split(expectedLine, COLUMN_SEPARATOR);
- int actualColumnCount = actualRow.size();
- int expectedColumnCount = expectedRow.size();
-
- //TODO: i18n the messages
-
- // Get actual value
- if (actualColumnCount != expectedColumnCount) {
- return("Incorrect number of columns at row = " + rowIndex + ", expected = " + expectedColumnCount + ", actual = " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- + actualColumnCount);
- }
-
- // Compare sorted actual record with sorted expected record column by column
- for (int columnIndex = 0; columnIndex < expectedColumnCount; columnIndex++) {
- // Get expected value
- Object expectedValue = expectedRow.get(columnIndex);
- Object actualValue = actualRow.get(columnIndex);
-
- // Compare these values
- if (expectedValue == null) {
- if (actualValue != null) {
- return getMismatchMessage(rowIndex, columnIndex, expectedValue, actualValue);
- }
- } else {
- if (!expectedValue.equals(actualValue)) {
- return getMismatchMessage(rowIndex, columnIndex, expectedValue, actualValue);
- }
- }
- } // end loop through columns
- expectedLine = expectedReader.readLine();
-
- rowIndex++;
- } // end loop through rows }
- } catch (IOException e) {
- //this should not happen because the code is simply reading from Strings in memory
- throw new MetaMatrixRuntimeException(e);
- }
- return null;
- }
-
- private static String getMismatchMessage(int rowIndex, int columnIndex, Object expectedValue, Object actualValue) {
- return (ERROR_MESSAGE_PREFIX + "Value mismatch at row " + rowIndex //$NON-NLS-1$
- + " and column " + columnIndex //$NON-NLS-1$
- + ": expected = " //$NON-NLS-1$
- + expectedValue + ", actual = " //$NON-NLS-1$
- + actualValue);
- }
-}
Deleted: branches/JCA/connector-sdk/src/main/java/com/metamatrix/core/commandshell/ScriptCommandTarget.java
===================================================================
--- branches/JCA/connector-sdk/src/main/java/com/metamatrix/core/commandshell/ScriptCommandTarget.java 2010-03-04 01:32:54 UTC (rev 1896)
+++ branches/JCA/connector-sdk/src/main/java/com/metamatrix/core/commandshell/ScriptCommandTarget.java 2010-03-04 01:56:20 UTC (rev 1897)
@@ -1,162 +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.core.commandshell;
-
-import java.util.Arrays;
-import java.util.List;
-
-import com.metamatrix.core.CorePlugin;
-import com.metamatrix.core.util.StringUtil;
-
-/**
- * Base command target class with scripting support.
- */
-public class ScriptCommandTarget extends CommandTarget implements StringUtil.Constants {
- protected static final String TEST_PREFIX = "test"; //$NON-NLS-1$
-
- protected int testFailureCount = 0;
-
- protected int testCount = 0;
-
- private ScriptFileNameStack scriptFileNames = new ScriptFileNameStack();
-
- private boolean runningSetUp = false;
-
- public void setScriptFile(String scriptFileName) {
- scriptFileNames.setDefaultScriptFileName(scriptFileName);
- }
-
- protected static final String SETUP_SCRIPT = "setUp"; //$NON-NLS-1$
-
- protected boolean hasSetupScript(String fileName) {
- String[] scriptNames = shell.getScriptNames(fileName);
- List scriptNameList = Arrays.asList(scriptNames);
- return scriptNameList.contains(SETUP_SCRIPT);
- }
-
- protected StringBuffer testFailureMessage;
-
- protected void runningScript(String fileName) {
- scriptFileNames.usingScriptFile(fileName);
- }
-
- public String run(String scriptName) {
- if (scriptFileNames.hasDefaultScriptFileBeenSet()) {
- return runScriptDirect(scriptFileNames.getUnexpandedCurrentScriptFileName(), scriptName);
- }
- throw new NoScriptFileException();
- }
-
- public String runScript(String fileName, String scriptName) {
- return runScriptDirect( fileName, scriptName );
- }
-
- private String runScriptDirect(String originalFileName, String scriptName) {
- String fileName = scriptFileNames.expandScriptFileName(originalFileName);
- testFailureMessage = new StringBuffer();
- if (!runningSetUp) {
- if (hasSetupScript(fileName)) {
- try {
- runningSetUp = true;
- runScript(fileName, SETUP_SCRIPT, null, null);
- } finally {
- runningSetUp = false;
- }
- }
- }
- runScript(fileName, scriptName, null, getScriptResultListener());
- return testFailureMessage.toString();
- }
-
- void runScript(String fileName, String scriptName, StringBuffer transcript, ScriptResultListener listener) {
- scriptFileNames.startingScriptFromFile(fileName);
- try {
- shell.runScript(fileName, scriptName, transcript, listener);
- } finally {
- scriptFileNames.finishedScript();
- }
- }
-
- private ScriptResultListener getScriptResultListener() {
- return new ScriptResultListener() {
- public void scriptResults(String scriptFileName, String scriptName, String expected, String actual) {
- ScriptCommandTarget.this.scriptResults(scriptFileName, scriptName, expected, actual);
- }
- };
- }
-
- private void scriptResults(String scriptFileName, String scriptName, String expected, String actual) {
- if(expected.equals(actual)) {
- } else {
- testFailureCount++;
- String diffString = ConnectorResultUtility.compareResultsStrings(expected, actual);
- testFailureMessage.append(CorePlugin.Util.getString("ScriptCommandTarget.Test_{0}.{1}_failed.{2}_2", new Object[] {scriptFileName, scriptName, diffString}) ); //$NON-NLS-1$
- testFailureMessage.append(NEW_LINE);
- }
- }
-
- protected void resetTestStatistics() {
- testCount = 0;
- testFailureCount = 0;
- testFailureMessage = new StringBuffer();
- }
-
- public String runAll() {
- resetTestStatistics();
- String fileName = scriptFileNames.expandScriptFileName(scriptFileNames.getUnexpandedCurrentScriptFileName());
- String[] scriptNames = shell.getScriptNames( fileName );
- boolean runSetup = hasSetupScript( fileName );
- for (int i=0; i<scriptNames.length; i++) {
- if (scriptNames[i].startsWith(TEST_PREFIX)){
- testCount++;
- if (runSetup) {
- runScript(fileName, SETUP_SCRIPT, null, null);
- runSetup = false;
- }
- runScript(fileName, scriptNames[i], null, getScriptResultListener());
- }
- }
- return getTestSummary();
- }
-
- protected String getTestSummary() {
- return testFailureMessage.toString() + CorePlugin.Util.getString("ScriptCommandTarget.Tests_run__{0}_test_failures__{1}_1", new Object[] {new Integer(testCount), new Integer(testFailureCount)}); //$NON-NLS-1$
- }
-
- public void runRep(int repCount, String scriptName) {
- for (int i=0; i<repCount; i++) {
- run(scriptName);
- }
- }
-
- public void setSilent(boolean silent) {
- shell.setSilent(silent);
- }
-
- protected Object clone() throws CloneNotSupportedException {
- ScriptCommandTarget result = (ScriptCommandTarget) super.clone();
- result.scriptFileNames = (ScriptFileNameStack) scriptFileNames.clone();
- return result;
- }
-
-}
Deleted: branches/JCA/connector-sdk/src/main/java/com/metamatrix/core/commandshell/ScriptFileNameStack.java
===================================================================
--- branches/JCA/connector-sdk/src/main/java/com/metamatrix/core/commandshell/ScriptFileNameStack.java 2010-03-04 01:32:54 UTC (rev 1896)
+++ branches/JCA/connector-sdk/src/main/java/com/metamatrix/core/commandshell/ScriptFileNameStack.java 2010-03-04 01:56:20 UTC (rev 1897)
@@ -1,143 +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.core.commandshell;
-
-import java.io.File;
-import java.util.Stack;
-
-/**
- * Keeps track of script file names and script directories as scripts are run.
- * Knows how to interpret relative file names in the context of other file names.
- */
-class ScriptFileNameStack implements Cloneable {
- private String defaultScriptFileName;
-
- private Stack executingScriptFileName = new Stack();
-
- /**
- * @param scriptFileName The default script file name to use when none is specified and when no scripts are executing.
- */
- public void setDefaultScriptFileName(String scriptFileName) {
- log("setDefaultScriptFileName", scriptFileName); //$NON-NLS-1$
- defaultScriptFileName = scriptFileName;
- }
-
-
- /**
- * Record that a script file name is being used. This will become the default if no default has been set.
- * @param scriptFileName
- */
- public void usingScriptFile(String scriptFileName) {
- log("usingScriptFile", scriptFileName); //$NON-NLS-1$
- if (!hasDefaultScriptFileBeenSet()) {
- setDefaultScriptFileName(scriptFileName);
- }
- }
-
- private void log(String method, String value) {
- //System.out.println("ScriptFileNames." + method + ": " + value);
- }
-
- /**
- * Expands relative file names to include path information from currently running file names.
- * @param scriptFileName
- * @return
- */
- public String expandScriptFileName(String scriptFileName) {
- log("expandScriptFileName", scriptFileName); //$NON-NLS-1$
- String result = scriptFileName;
- String parent = getParent();
- if (isAbsolute(scriptFileName) || parent == null) {
- } else {
- result = parent + File.separator + scriptFileName;
- }
- log("expandScriptFileName", "result=" + result); //$NON-NLS-1$ //$NON-NLS-2$
- return result;
- }
-
- private String getParent() {
- String parent = null;
- if (!executingScriptFileName.isEmpty()) {
- parent = new File(peek()).getParent();
- }
- return parent;
- }
-
-
- public boolean hasDefaultScriptFileBeenSet() {
- return defaultScriptFileName != null;
- }
-
- private String peek() {
- return (String) executingScriptFileName.peek();
- }
-
- private boolean isAbsolute(String fileName) {
- File file = new File(fileName);
- return file.isAbsolute() || fileName.startsWith("\\") || fileName.startsWith("/"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * Retrieves the default script file name.
- * If a script is currently executing this will return the name of the current executing script file rather than the default.
- * @return
- */
- public String getUnexpandedCurrentScriptFileName() {
- String result = getCurrentScriptFileNameDirect();
- log("getCurrentScriptFileName", result); //$NON-NLS-1$
- return result;
- }
-
- private String getCurrentScriptFileNameDirect() {
- if (executingScriptFileName.isEmpty()) {
- return defaultScriptFileName;
- }
- return new File(peek()).getName();
- }
-
- /**
- * Indicate that a script is about to be executed from the given file.
- * This must be called in order to maintain the stack tracking the current script file.
- * @param fileName
- */
- public void startingScriptFromFile(String fileName) {
- log("startingScriptFromFile", fileName); //$NON-NLS-1$
- executingScriptFileName.push(fileName);
- }
-
- /**
- * Indicate that a script has completed execution.
- * This must be called in order to maintain the stack tracking the current script file.
- */
- public void finishedScript() {
- log("finishedScript", ""); //$NON-NLS-1$ //$NON-NLS-2$
- executingScriptFileName.pop();
- }
-
- protected Object clone() throws CloneNotSupportedException {
- ScriptFileNameStack result = (ScriptFileNameStack) super.clone();
- executingScriptFileName = (Stack) executingScriptFileName.clone();
- return result;
- }
-
-}
Modified: branches/JCA/connector-sdk/src/test/java/com/metamatrix/core/commandshell/TestCommand.java
===================================================================
--- branches/JCA/connector-sdk/src/test/java/com/metamatrix/core/commandshell/TestCommand.java 2010-03-04 01:32:54 UTC (rev 1896)
+++ branches/JCA/connector-sdk/src/test/java/com/metamatrix/core/commandshell/TestCommand.java 2010-03-04 01:56:20 UTC (rev 1897)
@@ -22,26 +22,14 @@
package com.metamatrix.core.commandshell;
-import java.util.TimeZone;
import junit.framework.TestCase;
-import com.metamatrix.common.util.TimestampWithTimezone;
-import com.metamatrix.core.util.UnitTestUtil;
-
public class TestCommand extends TestCase {
public TestCommand(String name) {
super(name);
}
- public void setUp() {
- TimestampWithTimezone.resetCalendar(TimeZone.getTimeZone("GMT-06:00")); //$NON-NLS-1$
- }
-
- public void tearDown() {
- TimestampWithTimezone.resetCalendar(null);
- }
-
public void test() throws Exception {
FakeCommandTarget target = new FakeCommandTarget();
String commandName = "getLatest"; //$NON-NLS-1$
@@ -60,15 +48,6 @@
assertEquals("getLatest samplePath", target.getTrace()); //$NON-NLS-1$
}
- public void testArgConversion() throws Exception {
- FakeCommandTarget target = new FakeCommandTarget();
- String commandName = "checkin"; //$NON-NLS-1$
- String[] args = new String[] { "samplePath", UnitTestUtil.getTestDataPath() + "/fakeFile", "2003-10-01:00:00:00" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Command command = new Command(target, commandName, args);
- command.execute();
- assertEquals("checkin samplePath <data> Wed Oct 01 00:00:00 GMT-06:00 2003", target.getTrace()); //$NON-NLS-1$
- }
-
public void testArgConversionStringArray() throws Exception {
FakeCommandTarget target = new FakeCommandTarget();
String commandName = "method0"; //$NON-NLS-1$
@@ -95,14 +74,6 @@
assertEquals("getLatest samplePath", target.getTrace()); //$NON-NLS-1$
}
- public void testCommandParsingDates() throws Exception {
- FakeCommandTarget target = new FakeCommandTarget();
- String commandLine = "checkin samplePath " + UnitTestUtil.getTestDataPath() + "/fakeFile \"2003-10-01:00:00:00\""; //$NON-NLS-1$ //$NON-NLS-2$
- Command command = new Command(target, commandLine);
- command.execute();
- assertEquals("checkin samplePath <data> Wed Oct 01 00:00:00 GMT-06:00 2003", target.getTrace()); //$NON-NLS-1$
- }
-
public void testComment() throws Exception {
FakeCommandTarget target = new FakeCommandTarget();
String commandLine = "//command"; //$NON-NLS-1$
Deleted: branches/JCA/connector-sdk/src/test/java/com/metamatrix/core/commandshell/TestScriptFileNameStack.java
===================================================================
--- branches/JCA/connector-sdk/src/test/java/com/metamatrix/core/commandshell/TestScriptFileNameStack.java 2010-03-04 01:32:54 UTC (rev 1896)
+++ branches/JCA/connector-sdk/src/test/java/com/metamatrix/core/commandshell/TestScriptFileNameStack.java 2010-03-04 01:56:20 UTC (rev 1897)
@@ -1,184 +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.core.commandshell;
-
-import java.io.File;
-import junit.framework.TestCase;
-
-public class TestScriptFileNameStack extends TestCase {
- ScriptFileNameStack names = new ScriptFileNameStack();
-
- public void testCurrentDefaultSetRelativeDirectory() {
- names.setDefaultScriptFileName("a"+File.separator+"b"+File.separator+"c"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- assertEquals("a" + File.separator + "b" + File.separator + "c", names.getUnexpandedCurrentScriptFileName()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- public void testCurrentDefaultSetAbsoluteDirectory() {
- names.setDefaultScriptFileName(File.separator+"a"+File.separator+"b"+File.separator+"c"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- assertEquals(File.separator + "a" + File.separator + "b" + File.separator + "c", names.getUnexpandedCurrentScriptFileName()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- ////
-
- public void testCurrentDefaultWithExecutingScript() {
- names.setDefaultScriptFileName("a"+File.separator+"b"+File.separator+"c"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- names.startingScriptFromFile("d"); //$NON-NLS-1$
- assertEquals("d", names.getUnexpandedCurrentScriptFileName()); //$NON-NLS-1$
- }
-
- public void testCurrentDefaultSetWithExecutingScript() {
- names.setDefaultScriptFileName(File.separator+"a"+File.separator+"b"+File.separator+"c"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- names.startingScriptFromFile("d"); //$NON-NLS-1$
- assertEquals("d", names.getUnexpandedCurrentScriptFileName()); //$NON-NLS-1$
- }
-
- public void testCurrentDefaultWithExecutingRelativeScript() {
- names.setDefaultScriptFileName("a"+File.separator+"b"+File.separator+"c"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- names.startingScriptFromFile("d"+File.separator+"e"); //$NON-NLS-1$ //$NON-NLS-2$
- assertEquals("e", names.getUnexpandedCurrentScriptFileName()); //$NON-NLS-1$
- }
-
- public void testCurrentDefaultSetWithExecutingAbsoluteScript() {
- names.setDefaultScriptFileName(File.separator+"a"+File.separator+"b"+File.separator+"c"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- names.startingScriptFromFile(File.separator+"d"+File.separator+"e"); //$NON-NLS-1$ //$NON-NLS-2$
- assertEquals("e", names.getUnexpandedCurrentScriptFileName()); //$NON-NLS-1$
- }
-
- ////
-
- public void testExpandWithExecutingScript() {
- names.setDefaultScriptFileName("a"+File.separator+"b"+File.separator+"c"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- names.startingScriptFromFile("d"); //$NON-NLS-1$
- assertEquals("e", names.expandScriptFileName("e")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public void testExpandWithExecutingScript2() {
- names.setDefaultScriptFileName(File.separator+"a"+File.separator+"b"+File.separator+"c"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- names.startingScriptFromFile("d"); //$NON-NLS-1$
- assertEquals("e", names.expandScriptFileName("e")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public void testExpandWithExecutingRelativeScript() {
- names.setDefaultScriptFileName("a"+File.separator+"b"+File.separator+"c"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- names.startingScriptFromFile("d"+File.separator+"e"); //$NON-NLS-1$ //$NON-NLS-2$
- assertEquals("d" + File.separator + "f", names.expandScriptFileName("f")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- public void testExpandWithExecutingAbsoluteScript() {
- names.setDefaultScriptFileName(File.separator+"a"+File.separator+"b"+File.separator+"c"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- names.startingScriptFromFile(File.separator+"d"+File.separator+"e"); //$NON-NLS-1$ //$NON-NLS-2$
- assertEquals(File.separator + "d" + File.separator + "f", names.expandScriptFileName("f")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- public void testExpandWithExecutingBaseScript() {
- names.setDefaultScriptFileName("a"+File.separator+"b"+File.separator+"c"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- names.startingScriptFromFile("d"+File.separator+"e"); //$NON-NLS-1$ //$NON-NLS-2$
- assertEquals("d" + File.separator + "f", names.expandScriptFileName("f")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- public void testExpandWithExecutingScriptStack() {
- names.setDefaultScriptFileName("a"+File.separator+"b"+File.separator+"c"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- names.startingScriptFromFile("d"+File.separator+"e"); //$NON-NLS-1$ //$NON-NLS-2$
- names.startingScriptFromFile("f"+File.separator+"g"); //$NON-NLS-1$ //$NON-NLS-2$
- assertEquals("f" + File.separator + "h", names.expandScriptFileName("h")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- public void testExpandWithExecutingScriptStackExpand() {
- names.setDefaultScriptFileName("a"+File.separator+"b"+File.separator+"c"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- names.startingScriptFromFile(names.expandScriptFileName("d"+File.separator+"e")); //$NON-NLS-1$ //$NON-NLS-2$
- names.startingScriptFromFile(names.expandScriptFileName("f"+File.separator+"g")); //$NON-NLS-1$ //$NON-NLS-2$
- assertEquals("d" + File.separator + "f" + File.separator + "h", names.expandScriptFileName("h")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- public void testExpandWithExecutingScriptStackExpand2() {
- names.setDefaultScriptFileName("a"+File.separator+"b"+File.separator+"c"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- names.startingScriptFromFile(names.expandScriptFileName("a"+File.separator+"b"+File.separator+"c")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- names.startingScriptFromFile(names.expandScriptFileName("d"+File.separator+"e")); //$NON-NLS-1$ //$NON-NLS-2$
- names.startingScriptFromFile(names.expandScriptFileName("f"+File.separator+"g")); //$NON-NLS-1$ //$NON-NLS-2$
- assertEquals("a" + File.separator + "b" + File.separator + "d" + File.separator + "f" + File.separator + "h", names.expandScriptFileName("h")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- }
-
- public void testExpandWithExecutingScriptStackRelative() {
- names.setDefaultScriptFileName("a"+File.separator+"b"+File.separator+"c"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- names.startingScriptFromFile("d"+File.separator+"e"); //$NON-NLS-1$ //$NON-NLS-2$
- names.startingScriptFromFile("d"+File.separator+"f"+File.separator+"g"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- assertEquals("d" + File.separator + "f" + File.separator + "h", names.expandScriptFileName("h")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- ////
-
- public void testExpandFromRelativeDirectory() {
- names.setDefaultScriptFileName("a"+File.separator+"b"+File.separator+"c"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- assertEquals("d", names.expandScriptFileName("d")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public void testExpandFromAbsoluteDirectory() {
- names.setDefaultScriptFileName(File.separator+"a"+File.separator+"b"+File.separator+"c"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- assertEquals("d", names.expandScriptFileName("d")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public void testExpandWithoutReferencesingBaseDirectoryAbsolute() {
- names.setDefaultScriptFileName(File.separator+"a"+File.separator+"b"+File.separator+"c"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- assertEquals(File.separator + "d" + File.separator + "e", names.expandScriptFileName(File.separator + "d" + File.separator + "e")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- public void testExpandWithoutReferencesingBaseDirectoryRelative() {
- names.setDefaultScriptFileName(File.separator+"a"+File.separator+"b"+File.separator+"c"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- assertEquals("d" + File.separator + "e", names.expandScriptFileName("d" + File.separator + "e")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- public void testHasBaseDefaultBeenSet() {
- assertFalse(names.hasDefaultScriptFileBeenSet());
- names.setDefaultScriptFileName("a"); //$NON-NLS-1$
- assertTrue(names.hasDefaultScriptFileBeenSet());
- }
-
- public void testSettingDefaultByUsing() {
- names.usingScriptFile("a"); //$NON-NLS-1$
- assertTrue(names.hasDefaultScriptFileBeenSet());
- }
-
- public void testUsingIgnoredAfterSetDefaultCalled() {
- names.setDefaultScriptFileName("a"); //$NON-NLS-1$
- names.usingScriptFile("b"); //$NON-NLS-1$
- assertEquals("a", names.getUnexpandedCurrentScriptFileName()); //$NON-NLS-1$
- }
-
- public void testExecutingScriptAsStack() {
- names.setDefaultScriptFileName(File.separator+"a"+File.separator+"b"+File.separator+"c"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- names.startingScriptFromFile(File.separator+"d"+File.separator+"e"); //$NON-NLS-1$ //$NON-NLS-2$
- names.startingScriptFromFile(File.separator+"f"+File.separator+"g"); //$NON-NLS-1$ //$NON-NLS-2$
- names.startingScriptFromFile(File.separator+"h"+File.separator+"i"); //$NON-NLS-1$ //$NON-NLS-2$
- names.finishedScript();
- assertEquals("g", names.getUnexpandedCurrentScriptFileName()); //$NON-NLS-1$
- }
-
- public void testClone() throws CloneNotSupportedException {
- names.startingScriptFromFile("a"); //$NON-NLS-1$
- names.startingScriptFromFile("b"); //$NON-NLS-1$
- ScriptFileNameStack names2 = (ScriptFileNameStack) names.clone();
- names.finishedScript();
- assertEquals("b", names2.getUnexpandedCurrentScriptFileName()); //$NON-NLS-1$
- }
-
-}
Modified: branches/JCA/engine/src/main/java/com/metamatrix/common/buffer/impl/FileStorageManager.java
===================================================================
--- branches/JCA/engine/src/main/java/com/metamatrix/common/buffer/impl/FileStorageManager.java 2010-03-04 01:32:54 UTC (rev 1896)
+++ branches/JCA/engine/src/main/java/com/metamatrix/common/buffer/impl/FileStorageManager.java 2010-03-04 01:56:20 UTC (rev 1897)
@@ -44,7 +44,8 @@
* Implements file storage that automatically splits large files and limits the number of open files.
*/
public class FileStorageManager implements StorageManager {
-
+
+ private static final int DEFAULT_MAX_OPEN_FILES = 128;
private static final String FILE_PREFIX = "b_"; //$NON-NLS-1$
private class FileInfo {
@@ -151,7 +152,7 @@
}
// Initialization
- private int maxOpenFiles = 32;
+ private int maxOpenFiles = DEFAULT_MAX_OPEN_FILES;
private long maxFileSize = 2L * 1024L * 1024L * 1024L; // 2GB
private String directory;
private File dirFile;
@@ -173,11 +174,7 @@
});
/**
- * Initialize with properties
- * @param props Initialization properties
- * @see com.metamatrix.common.buffer.BufferManager#BUFFER_STORAGE_DIRECTORY
- * @see com.metamatrix.common.buffer.BufferManager#MAX_OPEN_FILES
- * @see com.metamatrix.common.buffer.BufferManager#MAX_FILE_SIZE
+ * Initialize
*/
public void initialize() throws MetaMatrixComponentException {
if(this.directory == null) {
Deleted: branches/JCA/test-integration/common/src/test/java/com/metamatrix/cdk/TestConnectorShell.java
===================================================================
--- branches/JCA/test-integration/common/src/test/java/com/metamatrix/cdk/TestConnectorShell.java 2010-03-04 01:32:54 UTC (rev 1896)
+++ branches/JCA/test-integration/common/src/test/java/com/metamatrix/cdk/TestConnectorShell.java 2010-03-04 01:56:20 UTC (rev 1897)
@@ -1,265 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.cdk;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-
-import com.metamatrix.core.commandshell.CommandShell;
-import com.metamatrix.core.commandshell.CommandShellTest;
-import com.metamatrix.core.util.StringUtil;
-import com.metamatrix.core.util.UnitTestUtil;
-
-public class TestConnectorShell extends CommandShellTest {
- private ConnectorShell connectorShell;
- private ConnectorShellCommandTarget commandTarget;
-
- public TestConnectorShell(String name) {
- super(name);
- }
-
- /*
- * @see junit.framework.TestCase#setUp()
- */
- protected void setUp() throws Exception {
- super.setUp();
- commandTarget = new ConnectorShellCommandTarget();
- connectorShell = new ConnectorShell(commandTarget);
- connectorShell.setSilent(true);
- connectorShell.setPrintStackTraceOnException(false);
- connectorShell.setDefaultFilePath(UnitTestUtil.getTestDataPath() + File.separator);
- }
-
- public void testLoad() {
- String result = loadLoopBackConnector();
- assertNull(result);
- }
-
- private String loadLoopBackConnector() {
- return connectorShell.execute("load com.metamatrix.connector.loopback.LoopbackConnector partssupplier/PartsSupplier.vdb"); //$NON-NLS-1$
- }
-
- private void start() {
- connectorShell.execute("start"); //$NON-NLS-1$
- }
-
- public void testSelect() {
- loadLoopBackConnector();
- start();
- String result = connectorShell.execute("select * from partssupplier.partssupplier.parts;"); //$NON-NLS-1$
- assertEquals("PART_ID\tPART_NAME\tPART_COLOR\tPART_WEIGHT" + StringUtil.LINE_SEPARATOR + "ABCDEFGHIJ\tABCDEFGHIJ\tABCDEFGHIJ\tABCDEFGHIJ" + StringUtil.LINE_SEPARATOR, result); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
-
- public void testRun() {
- loadLoopBackConnector();
- start();
- setScriptFile();
- connectorShell.turnOffExceptionHandling();
- String result = connectorShell.execute("run test1"); //$NON-NLS-1$
- assertEquals("Test " + UnitTestUtil.getTestDataPath() + File.separator + "script.txt.test1 failed. CompareResults Error: Expected 1 records but received 2\n", result); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- private void setScriptFile() {
- setScriptFile( "script.txt" ); //$NON-NLS-1$
- }
-
- private void setScriptFile(String fileName) {
- connectorShell.execute("setScriptFile " + UnitTestUtil.getTestDataPath() + File.separator + fileName); //$NON-NLS-1$
- }
-
- public void testCallingScriptFromAnotherScriptFile() {
- commandTarget.setFailOnError(true);
- connectorShell.execute( "setscriptfile " + UnitTestUtil.getTestDataPath() + File.separator + "/cdk/s1.txt" ); //$NON-NLS-1$ //$NON-NLS-2$
-
- assertEquals( "", connectorShell.execute( "s3" ) ); //$NON-NLS-1$ //$NON-NLS-2$
- assertEquals( "", connectorShell.execute( "s1" ) ); //$NON-NLS-1$ //$NON-NLS-2$
- connectorShell.execute( "s4" ); //$NON-NLS-1$
- connectorShell.execute( "s2" ); //$NON-NLS-1$
- }
-
- public void testCallingScriptFromAnotherScriptFileThatCallsAScript() {
- commandTarget.setFailOnError(true);
- connectorShell.setDefaultFilePath(""); //$NON-NLS-1$
- connectorShell.execute( "setscriptfile " + UnitTestUtil.getTestDataPath() + File.separator + "/cdk/s3.txt" ); //$NON-NLS-1$ //$NON-NLS-2$
-
- assertEquals( "", connectorShell.execute( "s3_3" ) ); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public void testRunAllTests() {
- loadLoopBackConnector();
- start();
- setScriptFile();
- String result = connectorShell.execute("runAll"); //$NON-NLS-1$
- assertEquals("Test " + UnitTestUtil.getTestDataPath() + File.separator + "script.txt.test1 failed. CompareResults Error: Expected 1 records but received 2\nTest " + UnitTestUtil.getTestDataPath() + File.separator +"script.txt.testBadData failed. CompareResults Error: Value mismatch at row 1 and column 2: expected = XX, actual = ABCDEFGHIJ\nTests run: 14 test failures: 2", result); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- public void testSetProperty() {
- connectorShell.setDefaultFilePath(UnitTestUtil.getTestDataPath() + File.separator);
- setScriptFile();
- String result = connectorShell.execute("run testSetProperty"); //$NON-NLS-1$
- assertEquals("", result); //$NON-NLS-1$
- }
-
- public void testSetPropertyAfterConnectorHostStart() {
- connectorShell.setDefaultFilePath(UnitTestUtil.getTestDataPath() + File.separator);
- setScriptFile();
- start();
- String result = connectorShell.execute("run testSetPropertyAfterConnectorHostStart"); //$NON-NLS-1$
- assertEquals("", result); //$NON-NLS-1$
- }
-
- public void testLoadingClearsProperties() {
- connectorShell.setDefaultFilePath(UnitTestUtil.getTestDataPath() + File.separator);
- setScriptFile();
- String result = connectorShell.execute("run testLoadingClearsProperties"); //$NON-NLS-1$
- assertEquals("", result); //$NON-NLS-1$
- }
-
- public void testRunAllTestsWithoutSetup() {
- loadLoopBackConnector();
- start();
- setScriptFile("scriptWithoutSetup.txt"); //$NON-NLS-1$
- String result = connectorShell.execute("runAll"); //$NON-NLS-1$
- assertEquals("Test " + UnitTestUtil.getTestDataPath() + File.separator + "scriptWithoutSetup.txt.test1 failed. CompareResults Error: Expected 1 records but received 2\nTests run: 3 test failures: 1", result); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public void testCaseInsensitiveCommands() {
- loadLoopBackConnector();
- setScriptFile();
- String result = connectorShell.execute("run testCaseInsensitiveCommands"); //$NON-NLS-1$
- assertEquals("", result); //$NON-NLS-1$
- }
-
- public void testInvokingAsCommandLine() {
- new ConnectorShell(new ConnectorShellCommandTarget()).run(new String[] {"quit"}, UnitTestUtil.getTestScratchPath() + "/connector_shell.log"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
-
- /*
- * @see com.metamatrix.core.commandshell.CommandShellTest#getCommandShell()
- */
- protected CommandShell getCommandShell() {
- return connectorShell;
- }
-
- public void testLoadArchive() {
- runTest("testLoadArchive"); //$NON-NLS-1$
- }
-
- public void testCreateArchive() {
- File f = UnitTestUtil.getTestScratchFile("foo.caf");
- f.delete();
- connectorShell.execute("createArchive "+UnitTestUtil.getTestScratchPath()+"/foo.caf "+UnitTestUtil.getTestDataPath()+"/sample/sample2.cdk "+UnitTestUtil.getTestDataPath()+"/sample");
- assertTrue("failed to create archive file", f.exists());
- }
-
- public void testHelp() {
- runTest("testHelp"); //$NON-NLS-1$
- }
-
- public void testNotLoadingConnector() {
- runTest("testNotLoadingConnector"); //$NON-NLS-1$
- }
-
- public void testStart() {
- loadLoopBackConnector();
- connectorShell.execute("start"); //$NON-NLS-1$
- }
-
- public void testStop() {
- loadLoopBackConnector();
- start();
- connectorShell.execute("stop"); //$NON-NLS-1$
- }
-
- public void testLoadXMLProperties() {
- loadLoopBackConnector();
- connectorShell.execute("loadProperties " + UnitTestUtil.getTestDataPath() + File.separator+ "properties.cdk"); //$NON-NLS-1$ //$NON-NLS-2$
- start();
- String loadedProperties = connectorShell.execute("getProperties"); //$NON-NLS-1$
- String expected = new StringBuffer("property1=PropVal1") //$NON-NLS-1$
- .append(StringUtil.LINE_SEPARATOR)
- .append("property2=PropVal2") //$NON-NLS-1$
- .append(StringUtil.LINE_SEPARATOR)
- .append("property3=com.metamatrix.cdk.propertyVal") //$NON-NLS-1$
- .append(StringUtil.LINE_SEPARATOR)
- .toString();
- assertEquals(expected, loadedProperties);
- }
-
- public void testLoadPropertiesFromPropertiesFile() {
- loadLoopBackConnector();
- connectorShell.execute("loadProperties " + UnitTestUtil.getTestDataPath() + File.separator+ "/cdk/connector.properties"); //$NON-NLS-1$ //$NON-NLS-2$
- start();
- String loadedProperties = connectorShell.execute("getProperties"); //$NON-NLS-1$
- assertNotNull(loadedProperties);
- String expected = new StringBuffer("property1=PropVal1") //$NON-NLS-1$
- .append(StringUtil.LINE_SEPARATOR)
- .append("property2=PropVal2") //$NON-NLS-1$
- .append(StringUtil.LINE_SEPARATOR)
- .append("property3=com.metamatrix.cdk.propertyVal") //$NON-NLS-1$
- .append(StringUtil.LINE_SEPARATOR)
- .toString();
- assertEquals(expected, loadedProperties);
- }
-
-
- public void testCreateTemplateFileDoesNotExistNoPath() throws FileNotFoundException, IOException {
- //Create a template file. The file does not exist yet. The filename does not include a path.
- runTemplateTestAndDeleteFile("testTemplate1"); //$NON-NLS-1$
- }
-
- public void testCreateTemplateFileDoesNotExist() throws FileNotFoundException, IOException {
- //Create a template file. The file does not exist yet. The filename does not include a path.
- runTemplateTestAndDeleteFile("testTemplate2"); //$NON-NLS-1$
- }
-
- private void runTemplateTestAndDeleteFile(String fileName) throws FileNotFoundException, IOException {
- fileName = UnitTestUtil.getTestScratchPath() + File.separator + fileName;
- new File(fileName).delete();
- runTemplateTest(fileName);
- }
-
- private void runTemplateTest(String tempFileName) throws FileNotFoundException, IOException {
- connectorShell.execute("setFailOnError true"); //$NON-NLS-1$
- connectorShell.execute("createTemplate " + tempFileName); //$NON-NLS-1$
-
- FileInputStream template = new FileInputStream(new File(tempFileName));
- InputStream original = getClass().getResourceAsStream("Template.cdk"); //$NON-NLS-1$
- int originalByte= 0, tempByte = 0;
- int bytesCompared = 0;
- while((originalByte = original.read()) != -1 && (tempByte = template.read()) != -1) {
- assertEquals(originalByte, tempByte);
- bytesCompared++;
- }
- assertTrue(bytesCompared>0);
- // Ensure that the end of the master template has been reached
- assertEquals(-1, originalByte);
- template.close();
- original.close();
- }
-}
Deleted: branches/JCA/test-integration/common/src/test/java/com/metamatrix/cdk/api/TestConnectorResultUtility.java
===================================================================
--- branches/JCA/test-integration/common/src/test/java/com/metamatrix/cdk/api/TestConnectorResultUtility.java 2010-03-04 01:32:54 UTC (rev 1896)
+++ branches/JCA/test-integration/common/src/test/java/com/metamatrix/cdk/api/TestConnectorResultUtility.java 2010-03-04 01:56:20 UTC (rev 1897)
@@ -1,191 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.cdk.api;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-import com.metamatrix.core.commandshell.ConnectorResultUtility;
-import com.metamatrix.core.util.StringUtil;
-
-public class TestConnectorResultUtility extends TestCase {
- List bob1;
- List bob2;
- List jim1;
- List bobShort;
- List bobMultiLineWithTabs;
-
- List nullList;
-
- List results1;
- List results2;
-
- public TestConnectorResultUtility(String name) {
- super(name);
- }
-
- public void testSame() {
- results1.add(bob1);
- results1.add(jim1);
-
- results2.add(bob1);
- results2.add(jim1);
-
- String expected = ConnectorResultUtility.resultsToString(results1);
- String actual = ConnectorResultUtility.resultsToString(results2);
- String result = ConnectorResultUtility.compareResultsStrings(expected, actual);
- assertNull(result);
- }
-
- public void testDifferent() {
- results1.add(bob1);
- results1.add(jim1);
-
- results2.add(bob2);
- results2.add(jim1);
-
- String expected = ConnectorResultUtility.resultsToString(results1);
- String actual = ConnectorResultUtility.resultsToString(results2);
- String result = ConnectorResultUtility.compareResultsStrings(expected, actual);
- assertEquals("CompareResults Error: Value mismatch at row 1 and column 1: expected = 45, actual = 25", result); //$NON-NLS-1$
- }
-
- public void testTooFewRows() {
- results1.add(bob1);
- results1.add(jim1);
-
- results2.add(bob1);
-
- String expected = ConnectorResultUtility.resultsToString(results1);
- String actual = ConnectorResultUtility.resultsToString(results2);
- String result = ConnectorResultUtility.compareResultsStrings(expected, actual);
- assertEquals("CompareResults Error: Expected 3 records but received only 2", result); //$NON-NLS-1$
- }
-
- public void testTooManyRows() {
- results1.add(bob1);
-
- results2.add(bob1);
- results2.add(jim1);
-
- String expected = ConnectorResultUtility.resultsToString(results1);
- String actual = ConnectorResultUtility.resultsToString(results2);
- String result = ConnectorResultUtility.compareResultsStrings(expected, actual);
- assertEquals("CompareResults Error: Expected 2 records but received 3", result); //$NON-NLS-1$
- }
-
- public void testNullColumns() {
- results1.add(bob1);
-
- results2.add(nullList);
-
- String expected = ConnectorResultUtility.resultsToString(results1);
- String actual = ConnectorResultUtility.resultsToString(results2);
- String result = ConnectorResultUtility.compareResultsStrings(expected, actual);
- assertEquals("CompareResults Error: Value mismatch at row 1 and column 0: expected = bob, actual = <null>", result); //$NON-NLS-1$
- }
-
- public void testNullColumnInFirstRowWithDataLater() {
- results1.add(nullList);
- results1.add(bob1);
- String result = ConnectorResultUtility.resultsToString(results1);
- assertEquals(
- "col1\tcol2" + StringUtil.LINE_SEPARATOR + //$NON-NLS-1$
- "<null>\t<null>" + StringUtil.LINE_SEPARATOR + //$NON-NLS-1$
- "bob\t45" + StringUtil.LINE_SEPARATOR, //$NON-NLS-1$
- result);
- }
-
- public void testNullColumnInFirstRowWithNoDataLater() {
- results1.add(nullList);
- results1.add(nullList);
- String result = ConnectorResultUtility.resultsToString(results1);
- assertEquals(
- "col1\tcol2" + StringUtil.LINE_SEPARATOR + //$NON-NLS-1$
- "<null>\t<null>" + StringUtil.LINE_SEPARATOR + //$NON-NLS-1$
- "<null>\t<null>" + StringUtil.LINE_SEPARATOR, //$NON-NLS-1$
- result);
- }
-
- public void testTooFewColumns() {
- results1.add(bob1);
-
- results2.add(bobShort);
-
- String expected = ConnectorResultUtility.resultsToString(results1);
- String actual = ConnectorResultUtility.resultsToString(results2);
- String result = ConnectorResultUtility.compareResultsStrings(expected, actual);
- assertEquals("Incorrect number of columns at row = 0, expected = 2, actual = 1", result); //$NON-NLS-1$
- }
-
- public void testTooManyColumns() {
- results1.add(bobShort);
-
- results2.add(bob1);
-
- String expected = ConnectorResultUtility.resultsToString(results1);
- String actual = ConnectorResultUtility.resultsToString(results2);
- String result = ConnectorResultUtility.compareResultsStrings(expected, actual);
- assertEquals("Incorrect number of columns at row = 0, expected = 1, actual = 2", result); //$NON-NLS-1$
- }
-
- public void testTabsAndNewLines() {
- results1.add(bobMultiLineWithTabs);
- String result = ConnectorResultUtility.resultsToString(results1);
- //tabs and newlines in Strings in the result object end up as literal "\t" and "\n" values in the string version
- assertEquals("col1\tcol2" + StringUtil.LINE_SEPARATOR + "bob\\tsmith\\nEsquire\t45" + StringUtil.LINE_SEPARATOR, result); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /*
- * @see junit.framework.TestCase#setUp()
- */
- protected void setUp() throws Exception {
- super.setUp();
- bob1 = new ArrayList();
- bob1.add("bob"); //$NON-NLS-1$
- bob1.add(new Integer(45));
- jim1 = new ArrayList();
- jim1.add("jim"); //$NON-NLS-1$
- jim1.add(new Integer(19));
-
- bob2 = new ArrayList();
- bob2.add("bob"); //$NON-NLS-1$
- bob2.add(new Integer(25));
-
- bobShort = new ArrayList();
- bobShort.add("bob"); //$NON-NLS-1$
-
- bobMultiLineWithTabs = new ArrayList();
- bobMultiLineWithTabs.add("bob\tsmith\nEsquire"); //$NON-NLS-1$
- bobMultiLineWithTabs.add(new Integer(45));
-
- nullList = new ArrayList();
- nullList.add(null);
- nullList.add(null);
-
- results1 = new ArrayList();
- results2 = new ArrayList();
- }
-}
14 years, 2 months
teiid SVN: r1896 - in trunk: client-jdbc/src/test/java/com/metamatrix/jdbc/api and 1 other directories.
by teiid-commits@lists.jboss.org
Author: shawkins
Date: 2010-03-03 20:32:54 -0500 (Wed, 03 Mar 2010)
New Revision: 1896
Modified:
trunk/client-jdbc/src/main/java/com/metamatrix/jdbc/MMResultSet.java
trunk/client-jdbc/src/test/java/com/metamatrix/jdbc/api/AbstractQueryTest.java
trunk/connectors/connector-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCMetdataProcessor.java
Log:
minor cleanups prior to merge
Modified: trunk/client-jdbc/src/main/java/com/metamatrix/jdbc/MMResultSet.java
===================================================================
--- trunk/client-jdbc/src/main/java/com/metamatrix/jdbc/MMResultSet.java 2010-03-04 01:31:04 UTC (rev 1895)
+++ trunk/client-jdbc/src/main/java/com/metamatrix/jdbc/MMResultSet.java 2010-03-04 01:32:54 UTC (rev 1896)
@@ -25,6 +25,7 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
+import java.io.StringReader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
@@ -688,8 +689,12 @@
if (value instanceof Clob) {
return ((Clob) value).getCharacterStream();
}
-
- throw new MMSQLException(JDBCPlugin.Util.getString("MMResultSet.cannot_convert_to_character_stream")); //$NON-NLS-1$
+
+ if (value instanceof SQLXML) {
+ return ((SQLXML)value).getCharacterStream();
+ }
+
+ return new StringReader(getString(columnIndex));
}
/**
Modified: trunk/client-jdbc/src/test/java/com/metamatrix/jdbc/api/AbstractQueryTest.java
===================================================================
--- trunk/client-jdbc/src/test/java/com/metamatrix/jdbc/api/AbstractQueryTest.java 2010-03-04 01:31:04 UTC (rev 1895)
+++ trunk/client-jdbc/src/test/java/com/metamatrix/jdbc/api/AbstractQueryTest.java 2010-03-04 01:32:54 UTC (rev 1896)
@@ -142,7 +142,7 @@
}
protected Statement createPrepareCallStatement(String sql) throws SQLException{
- return this.internalConnection.prepareCall("{?=call "+sql+"}");
+ return this.internalConnection.prepareCall("{?=call "+sql+"}"); //$NON-NLS-1$ //$NON-NLS-2$
}
protected Statement createPrepareStatement(String sql) throws SQLException{
@@ -153,8 +153,6 @@
return this.internalConnection.createStatement();
}
-
-
private void setParameters(PreparedStatement stmt, Object[] params) throws SQLException{
for (int i = 0; i < params.length; i++) {
stmt.setObject(i+1, params[i]);
@@ -239,27 +237,17 @@
}
public void assertResultsSetEquals(ResultSet resultSet, File expected) {
- assertNotNull(resultSet);
-
- BufferedReader resultReader = null;
- BufferedReader expectedReader = null;
+ assertNotNull(resultSet);
try {
- resultReader = new BufferedReader(new ResultSetReader(resultSet, DELIMITER));
writeResultSet(expected, new BufferedReader(new ResultSetReader(resultSet, DELIMITER)));
if (resultSet.getType() != ResultSet.TYPE_FORWARD_ONLY) {
resultSet.beforeFirst();
}
- expectedReader = new BufferedReader(new FileReader(expected));
- compareResults(resultReader, expectedReader);
- } catch (Exception e) {
+ assertReaderEquals(new ResultSetReader(resultSet, DELIMITER), new FileReader(expected));
+ } catch (IOException e) {
throw new RuntimeException(e);
- }finally {
- try {
- resultReader.close();
- expectedReader.close();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
}
}
@@ -283,23 +271,7 @@
public void assertResultsSetEquals(ResultSet resultSet,String expected) {
assertNotNull(resultSet);
-
- BufferedReader resultReader = null;
- BufferedReader expectedReader = null;
- try {
- resultReader = new BufferedReader(new ResultSetReader(resultSet, DELIMITER));
- expectedReader = new BufferedReader(new StringReader(expected));
- compareResults(resultReader, expectedReader);
- }catch(Exception e){
- throw new RuntimeException(e);
- }finally {
- try {
- resultReader.close();
- expectedReader.close();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
+ assertReaderEquals(new ResultSetReader(resultSet, DELIMITER), new StringReader(expected));
}
public void assertResults(String[] expected) {
@@ -312,32 +284,13 @@
public void assertResultsSetEquals(ResultSet resultSet, String[] expected) {
assertNotNull(resultSet);
-
- BufferedReader resultReader = null;
- BufferedReader expectedReader = null;
- try {
- resultReader = new BufferedReader(new ResultSetReader(resultSet, DELIMITER));
- expectedReader = new BufferedReader(new StringArrayReader(expected));
- compareResults(resultReader, expectedReader);
- }catch(Exception e){
- throw new RuntimeException(e);
- }finally {
- try {
- resultReader.close();
- expectedReader.close();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
+ assertReaderEquals(new ResultSetReader(resultSet, DELIMITER), new StringArrayReader(expected));
}
public void assertReaderEquals(Reader expected, Reader reader) {
-
- BufferedReader resultReader = null;
- BufferedReader expectedReader = null;
+ BufferedReader resultReader = new BufferedReader(expected);
+ BufferedReader expectedReader = new BufferedReader(reader);
try {
- expectedReader = new BufferedReader(expected);
- resultReader = new BufferedReader(reader);
compareResults(resultReader, expectedReader);
} catch (Exception e) {
throw new RuntimeException(e);
@@ -353,47 +306,19 @@
public void assertResultsSetMetadataEquals(ResultSetMetaData metadata, File expected) {
assertNotNull(metadata);
-
- BufferedReader resultReader = null;
- BufferedReader expectedReader = null;
try {
- resultReader = new BufferedReader(new MetadataReader(metadata, DELIMITER));
writeResultSet(expected, new BufferedReader(new MetadataReader(metadata, DELIMITER)));
- expectedReader = new BufferedReader(new FileReader(expected));
- compareResults(resultReader, expectedReader);
- } catch (Exception e) {
+ assertReaderEquals(new MetadataReader(metadata, DELIMITER), new FileReader(expected));
+ } catch (IOException e) {
throw new RuntimeException(e);
- }finally {
- try {
- resultReader.close();
- expectedReader.close();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
+ }
}
public void assertResultsSetMetadataEquals(ResultSetMetaData metadata, String[] expected) {
- assertNotNull(metadata);
-
- BufferedReader resultReader = null;
- BufferedReader expectedReader = null;
- try {
- resultReader = new BufferedReader(new MetadataReader(metadata, DELIMITER));
- expectedReader = new BufferedReader(new StringArrayReader(expected));
- compareResults(resultReader, expectedReader);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }finally {
- try {
- resultReader.close();
- expectedReader.close();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
+ assertNotNull(metadata);
+ assertReaderEquals(new MetadataReader(metadata, DELIMITER), new StringArrayReader(expected));
}
-
+
protected static String read(BufferedReader r, boolean casesensitive) throws IOException {
StringBuffer result = new StringBuffer();
String s = null;
Modified: trunk/connectors/connector-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCMetdataProcessor.java
===================================================================
--- trunk/connectors/connector-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCMetdataProcessor.java 2010-03-04 01:31:04 UTC (rev 1895)
+++ trunk/connectors/connector-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCMetdataProcessor.java 2010-03-04 01:32:54 UTC (rev 1896)
@@ -204,49 +204,34 @@
String remarks = tables.getString(5);
table.setAnnotation(remarks);
tableMap.put(fullName, new TableInfo(tableCatalog, tableSchema, tableName, table));
+
+ ResultSet columns = metadata.getColumns(tableCatalog, tableSchema, tableName, null);
+ int rsColumns = columns.getMetaData().getColumnCount();
+ while (columns.next()) {
+ String columnName = columns.getString(4);
+ int type = columns.getInt(5);
+ String typeName = columns.getString(6);
+ type = checkForUnsigned(type, typeName);
+ //note that the resultset is already ordered by position, so we can rely on just adding columns in order
+ Column column = metadataFactory.addColumn(columnName, TypeFacility.getDataTypeNameFromSQLType(type), table);
+ column.setNameInSource(quoteName(columnName));
+ column.setNativeType(columns.getString(6));
+ column.setRadix(columns.getInt(10));
+ column.setNullType(NullType.values()[columns.getShort(11)]);
+ column.setUpdatable(true);
+ column.setAnnotation(columns.getString(12));
+ column.setCharOctetLength(columns.getInt(16));
+ if (rsColumns >= 23) {
+ column.setAutoIncrementable("YES".equalsIgnoreCase(columns.getString(23))); //$NON-NLS-1$
+ }
+ }
+ columns.close();
}
tables.close();
- getColumns(metadataFactory, metadata, tableMap);
return tableMap;
}
- private void getColumns(MetadataFactory metadataFactory,
- DatabaseMetaData metadata, Map<String, TableInfo> tableMap)
- throws SQLException, ConnectorException {
- logger.logDetail("JDBCMetadataProcessor - Importing columns"); //$NON-NLS-1$
- ResultSet columns = metadata.getColumns(catalog, schemaPattern, tableNamePattern, null);
- int rsColumns = columns.getMetaData().getColumnCount();
- while (columns.next()) {
- String tableCatalog = columns.getString(1);
- String tableSchema = columns.getString(2);
- String tableName = columns.getString(3);
- String fullTableName = getFullyQualifiedName(tableCatalog, tableSchema, tableName);
- TableInfo tableInfo = tableMap.get(fullTableName);
- if (tableInfo == null) {
- continue;
- }
- String columnName = columns.getString(4);
- int type = columns.getInt(5);
- String typeName = columns.getString(6);
- type = checkForUnsigned(type, typeName);
- //note that the resultset is already ordered by position, so we can rely on just adding columns in order
- Column column = metadataFactory.addColumn(columnName, TypeFacility.getDataTypeNameFromSQLType(type), tableInfo.table);
- column.setNameInSource(quoteName(columnName));
- column.setNativeType(columns.getString(6));
- column.setRadix(columns.getInt(10));
- column.setNullType(NullType.values()[columns.getShort(11)]);
- column.setUpdatable(true);
- String remarks = columns.getString(12);
- column.setAnnotation(remarks);
- column.setCharOctetLength(columns.getInt(16));
- if (rsColumns >= 23) {
- column.setAutoIncrementable("YES".equalsIgnoreCase(columns.getString(23))); //$NON-NLS-1$
- }
- }
- columns.close();
- }
-
private String quoteName(String name) {
if (quoteNameInSource) {
return quoteString + StringUtil.replaceAll(name, quoteString, quoteString + quoteString) + quoteString;
14 years, 2 months
teiid SVN: r1895 - trunk/test-integration/common/src/test/java/com/metamatrix/connector/jdbc/extension.
by teiid-commits@lists.jboss.org
Author: shawkins
Date: 2010-03-03 20:31:04 -0500 (Wed, 03 Mar 2010)
New Revision: 1895
Modified:
trunk/test-integration/common/src/test/java/com/metamatrix/connector/jdbc/extension/TestSQLConversionVisitor.java
Log:
TEIID-989 adding an unrelated order by test
Modified: trunk/test-integration/common/src/test/java/com/metamatrix/connector/jdbc/extension/TestSQLConversionVisitor.java
===================================================================
--- trunk/test-integration/common/src/test/java/com/metamatrix/connector/jdbc/extension/TestSQLConversionVisitor.java 2010-03-03 23:08:18 UTC (rev 1894)
+++ trunk/test-integration/common/src/test/java/com/metamatrix/connector/jdbc/extension/TestSQLConversionVisitor.java 2010-03-04 01:31:04 UTC (rev 1895)
@@ -441,5 +441,14 @@
input,
output, TRANSLATOR);
}
+
+ @Test public void testOrderByUnrelated() throws Exception {
+ String input = "select part_id id FROM parts order by part_name"; //$NON-NLS-1$
+ String output = "SELECT rtrim(PARTS.PART_ID) AS id FROM PARTS ORDER BY PARTS.PART_NAME"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.PARTS_VDB,
+ input,
+ output, TRANSLATOR);
+ }
}
14 years, 2 months
teiid SVN: r1894 - in branches/JCA: client/src/main/java/org/teiid/adminapi and 26 other directories.
by teiid-commits@lists.jboss.org
Author: rareddy
Date: 2010-03-03 18:08:18 -0500 (Wed, 03 Mar 2010)
New Revision: 1894
Added:
branches/JCA/client/src/main/java/org/teiid/adminapi/impl/DataRoleMetadata.java
Removed:
branches/JCA/client/src/main/java/org/teiid/adminapi/Visibility.java
branches/JCA/common-internal/src/main/java/com/metamatrix/api/exception/
branches/JCA/common-internal/src/main/java/com/metamatrix/common/config/api/
branches/JCA/common-internal/src/main/java/com/metamatrix/common/extensionmodule/
branches/JCA/common-internal/src/main/java/com/metamatrix/common/util/crypto/
branches/JCA/common-internal/src/main/java/com/metamatrix/common/vdb/
branches/JCA/common-internal/src/main/java/com/metamatrix/common/xml/XMLReaderWriter.java
branches/JCA/common-internal/src/main/java/com/metamatrix/common/xml/XMLReaderWriterImpl.java
branches/JCA/common-internal/src/main/java/com/metamatrix/core/xml/
branches/JCA/common-internal/src/main/java/com/metamatrix/platform/admin/api/
branches/JCA/common-internal/src/main/java/com/metamatrix/server/admin/api/
branches/JCA/common-internal/src/main/java/com/metamatrix/server/admin/apiimpl/
branches/JCA/common-internal/src/main/java/com/metamatrix/vdb/materialization/template/
branches/JCA/jboss-integration/src/main/java/com/metamatrix/dqp/
branches/JCA/runtime/src/main/java/org/teiid/deployers/ManifestMetaData.java
branches/JCA/runtime/src/main/java/org/teiid/deployers/ManifestParser.java
Modified:
branches/JCA/build/kit-jboss-container/deployers/teiid.deployer/teiid-deployer-jboss-beans.xml
branches/JCA/client/src/main/java/org/teiid/adminapi/Model.java
branches/JCA/client/src/main/java/org/teiid/adminapi/impl/AdminObjectImpl.java
branches/JCA/client/src/main/java/org/teiid/adminapi/impl/ModelMetaData.java
branches/JCA/client/src/main/java/org/teiid/adminapi/impl/ModelMetadataMapper.java
branches/JCA/client/src/main/java/org/teiid/adminapi/impl/PropertyMetadata.java
branches/JCA/client/src/main/java/org/teiid/adminapi/impl/ReferenceMappingMetadata.java
branches/JCA/client/src/main/java/org/teiid/adminapi/impl/VDBMetaData.java
branches/JCA/client/src/main/resources/vdb-deployer.xsd
branches/JCA/client/src/test/java/org/teiid/adminapi/impl/TestVDBMetaData.java
branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/CachedFinder.java
branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/DataTierManagerImpl.java
branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/multisource/MultiSourcePlanToProcessConverter.java
branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/validator/AuthorizationValidationVisitor.java
branches/JCA/engine/src/main/java/org/teiid/metadata/TransformationMetadata.java
branches/JCA/engine/src/test/java/com/metamatrix/query/unittest/FakeMetadataFactory.java
branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/TestConnectorCapabilitiesFinder.java
branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java
branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourcePlanToProcessConverter.java
branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/validator/TestAuthorizationValidationVisitor.java
branches/JCA/engine/src/test/java/org/teiid/metadata/TestTransformationMetadata.java
branches/JCA/jboss-integration/src/main/java/org/teiid/adminapi/jboss/Admin.java
branches/JCA/jboss-integration/src/main/java/org/teiid/adminapi/jboss/ManagedUtil.java
branches/JCA/jboss-integration/src/test/java/org/teiid/adminapi/jboss/TestConnectorBindings.java
branches/JCA/metadata/src/main/java/org/teiid/metadata/index/IndexMetadataFactory.java
branches/JCA/runtime/src/main/java/org/teiid/deployers/DynamicVDBDeployer.java
branches/JCA/runtime/src/main/java/org/teiid/deployers/SystemVDBDeployer.java
branches/JCA/runtime/src/main/java/org/teiid/deployers/VDBDeployer.java
branches/JCA/runtime/src/main/java/org/teiid/deployers/VDBParserDeployer.java
branches/JCA/runtime/src/main/java/org/teiid/deployers/VDBStructure.java
Log:
TEIID-998: Adding changes resulting from creating the deployment from the XSD file.
Modified: branches/JCA/build/kit-jboss-container/deployers/teiid.deployer/teiid-deployer-jboss-beans.xml
===================================================================
--- branches/JCA/build/kit-jboss-container/deployers/teiid.deployer/teiid-deployer-jboss-beans.xml 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/build/kit-jboss-container/deployers/teiid.deployer/teiid-deployer-jboss-beans.xml 2010-03-03 23:08:18 UTC (rev 1894)
@@ -41,6 +41,7 @@
<property name="managedObjectFactory"><inject bean="ManagedObjectFactory"/></property>
<property name="VDBRepository"><inject bean="VDBRepository"/></property>
<property name="contextCache"><inject bean="ContextCache"/></property>
+ <property name="objectSerializer"><inject bean="ObjectSerializer"/></property>
<depends>SystemVDBDeployer</depends>
</bean>
Modified: branches/JCA/client/src/main/java/org/teiid/adminapi/Model.java
===================================================================
--- branches/JCA/client/src/main/java/org/teiid/adminapi/Model.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/client/src/main/java/org/teiid/adminapi/Model.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -22,14 +22,18 @@
package org.teiid.adminapi;
+import java.util.List;
+
/**
* Represents a metadata model in the Teiid system.
*
* @since 4.3
*/
public interface Model extends AdminObject {
-
+
+ enum Type {PHYSICAL, VIRTUAL, FUNCTION};
+
/**
* Determine if this model is a Source model.
*
@@ -49,15 +53,8 @@
* Retrieve the model type.
* @return model type
*/
- String getModelType();
+ Type getModelType();
- /**
- * Retrieve the model URI.
- *
- * @return model URI
- */
- String getModelURI();
-
/**
* Determine whether this model can support more than one connector binding.
*
@@ -66,20 +63,8 @@
boolean isSupportsMultiSourceBindings();
/**
- * Path of the model inside the VDB (optional)
+ * Associated Source Names for the Models (Connector Bindings)
* @return String
*/
- String getPath();
-
- /**
- * UUID of the Model (optional)
- * @return String
- */
- String getUuid();
-
- /**
- * Associated connector binding's reference name
- * @return String
- */
- String getConnectorReference();
+ List<String> getSourceNames();
}
\ No newline at end of file
Deleted: branches/JCA/client/src/main/java/org/teiid/adminapi/Visibility.java
===================================================================
--- branches/JCA/client/src/main/java/org/teiid/adminapi/Visibility.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/client/src/main/java/org/teiid/adminapi/Visibility.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -1,28 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.adminapi;
-
-import java.io.Serializable;
-
-public enum Visibility implements Serializable{
- PUBLIC,PRIVATE;
-}
\ No newline at end of file
Modified: branches/JCA/client/src/main/java/org/teiid/adminapi/impl/AdminObjectImpl.java
===================================================================
--- branches/JCA/client/src/main/java/org/teiid/adminapi/impl/AdminObjectImpl.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/client/src/main/java/org/teiid/adminapi/impl/AdminObjectImpl.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -74,7 +74,7 @@
}
}
- protected List<PropertyMetadata> getPropertiesDirect(){
+ protected List<PropertyMetadata> getJAXBProperties(){
return properties;
}
Added: branches/JCA/client/src/main/java/org/teiid/adminapi/impl/DataRoleMetadata.java
===================================================================
--- branches/JCA/client/src/main/java/org/teiid/adminapi/impl/DataRoleMetadata.java (rev 0)
+++ branches/JCA/client/src/main/java/org/teiid/adminapi/impl/DataRoleMetadata.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -0,0 +1,137 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.adminapi.impl;
+
+import java.io.Serializable;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlType;
+
+import org.jboss.managed.api.annotation.ManagementObject;
+
+
+/**
+ * <pre>
+ * <complexType>
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="resource-name" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="allow-create" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="allow-read" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="allow-update" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="allow-delete" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * </sequence>
+ * <attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ */
+(a)XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "", propOrder = {
+ "description",
+ "resourceName",
+ "allowCreate",
+ "allowRead",
+ "allowUpdate",
+ "allowDelete",
+})
+@ManagementObject
+public class DataRoleMetadata implements Serializable {
+
+ @XmlAttribute(name = "name", required = true)
+ protected String name;
+ @XmlElement(name = "description")
+ protected String description;
+ @XmlElement(name = "resource-name", required = true)
+ protected String resourceName;
+ @XmlElement(name = "allow-create")
+ protected Boolean allowCreate;
+ @XmlElement(name = "allow-read")
+ protected Boolean allowRead;
+ @XmlElement(name = "allow-update")
+ protected Boolean allowUpdate;
+ @XmlElement(name = "allow-delete")
+ protected Boolean allowDelete;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String value) {
+ this.name = value;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String value) {
+ this.description = value;
+ }
+
+ public String getResourceName() {
+ return resourceName;
+ }
+
+ public void setResourceName(String value) {
+ this.resourceName = value;
+ }
+
+ public Boolean isAllowCreate() {
+ return allowCreate;
+ }
+
+ public void setAllowCreate(Boolean value) {
+ this.allowCreate = value;
+ }
+
+ public Boolean isAllowRead() {
+ return allowRead;
+ }
+
+ public void setAllowRead(Boolean value) {
+ this.allowRead = value;
+ }
+
+ public Boolean isAllowUpdate() {
+ return allowUpdate;
+ }
+
+ public void setAllowUpdate(Boolean value) {
+ this.allowUpdate = value;
+ }
+
+ public Boolean isAllowDelete() {
+ return allowDelete;
+ }
+
+ public void setAllowDelete(Boolean value) {
+ this.allowDelete = value;
+ }
+}
Property changes on: branches/JCA/client/src/main/java/org/teiid/adminapi/impl/DataRoleMetadata.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: branches/JCA/client/src/main/java/org/teiid/adminapi/impl/ModelMetaData.java
===================================================================
--- branches/JCA/client/src/main/java/org/teiid/adminapi/impl/ModelMetaData.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/client/src/main/java/org/teiid/adminapi/impl/ModelMetaData.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -22,6 +22,8 @@
package org.teiid.adminapi.impl;
+import java.io.Serializable;
+import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
@@ -30,47 +32,45 @@
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
+import javax.xml.bind.annotation.XmlValue;
-import org.jboss.managed.api.annotation.ManagementComponent;
import org.jboss.managed.api.annotation.ManagementObject;
import org.jboss.managed.api.annotation.ManagementObjectID;
+import org.jboss.managed.api.annotation.ManagementProperties;
import org.jboss.managed.api.annotation.ManagementProperty;
import org.teiid.adminapi.Model;
-import org.teiid.adminapi.Visibility;
import com.metamatrix.core.vdb.ModelType;
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = "", propOrder = {
- "propertiesDirect",
- "connectorReference"
+ "JAXBProperties",
+ "JAXBSources",
+ "errors"
})
-@ManagementObject(componentType=@ManagementComponent(type="teiid",subtype="model"))
+(a)ManagementObject(properties=ManagementProperties.EXPLICIT)
public class ModelMetaData extends AdminObjectImpl implements Model {
private static final String SUPPORTS_MULTI_SOURCE_BINDINGS_KEY = "supports-multi-source-bindings"; //$NON-NLS-1$
-
private static final long serialVersionUID = 3714234763056162230L;
+
+ private ListOverMap<SourceMapping> sources = new ListOverMap(new KeyBuilder<SourceMapping>() {
+ @Override
+ public String getKey(SourceMapping entry) {
+ return entry.getName();
+ }
+ });
- @XmlElement(name = "connector-ref")
- private String connectorReference;
-
- @XmlAttribute(name = "type", required = true)
- private String modelType; //$NON-NLS-1$
+ @XmlAttribute(name = "type")
+ protected String modelType = Type.PHYSICAL.name(); //$NON-NLS-1$
- @XmlAttribute(name = "uri")
- private String modelURI; //$NON-NLS-1$
-
- @XmlAttribute(name = "path")
- private String path;
-
- @XmlAttribute(name = "uuid")
- private String uuid;
-
@XmlAttribute(name = "visible")
private Boolean visible = true;
+ @XmlElement(name = "validation-error")
+ protected List<ValidationError> errors;
+
@ManagementProperty(description="Model Name", readOnly=true)
@ManagementObjectID(type="model")
@XmlAttribute(name = "name", required = true)
@@ -100,17 +100,11 @@
@Override
@ManagementProperty(description = "Model Type", readOnly=true)
- public String getModelType() {
- return modelType;
+ public Type getModelType() {
+ return Type.valueOf(modelType);
}
@Override
- @ManagementProperty(description = "Model URI", readOnly=true)
- public String getModelURI() {
- return modelURI;
- }
-
- @Override
@ManagementProperty(description = "Does Model supports multi-source bindings", readOnly=true)
public boolean isSupportsMultiSourceBindings() {
String supports = getPropertyValue(SUPPORTS_MULTI_SOURCE_BINDINGS_KEY);
@@ -118,18 +112,6 @@
}
@Override
- @ManagementProperty(description = "Model path", readOnly=true)
- public String getPath() {
- return this.path;
- }
-
- @Override
- @ManagementProperty(description = "Model UUID", readOnly=true)
- public String getUuid() {
- return this.uuid;
- }
-
- @Override
@ManagementProperty(description = "Properties", readOnly=true)
public Properties getProperties() {
return new Properties(super.getProperties());
@@ -137,8 +119,8 @@
@Override
@XmlElement(name = "property", type = PropertyMetadata.class)
- protected List<PropertyMetadata> getPropertiesDirect(){
- return super.getPropertiesDirect();
+ protected List<PropertyMetadata> getJAXBProperties(){
+ return super.getJAXBProperties();
}
public void setSupportsMultiSourceBindings(boolean supports) {
@@ -148,45 +130,138 @@
public void setModelType(String modelType) {
this.modelType = modelType;
}
-
- public void setModelURI(String modelURI) {
- this.modelURI = modelURI;
- }
- public void setPath(String path) {
- this.path = path;
- }
-
- public void setUuid(String uuid) {
- this.uuid = uuid;
- }
-
public String toString() {
- if (this.connectorReference != null)
- return getName() + "["+this.connectorReference+"]";
-
- return getName();
+ return getName() + this.sources;
}
- public Visibility getVisibility(){
- return this.visible?Visibility.PUBLIC:Visibility.PRIVATE;
- }
-
- public void setVisibility(Visibility visibility){
- this.visible = (visibility == Visibility.PUBLIC);
- }
-
public void setVisible(Boolean value) {
this.visible = value;
}
+
+ @ManagementProperty(description = "Source Mappings (defined by user)")
+ public List<SourceMapping> getSourceMappings(){
+ return new ArrayList<SourceMapping>(this.sources.getMap().values());
+ }
+ @XmlElement(name = "source")
+ protected List<SourceMapping> getJAXBSources(){
+ // do not wrap this in another List object; we need direct access for jaxb
+ return this.sources;
+ }
+
@Override
- @ManagementProperty(description = "Connector Binding Reference Name", readOnly=true)
- public String getConnectorReference() {
- return connectorReference;
+ public List<String> getSourceNames() {
+ return new ArrayList<String>(this.sources.getMap().keySet());
}
+
+ public String getSourceJndiName(String sourceName) {
+ SourceMapping s = this.sources.getMap().get(sourceName);
+ return s.getJndiName();
+ }
+
+ public void addSourceMapping(String name, String jndiName) {
+ this.sources.getMap().put(name, new SourceMapping(name, jndiName));
+ }
+
+ @ManagementProperty(description = "Model Validity Errors", readOnly=true)
+ public List<ValidationError> getErrors(){
+ return this.errors;
+ }
+
+ public void addError(String severity, String message) {
+ if (this.errors == null) {
+ this.errors = new ArrayList<ValidationError>();
+ }
+ this.errors.add(new ValidationError(severity, message));
+ }
+
+ @XmlAccessorType(XmlAccessType.NONE)
+ @XmlType(name = "", propOrder = {
+ "value"
+ })
+ @ManagementObject(properties=ManagementProperties.EXPLICIT)
+ public static class ValidationError implements Serializable{
+ private static final long serialVersionUID = 2044197069467559527L;
- public void setConnectorReference(String refName) {
- this.connectorReference = refName;
- }
+ public enum Severity {ERROR, WARNING};
+
+ @XmlValue
+ protected String value;
+
+ @XmlAttribute(name = "severity")
+ protected String severity;
+
+ public ValidationError() {};
+
+ public ValidationError(String severity, String msg) {
+ this.severity = severity;
+ this.value = msg;
+ }
+
+ @ManagementProperty (description="Error Message", readOnly = true)
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+ @ManagementProperty (description="Severity", readOnly = true)
+ public String getSeverity() {
+ return severity;
+ }
+
+ public void setSeverity(String severity) {
+ this.severity = severity;
+ }
+ }
+
+ @XmlAccessorType(XmlAccessType.NONE)
+ @XmlType(name = "")
+ @ManagementObject(properties=ManagementProperties.EXPLICIT)
+ public static class SourceMapping implements Serializable {
+ private static final long serialVersionUID = -4417878417697685794L;
+
+ @XmlAttribute(name = "name", required = true)
+ private String name;
+
+ @XmlAttribute(name = "jndi-name")
+ private String jndiName;
+
+
+ public SourceMapping() {}
+
+ public SourceMapping(String name, String jndiName) {
+ this.name = name;
+ this.jndiName = jndiName;
+ }
+
+ @ManagementProperty (description="Source Name", readOnly = true)
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @ManagementProperty (description="JNDI Name of the resource to assosiate with Source name")
+ public String getJndiName() {
+ // this default could be controlled if needed.
+ if (this.jndiName == null) {
+ return "java:"+name;
+ }
+ return jndiName;
+ }
+
+ public void setJndiName(String jndiName) {
+ this.jndiName = jndiName;
+ }
+
+ public String toString() {
+ return getName()+":"+getJndiName();
+ }
+ }
}
Modified: branches/JCA/client/src/main/java/org/teiid/adminapi/impl/ModelMetadataMapper.java
===================================================================
--- branches/JCA/client/src/main/java/org/teiid/adminapi/impl/ModelMetadataMapper.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/client/src/main/java/org/teiid/adminapi/impl/ModelMetadataMapper.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -25,11 +25,12 @@
import java.util.Properties;
import org.jboss.metatype.api.types.CompositeMetaType;
+import org.jboss.metatype.api.types.MapCompositeMetaType;
import org.jboss.metatype.api.types.MetaType;
-import org.jboss.metatype.api.types.PropertiesMetaType;
import org.jboss.metatype.api.types.SimpleMetaType;
import org.jboss.metatype.api.values.CompositeValue;
import org.jboss.metatype.api.values.CompositeValueSupport;
+import org.jboss.metatype.api.values.MapCompositeValueSupport;
import org.jboss.metatype.api.values.MetaValue;
import org.jboss.metatype.api.values.MetaValueFactory;
import org.jboss.metatype.api.values.PropertiesMetaValue;
@@ -43,14 +44,13 @@
static {
metaType = new MutableCompositeMetaType(ModelMetaData.class.getName(), "The Model meta data");
- metaType.addItem("connectorReference", "connectorReference", SimpleMetaType.STRING);
- metaType.addItem("modelType", "modelType", SimpleMetaType.STRING);
- metaType.addItem("modelURI", "modelURI", SimpleMetaType.STRING);
- metaType.addItem("path", "path", SimpleMetaType.STRING);
- metaType.addItem("uuid", "uuid", SimpleMetaType.STRING);
- metaType.addItem("visible", "visible", SimpleMetaType.BOOLEAN_PRIMITIVE);
metaType.addItem("name", "name", SimpleMetaType.STRING);
- metaType.addItem("properties", "properties", PropertiesMetaType.INSTANCE);
+ metaType.addItem("visible", "visible", SimpleMetaType.BOOLEAN_PRIMITIVE);
+ metaType.addItem("modelType", "modelType", SimpleMetaType.STRING);
+
+
+
+ //metaType.addItem("properties", "properties", new MapCompositeMetaType());
metaType.freeze();
}
@@ -72,11 +72,7 @@
CompositeMetaType composite = (CompositeMetaType) metaType;
CompositeValueSupport request = new CompositeValueSupport(composite);
- request.set("connectorReference", SimpleValueSupport.wrap(object.getConnectorReference()));
- request.set("modelType", SimpleValueSupport.wrap(object.getModelType()));
- request.set("modelURI", SimpleValueSupport.wrap(object.getModelURI()));
- request.set("path", SimpleValueSupport.wrap(object.getPath()));
- request.set("uuid", SimpleValueSupport.wrap(object.getUuid()));
+ request.set("modelType", SimpleValueSupport.wrap(object.getModelType().name()));
request.set("visible", SimpleValueSupport.wrap(object.isVisible()));
request.set("name",SimpleValueSupport.wrap(object.getName()));
request.set("properties", new PropertiesMetaValue(object.getProperties()));
@@ -95,11 +91,14 @@
CompositeValue compositeValue = (CompositeValue) metaValue;
ModelMetaData model = new ModelMetaData();
- model.setConnectorReference((String) metaValueFactory.unwrap(compositeValue.get("connectorReference")));
- model.setModelType((String) metaValueFactory.unwrap(compositeValue.get("modelType")));
- model.setModelURI((String) metaValueFactory.unwrap(compositeValue.get("modelURI")));
- model.setPath((String) metaValueFactory.unwrap(compositeValue.get("path")));
- model.setUuid((String) metaValueFactory.unwrap(compositeValue.get("sourceRequest")));
+ String type = (String) metaValueFactory.unwrap(compositeValue.get("modelType"));
+ if (type != null) {
+ model.setModelType(type);
+ }
+ else {
+ model.setModelType("PHYSICAL");
+ }
+
model.setVisible((Boolean) metaValueFactory.unwrap(compositeValue.get("visible")));
model.setName((String) metaValueFactory.unwrap(compositeValue.get("name")));
model.setProperties((Properties) metaValueFactory.unwrap(compositeValue.get("properties")));
Modified: branches/JCA/client/src/main/java/org/teiid/adminapi/impl/PropertyMetadata.java
===================================================================
--- branches/JCA/client/src/main/java/org/teiid/adminapi/impl/PropertyMetadata.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/client/src/main/java/org/teiid/adminapi/impl/PropertyMetadata.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -46,8 +46,9 @@
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = "property")
public class PropertyMetadata implements Serializable{
-
- @XmlAttribute(name = "name", required = true)
+ private static final long serialVersionUID = -5040224539939758816L;
+
+ @XmlAttribute(name = "name", required = true)
protected String name;
@XmlAttribute(name = "value", required = true)
protected String value;
@@ -75,4 +76,8 @@
public void setValue(String value) {
this.value = value;
}
+
+ public String toString() {
+ return this.name+"="+this.value;
+ }
}
\ No newline at end of file
Modified: branches/JCA/client/src/main/java/org/teiid/adminapi/impl/ReferenceMappingMetadata.java
===================================================================
--- branches/JCA/client/src/main/java/org/teiid/adminapi/impl/ReferenceMappingMetadata.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/client/src/main/java/org/teiid/adminapi/impl/ReferenceMappingMetadata.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -85,6 +85,7 @@
this.refName = value;
}
+ @ManagementProperty(description="Resource Names")
public List<String> getResourceNames() {
if (this.resourceNames == null) {
this.resourceNames = new ArrayList<String>();
@@ -92,7 +93,6 @@
return this.resourceNames;
}
- @ManagementProperty(description="Resource Names")
public void setResourceNames(List<String> names) {
this.resourceNames = new ArrayList<String>(names);
}
Modified: branches/JCA/client/src/main/java/org/teiid/adminapi/impl/VDBMetaData.java
===================================================================
--- branches/JCA/client/src/main/java/org/teiid/adminapi/impl/VDBMetaData.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/client/src/main/java/org/teiid/adminapi/impl/VDBMetaData.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -21,9 +21,7 @@
*/
package org.teiid.adminapi.impl;
-import java.io.Serializable;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
@@ -35,27 +33,25 @@
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
-import javax.xml.bind.annotation.XmlValue;
import org.jboss.managed.api.annotation.ManagementComponent;
import org.jboss.managed.api.annotation.ManagementObject;
import org.jboss.managed.api.annotation.ManagementObjectID;
import org.jboss.managed.api.annotation.ManagementOperation;
import org.jboss.managed.api.annotation.ManagementProperty;
+import org.teiid.adminapi.Model;
import org.teiid.adminapi.VDB;
+import org.teiid.adminapi.impl.ModelMetaData.ValidationError;
import com.metamatrix.core.CoreConstants;
-import com.metamatrix.core.vdb.ModelType;
@ManagementObject(componentType=@ManagementComponent(type="teiid",subtype="vdb"))
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = "", propOrder = {
"description",
- "propertiesDirect",
- "modelsDirect",
- "connectorMappings",
+ "JAXBProperties",
+ "JAXBModels",
"securityRoleMappings",
- "problemMarkers"
})
@XmlRootElement(name = "vdb")
public class VDBMetaData extends AdminObjectImpl implements VDB {
@@ -69,27 +65,21 @@
return entry.getName();
}
});
-
+
@XmlAttribute(name = "version", required = true)
private int version = 1;
@XmlElement(name = "description")
private String description;
- @XmlElement(name = "connector-mapping")
- protected ListOverMap<ReferenceMappingMetadata> connectorMappings = new ListOverMap<ReferenceMappingMetadata>(new KeyBuilder<ReferenceMappingMetadata>() {
+ @XmlElement(name = "role-mapping")
+ protected ListOverMap<ReferenceMappingMetadata> securityRoleMappings = new ListOverMap<ReferenceMappingMetadata>(new KeyBuilder<ReferenceMappingMetadata>() {
@Override
public String getKey(ReferenceMappingMetadata entry) {
return entry.getRefName();
}
- });
+ });
- @XmlElement(name = "security-role-mapping")
- protected List<ReferenceMappingMetadata> securityRoleMappings;
-
- @XmlElement(name = "problem-marker")
- protected List<ProblemMarker> problemMarkers;
-
private String fileUrl = null;
public VDBMetaData() {
@@ -97,13 +87,10 @@
ModelMetaData system = new ModelMetaData();
system.setName(CoreConstants.SYSTEM_MODEL);
system.setVisible(true);
- system.setModelType(ModelType.getString(ModelType.PHYSICAL));
- system.setConnectorReference("system");
+ system.setModelType(Model.Type.PHYSICAL.name());
+ system.addSourceMapping("system", "system");
system.setSupportsMultiSourceBindings(false);
- system.setPath("builtin");
-
- addConnectorMapping(new ReferenceMappingMetadata("system", "system"));
-
+
addModel(system);
}
@@ -153,7 +140,7 @@
this.fileUrl = url;
}
- @ManagementProperty(description="Model list in a VDB", managed=true)
+ @ManagementProperty(description="Models in a VDB", managed=true)
public List<ModelMetaData> getModels(){
return new ArrayList<ModelMetaData>(this.models.getMap().values());
}
@@ -164,7 +151,7 @@
* @return
*/
@XmlElement(name = "model", required = true, type = ModelMetaData.class)
- protected List<ModelMetaData> getModelsDirect(){
+ protected List<ModelMetaData> getJAXBModels(){
return models;
}
@@ -185,16 +172,18 @@
@Override
@ManagementProperty(description = "VDB validity errors", readOnly=true)
public List<String> getValidityErrors(){
- if (this.problemMarkers != null && !this.problemMarkers.isEmpty()) {
- List<String> errors = new ArrayList<String>();
- for (ProblemMarker m:this.problemMarkers) {
- if (m.getSeverity().equalsIgnoreCase("ERROR")) {
- errors.add(m.getValue());
+ List<String> allErrors = new ArrayList<String>();
+ for (ModelMetaData model:this.models.getMap().values()) {
+ List<ValidationError> errors = model.getErrors();
+ if (errors != null && !errors.isEmpty()) {
+ for (ValidationError m:errors) {
+ if (ValidationError.Severity.valueOf(m.getSeverity()).equals(ValidationError.Severity.ERROR)) {
+ allErrors.add(m.getValue());
+ }
}
}
- return errors;
}
- return Collections.emptyList();
+ return allErrors;
}
@Override
@@ -209,12 +198,7 @@
}
for(ModelMetaData m: this.models.getMap().values()) {
if (m.isSource()) {
- String connectorReference = m.getConnectorReference();
- if (connectorReference == null) {
- return false;
- }
-
- List<String> resourceNames = getConnectorBindingNames(connectorReference);
+ List<String> resourceNames = m.getSourceNames();
if (resourceNames.isEmpty()) {
return false;
}
@@ -224,7 +208,7 @@
}
public String toString() {
- return getName()+"."+getVersion()+ models; //$NON-NLS-1$
+ return getName()+"."+getVersion()+ models.getMap().values(); //$NON-NLS-1$
}
@ManagementOperation(description = "Get the model with given name")
@@ -242,33 +226,13 @@
return list;
}
- @ManagementProperty(description="Connector reference mappings")
- public List<ReferenceMappingMetadata> getConnectorMappings() {
- return connectorMappings;
- }
-
- public List<String> getConnectorBindingNames(String referenceName) {
- ReferenceMappingMetadata rmm = this.connectorMappings.getMap().get(referenceName);
- if (rmm != null) {
- return rmm.getResourceNames();
- }
- return Collections.emptyList();
- }
-
- public void addConnectorMapping(ReferenceMappingMetadata data) {
- this.connectorMappings.getMap().put(data.getRefName(), data);
- }
-
- @ManagementProperty(description="Security refrence mappings")
+ @ManagementProperty(description="Security refrence mappings", managed=true)
public List<ReferenceMappingMetadata> getSecurityRoleMappings() {
- return securityRoleMappings;
+ return new ArrayList<ReferenceMappingMetadata>(this.securityRoleMappings);
}
public void addSecurityRoleMapping(ReferenceMappingMetadata data) {
- if (this.securityRoleMappings == null) {
- this.securityRoleMappings = new ArrayList<ReferenceMappingMetadata>();
- }
- this.securityRoleMappings.add(data);
+ this.securityRoleMappings.getMap().put(data.getRefName(), data);
}
// this one manages the Management API
@@ -281,51 +245,7 @@
// This one manages the JAXB binding
@Override
@XmlElement(name = "property", type = PropertyMetadata.class)
- protected List<PropertyMetadata> getPropertiesDirect(){
- return super.getPropertiesDirect();
+ protected List<PropertyMetadata> getJAXBProperties(){
+ return super.getJAXBProperties();
}
-
- public void addProblemMarker(String severity, String message) {
- if (this.problemMarkers == null) {
- this.problemMarkers = new ArrayList<ProblemMarker>();
- }
- this.problemMarkers.add(new ProblemMarker(severity, message));
- }
-
- @XmlAccessorType(XmlAccessType.NONE)
- @XmlType(name = "", propOrder = {
- "value"
- })
- public static class ProblemMarker implements Serializable{
-
- private static final long serialVersionUID = -2939032879707369197L;
-
- @XmlValue
- protected String value;
- @XmlAttribute(name = "severity")
- protected String severity;
-
- public ProblemMarker() {};
-
- public ProblemMarker(String severity, String msg) {
- this.severity = severity;
- this.value = msg;
- }
-
- public String getValue() {
- return value;
- }
-
- public void setValue(String value) {
- this.value = value;
- }
-
- public String getSeverity() {
- return severity;
- }
-
- public void setSeverity(String value) {
- this.severity = value;
- }
- }
}
Modified: branches/JCA/client/src/main/resources/vdb-deployer.xsd
===================================================================
--- branches/JCA/client/src/main/resources/vdb-deployer.xsd 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/client/src/main/resources/vdb-deployer.xsd 2010-03-03 23:08:18 UTC (rev 1894)
@@ -12,27 +12,65 @@
<xs:complexType>
<xs:sequence>
<xs:element name="property" type="property" minOccurs="0" maxOccurs="unbounded"/>
- <xs:element name="connector-ref" type="xs:string" minOccurs="0"/>
+ <xs:element name="source" minOccurs="0" maxOccurs="unbounded">
+ <xs:complexType>
+ <xs:attribute name="name" type="xs:string" use="required"/>
+ <xs:attribute name="jndi-name" type="xs:string"/>
+ </xs:complexType>
+ </xs:element>
+ <xs:element name="validation-error" minOccurs="0" maxOccurs="unbounded">
+ <xs:complexType>
+ <xs:simpleContent>
+ <xs:extension base="xs:string">
+ <xs:attribute name="severity">
+ <xs:simpleType>
+ <xs:restriction base="xs:string">
+ <xs:enumeration value="ERROR"/>
+ <xs:enumeration value="WARNING"/>
+ </xs:restriction>
+ </xs:simpleType>
+ </xs:attribute>
+ </xs:extension>
+ </xs:simpleContent>
+ </xs:complexType>
+ </xs:element>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required"/>
- <xs:attribute name="type" type="xs:string" use="required"/>
- <xs:attribute name="uri" type="xs:string"/>
- <xs:attribute name="path" type="xs:string"/>
- <xs:attribute name="visibility" type="xs:string"/>
- <xs:attribute name="uuid" type="xs:string"/>
+ <xs:attribute name="type" default="PHYSICAL">
+ <xs:simpleType>
+ <xs:restriction base="xs:string">
+ <xs:enumeration value="PHYSICAL"/>
+ <xs:enumeration value="VIRTUAL"/>
+ <xs:enumeration value="FUNCTION"/>
+ </xs:restriction>
+ </xs:simpleType>
+ </xs:attribute>
+ <xs:attribute name="visible" type="xs:boolean" default="true"/>
</xs:complexType>
</xs:element>
- <xs:element name="connector-mapping" type="reference-mapping" minOccurs="0" maxOccurs="unbounded"/>
- <xs:element name="security-role-mapping" type="reference-mapping" minOccurs="0" maxOccurs="unbounded"/>
- <xs:element name="problem-marker" minOccurs="0" maxOccurs="unbounded">
+ <xs:element name="role" minOccurs="0" maxOccurs="unbounded">
+ <xs:complexType>
+ <xs:sequence>
+ <xs:element name="description" type="xs:string" minOccurs="0"/>
+ <xs:element name="resource-name" type="xs:string"/>
+ <xs:element name="allow-create" type="xs:boolean" minOccurs="0"/>
+ <xs:element name="allow-read" type="xs:boolean" minOccurs="0"/>
+ <xs:element name="allow-update" type="xs:boolean" minOccurs="0"/>
+ <xs:element name="allow-delete" type="xs:boolean" minOccurs="0"/>
+ </xs:sequence>
+ <xs:attribute name="name" type="xs:string" use="required"/>
+ </xs:complexType>
+ </xs:element>
+ <xs:element name="entry" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
- <xs:simpleContent>
- <xs:extension base="xs:string">
- <xs:attribute name="severity" type="xs:string"/>
- </xs:extension>
- </xs:simpleContent>
+ <xs:sequence>
+ <xs:element name="description" type="xs:string" minOccurs="0"/>
+ <xs:element name="property" type="property" minOccurs="0" maxOccurs="unbounded"/>
+ </xs:sequence>
+ <xs:attribute name="path" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
+ <xs:element name="role-mapping" type="reference-mapping" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required"/>
<xs:attribute name="version" type="xs:int" use="required"/>
Modified: branches/JCA/client/src/test/java/org/teiid/adminapi/impl/TestVDBMetaData.java
===================================================================
--- branches/JCA/client/src/test/java/org/teiid/adminapi/impl/TestVDBMetaData.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/client/src/test/java/org/teiid/adminapi/impl/TestVDBMetaData.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -21,20 +21,21 @@
*/
package org.teiid.adminapi.impl;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.*;
import java.io.StringReader;
import java.io.StringWriter;
+import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
+import javax.xml.validation.Schema;
+import javax.xml.validation.SchemaFactory;
import org.junit.Test;
+import org.teiid.adminapi.Model;
+import org.teiid.adminapi.impl.ModelMetaData.ValidationError;
public class TestVDBMetaData {
@@ -50,40 +51,39 @@
ModelMetaData modelOne = new ModelMetaData();
modelOne.setName("model-one");
- modelOne.setConnectorReference("java:mybinding");
- modelOne.setModelType("physical");
+ modelOne.addSourceMapping("s1", "java:mybinding");
+ modelOne.setModelType("PHYSICAL");
modelOne.addProperty("model-prop", "model-value");
modelOne.addProperty("model-prop", "model-value-override");
modelOne.setVisible(false);
+ modelOne.addError("ERROR", "There is an error in VDB");
vdb.addModel(modelOne);
ModelMetaData modelTwo = new ModelMetaData();
modelTwo.setName("model-two");
- modelTwo.setConnectorReference("binding-two-ref");
- modelTwo.setModelType("virtual");
+ modelTwo.addSourceMapping("s1", "java:binding-one");
+ modelTwo.addSourceMapping("s2", "java:binding-two");
+ modelTwo.setModelType("VIRTUAL");
modelTwo.addProperty("model-prop", "model-value");
vdb.addModel(modelTwo);
- ReferenceMappingMetadata ref = new ReferenceMappingMetadata();
- ref.setRefName("binding-two-ref");
- ref.addResourceName("java:binding-one");
- ref.addResourceName("java:binding-two");
- vdb.addConnectorMapping(ref);
-
- vdb.addProblemMarker("ERROR", "There is an error in VDB");
-
+
+ SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+ Schema schema = schemaFactory.newSchema(VDBMetaData.class.getResource("/vdb-deployer.xsd"));
JAXBContext jc = JAXBContext.newInstance(new Class<?>[] {VDBMetaData.class});
Marshaller marshell = jc.createMarshaller();
+ marshell.setSchema(schema);
marshell.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,new Boolean(true));
StringWriter sw = new StringWriter();
marshell.marshal(vdb, sw);
- Unmarshaller un = jc.createUnmarshaller();
-
+
System.out.println(sw.toString());
-
+
+ // UnMarshell
+ Unmarshaller un = jc.createUnmarshaller();
vdb = (VDBMetaData)un.unmarshal(new StringReader(sw.toString()));
assertEquals("myVDB", vdb.getName());
@@ -97,28 +97,20 @@
modelOne = vdb.getModel("model-one");
assertEquals("model-one", modelOne.getName());
- assertEquals("java:mybinding", modelOne.getConnectorReference());
- assertEquals("physical", modelOne.getModelType());
+ assertEquals("s1", modelOne.getSourceNames().get(0));
+ assertEquals(Model.Type.PHYSICAL, modelOne.getModelType());
assertEquals("model-value-override", modelOne.getPropertyValue("model-prop"));
assertFalse(modelOne.isVisible());
modelTwo = vdb.getModel("model-two");
assertEquals("model-two", modelTwo.getName());
- assertEquals("binding-two-ref", modelTwo.getConnectorReference());
- assertEquals("virtual", modelTwo.getModelType()); // this is not persisted in the XML
+ assertTrue(modelTwo.getSourceNames().contains("s1"));
+ assertTrue(modelTwo.getSourceNames().contains("s2"));
+ assertEquals(Model.Type.VIRTUAL, modelTwo.getModelType()); // this is not persisted in the XML
assertEquals("model-value", modelTwo.getPropertyValue("model-prop"));
- assertTrue(vdb.getConnectorMappings().size()==2);
- ref = vdb.getConnectorMappings().get(1);
-
- assertEquals("binding-two-ref", ref.getRefName());
- assertTrue(ref.getResourceNames().contains("java:binding-one"));
- assertTrue(ref.getResourceNames().contains("java:binding-two"));
- assertEquals(2, vdb.getConnectorBindingNames("binding-two-ref").size());
- assertTrue(vdb.getConnectorBindingNames("binding-two-ref").contains("java:binding-one"));
-
assertTrue(vdb.getValidityErrors().contains("There is an error in VDB"));
}
}
Deleted: branches/JCA/common-internal/src/main/java/com/metamatrix/common/xml/XMLReaderWriter.java
===================================================================
--- branches/JCA/common-internal/src/main/java/com/metamatrix/common/xml/XMLReaderWriter.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/common-internal/src/main/java/com/metamatrix/common/xml/XMLReaderWriter.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -1,60 +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.xml;
-
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-import org.jdom.Document;
-import org.jdom.JDOMException;
-
-
-/**
-* This interface is used to read and write JDOM compliant XML files.
-*/
-public interface XMLReaderWriter {
-
- /**
- * This method will write a JDOM Document to an OutputStream.
- *
- * @param doc the JDOM document to be written to the OutputStream
- * @param stream the output stream to be written to.
- * @throws IOException if there is a problem writing to the OutputStream
- */
- public void writeDocument(Document doc, OutputStream stream) throws IOException;
-
- /**
- * This method will write a JDOM Document to an OutputStream.
- *
- * @param stream the input stream to read the XML document from.
- * @return the JDOM document reference that represents the XML text in the
- * InputStream.
- * @throws IOException if there is a problem reading from the InputStream
- * @throws JDOMException if the InputStream does not represent a JDOM
- * compliant XML document.
- */
- public Document readDocument(InputStream stream) throws JDOMException, IOException;
-
-}
Deleted: branches/JCA/common-internal/src/main/java/com/metamatrix/common/xml/XMLReaderWriterImpl.java
===================================================================
--- branches/JCA/common-internal/src/main/java/com/metamatrix/common/xml/XMLReaderWriterImpl.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/common-internal/src/main/java/com/metamatrix/common/xml/XMLReaderWriterImpl.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -1,104 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.common.xml;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-import org.jdom.Document;
-import org.jdom.output.XMLOutputter;
-import org.jdom.JDOMException;
-
-import com.metamatrix.internal.core.xml.JdomHelper;
-
-
-/**
-* This implementation will use the JDOMhelper to read in XML files and will
-* use the JDOM utility to write out JDOM XML files.
-*/
-public class XMLReaderWriterImpl implements XMLReaderWriter{
-
- public static final int DEFAULT_INDENT_SIZE = 4;
- public static final boolean DEFAULT_USE_NEW_LINES = true;
-
- private int indent = DEFAULT_INDENT_SIZE;
- private boolean newLines = DEFAULT_USE_NEW_LINES;
-
- /**
- * This method will write a JDOM Document to an OutputStream.
- *
- * @param doc the JDOM document to be written to the OutputStream
- * @param stream the output stream to be written to.
- * @throws IOException if there is a problem writing to the OutputStream
- */
- public void writeDocument(Document doc, OutputStream stream) throws IOException{
- StringBuffer indentBuffer = new StringBuffer();
- for (int i = 0; i < indent; i++) {
- indentBuffer.append(" "); //$NON-NLS-1$
- }
- XMLOutputter outputter = new XMLOutputter(JdomHelper.getFormat(indentBuffer.toString(), newLines));
-
- outputter.output(doc, stream);
- stream.flush();
- stream.close();
-
- }
-
- /**
- * This method will write a JDOM Document to an OutputStream.
- *
- * @param stream the input stream to read the XML document from.
- * @return the JDOM document reference that represents the XML text in the
- * InputStream.
- * @throws IOException if there is a problem reading from the InputStream
- * @throws JDOMException if the InputStream does not represent a JDOM
- * compliant XML document.
- */
- public Document readDocument(InputStream stream) throws JDOMException, IOException{
- return JdomHelper.buildDocument(stream);
- }
-
- /**
- * This method will set the indent size of all JDOM Documents that are
- * written using this object.
- *
- * @param indent the number of spaces to indent the XML heirarchy in the
- * output files.
- */
- public void setIndentSize(int indent) {
- this.indent = indent;
- }
-
- /**
- * This method will set whether or not new Lines are used to mimic the
- * hierarchal structure of all JDOM Documents that are
- * written using this object.
- *
- * @param newLines whether or not to include new line chars in output files.
- */
- public void setUseNewLines(boolean newLines) {
- this.newLines = newLines;
- }
-
-}
Modified: branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/CachedFinder.java
===================================================================
--- branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/CachedFinder.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/CachedFinder.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -68,9 +68,9 @@
}
ConnectorException exception = null;
ModelMetaData model = vdb.getModel(modelName);
- for (String binding:vdb.getConnectorBindingNames(model.getConnectorReference())) {
+ for (String sourceName:model.getSourceNames()) {
try {
- ConnectorManager mgr = this.connectorRepo.getConnectorManager(binding);
+ ConnectorManager mgr = this.connectorRepo.getConnectorManager(model.getSourceJndiName(sourceName));
caps = mgr.getCapabilities();
break;
} catch(ConnectorException e) {
Modified: branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/DataTierManagerImpl.java
===================================================================
--- branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/DataTierManagerImpl.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/DataTierManagerImpl.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -36,7 +36,6 @@
import javax.sql.rowset.serial.SerialBlob;
import javax.sql.rowset.serial.SerialClob;
-import org.teiid.adminapi.Visibility;
import org.teiid.adminapi.impl.ModelMetaData;
import org.teiid.adminapi.impl.VDBMetaData;
import org.teiid.connector.api.ConnectorException;
@@ -46,8 +45,8 @@
import org.teiid.connector.metadata.runtime.Datatype;
import org.teiid.connector.metadata.runtime.ForeignKey;
import org.teiid.connector.metadata.runtime.KeyRecord;
-import org.teiid.connector.metadata.runtime.ProcedureParameter;
import org.teiid.connector.metadata.runtime.Procedure;
+import org.teiid.connector.metadata.runtime.ProcedureParameter;
import org.teiid.connector.metadata.runtime.Schema;
import org.teiid.connector.metadata.runtime.Table;
import org.teiid.dqp.internal.datamgr.impl.ConnectorManager;
@@ -318,7 +317,7 @@
ArrayList<Schema> result = new ArrayList<Schema>();
for (Schema schema : metadata.getSchemas().values()) {
ModelMetaData model = vdb.getModel(schema.getName());
- if(model.getVisibility() == Visibility.PUBLIC) {
+ if(model.isVisible()) {
result.add(schema);
}
}
@@ -344,12 +343,12 @@
if (connectorBindingId == null) {
VDBMetaData vdb = workItem.getDqpWorkContext().getVDB();
ModelMetaData model = vdb.getModel(modelName);
- List<String> bindings = vdb.getConnectorBindingNames(model.getConnectorReference());
+ List<String> bindings = model.getSourceNames();
if (bindings == null || bindings.size() != 1) {
// this should not happen, but it did occur when setting up the SystemAdmin models
throw new MetaMatrixComponentException(DQPPlugin.Util.getString("DataTierManager.could_not_obtain_connector_binding", new Object[]{modelName, workItem.getDqpWorkContext().getVdbName(), workItem.getDqpWorkContext().getVdbVersion() })); //$NON-NLS-1$
}
- connectorBindingId = bindings.get(0);
+ connectorBindingId = model.getSourceJndiName(bindings.get(0));
Assertion.isNotNull(connectorBindingId, "could not obtain connector id"); //$NON-NLS-1$
}
aqr.setConnectorName(connectorBindingId);
Modified: branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/multisource/MultiSourcePlanToProcessConverter.java
===================================================================
--- branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/multisource/MultiSourcePlanToProcessConverter.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/multisource/MultiSourcePlanToProcessConverter.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -89,18 +89,18 @@
ModelMetaData model = vdb.getModel(modelName);
List<AccessNode> accessNodes = new ArrayList<AccessNode>();
- for(String bindingName:vdb.getConnectorBindingNames(model.getConnectorReference())) {
+ for(String sourceName:model.getSourceNames()) {
// Create a new cloned version of the access node and set it's model name to be the bindingUUID
AccessNode instanceNode = (AccessNode) accessNode.clone();
instanceNode.setID(getID());
- instanceNode.setConnectorBindingId(bindingName);
+ instanceNode.setConnectorBindingId(model.getSourceJndiName(sourceName));
// Modify the command to pull the instance column and evaluate the criteria
Command command = (Command)instanceNode.getCommand().clone();
// Replace all multi-source elements with the source name
- DeepPreOrderNavigator.doVisit(command, new MultiSourceElementReplacementVisitor(bindingName));
+ DeepPreOrderNavigator.doVisit(command, new MultiSourceElementReplacementVisitor(sourceName));
// Rewrite the command now that criteria may have been simplified
try {
Modified: branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/validator/AuthorizationValidationVisitor.java
===================================================================
--- branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/validator/AuthorizationValidationVisitor.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/validator/AuthorizationValidationVisitor.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -31,7 +31,6 @@
import java.util.List;
import java.util.Map;
-import org.teiid.adminapi.Visibility;
import org.teiid.adminapi.impl.ModelMetaData;
import org.teiid.adminapi.impl.VDBMetaData;
import org.teiid.dqp.internal.process.DQPWorkContext;
@@ -302,7 +301,7 @@
try {
String modelName = getMetadata().getFullName(modelID);
ModelMetaData model = vdb.getModel(modelName);
- if(model.getVisibility() != Visibility.PUBLIC) {
+ if(!model.isVisible()) {
handleValidationError(DQPPlugin.Util.getString("ERR.018.005.0088", getMetadata().getFullName(group.getMetadataID()))); //$NON-NLS-1$
}
} catch (MetaMatrixComponentException e) {
Modified: branches/JCA/engine/src/main/java/org/teiid/metadata/TransformationMetadata.java
===================================================================
--- branches/JCA/engine/src/main/java/org/teiid/metadata/TransformationMetadata.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/engine/src/main/java/org/teiid/metadata/TransformationMetadata.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -37,7 +37,6 @@
import java.util.Properties;
import org.jboss.virtual.VirtualFile;
-import org.teiid.adminapi.Visibility;
import org.teiid.adminapi.impl.VDBMetaData;
import org.teiid.connector.metadata.runtime.AbstractMetadataRecord;
import org.teiid.connector.metadata.runtime.Column;
@@ -97,7 +96,7 @@
private static UnmodifiableProperties EMPTY_PROPS = new UnmodifiableProperties(new Properties());
private final CompositeMetadataStore store;
- private Map<VirtualFile, Visibility> vdbEntries;
+ private Map<VirtualFile, Boolean> vdbEntries;
private FunctionLibrary functionLibrary;
private VDBMetaData vdbMetaData;
@@ -112,7 +111,7 @@
* TransformationMetadata constructor
* @param context Object containing the info needed to lookup metadta.
*/
- public TransformationMetadata(VDBMetaData vdbMetadata, final CompositeMetadataStore store, Map<VirtualFile, Visibility> vdbEntries, Collection <FunctionMethod> udfMethods) {
+ public TransformationMetadata(VDBMetaData vdbMetadata, final CompositeMetadataStore store, Map<VirtualFile, Boolean> vdbEntries, Collection <FunctionMethod> udfMethods) {
ArgCheck.isNotNull(store);
this.vdbMetaData = vdbMetadata;
this.store = store;
@@ -988,8 +987,8 @@
public String getCharacterVDBResource(String resourcePath) throws MetaMatrixComponentException, QueryMetadataException {
for (VirtualFile f:this.vdbEntries.keySet()) {
if (f.getPathName().equals(resourcePath)) {
- Visibility v = this.vdbEntries.get(f);
- if (v.equals(Visibility.PUBLIC)) {
+ Boolean v = this.vdbEntries.get(f);
+ if (v.booleanValue()) {
try {
return ObjectConverterUtil.convertToString(f.openStream());
} catch (IOException e) {
@@ -1015,8 +1014,8 @@
public String[] getVDBResourcePaths() throws MetaMatrixComponentException, QueryMetadataException {
ArrayList<String> paths = new ArrayList<String>();
for (VirtualFile f:this.vdbEntries.keySet()) {
- Visibility v = this.vdbEntries.get(f);
- if (v.equals(Visibility.PUBLIC)) {
+ Boolean v = this.vdbEntries.get(f);
+ if (v.booleanValue()) {
paths.add(f.getPathName());
}
}
Modified: branches/JCA/engine/src/test/java/com/metamatrix/query/unittest/FakeMetadataFactory.java
===================================================================
--- branches/JCA/engine/src/test/java/com/metamatrix/query/unittest/FakeMetadataFactory.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/engine/src/test/java/com/metamatrix/query/unittest/FakeMetadataFactory.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -29,7 +29,6 @@
import java.util.Iterator;
import java.util.List;
-import org.teiid.adminapi.Visibility;
import org.teiid.adminapi.impl.ModelMetaData;
import org.teiid.adminapi.impl.VDBMetaData;
import org.teiid.connector.metadata.runtime.Table;
@@ -158,9 +157,9 @@
else {
model.setModelType(ModelType.getString(ModelType.VIRTUAL));
}
- model.setVisibility(Visibility.PUBLIC);
+ model.setVisible(true);
model.setSupportsMultiSourceBindings(false);
- model.setConnectorReference(name);
+ model.addSourceMapping(name, null);
return model;
}
@@ -2310,7 +2309,7 @@
vdb.setName("example1");
vdb.setVersion(1);
ModelMetaData m = createModel("pm1", true);
- m.setVisibility(Visibility.PRIVATE);
+ m.setVisible(false);
vdb.addModel(m);
vdb.addModel(createModel("vm1", false));
@@ -2536,10 +2535,9 @@
ModelMetaData model = new ModelMetaData();
model.setName("MultiModel");
model.setModelType(ModelType.getString(ModelType.PHYSICAL));
- model.setVisibility(Visibility.PUBLIC);
+ model.setVisible(true);
model.setSupportsMultiSourceBindings(true);
- model.setConnectorReference("refname");
vdb.addModel(model);
vdb.addModel(createModel("Virt", false));
Modified: branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/TestConnectorCapabilitiesFinder.java
===================================================================
--- branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/TestConnectorCapabilitiesFinder.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/TestConnectorCapabilitiesFinder.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -60,8 +60,7 @@
VDBMetaData vdb = Mockito.mock(VDBMetaData.class);
ModelMetaData model = Mockito.mock(ModelMetaData.class);
Mockito.stub(vdb.getModel(modelName)).toReturn(model);
- Mockito.stub(model.getConnectorReference()).toReturn("ref-name");
- Mockito.stub(vdb.getConnectorBindingNames("ref-name")).toReturn(bindings);
+ Mockito.stub(model.getSourceNames()).toReturn(bindings);
BasicSourceCapabilities basicSourceCapabilities = new BasicSourceCapabilities();
basicSourceCapabilities.setFunctionSupport(functionName, true);
@@ -69,7 +68,7 @@
ConnectorManagerRepository repo = Mockito.mock(ConnectorManagerRepository.class);
ConnectorManager cm = Mockito.mock(ConnectorManager.class);
Mockito.stub(cm.getCapabilities()).toReturn(basicSourceCapabilities);
- Mockito.stub(repo.getConnectorManager(modelName)).toReturn(cm);
+ Mockito.stub(repo.getConnectorManager(Mockito.anyString())).toReturn(cm);
CachedFinder finder = new CachedFinder(repo, vdb);
Modified: branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java
===================================================================
--- branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -22,9 +22,7 @@
package org.teiid.dqp.internal.process;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.*;
import java.sql.ResultSet;
import java.util.concurrent.ExecutionException;
@@ -35,7 +33,6 @@
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
-import org.teiid.adminapi.Visibility;
import org.teiid.dqp.internal.datamgr.impl.ConnectorManagerRepository;
import org.teiid.dqp.internal.datamgr.impl.FakeTransactionService;
@@ -55,7 +52,7 @@
@Before public void setUp() throws Exception {
DQPWorkContext context = FakeMetadataFactory.buildWorkContext(FakeMetadataFactory.exampleBQTCached(), FakeMetadataFactory.exampleBQTVDB());
- context.getVDB().getModel("BQT3").setVisibility(Visibility.PRIVATE); //$NON-NLS-1$
+ context.getVDB().getModel("BQT3").setVisible(false); //$NON-NLS-1$
ConnectorManagerRepository repo = Mockito.mock(ConnectorManagerRepository.class);
Mockito.stub(repo.getConnectorManager(Mockito.anyString())).toReturn(new AutoGenDataService());
Modified: branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourcePlanToProcessConverter.java
===================================================================
--- branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourcePlanToProcessConverter.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourcePlanToProcessConverter.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -22,10 +22,8 @@
package org.teiid.dqp.internal.process.multisource;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
+import static org.junit.Assert.*;
-import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
@@ -35,7 +33,6 @@
import org.junit.Test;
import org.teiid.adminapi.impl.ModelMetaData;
-import org.teiid.adminapi.impl.ReferenceMappingMetadata;
import org.teiid.adminapi.impl.VDBMetaData;
import org.teiid.dqp.internal.process.DQPWorkContext;
@@ -102,12 +99,10 @@
char sourceID = 'a';
// by default every model has one binding associated, but for multi-source there were none assigned.
ModelMetaData m = vdb.getModel(model);
- int x = vdb.getConnectorBindingNames(m.getConnectorReference()).size();
- ArrayList<String> names = new ArrayList<String>();
+ int x = m.getSourceNames().size();
for(int i=x; i<sourceCount; i++, sourceID++) {
- names.add("" + sourceID);
+ m.addSourceMapping("" + sourceID, null);
}
- vdb.addConnectorMapping(new ReferenceMappingMetadata(m.getConnectorReference(), names));
}
MultiSourceMetadataWrapper wrapper = new MultiSourceMetadataWrapper(metadata, multiSourceModels);
Modified: branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/validator/TestAuthorizationValidationVisitor.java
===================================================================
--- branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/validator/TestAuthorizationValidationVisitor.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/validator/TestAuthorizationValidationVisitor.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -30,7 +30,6 @@
import junit.framework.TestCase;
import org.mockito.Mockito;
-import org.teiid.adminapi.Visibility;
import org.teiid.adminapi.impl.VDBMetaData;
import org.teiid.dqp.internal.process.Request;
@@ -244,7 +243,7 @@
private void helpTestLookupVisibility(boolean visible) throws QueryParserException, QueryValidatorException, MetaMatrixComponentException {
VDBMetaData vdb = FakeMetadataFactory.example1VDB();
if (!visible) {
- vdb.getModel("pm1").setVisibility(Visibility.PRIVATE); //$NON-NLS-1$
+ vdb.getModel("pm1").setVisible(false);
}
AuthorizationValidationVisitor mvvv = new AuthorizationValidationVisitor(Mockito.mock(AuthorizationService.class), vdb);
String sql = "select lookup('pm1.g1', 'e1', 'e2', 1)"; //$NON-NLS-1$
Modified: branches/JCA/engine/src/test/java/org/teiid/metadata/TestTransformationMetadata.java
===================================================================
--- branches/JCA/engine/src/test/java/org/teiid/metadata/TestTransformationMetadata.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/engine/src/test/java/org/teiid/metadata/TestTransformationMetadata.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -31,7 +31,6 @@
import java.util.Properties;
import org.junit.Test;
-import org.teiid.adminapi.Visibility;
import org.teiid.adminapi.impl.ModelMetaData;
import org.teiid.adminapi.impl.VDBMetaData;
import org.teiid.connector.metadata.runtime.Datatype;
@@ -76,7 +75,7 @@
ModelMetaData model = new ModelMetaData();
model.setName(name);
model.setModelType(ModelType.getString(ModelType.PHYSICAL));
- model.setVisibility(Visibility.PUBLIC);
+ model.setVisible(true);
return model;
}
@@ -99,7 +98,7 @@
ModelMetaData model2 = new ModelMetaData();
model2.setName("x");
- model2.setVisibility(Visibility.PUBLIC);
+ model2.setVisible(true);
vdb.addModel(model2);
TransformationMetadata tm = new TransformationMetadata(vdb, cms, null, null);
@@ -108,7 +107,7 @@
FakeMetadataFactory.buildWorkContext(tm, vdb);
- model.setVisibility(Visibility.PRIVATE);
+ model.setVisible(false);
tm = new TransformationMetadata(vdb, cms, null, null);
result = tm.getGroupsForPartialName("y"); //$NON-NLS-1$
Modified: branches/JCA/jboss-integration/src/main/java/org/teiid/adminapi/jboss/Admin.java
===================================================================
--- branches/JCA/jboss-integration/src/main/java/org/teiid/adminapi/jboss/Admin.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/jboss-integration/src/main/java/org/teiid/adminapi/jboss/Admin.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -33,6 +33,7 @@
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
@@ -45,13 +46,10 @@
import org.jboss.managed.api.ComponentType;
import org.jboss.managed.api.DeploymentTemplateInfo;
import org.jboss.managed.api.ManagedComponent;
-import org.jboss.managed.api.ManagedDeployment;
+import org.jboss.managed.api.ManagedObject;
import org.jboss.managed.api.ManagedProperty;
-import org.jboss.metatype.api.types.CollectionMetaType;
import org.jboss.metatype.api.types.MapCompositeMetaType;
-import org.jboss.metatype.api.types.SimpleMetaType;
import org.jboss.metatype.api.values.CollectionValueSupport;
-import org.jboss.metatype.api.values.CompositeValueSupport;
import org.jboss.metatype.api.values.MapCompositeValueSupport;
import org.jboss.metatype.api.values.MetaValue;
import org.jboss.metatype.api.values.MetaValueFactory;
@@ -65,7 +63,6 @@
import org.teiid.adminapi.AdminProcessingException;
import org.teiid.adminapi.ConnectionPoolStatistics;
import org.teiid.adminapi.ConnectorBinding;
-import org.teiid.adminapi.Model;
import org.teiid.adminapi.PropertyDefinition;
import org.teiid.adminapi.Request;
import org.teiid.adminapi.Session;
@@ -81,10 +78,10 @@
import org.teiid.adminapi.impl.SessionMetadata;
import org.teiid.adminapi.impl.TransactionMetadata;
import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.adminapi.impl.ModelMetaData.SourceMapping;
+import org.teiid.adminapi.impl.ModelMetaData.ValidationError;
import org.teiid.jboss.deployers.RuntimeEngineDeployer;
-import com.metamatrix.core.CoreConstants;
-
public class Admin extends TeiidAdmin {
protected Logger log = Logger.getLogger(getClass());
private static final ProfileKey DEFAULT_PROFILE_KEY = new ProfileKey(ProfileKey.DEFAULT);
@@ -343,12 +340,12 @@
HashMap<String, ConnectorBinding> bindingMap = new HashMap<String, ConnectorBinding>();
VDBMetaData vdb = (VDBMetaData) getVDB(vdbName, vdbVersion);
if (vdb != null) {
- for (Model model:vdb.getModels()) {
+ for (ModelMetaData model:vdb.getModels()) {
if (model.isSource()) {
- for (String bindingName : vdb.getConnectorBindingNames(model.getConnectorReference())) {
- ConnectorBinding binding = getConnectorBinding(bindingName);
+ for (String sourceName : model.getSourceNames()) {
+ ConnectorBinding binding = getConnectorBinding(model.getSourceJndiName(sourceName));
if (binding != null) {
- bindingMap.put(bindingName, binding);
+ bindingMap.put(sourceName, binding);
}
}
}
@@ -445,45 +442,45 @@
VDBMetaData vdb = new VDBMetaData();
vdb.setName(ManagedUtil.getSimpleValue(mc, "name", String.class));
vdb.setDescription(ManagedUtil.getSimpleValue(mc, "description", String.class));
- vdb.setStatus(VDB.Status.valueOf(ManagedUtil.getSimpleValue(mc, "status", String.class)));
+ String status = ManagedUtil.getSimpleValue(mc, "status", String.class);
+ if (status != null) {
+ vdb.setStatus(VDB.Status.valueOf(status));
+ }
vdb.setVersion(ManagedUtil.getSimpleValue(mc, "version", Integer.class));
vdb.setUrl(mc.getDeployment().getName());
+ vdb.setProperties(ManagedUtil.getPropertiesValue(mc, "properties"));
- ArrayList<String> errors = new ArrayList<String>();
- ManagedUtil.getCollectionValue(mc, "validityErrors", errors, String.class);
- for (String error:errors) {
- vdb.addProblemMarker("ERROR", error);
+ // models
+ ManagedProperty mp = mc.getProperty("models");
+ List<ManagedObject> models = (List<ManagedObject>)MetaValueFactory.getInstance().unwrap(mp.getValue());
+ for(ManagedObject mo:models) {
+ vdb.addModel(buildModel(mo));
}
- ManagedDeployment deployment = mc.getDeployment();
- Collection<ManagedComponent> models = deployment.getComponents().values();
- for (ManagedComponent mm:models) {
- if (mm.getType().equals(MODELTYPE)) {
- String modelName = ManagedUtil.getSimpleValue(mm, "name", String.class);
- if (!modelName.equals(CoreConstants.SYSTEM_MODEL)) {
- vdb.addModel(buildModel(mm));
- }
- }
- }
-
// TODO: add the following
- // ConnectorMappings
// SecurityRoleMappings
return vdb;
}
- private ModelMetaData buildModel(ManagedComponent mc) {
+ private ModelMetaData buildModel(ManagedObject mc) {
ModelMetaData model = new ModelMetaData();
model.setName(ManagedUtil.getSimpleValue(mc, "name", String.class));
- model.setModelURI(ManagedUtil.getSimpleValue(mc, "modelURI", String.class));
- model.setModelType(ManagedUtil.getSimpleValue(mc, "modelType", String.class));
- model.setPath(ManagedUtil.getSimpleValue(mc, "path", String.class));
- model.setUuid(ManagedUtil.getSimpleValue(mc, "uuid", String.class));
model.setVisible(ManagedUtil.getSimpleValue(mc, "visible", Boolean.class));
- model.setConnectorReference(ManagedUtil.getSimpleValue(mc, "connectorReference", String.class));
+ model.setModelType(ManagedUtil.getSimpleValue(mc, "modelType", String.class));
model.setProperties(ManagedUtil.getPropertiesValue(mc, "properties"));
+ List<SourceMapping> mappings = (List<SourceMapping>)MetaValueFactory.getInstance().unwrap(mc.getProperty("sourceMappings").getValue());
+ for (SourceMapping s:mappings) {
+ model.addSourceMapping(s.getName(), s.getJndiName());
+ }
+
+ List<ValidationError> errors = (List<ValidationError>)MetaValueFactory.getInstance().unwrap(mc.getProperty("errors").getValue());
+ if (errors != null) {
+ for (ValidationError error:errors) {
+ model.addError(error.getSeverity(), error.getValue());
+ }
+ }
return model;
}
@@ -870,46 +867,41 @@
@Override
public void assignBindingsToModel(String vdbName, int vdbVersion, String modelName, String[] connectorBindingNames) throws AdminException {
- ManagedComponent mc = getVDBManagedComponent(vdbName, vdbVersion);
- if (mc != null) {
- VDBMetaData vdb = buildVDB(mc);
- if (vdb == null) {
-
- }
-
- ModelMetaData model = vdb.getModel(modelName);
- if (model == null) {
- throw new AdminProcessingException("Model name = "+modelName+" not found in the VDB with name = "+vdbName + " version = "+ vdbVersion);
- }
-
- String referenceName = model.getConnectorReference();
- ArrayList<MetaValue> newBindings = new ArrayList<MetaValue>();
- for (String name:connectorBindingNames) {
- newBindings.add(new SimpleValueSupport(SimpleMetaType.STRING, name));
- }
-
- ManagedProperty mappings = mc.getProperty("connectorMappings");
- MetaValue[] elements = ((CollectionValueSupport)mappings.getValue()).getElements();
- ArrayList<MetaValue> modifiedElements = new ArrayList<MetaValue>();
- for (MetaValue mv:elements) {
- MetaValue value = ((CompositeValueSupport)mv).get("refName");
- if (value != null && ManagedUtil.stringValue(value).equals(referenceName)) {
- CollectionValueSupport bindings = (CollectionValueSupport)((CompositeValueSupport)mv).get("resourceNames");
- bindings.setElements(newBindings.toArray(new MetaValue[newBindings.size()]));
- }
- else {
- modifiedElements.add(mv);
- }
- }
-
- try {
- getView().updateComponent(mc);
- } catch (Exception e) {
- throw new AdminComponentException(e.getMessage(), e);
- }
- }
-
- throw new AdminProcessingException("VDB with name = "+vdbName + " version = "+ vdbVersion + " not found in configuration");
+// ManagedComponent mc = getVDBManagedComponent(vdbName, vdbVersion);
+// if (mc == null) {
+// throw new AdminProcessingException("VDB with name = "+vdbName + " version = "+ vdbVersion + " not found in configuration");
+// }
+// VDBMetaData vdb = buildVDB(mc);
+// ModelMetaData model = vdb.getModel(modelName);
+// if (model == null) {
+// throw new AdminProcessingException("Model name = "+modelName+" not found in the VDB with name = "+vdbName + " version = "+ vdbVersion);
+// }
+//
+// String referenceName = model.getConnectorReference();
+// ArrayList<MetaValue> newBindings = new ArrayList<MetaValue>();
+// for (String name:connectorBindingNames) {
+// newBindings.add(new SimpleValueSupport(SimpleMetaType.STRING, name));
+// }
+//
+// ManagedProperty mappings = mc.getProperty("connectorMappings");
+// MetaValue[] elements = ((CollectionValueSupport)mappings.getValue()).getElements();
+// ArrayList<MetaValue> modifiedElements = new ArrayList<MetaValue>();
+// for (MetaValue mv:elements) {
+// MetaValue value = ((CompositeValueSupport)mv).get("refName");
+// if (value != null && ManagedUtil.stringValue(value).equals(referenceName)) {
+// CollectionValueSupport bindings = (CollectionValueSupport)((CompositeValueSupport)mv).get("resourceNames");
+// bindings.setElements(newBindings.toArray(new MetaValue[newBindings.size()]));
+// }
+// else {
+// modifiedElements.add(mv);
+// }
+// }
+//
+// try {
+// getView().updateComponent(mc);
+// } catch (Exception e) {
+// throw new AdminComponentException(e.getMessage(), e);
+// }
}
}
Modified: branches/JCA/jboss-integration/src/main/java/org/teiid/adminapi/jboss/ManagedUtil.java
===================================================================
--- branches/JCA/jboss-integration/src/main/java/org/teiid/adminapi/jboss/ManagedUtil.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/jboss-integration/src/main/java/org/teiid/adminapi/jboss/ManagedUtil.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -35,7 +35,7 @@
import org.jboss.deployers.spi.management.deploy.DeploymentManager;
import org.jboss.deployers.spi.management.deploy.DeploymentProgress;
import org.jboss.deployers.spi.management.deploy.DeploymentStatus;
-import org.jboss.managed.api.ManagedComponent;
+import org.jboss.managed.api.ManagedCommon;
import org.jboss.managed.api.ManagedOperation;
import org.jboss.managed.api.ManagedProperty;
import org.jboss.metatype.api.types.MapCompositeMetaType;
@@ -101,7 +101,7 @@
return null;
}
- public static <T> T getSimpleValue(ManagedComponent mc, String prop, Class<T> expectedType) {
+ public static <T> T getSimpleValue(ManagedCommon mc, String prop, Class<T> expectedType) {
ManagedProperty mp = mc.getProperty(prop);
if (mp != null) {
MetaType metaType = mp.getMetaType();
@@ -118,7 +118,7 @@
return null;
}
- public static Properties getPropertiesValue(ManagedComponent mc, String prop) {
+ public static Properties getPropertiesValue(ManagedCommon mc, String prop) {
ManagedProperty mp = mc.getProperty(prop);
if (mp != null) {
MetaType metaType = mp.getMetaType();
@@ -140,7 +140,7 @@
return null;
}
- public static <T> void getCollectionValue(ManagedComponent mc, String prop, Collection<T> list, Class<T> expectedType) {
+ public static <T> void getCollectionValue(ManagedCommon mc, String prop, Collection<T> list, Class<T> expectedType) {
ManagedProperty mp = mc.getProperty(prop);
if (mp != null) {
MetaType metaType = mp.getMetaType();
@@ -274,7 +274,7 @@
}
}
- public static MetaValue executeOperation(ManagedComponent mc, String operation, MetaValue... args) {
+ public static MetaValue executeOperation(ManagedCommon mc, String operation, MetaValue... args) {
for (ManagedOperation mo:mc.getOperations()) {
if (mo.getName().equals(operation)) {
return mo.invoke(args);
Modified: branches/JCA/jboss-integration/src/test/java/org/teiid/adminapi/jboss/TestConnectorBindings.java
===================================================================
--- branches/JCA/jboss-integration/src/test/java/org/teiid/adminapi/jboss/TestConnectorBindings.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/jboss-integration/src/test/java/org/teiid/adminapi/jboss/TestConnectorBindings.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -1,10 +1,7 @@
package org.teiid.adminapi.jboss;
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertNotNull;
-import static junit.framework.Assert.assertNull;
-import static junit.framework.Assert.assertTrue;
+import static junit.framework.Assert.*;
import java.io.File;
import java.io.InputStream;
@@ -18,6 +15,7 @@
import org.junit.Ignore;
import org.junit.Test;
import org.teiid.adminapi.Admin;
+import org.teiid.adminapi.AdminFactory;
import org.teiid.adminapi.ConnectionPoolStatistics;
import org.teiid.adminapi.ConnectorBinding;
import org.teiid.adminapi.PropertyDefinition;
@@ -33,21 +31,18 @@
@Ignore
public class TestConnectorBindings extends BaseConnection {
ServerDatasourceConnection ds;
- com.metamatrix.jdbc.api.Connection conn;
Admin admin;
@Before
public void setUp() throws Exception {
//if (!Bootstrap.getInstance().isStarted()) Bootstrap.getInstance().bootstrap();
ds = new ServerDatasourceConnection();
- conn = (com.metamatrix.jdbc.api.Connection)ds.getConnection("admin");
- admin = AdminProvider.getRemote( "jnp://localhost:1099", "javaduke", "anotherduke");
- //admin = AdminFactory.getInstance().createAdmin("admin", "admin".toCharArray(), "mm://localhost:31443");
+ //admin = AdminProvider.getRemote( "jnp://localhost:1099", "javaduke", "anotherduke");
+ admin = AdminFactory.getInstance().createAdmin("admin", "admin".toCharArray(), "mm://localhost:31443");
}
@After
public void tearDown() throws Exception {
- this.conn.close();
}
@Test public void testConnectorBinding() throws Exception {
@@ -305,5 +300,16 @@
assertTrue(f.exists());
f.delete();
}
-
+
+ @Test public void testAssignConnectorBinding() throws Exception {
+
+ VDB vdb = admin.getVDB("TransactionsRevisited", 1);
+ if (vdb == null) {
+ admin.deleteVDB("TransactionsRevisited", 1);
+ File f = UnitTestUtil.getTestDataFile("TransactionsRevisited.vdb");
+ admin.deployVDB(f.getName(), f.toURI().toURL());
+ }
+
+ admin.assignBindingsToModel("TransactionsRevisited", 1, "pm1", new String[] {"java:foo", "java:bar"});
+ }
}
Modified: branches/JCA/metadata/src/main/java/org/teiid/metadata/index/IndexMetadataFactory.java
===================================================================
--- branches/JCA/metadata/src/main/java/org/teiid/metadata/index/IndexMetadataFactory.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/metadata/src/main/java/org/teiid/metadata/index/IndexMetadataFactory.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -33,7 +33,6 @@
import java.util.Map;
import org.jboss.virtual.VirtualFile;
-import org.teiid.adminapi.Visibility;
import org.teiid.connector.metadata.runtime.AbstractMetadataRecord;
import org.teiid.connector.metadata.runtime.Column;
import org.teiid.connector.metadata.runtime.ColumnSet;
@@ -41,8 +40,8 @@
import org.teiid.connector.metadata.runtime.ForeignKey;
import org.teiid.connector.metadata.runtime.KeyRecord;
import org.teiid.connector.metadata.runtime.MetadataStore;
-import org.teiid.connector.metadata.runtime.ProcedureParameter;
import org.teiid.connector.metadata.runtime.Procedure;
+import org.teiid.connector.metadata.runtime.ProcedureParameter;
import org.teiid.connector.metadata.runtime.Schema;
import org.teiid.connector.metadata.runtime.Table;
import org.teiid.core.index.IEntryResult;
@@ -67,7 +66,7 @@
private Map<String, Table> tableCache = new HashMap<String, Table>();
private MetadataStore store;
private HashSet<VirtualFile> indexFiles = new HashSet<VirtualFile>();
- private Map<VirtualFile, Visibility> vdbEntries;
+ private Map<VirtualFile, Boolean> vdbEntries;
public MetadataStore getMetadataStore() throws IOException {
if (this.store == null) {
@@ -89,11 +88,11 @@
this.indexFiles.add(f);
}
- public void addEntriesPlusVisibilities(Map<VirtualFile, Visibility> entries) {
+ public void addEntriesPlusVisibilities(Map<VirtualFile, Boolean> entries) {
this.vdbEntries = entries;
}
- public Map<VirtualFile, Visibility> getEntriesPlusVisibilities(){
+ public Map<VirtualFile, Boolean> getEntriesPlusVisibilities(){
return this.vdbEntries;
}
Modified: branches/JCA/runtime/src/main/java/org/teiid/deployers/DynamicVDBDeployer.java
===================================================================
--- branches/JCA/runtime/src/main/java/org/teiid/deployers/DynamicVDBDeployer.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/runtime/src/main/java/org/teiid/deployers/DynamicVDBDeployer.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -77,7 +77,7 @@
}
private MetadataStore buildDynamicMetadataStore(VFSDeploymentUnit unit, VDBMetaData vdb, ModelMetaData model) throws DeploymentException{
- if (vdb.getConnectorBindingNames(model.getConnectorReference()).isEmpty()) {
+ if (model.getSourceNames().isEmpty()) {
throw new DeploymentException(vdb.getName()+"-"+vdb.getVersion()+" Can not be deployed because model {"+model.getName()+"} is not fully configured.");
}
@@ -98,7 +98,7 @@
Exception exception = null;
- for (String connectorName: vdb.getConnectorBindingNames(model.getConnectorReference())) {
+ for (String connectorName: model.getSourceNames()) {
ConnectorManager cm = this.connectorManagerRepository.getConnectorManager(connectorName);
if (cm == null) {
continue;
Deleted: branches/JCA/runtime/src/main/java/org/teiid/deployers/ManifestMetaData.java
===================================================================
--- branches/JCA/runtime/src/main/java/org/teiid/deployers/ManifestMetaData.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/runtime/src/main/java/org/teiid/deployers/ManifestMetaData.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -1,36 +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.deployers;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.jboss.managed.api.annotation.ManagementObject;
-import org.teiid.adminapi.impl.ModelMetaData;
-
-@ManagementObject
-public class ManifestMetaData {
- String vdbName;
- String vdbDescription;
- List<ModelMetaData> models = new ArrayList<ModelMetaData>();
- List<String> errors = new ArrayList<String>();
-}
Deleted: branches/JCA/runtime/src/main/java/org/teiid/deployers/ManifestParser.java
===================================================================
--- branches/JCA/runtime/src/main/java/org/teiid/deployers/ManifestParser.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/runtime/src/main/java/org/teiid/deployers/ManifestParser.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -1,112 +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.deployers;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.List;
-
-import org.jdom.Document;
-import org.jdom.Element;
-import org.jdom.JDOMException;
-import org.jdom.Namespace;
-import org.teiid.adminapi.Visibility;
-import org.teiid.adminapi.impl.ModelMetaData;
-
-import com.metamatrix.common.xml.XMLReaderWriter;
-import com.metamatrix.common.xml.XMLReaderWriterImpl;
-import com.metamatrix.core.util.StringUtil;
-
-
-/**
- * VDB Manifest file; right now this is defined as EMF resource in the vdb.edit code,
- * so to break the dependency from EMF we have defined as the simple XML type here. This
- * will defined as simple xml in future then we can remove this. There is defect logged on this
- * in JIRA
- */
-public class ManifestParser{
-
- public static ManifestMetaData load(InputStream in) throws IOException {
-
- ManifestMetaData vdb = new ManifestMetaData();
-
- try {
- XMLReaderWriter reader = new XMLReaderWriterImpl();
- Document doc = reader.readDocument(in);
- Element root = doc.getRootElement();
-
- Namespace ns= root.getNamespace(NS);
- Element vdbElement = root.getChild(VDB_ELEMENT, ns);
- if (vdbElement != null) {
- vdb.vdbName = vdbElement.getAttributeValue(NAME);
- vdb.vdbDescription = vdbElement.getAttributeValue(DESCRIPTION);
-
- // build the models
- List<Element> modelElements = vdbElement.getChildren(MODELS);
- for(Element modelElement:modelElements) {
-
- String modelName = StringUtil.getFirstToken(modelElement.getAttributeValue(NAME), ".");
- ModelMetaData model = new ModelMetaData();
- model.setName(modelName);
-
- model.setModelType(modelElement.getAttributeValue(MODEL_TYPE));
- model.setPath(modelElement.getAttributeValue(MODEL_PATH,""));
- model.setUuid(modelElement.getAttributeValue(UUID));
- model.setModelURI(modelElement.getAttributeValue(PRIMARY_METAMODEL_URI));
-
- String visibility = modelElement.getAttributeValue(ACCESSIBILITY);
- if (visibility != null) {
- model.setVisibility(Visibility.valueOf(Visibility.class, visibility.toUpperCase()));
- }
-
- List<Element> markers = modelElement.getChildren(MARKERS);
- for(Element marker:markers) {
- String severity = marker.getAttributeValue(SEVERITY);
- if (severity.equals(ERROR)) {
- vdb.errors.add(marker.getAttributeValue(MESSAGE));
- }
- }
- vdb.models.add(model);
- }
- }
- } catch (JDOMException e) {
- throw new IOException("Failed to read the VDB-Manifest file"); //$NON-NLS-1$
- }
- return vdb;
- }
-
- private static final String MODELS = "models"; //$NON-NLS-1$
- private static final String ACCESSIBILITY = "accessibility"; //$NON-NLS-1$
- private static final String PRIMARY_METAMODEL_URI = "primaryMetamodelUri"; //$NON-NLS-1$
- private static final String UUID = "uuid"; //$NON-NLS-1$
- private static final String NS = "vdb"; //$NON-NLS-1$
- private static final String MESSAGE = "message"; //$NON-NLS-1$
- private static final String ERROR = "ERROR"; //$NON-NLS-1$
- private static final String SEVERITY = "severity"; //$NON-NLS-1$
- private static final String NAME = "name"; //$NON-NLS-1$
- private static final String MODEL_PATH = "modelLocation";//$NON-NLS-1$
- private static final String MODEL_TYPE = "modelType";//$NON-NLS-1$
- private static final String VDB_ELEMENT = "VirtualDatabase";//$NON-NLS-1$
- private static final String DESCRIPTION = "description";//$NON-NLS-1$
- private static final String MARKERS = "markers";//$NON-NLS-1$
-}
Modified: branches/JCA/runtime/src/main/java/org/teiid/deployers/SystemVDBDeployer.java
===================================================================
--- branches/JCA/runtime/src/main/java/org/teiid/deployers/SystemVDBDeployer.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/runtime/src/main/java/org/teiid/deployers/SystemVDBDeployer.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -29,7 +29,6 @@
import org.jboss.virtual.VirtualFile;
import org.jboss.virtual.VirtualFileFilter;
import org.jboss.virtual.plugins.context.zip.ZipEntryContext;
-import org.teiid.adminapi.Visibility;
import org.teiid.adminapi.impl.ModelMetaData;
import org.teiid.adminapi.impl.VDBMetaData;
import org.teiid.metadata.index.IndexConstants;
@@ -45,7 +44,7 @@
public void start() {
ModelMetaData model = new ModelMetaData();
model.setName(CoreConstants.SYSTEM_MODEL);
- model.setVisibility(Visibility.PUBLIC);
+ model.setVisible(true);
VDBMetaData deployment = new VDBMetaData();
deployment.setName(CoreConstants.SYSTEM_VDB);
Modified: branches/JCA/runtime/src/main/java/org/teiid/deployers/VDBDeployer.java
===================================================================
--- branches/JCA/runtime/src/main/java/org/teiid/deployers/VDBDeployer.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/runtime/src/main/java/org/teiid/deployers/VDBDeployer.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -21,21 +21,26 @@
*/
package org.teiid.deployers;
+import java.io.File;
+import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+
import org.jboss.deployers.spi.DeploymentException;
import org.jboss.deployers.spi.deployer.helpers.AbstractSimpleRealDeployer;
import org.jboss.deployers.spi.deployer.managed.ManagedObjectCreator;
import org.jboss.deployers.structure.spi.DeploymentUnit;
+import org.jboss.deployers.vfs.spi.structure.VFSDeploymentUnit;
import org.jboss.logging.Logger;
import org.jboss.managed.api.ManagedObject;
import org.jboss.managed.api.factory.ManagedObjectFactory;
import org.jboss.virtual.VirtualFile;
import org.teiid.adminapi.VDB;
-import org.teiid.adminapi.Visibility;
import org.teiid.adminapi.impl.ModelMetaData;
import org.teiid.adminapi.impl.VDBMetaData;
import org.teiid.connector.metadata.runtime.MetadataStore;
@@ -45,7 +50,6 @@
import org.teiid.metadata.index.IndexMetadataFactory;
import com.metamatrix.core.CoreConstants;
-import com.metamatrix.dqp.embedded.DQPEmbeddedPlugin;
import com.metamatrix.query.function.metadata.FunctionMethod;
import com.metamatrix.query.metadata.QueryMetadataInterface;
@@ -54,6 +58,7 @@
private ManagedObjectFactory mof;
private VDBRepository vdbRepository;
private DQPContextCache contextCache;
+ private ObjectSerializer serializer;
public VDBDeployer() {
super(VDBMetaData.class);
@@ -68,6 +73,11 @@
log.info("Re-deploying VDB = "+deployment);
}
+ List<String> errors = deployment.getValidityErrors();
+ if (errors != null && !errors.isEmpty()) {
+ throw new DeploymentException("VDB has validaity errors; failed to deploy");
+ }
+
this.vdbRepository.addVDB(deployment);
TransformationMetadata metadata = null;
@@ -80,7 +90,7 @@
IndexMetadataFactory indexFactory = unit.getAttachment(IndexMetadataFactory.class);
UDFMetaData udf = unit.getAttachment(UDFMetaData.class);
if (indexFactory != null) {
- Map<VirtualFile, Visibility> visibilityMap = indexFactory.getEntriesPlusVisibilities();
+ Map<VirtualFile, Boolean> visibilityMap = indexFactory.getEntriesPlusVisibilities();
metadata = buildTransformationMetaData(deployment, visibilityMap, store, udf);
}
else {
@@ -96,39 +106,33 @@
// add transformation metadata to the repository.
this.vdbRepository.addMetadata(deployment, metadata);
+
+ boolean valid = true;
+ for(ModelMetaData model:deployment.getModels()) {
+ for (String sourceName:model.getSourceNames()) {
+ String jndiName = model.getSourceJndiName(sourceName);
+ try {
+ InitialContext ic = new InitialContext();
+ ic.lookup(jndiName);
+ } catch (NamingException e) {
+ valid = false;
+ String msg = "Jndi resource = "+ jndiName + " not found for Source Name = "+sourceName;
+ model.addError(ModelMetaData.ValidationError.Severity.ERROR.name(), msg);
+ log.info(msg);
+ }
+ }
+ }
// Check if the VDB is fully configured.
- if (isFullyConfiguredVDB(deployment)) {
+ if (valid) {
deployment.setStatus(VDB.Status.ACTIVE);
}
- else {
- log.info(DQPEmbeddedPlugin.Util.getString("VDBService.vdb_missing_bindings", new Object[] {deployment.getName(), deployment.getVersion()})); //$NON-NLS-1$
- }
-
log.info("VDB = "+deployment + " deployed");
}
- public boolean isFullyConfiguredVDB(VDBMetaData vdb) {
- for(ModelMetaData m: vdb.getModels()) {
- if (m.isSource()) {
- String connectorReference = m.getConnectorReference();
- if (connectorReference == null) {
- log.warn("VDB = "+vdb.getName() +" Model = "+m.getName()+"; No Connector Reference defined");
- }
-
- List<String> resourceNames = vdb.getConnectorBindingNames(connectorReference);
- if (resourceNames.isEmpty()) {
- return false;
- }
- log.warn("VDB = "+vdb.getName() +" Model = "+m.getName()+"; No Connector Bindings are mapped for Connector Reference = "+connectorReference);
- }
- }
- return true;
- }
-
// does this need to be synchronized?
- private TransformationMetadata buildTransformationMetaData(VDBMetaData vdb, Map<VirtualFile, Visibility> visibilityMap, CompositeMetadataStore store, UDFMetaData udf) throws DeploymentException {
+ private TransformationMetadata buildTransformationMetaData(VDBMetaData vdb, Map<VirtualFile, Boolean> visibilityMap, CompositeMetadataStore store, UDFMetaData udf) throws DeploymentException {
// get the system VDB metadata store
MetadataStore systemStore = this.vdbRepository.getMetadataStore(CoreConstants.SYSTEM_VDB, 1);
@@ -191,10 +195,26 @@
this.contextCache.removeVDBScopedCache(deployment.getName(), deployment.getVersion());
}
+ try {
+ if (((VFSDeploymentUnit)unit).getRoot().exists()) {
+ File cacheFileName = this.serializer.getAttachmentPath((VFSDeploymentUnit)unit, deployment.getName()+"_"+deployment.getVersion());
+ if (cacheFileName.exists()) {
+ cacheFileName.delete();
+ }
+ }
+ } catch (IOException e) {
+ log.warn("failed to delete the cached metadata files due to:" + e.getMessage());
+ }
+
log.info("VDB = "+deployment + " undeployed");
}
public void setContextCache(DQPContextCache cache) {
this.contextCache = cache;
- }
+ }
+
+ public void setObjectSerializer(ObjectSerializer serializer) {
+ this.serializer = serializer;
+ }
+
}
Modified: branches/JCA/runtime/src/main/java/org/teiid/deployers/VDBParserDeployer.java
===================================================================
--- branches/JCA/runtime/src/main/java/org/teiid/deployers/VDBParserDeployer.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/runtime/src/main/java/org/teiid/deployers/VDBParserDeployer.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -33,7 +33,6 @@
import org.jboss.deployers.vfs.spi.structure.VFSDeploymentUnit;
import org.jboss.logging.Logger;
import org.jboss.virtual.VirtualFile;
-import org.teiid.adminapi.Visibility;
import org.teiid.adminapi.impl.ModelMetaData;
import org.teiid.adminapi.impl.VDBMetaData;
import org.teiid.metadata.CompositeMetadataStore;
@@ -60,7 +59,6 @@
private static Map<String, Class<?>> getCustomMappings() {
Map<String, Class<?>> mappings = new HashMap<String, Class<?>>();
mappings.put(VdbConstants.DEF_FILE_NAME, VDBMetaData.class);
- mappings.put(VdbConstants.MANIFEST_MODEL_NAME, ManifestMetaData.class);
mappings.put(VdbConstants.UDF_FILE_NAME, UDFMetaData.class);
return mappings;
}
@@ -74,10 +72,6 @@
return expectedType.cast(def);
}
- else if (expectedType.equals(ManifestMetaData.class)) {
- ManifestMetaData manifest = ManifestParser.load(file.openStream());
- return expectedType.cast(manifest);
- }
else if (expectedType.equals(UDFMetaData.class)) {
UDFMetaData udf = new UDFMetaData(FunctionMetadataReader.loadFunctionMethods(file.openStream()));
return expectedType.cast(udf);
@@ -102,24 +96,21 @@
@Override
protected VDBMetaData mergeMetaData(VFSDeploymentUnit unit, Map<Class<?>, List<Object>> metadata) throws Exception {
VDBMetaData def = getInstance(metadata, VDBMetaData.class);
- ManifestMetaData manifest = getInstance(metadata, ManifestMetaData.class);
UDFMetaData udf = getInstance(metadata, UDFMetaData.class);
- if (def == null || manifest == null) {
+ if (def == null) {
log.error("Invalid VDB file deployment failed ="+unit.getRoot().getName());
return null;
}
- // merge mainfest and def
- def = merge(def, manifest);
def.setUrl(unit.getRoot().toURL().toExternalForm());
// add the entries and determine their visibility
VirtualFile root = unit.getRoot();
List<VirtualFile> children = root.getChildrenRecursively();
- Map<VirtualFile, Visibility> visibilityMap = new LinkedHashMap<VirtualFile, Visibility>();
+ Map<VirtualFile, Boolean> visibilityMap = new LinkedHashMap<VirtualFile, Boolean>();
for(VirtualFile f: children) {
- visibilityMap.put(f, getFileVisibility(f.getPathName(), def));
+ visibilityMap.put(f, isFileVisible(f.getPathName(), def));
}
// build the metadata store
@@ -153,64 +144,48 @@
return def;
}
- private VDBMetaData merge(VDBMetaData def, ManifestMetaData manifest) {
- for(ModelMetaData manifestModel: manifest.models) {
- ModelMetaData model = def.getModel(manifestModel.getName());
- if (model != null) {
- model.setModelType(manifestModel.getModelType());
- model.setModelURI(manifestModel.getModelURI());
- model.setPath(manifestModel.getPath());
- model.setUuid(manifestModel.getUuid());
- if (manifestModel.getVisibility() != null) {
- model.setVisibility(manifestModel.getVisibility());
- }
- }
- }
- return def;
- }
-
private final static boolean isSystemModelWithSystemTableType(String modelName) {
return CoreConstants.SYSTEM_MODEL.equalsIgnoreCase(modelName);
}
- private Visibility getFileVisibility(String pathInVDB, VDBMetaData vdb) {
+ private boolean isFileVisible(String pathInVDB, VDBMetaData vdb) {
String modelName = StringUtil.getFirstToken(StringUtil.getLastToken(pathInVDB, "/"), "."); //$NON-NLS-1$ //$NON-NLS-2$
// If this is any of the Public System Models, like JDBC,ODBC system
// models
if (isSystemModelWithSystemTableType(modelName)) {
- return Visibility.PUBLIC;
+ return true;
}
ModelMetaData model = vdb.getModel(modelName);
if (model != null) {
- return model.getVisibility();
+ return model.isVisible();
}
String entry = StringUtil.getLastToken(pathInVDB, "/"); //$NON-NLS-1$
// index files should not be visible
if( entry.endsWith(VdbConstants.INDEX_EXT) || entry.endsWith(VdbConstants.SEARCH_INDEX_EXT)) {
- return Visibility.PRIVATE;
+ return false;
}
// manifest file should not be visible
if(entry.equalsIgnoreCase(VdbConstants.MANIFEST_MODEL_NAME)) {
- return Visibility.PRIVATE;
+ return false;
}
// materialization models should not be visible
if(entry.startsWith(VdbConstants.MATERIALIZATION_MODEL_NAME) && entry.endsWith(VdbConstants.MODEL_EXT)) {
- return Visibility.PRIVATE;
+ return false;
}
-
+
// wldl file should be visible
if(entry.equalsIgnoreCase(VdbConstants.WSDL_FILENAME)) {
- return Visibility.PUBLIC;
+ return false;
}
// any other file should be visible
- return Visibility.PUBLIC;
+ return true;
}
public void setObjectSerializer(ObjectSerializer serializer) {
Modified: branches/JCA/runtime/src/main/java/org/teiid/deployers/VDBStructure.java
===================================================================
--- branches/JCA/runtime/src/main/java/org/teiid/deployers/VDBStructure.java 2010-03-03 21:54:32 UTC (rev 1893)
+++ branches/JCA/runtime/src/main/java/org/teiid/deployers/VDBStructure.java 2010-03-03 23:08:18 UTC (rev 1894)
@@ -48,9 +48,6 @@
if (file.getChild(VdbConstants.DEF_FILE_NAME) == null) {
return false;
}
- if (file.getChild(VdbConstants.MANIFEST_MODEL_NAME) == null) {
- return false;
- }
createContext(structureContext, new String[] {"/", "runtime-inf"});
return true;
}
14 years, 2 months
teiid SVN: r1893 - in branches/JCA: common-core/src/main/java/com/metamatrix/common/protocol and 17 other directories.
by teiid-commits@lists.jboss.org
Author: shawkins
Date: 2010-03-03 16:54:32 -0500 (Wed, 03 Mar 2010)
New Revision: 1893
Added:
branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/BasicCryptor.java
branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/SymmetricCryptor.java
Removed:
branches/JCA/common-core/src/main/java/com/metamatrix/common/classloader/
branches/JCA/common-core/src/main/java/com/metamatrix/common/jdbc/
branches/JCA/common-core/src/main/java/com/metamatrix/common/protocol/MMURLConnection.java
branches/JCA/common-core/src/main/java/com/metamatrix/common/protocol/MetaMatrixURLStreamHandlerFactory.java
branches/JCA/common-core/src/main/java/com/metamatrix/common/protocol/URLHelper.java
branches/JCA/common-core/src/main/java/com/metamatrix/common/protocol/classpath/
branches/JCA/common-core/src/main/java/com/metamatrix/common/protocol/jar/
branches/JCA/common-core/src/main/java/com/metamatrix/common/protocol/mmfile/
branches/JCA/common-core/src/main/java/com/metamatrix/common/protocol/mmrofile/
branches/JCA/common-core/src/main/java/com/metamatrix/common/util/ByteArrayHelper.java
branches/JCA/common-core/src/main/java/com/metamatrix/common/util/WSDLServletUtil.java
branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/CryptoUtil.java
branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/Decryptor.java
branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/Encryptor.java
branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/PasswordChangeUtility.java
branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/cipher/BasicCryptor.java
branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/cipher/SymmetricCryptor.java
branches/JCA/common-core/src/main/java/com/metamatrix/core/io/
branches/JCA/common-core/src/main/java/com/metamatrix/core/util/DateUtil.java
branches/JCA/common-core/src/main/java/com/metamatrix/core/util/StringUtilities.java
branches/JCA/common-core/src/main/java/com/metamatrix/core/util/ZipFileUtil.java
branches/JCA/common-core/src/main/java/com/metamatrix/core/vdb/VDBStatus.java
branches/JCA/common-core/src/test/java/com/metamatrix/common/classloader/
branches/JCA/common-core/src/test/java/com/metamatrix/common/jdbc/
branches/JCA/common-core/src/test/java/com/metamatrix/common/protocol/
branches/JCA/common-core/src/test/java/com/metamatrix/common/util/TestByteArrayHelper.java
branches/JCA/common-core/src/test/java/com/metamatrix/common/util/crypto/TestPasswordChangeUtility.java
branches/JCA/common-core/src/test/java/com/metamatrix/core/util/TestStringUtilities.java
branches/JCA/common-core/src/test/java/com/metamatrix/core/util/TestZipFileUtil.java
Modified:
branches/JCA/common-core/src/main/java/com/metamatrix/common/util/ApplicationInfo.java
branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/Cryptor.java
branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/DhKeyGenerator.java
branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/NullCryptor.java
branches/JCA/common-core/src/main/java/com/metamatrix/core/util/StringUtil.java
branches/JCA/common-core/src/main/java/com/metamatrix/core/vdb/VdbConstants.java
branches/JCA/common-core/src/test/java/com/metamatrix/api/exception/TestExceptionHolder.java
branches/JCA/common-core/src/test/java/com/metamatrix/common/util/crypto/TestDhKeyGenerator.java
branches/JCA/common-core/src/test/java/com/metamatrix/common/util/crypto/TestEncryptDecrypt.java
branches/JCA/connector-sdk/src/main/java/com/metamatrix/core/commandshell/Command.java
branches/JCA/connector-sdk/src/main/java/com/metamatrix/core/commandshell/ScriptReader.java
branches/JCA/connector-sdk/src/test/java/com/metamatrix/core/commandshell/TestShell.java
branches/JCA/engine/src/main/java/com/metamatrix/common/buffer/impl/MemoryStorageManager.java
branches/JCA/engine/src/test/java/com/metamatrix/query/analysis/TestAnalysisRecord.java
branches/JCA/engine/src/test/java/com/metamatrix/query/processor/proc/TestProcedureProcessor.java
branches/JCA/test-integration/common/src/test/java/com/metamatrix/cdk/TestConnectorShell.java
Log:
TEIID-833 cleaning common-core
Deleted: branches/JCA/common-core/src/main/java/com/metamatrix/common/protocol/MMURLConnection.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/common/protocol/MMURLConnection.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/common/protocol/MMURLConnection.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -1,77 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.common.protocol;
-
-import java.net.URL;
-import java.net.URLConnection;
-import java.util.Properties;
-import java.util.StringTokenizer;
-
-
-
-/**
- * Base URL Connection Class
- * @since 4.4
- */
-public abstract class MMURLConnection extends URLConnection {
- protected static final String READ = "read"; //$NON-NLS-1$
- protected static final String WRITE = "write"; //$NON-NLS-1$
- protected static final String LIST = "list"; //$NON-NLS-1$
- protected static final String DELETE = "delete"; //$NON-NLS-1$
-
- public static final String FILE_LIST_SORT = "sort"; //$NON-NLS-1$
- public static final String DATE = "date"; //$NON-NLS-1$
- public static final String ALPHA = "alpha"; //$NON-NLS-1$
- public static final String REVERSEALPHA = "reversealpha"; //$NON-NLS-1$
-
-
- protected String action = READ;
- protected Properties props = null;
-
- public MMURLConnection(URL url) {
- super(url);
-
- // If the URL has any query part parse it and handle it.
- String query = url.getQuery();
- if (query != null) {
- StringTokenizer st = new StringTokenizer(query, "&"); //$NON-NLS-1$
- while (st.hasMoreTokens()) {
- String option = st.nextToken();
- int index = option.indexOf('=');
- if (index != -1) {
- String task = option.substring(0, index);
- String value = option.substring(index+1);
- if (task.equals("action")) { //$NON-NLS-1$
- action = value;
- }
- else {
- if (props == null) {
- props = new Properties();
- }
- props.setProperty(task, value);
- }
- }
- }
- }
- }
-}
Deleted: branches/JCA/common-core/src/main/java/com/metamatrix/common/protocol/MetaMatrixURLStreamHandlerFactory.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/common/protocol/MetaMatrixURLStreamHandlerFactory.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/common/protocol/MetaMatrixURLStreamHandlerFactory.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -1,65 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package com.metamatrix.common.protocol;
-
-import java.net.URLStreamHandler;
-import java.net.URLStreamHandlerFactory;
-
-import com.metamatrix.common.protocol.classpath.ClasspathURLConnection;
-import com.metamatrix.common.protocol.jar.JarURLConnection;
-import com.metamatrix.common.protocol.mmfile.MMFileURLConnection;
-import com.metamatrix.common.protocol.mmrofile.MMROFileURLConnection;
-
-
-/**
- * A facory class for registering the "classpath:" and "mmfile:" protocol based URL.
- * since we can not register in app servers currently this only used for testing.
- * @since 4.4
- */
-public class MetaMatrixURLStreamHandlerFactory implements URLStreamHandlerFactory {
- private static final String DEFAULT_HANDLER_PKG = "sun.net.www.protocol"; //$NON-NLS-1$
-
- public URLStreamHandler createURLStreamHandler(String protocol) {
- if (protocol.equals(ClasspathURLConnection.PROTOCOL)) {
- return new com.metamatrix.common.protocol.classpath.Handler();
- }
- else if (protocol.equals(MMFileURLConnection.PROTOCOL)) {
- return new com.metamatrix.common.protocol.mmfile.Handler();
- }
- else if (protocol.equals(MMROFileURLConnection.PROTOCOL)) {
- return new com.metamatrix.common.protocol.mmrofile.Handler();
- }
- else if (protocol.equals(JarURLConnection.PROTOCOL)) {
- return new com.metamatrix.common.protocol.jar.Handler();
- }
- else {
- String handlerName = DEFAULT_HANDLER_PKG+"."+protocol+".Handler"; //$NON-NLS-1$ //$NON-NLS-2$
- try {
- Class handlerClass = Class.forName(handlerName);
- return (URLStreamHandler)handlerClass.newInstance();
- } catch (Exception e) {
- // eat it and return null
- }
- }
- return null;
- }
-}
Deleted: branches/JCA/common-core/src/main/java/com/metamatrix/common/protocol/URLHelper.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/common/protocol/URLHelper.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/common/protocol/URLHelper.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -1,392 +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.protocol;
-
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.net.Authenticator;
-import java.net.MalformedURLException;
-import java.net.PasswordAuthentication;
-import java.net.URL;
-import java.net.URLConnection;
-
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.SSLSession;
-
-import com.metamatrix.common.protocol.classpath.ClasspathURLConnection;
-import com.metamatrix.common.protocol.mmfile.MMFileURLConnection;
-import com.metamatrix.common.protocol.mmrofile.MMROFileURLConnection;
-import com.metamatrix.core.io.FileUrl;
-
-/**
- * Helper class to build the URL objects from the strings. Since as an
- * application we do not know if we are embedded or we are in our own server, we
- * can not install the "URLStreamHandlers" in the VM, as they can be only
- * installed once per VM, as an alternative, the stream handler must be
- * specified at the time URL it is constructed. This class will help us to this
- * code at one place.
- *
- * Here inspect the given string and build the correct type of URL with correct
- * handler.
- *
- * @since 4.4
- */
-public class URLHelper {
- private static final String SEPARATOR = ":"; //$NON-NLS-1$
-
- static {
- // Very important that this property is set, so that loading of
- // custom extension module URLHandlers will work
-
- String propKey = "java.protocol.handler.pkgs"; //$NON-NLS-1$
- String directory = "com.metamatrix.common.protocol"; //$NON-NLS-1$
-
- String value = System.getProperty(propKey);
- if (value == null || value.trim().length() == 0) {
- System.setProperty(propKey, directory);
- } else if (value.indexOf(directory) < 0) {
- value = value + "|" + directory; //$NON-NLS-1$
- System.setProperty(propKey, value);
- }
- }
-
- /**
- * Construct the URL based on the String
- *
- * @param url
- * @return
- * @throws MalformedURLException
- * @since 4.4
- */
- public static URL buildURL(String url) throws MalformedURLException {
-
- if (url == null) {
- throw new MalformedURLException();
- }
-
- url = convertBackSlashes(url);
-
- if (url.startsWith(ClasspathURLConnection.PROTOCOL + SEPARATOR)) {
- String filename = url.substring((ClasspathURLConnection.PROTOCOL + SEPARATOR).length());
- return new URL(ClasspathURLConnection.PROTOCOL,"", -1, filename, new com.metamatrix.common.protocol.classpath.Handler()); //$NON-NLS-1$
- } else if (url.startsWith(MMFileURLConnection.PROTOCOL + SEPARATOR)) {
- String filename = url.substring((MMFileURLConnection.PROTOCOL + SEPARATOR).length());
- return new URL(MMFileURLConnection.PROTOCOL,"", -1, filename, new com.metamatrix.common.protocol.mmfile.Handler()); //$NON-NLS-1$
- } else if (url.startsWith(MMROFileURLConnection.PROTOCOL + SEPARATOR)) {
- String filename = url.substring((MMROFileURLConnection.PROTOCOL + SEPARATOR).length());
- return new URL(MMROFileURLConnection.PROTOCOL,"", -1, filename, new com.metamatrix.common.protocol.mmrofile.Handler()); //$NON-NLS-1$
- }
- else if (isFile(url)) {
- String filename = extractFileName(url);
- return new URL(MMFileURLConnection.PROTOCOL,"", -1, filename, new com.metamatrix.common.protocol.mmfile.Handler()); //$NON-NLS-1$
- }
- return new URL(url);
- }
-
- public static URL buildURL(URL context, String url)
- throws MalformedURLException {
-
- if (url == null) {
- throw new MalformedURLException();
- }
-
- if (context == null) {
- return buildURL(url);
- }
-
- url = convertBackSlashes(url);
-
- if (url.startsWith(ClasspathURLConnection.PROTOCOL + SEPARATOR)) {
- String filename = url.substring((ClasspathURLConnection.PROTOCOL + SEPARATOR).length());
- return new URL(ClasspathURLConnection.PROTOCOL,"", -1, filename, new com.metamatrix.common.protocol.classpath.Handler()); //$NON-NLS-1$
- } else if (url.startsWith(MMFileURLConnection.PROTOCOL + SEPARATOR)) {
- String filename = url.substring((MMFileURLConnection.PROTOCOL + SEPARATOR).length());
- return new URL(MMFileURLConnection.PROTOCOL,"", -1, filename, new com.metamatrix.common.protocol.mmfile.Handler()); //$NON-NLS-1$
- } else if (url.startsWith(MMROFileURLConnection.PROTOCOL + SEPARATOR)) {
- String filename = url.substring((MMROFileURLConnection.PROTOCOL + SEPARATOR).length());
- return new URL(MMROFileURLConnection.PROTOCOL,"", -1, filename, new com.metamatrix.common.protocol.mmrofile.Handler()); //$NON-NLS-1$
- } else if (isFile(url)) {
- String filename = extractFileName(url);
- String contextURL = context.toString();
-
- if (contextURL.startsWith(ClasspathURLConnection.PROTOCOL+ SEPARATOR)) {
- return new URL(context, filename,new com.metamatrix.common.protocol.classpath.Handler());
- } else if (contextURL.startsWith(MMFileURLConnection.PROTOCOL+ SEPARATOR)) {
- return new URL(context, filename,new com.metamatrix.common.protocol.mmfile.Handler());
- } else if (contextURL.startsWith(MMROFileURLConnection.PROTOCOL+ SEPARATOR)) {
- return new URL(URLHelper.buildURL(context.getPath()), filename,new com.metamatrix.common.protocol.mmfile.Handler());
- }
- }
- return new URL(context, url);
-
- }
-
- public static URL buildURL(URL url) {
- try {
- return buildURL(url.toExternalForm());
- } catch (MalformedURLException e) {
- // since it came as url it should not have any issues with this
- }
- return null;
- }
-
- /**
- * Determines whether a URL object resolves to a valid url. This will work
- * for any protocol (file, HTTP, etc.).
- *
- * @param url
- * @param userName
- * @param password
- * @param verifyHostname whether to verify hostname for HTTPS connection
- * @return resolved boolean
- * @throws MalformedURLException, IOException
- * @since 5.1
- */
- public static boolean resolveUrl(final URL url, final String userName, final String password, boolean verifyHostname) throws MalformedURLException, IOException{
- if(userName != null && userName.length() != 0 && password != null) {
- Authenticator.setDefault( new Authenticator() {
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(userName, password.toCharArray());
- }
- });
- }
- return resolveUrl(url, verifyHostname);
- }
-
- /**
- * Determines whether a URL object resolves to a valid url. This will work
- * for any protocol (file, HTTP, etc.).
- *
- * @param url
- * @return resolved boolean
- * @throws MalformedURLException, IOException
- * @since 5.1
- */
- public static boolean resolveUrl(final URL url) throws MalformedURLException, IOException{
- return resolveUrl(url, true);
- }
-
- /**
- * Determines whether a URL object resolves to a valid url. This will work
- * for any protocol (file, HTTP, etc.).
- *
- * @param url
- * @param verifyHostname whether to verify hostname for HTTPS connection
- * @return resolved boolean
- * @throws MalformedURLException, IOException
- * @since 5.5
- */
- public static boolean resolveUrl(final URL url, boolean verifyHostname) throws MalformedURLException, IOException{
- boolean resolved = true;
- if (url==null){
- return resolved;
- }
- String nextLine;
- URLConnection urlConn = null;
- InputStreamReader inStream = null;
- BufferedReader buff = null;
- // Add a time-out here....
- long timeOut = 30000;
-
- long startTime = System.currentTimeMillis();
- long deltaTime = 0;
- try {
- urlConn = url.openConnection();
- if(!verifyHostname && urlConn instanceof HttpsURLConnection) {
- ((HttpsURLConnection)urlConn).setHostnameVerifier(new HostnameVerifier() {
- public boolean verify(String arg, SSLSession session) {
- return true;
- }
- });
- }
- inStream = new InputStreamReader(urlConn.getInputStream());
- buff = new BufferedReader(inStream);
- boolean keepReading = true;
- // Read and print the lines from index.html
- while (keepReading ) {
- nextLine = buff.readLine();
- if (nextLine != null) {
-
- } else {
- break;
- }
- deltaTime = System.currentTimeMillis() - startTime;
- if( deltaTime > timeOut ) {
- keepReading = false;
- resolved = false;
- }
- }
- } finally {
- if (inStream != null){
- inStream.close();
- }
- }
-
- return resolved;
- }
-
- /**
- * Download the content from the given URL and save it into the specified file.
- * @param url URL of the file to be saved
- * @param filePath the full path of the file name
- * @param userName user name if authentication is required
- * @param password password if authentication is required
- * @param verifyHostname whether to verify hostname for HTTPS connection
- * @return the file created
- * @throws MalformedURLException
- * @throws IOException
- * @since 5.5
- */
- public static File createFileFromUrl(final URL url,
- final String filePath, final String userName, final String password, boolean verifyHostname) throws MalformedURLException, IOException{
- if(userName != null && userName.length() != 0 && password != null) {
- Authenticator.setDefault( new Authenticator() {
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(userName, password.toCharArray());
- }
- });
- }
- File file = null;
- String tempDir = System.getProperty("java.io.tmpdir");//$NON-NLS-1$
- if(filePath.indexOf("/") != -1 || filePath.indexOf("\\") != -1 ) {//$NON-NLS-1$//$NON-NLS-2$
-
- int lastPart = filePath.lastIndexOf("/");//$NON-NLS-1$
- if(lastPart == -1) {
- lastPart = filePath.lastIndexOf("\\");//$NON-NLS-1$
- }
- String relativeDir = filePath.substring(0, lastPart);
- File dir = new File(new File(tempDir), relativeDir);
- if(!dir.exists()) {
- dir.mkdirs();
- }
- file = new File(dir, filePath.substring(lastPart + 1));
- }else{
- file = new File(new File(tempDir), filePath);
- }
- return createFileFromUrlInternal(url, new FileUrl(file.toURI()), verifyHostname);
- }
-
- /**
- * Build a {@link java.io.File} from a {@link java.net.URL} object.
- *
- * @param url
- * @param fileNamePrefix
- * @param fileNameSuffix
- * @return File
- * @since 5.1
- */
- public static File createFileFromUrl(final URL url,
- final String fileNamePrefix,
- final String fileNameSuffix) throws MalformedURLException, IOException{
-
- return createFileFromUrlInternal(url, FileUrl.createTempFile(fileNamePrefix,fileNameSuffix), true);
- }
-
- private static File createFileFromUrlInternal(final URL url, final File file, boolean verifyHostname) throws MalformedURLException, IOException{
- String nextLine;
- URLConnection urlConn = null;
- InputStreamReader inStream = null;
- BufferedReader buff = null;
- FileWriter fw = null;
- BufferedWriter bw = null;
- try {
- file.deleteOnExit();
- ((FileUrl)file).setOriginalUrlString(url.toString());
- fw = new FileWriter(file);
- bw = new BufferedWriter(fw);
- urlConn = url.openConnection();
- if(!verifyHostname && urlConn instanceof HttpsURLConnection) {
- ((HttpsURLConnection)urlConn).setHostnameVerifier(new HostnameVerifier() {
- public boolean verify(String arg, SSLSession session) {
- return true;
- }
- });
- }
- inStream = new InputStreamReader(urlConn.getInputStream());
- buff = new BufferedReader(inStream);
-
- // Read and print the lines from index.html
- while (true) {
- nextLine = buff.readLine();
- if (nextLine != null) {
- bw.write(nextLine);
- } else {
- break;
- }
- }
- } finally {
- if (inStream!=null){
- inStream.close();
- }
- if (bw!=null){
- bw.close();
- }
- }
-
- return file;
- }
-
- static boolean isFile(String file) {
- return extractFileName(file) != null;
- }
-
- static String extractFileName(String file) {
-
- if (file.matches("^(\\w){2,}:.*")) { //$NON-NLS-1$
- // Handles URLs - No conversion nessasary
- // http://lib/foo.txt - currently do not support, converts to local
- // host with absolute path
- // file://lib/foo.txt
- // file:///c:/lib/foo.txt
- return null;
- } else if (file.matches("^\\/.*")) { //$NON-NLS-1$
- // Handles absolute paths- it can be file or URL depending upon
- // context Conversion needed
- // /lib/foo.txt
- return file;
- } else if (file.matches("^\\w:[\\\\,\\/].*")) { //$NON-NLS-1$
- // Handles windows absolute path - no conversion needed
- // c:\\lib\\foo.txt
- // c:/lib.foo.txt
- file = file.replaceAll("\\\\", "\\/"); //$NON-NLS-1$ //$NON-NLS-2$
- return "/" + file; //$NON-NLS-1$
- } else if (file.matches("^(\\.)+\\/.*|^\\w+\\/.*|^\\w+.*")) { //$NON-NLS-1$
- // Handles relative paths - these can be urls or files - conversion
- // nessasary
- // ./lib/foo.txt
- // ../lib/foo.txt
- // lib/foo.txt
- return file;
- }
- return null;
- }
-
- static String convertBackSlashes(String str) {
- return str.replaceAll("\\\\", "/"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-}
Modified: branches/JCA/common-core/src/main/java/com/metamatrix/common/util/ApplicationInfo.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/common/util/ApplicationInfo.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/common/util/ApplicationInfo.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -27,7 +27,9 @@
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
+import java.text.DateFormat;
import java.util.ArrayList;
+import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
@@ -37,7 +39,7 @@
import java.util.StringTokenizer;
import com.metamatrix.core.MetaMatrixRuntimeException;
-import com.metamatrix.core.util.DateUtil;
+import com.metamatrix.core.util.ObjectConverterUtil;
public final class ApplicationInfo implements Serializable {
@@ -123,7 +125,7 @@
String classPath = getClassPath();
StringBuffer sb = new StringBuffer();
- sb.append("\nDate: " + DateUtil.getCurrentDateAsString());//$NON-NLS-1$
+ sb.append("\nDate: " + DateFormat.getDateInstance().format(new Date()));//$NON-NLS-1$
sb.append( LINE_SEPARATOR );
Map pathResults = new HashMap();
@@ -187,7 +189,7 @@
sb.append("Patch " + url.getFile() + ":"); //$NON-NLS-1$ //$NON-NLS-2$
sb.append( LINE_SEPARATOR );
InputStream is = url.openStream();
- byte[] data = ByteArrayHelper.toByteArray(is);
+ byte[] data = ObjectConverterUtil.convertToByteArray(is);
sb.append(new String(data));
sb.append("-------------------------------------");//$NON-NLS-1$
sb.append( LINE_SEPARATOR );
Deleted: branches/JCA/common-core/src/main/java/com/metamatrix/common/util/ByteArrayHelper.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/common/util/ByteArrayHelper.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/common/util/ByteArrayHelper.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -1,179 +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.util;
-
-import java.io.BufferedInputStream;
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Iterator;
-
-public class ByteArrayHelper {
-
- /**
- * <p>The default size of each temporary byte array that is instantiated
- * to buffer data from an InputStream, in the
- * {@link #toByteArray(InputStream)}method.</p>
- *
- * <p>Ideally, this number
- * should be big enough that only one byte array is needed, but
- * small enough that wasted memory isn't allocated. If the first
- * temp array is filled, then a second one of this size will be
- * created, and so on until all of the stream is read.</p>
- */
- public static final int CHUNK_SIZE = 32000;
-
- /**
- * <p>Reads data from the file and returns it as a
- * byte array. The returned byte array is exactly filled with the data from the
- * InputStream, with no space left over.</p>
- *
- * @param file data to be converted to a byte array
- * @return byte array exactly filled with data; no leftover space
- * @throws IOException if there is an Exception reading from the InputStream
- */
- public static byte[] toByteArray(File file) throws IOException {
-
- FileInputStream fis = null;
- try {
- fis = new FileInputStream(file);
- return ByteArrayHelper.toByteArray(fis);
- } finally {
- if (fis != null) {
- fis.close();
- }
- }
- }
- /**
- * <p>Reads binary data from the InputStream and returns it as a
- * byte array. The InputStream is not closed in this method.
- * The returned byte array is exactly filled with the data from the
- * InputStream, with no space left over.</p>
- *
- * <p>If the amount of data in the input stream is known, use
- * {@link #toByteArray(InputStream, int) toByteArray(InputStream, int)}.
- * </p>
- * @param stream data to be converted to a byte array
- * @return byte array exactly filled with data; no leftover space
- * @throws IOException if there is an Exception reading from the InputStream
- */
- public static byte[] toByteArray(InputStream stream) throws IOException {
- return toByteArray(stream, CHUNK_SIZE);
- }
-
- /**
- * <p>Reads binary data from the InputStream and returns it as a
- * byte array. The InputStream is not closed in this method.
- * The returned byte array is exactly filled with the data from the
- * InputStream, with no space left over.</p>
- *
- * <p>The chunkSize parameter controls the size of intermediate
- * byte array(s) that are used to buffer the stream data.
- * Ideally, this number
- * should be big enough that only one byte array is needed, but
- * small enough that wasted memory isn't allocated. If the first
- * temp array is filled, then a second one of this size will be
- * created, and so on until all of the stream is read. Then, data
- * will be copied into the final, correctly-size byte array which is
- * returned form this method.</p>
- *
- * <p>If the size of the input stream is known beforehand (for example,
- * if the size of a file represented by a FileInputStream is known), then
- * that size <i>plus one</i> should be passed in as the chunkSize.</p>
- *
- * <p>Implementation notes: If more than one intermediate byte array
- * is needed, an ArrayList is instantiated to hold the intermediate byte
- * arrays until all data is read from the stream. Afterward, the
- * ArrayList is iterated through; the intermediate array(s) are
- * copied using System.arrayCopy into the final byte array.</p>
- *
- * @param stream data to be converted to a byte array
- * @param chunkSize size of intermediate byte array(s) to buffer data
- * @return byte array exactly filled with data; no leftover space
- * @throws IOException if there is an Exception reading from the InputStream
- */
- public static byte[] toByteArray(InputStream stream, int chunkSize) throws IOException {
-
- byte[] data = null;
- ArrayList dataArrays = null;
-
- //intermediate byte array(s) reference
- data= new byte[chunkSize];
-
- int pos= 0;
- int finalSize = 0;
- while (stream.available() > 0 ) {
- int n= stream.read(data, pos, data.length - pos);
- if (n>=0){ //n could equal -1 for some streams, indicating EOF
- pos += n;
- }
-
- if (data.length - pos == 0 ){
- if ( dataArrays == null){
- dataArrays = new ArrayList();
- }
- dataArrays.add(data);
- data= new byte[chunkSize];
- pos = 0;
- finalSize = finalSize + chunkSize;
- }
-
- }
-
- finalSize = finalSize + pos;
- //final, correctly-sized byte array
- byte[] result = new byte[finalSize];
- int offSet = 0;
-
- if (dataArrays != null){
- Iterator i = dataArrays.iterator();
- byte[] tempArray = null;
- for (; i.hasNext(); offSet=offSet+chunkSize){
- tempArray = (byte[])i.next();
- System.arraycopy(tempArray,0,result,offSet,chunkSize);
- }
- }
-
- System.arraycopy(data,0,result,offSet,pos);
-
- return result;
- }
-
-
- /**
- * converts the byte array to an input stream
- */
- public static InputStream toInputStream(byte[] data) throws Exception {
- ByteArrayInputStream bais = new ByteArrayInputStream(data);
- InputStream isContent = new BufferedInputStream(bais);
-
- return isContent;
-
-
-
- }
-
-}
Deleted: branches/JCA/common-core/src/main/java/com/metamatrix/common/util/WSDLServletUtil.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/common/util/WSDLServletUtil.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/common/util/WSDLServletUtil.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -1,225 +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.util;
-
-import java.io.UnsupportedEncodingException;
-import java.net.URLEncoder;
-import java.text.MessageFormat;
-import java.util.Iterator;
-import java.util.List;
-
-/**
- * Constants pertaining to WSDL servlet execution.
- *
- * @since 4.2
- */
-
-public class WSDLServletUtil {
-
- /**
- * General keys
- */
- public static final String SERVER_URL_KEY = "ServerURL"; //$NON-NLS-1$
-
- public static final String SECURE_PROTOCOL = "Secure"; //$NON-NLS-1$
-
- public static final String VDB_NAME_KEY = "VDBName"; //$NON-NLS-1$
-
- public static final String VDB_VERSION_KEY = "VDBVersion"; //$NON-NLS-1$
-
- public static final String ADD_PROPS = "AdditionalProperties"; //$NON-NLS-1$
-
- public static final String TXN_AUTO_WRAP = "txnAutoWrap"; //$NON-NLS-1$
-
- public static final String ADD_EXEC_PROPS = "AddExecProperties"; //$NON-NLS-1$
-
- public static final String MM_WEBSERVICE_QUERY_TIMEOUT = "com.metamatrix.webservice.querytimeout"; //$NON-NLS-1$
-
- public static final String DISCOVERED_WSDL = "discovered_wsdl"; //$NON-NLS-1$
-
- /*
- * This is the parameter that will tell this servlet when the web service endpoint as defined in WSDL served up by this
- * servlet will use the HTTP vs HTTPS protocol.
- */
- public static final String HTTP_TYPE_PARAMETER_KEY = "httptype"; //$NON-NLS-1$
-
- /*
- * This is the value of the httptype URL request param that will indicate that the returned WSDL should have an http endpoint
- * instead of an https endpoint.
- */
- public static final String HTTP_PARAMETER_VALUE = "http"; //$NON-NLS-1$
-
- /*
- * Static contant representing the standard http protocol.
- */
- public static final String HTTP = "http"; //$NON-NLS-1$
-
- /**
- * Static contant representing the secure http protocol.
- */
- public static final String HTTPS = "https"; //$NON-NLS-1$
-
- /**
- * Default content type for the VDBResourceServlet
- */
- public static final String DEFAULT_CONTENT_TYPE = "text/html"; //$NON-NLS-1$
-
- /**
- * XML content type for the VDBResourceServlet
- */
- public static final String XML_CONTENT_TYPE = "text/xml"; //$NON-NLS-1$
-
- /**
- * WSDL URL Generator keys
- */
- public static final String MMSERVER_HOST_PORT_KEY = "MMServerHostAndPort"; //$NON-NLS-1$
-
- public static final String TARGET_HOST_KEY = "TargetHost"; //$NON-NLS-1$
-
- public static final String TARGET_PORT_KEY = "TargetPort"; //$NON-NLS-1$
-
- public static final String SERVLET_PATH = "/servlet/ArtifactDocumentService"; //$NON-NLS-1$
-
- public static final String SQLQUERYWEBSERVICE_WSDL_PATH = "/services/SqlQueryWebService?wsdl"; //$NON-NLS-1$
-
- public static final String GENERATED_WSDL_NAME = "MetaMatrixDataServices"; //$NON-NLS-1$
-
- public static final String GENERATED_WSDL_FILENAME = GENERATED_WSDL_NAME + ".wsdl"; //$NON-NLS-1$
-
- public static final String COLON = ":"; //$NON-NLS-1$
-
- public static final String SLASH = "/"; //$NON-NLS-1$
-
- public static final String DOUBLE_SLASH = "//"; //$NON-NLS-1$
-
- public static final String AMP = "&"; //$NON-NLS-1$
-
- public static final String QUESTION_MARK = "?"; //$NON-NLS-1$
-
- public static final String EQUALS = "="; //$NON-NLS-1$
-
- public static final String COMMA = ","; //$NON-NLS-1$
-
- private static final String SQLQUERYWEBSERVICE_URL_FORMAT = "{0}://{1}:{2}/{3}"; //$NON-NLS-1$
-
- /*
- * this default value is based on Tomcat's default value in its server.xml file. This value can be overridden by setting the
- * com.metamatrix.webservice.dataservice.httpsport System property for the VM that this servlet is running in.
- */
- private static final String DEFAULT_HTTPS_PORT = "8443"; //$NON-NLS-1$
-
- private static final String DEFAULT_HTTP_PORT = "8080"; //$NON-NLS-1$
-
- private static final String HTTPS_PORT_PROPERTY_KEY = "com.metamatrix.webservice.dataservice.httpsport"; //$NON-NLS-1$
-
- private static final String HTTP_PORT_PROPERTY_KEY = "com.metamatrix.webservice.dataservice.httpport"; //$NON-NLS-1$
-
- /**
- * Returns the formatted url from the supplied info
- *
- * @param scheme the server scheme
- * @param host the server host name
- * @param port the server port
- * @param appContext the context of this application to use in the WSDL url
- * @param serverURLs the list of server url info, first url is full url including protocol. Subsequent items are just the
- * host:port strings.
- * @param vdbName the vdb name
- * @param vdbVersion the vdb version number
- */
- public static String formatURL( String scheme,
- String host,
- String port,
- String appContext,
- List serverURLs,
- String vdbName,
- String vdbVersion ) {
-
- StringBuffer result = new StringBuffer();
- try {
- boolean hasPort = true;
- boolean hasVDBVersion = true;
-
- if (port == null || port.length() == 0) {
- hasPort = false;
- }
-
- if (vdbVersion == null || vdbVersion.trim().length() == 0) {
- hasVDBVersion = false;
- }
-
- result.append(scheme).append(COLON).append(DOUBLE_SLASH).append(host);
-
- if (hasPort) {
- result.append(COLON).append(port);
- }
-
- result.append(appContext).append(SERVLET_PATH).append(SLASH).append(GENERATED_WSDL_FILENAME);
- result.append(QUESTION_MARK).append(SERVER_URL_KEY).append(EQUALS);
- // Append comma-delimited server urls
- Iterator iter = serverURLs.iterator();
- while (iter.hasNext()) {
- String serverURL = (String)iter.next();
- result.append(serverURL);
- // If there is another url coming, add an encoded comma
- if (iter.hasNext()) {
- result.append(URLEncoder.encode(COMMA, "UTF-8")); //$NON-NLS-1$
- }
- }
- result.append(AMP).append(VDB_NAME_KEY).append(EQUALS).append(vdbName);
- if (hasVDBVersion) {
- result.append(AMP).append(VDB_VERSION_KEY).append(EQUALS).append(vdbVersion);
- }
-
- } catch (UnsupportedEncodingException err) {
- // ignore
- }
-
- return result.toString();
- }
-
- /**
- * Returns the formatted wsdl url for the SqlQueryWebService
- *
- * @param server - server name
- * @param appContext the context of this application to use in the WSDL url
- * @param secure - secure ssl (true) or non-secure (false)
- * @return wsdlUrl - String
- * @since 4.3
- */
- public static String getSqlQueryWebServiceUrl( final String server,
- String appContext,
- final boolean secure ) {
-
- appContext=appContext.replace("/",""); //$NON-NLS-1$ //$NON-NLS-2$
- return MessageFormat.format(SQLQUERYWEBSERVICE_URL_FORMAT, new Object[] {secure ? HTTPS : HTTP, server,
- secure ? getHttpsPort() : getHttpPort(), appContext+SQLQUERYWEBSERVICE_WSDL_PATH});
- }
-
- public static final String getHttpsPort() {
- return System.getProperty(HTTPS_PORT_PROPERTY_KEY, DEFAULT_HTTPS_PORT);
- }
-
- public static final String getHttpPort() {
- return System.getProperty(HTTP_PORT_PROPERTY_KEY, DEFAULT_HTTP_PORT);
- }
-}
Added: branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/BasicCryptor.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/BasicCryptor.java (rev 0)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/BasicCryptor.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -0,0 +1,220 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package com.metamatrix.common.util.crypto;
+
+import java.io.Serializable;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.NoSuchAlgorithmException;
+
+import javax.crypto.Cipher;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.SealedObject;
+
+import com.metamatrix.core.CorePlugin;
+import com.metamatrix.core.ErrorMessageKeys;
+import com.metamatrix.core.util.Base64;
+
+/**
+ * <p>Public methods in this class throw only <code>CryptoException</code>s. </p>
+ */
+public class BasicCryptor implements Cryptor {
+
+ /** The key to be used for decryption. */
+ protected Key decryptKey;
+ /** The <code>Cipher</code> to use for decryption. */
+ private Cipher decryptCipher;
+ /** The key to be used for encryption. */
+ private Key encryptKey;
+ /** The <code>Cipher</code> to use for encryption. */
+ protected Cipher encryptCipher;
+ protected String cipherAlgorithm;
+ public static final String OLD_ENCRYPT_PREFIX = "{mm-encrypt}"; //$NON-NLS-1$
+ public static final String ENCRYPT_PREFIX = "{teiid-encrypt}"; //$NON-NLS-1$
+
+ public BasicCryptor( Key encryptKey, Key decryptKey, String algorithm) throws CryptoException {
+ this.encryptKey = encryptKey;
+ this.cipherAlgorithm = algorithm;
+ this.decryptKey = decryptKey;
+
+ initEncryptCipher();
+ initDecryptCipher();
+ }
+
+ /**
+ * Decrypt the ciphertext to yield the original cleartext.
+ * @param ciphertext The text to be encrypted, in byte form
+ * @param The decrypted cleartext, in byte form
+ */
+ public synchronized byte[] decrypt( byte[] ciphertext ) throws CryptoException {
+ try {
+ return decryptCipher.doFinal(ciphertext);
+ } catch ( Exception e ) {
+ try {
+ initDecryptCipher();
+ } catch (CryptoException err) {
+ //shouldn't happen
+ }
+ throw new CryptoException( ErrorMessageKeys.CM_UTIL_ERR_0071, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0071, e.getClass().getName(), e.getMessage()));
+ }
+ }
+
+ public String decrypt( String ciphertext ) throws CryptoException {
+ if ( ciphertext == null ) {
+ throw new CryptoException( ErrorMessageKeys.CM_UTIL_ERR_0074, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0074));
+ }
+
+ ciphertext = stripEncryptionPrefix(ciphertext);
+
+ // Decode the previously encoded text into bytes...
+ byte[] cipherBytes = null;
+ try {
+ cipherBytes = Base64.decode(ciphertext);
+ } catch ( IllegalArgumentException e ) {
+ throw new CryptoException( ErrorMessageKeys.CM_UTIL_ERR_0075, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0075, e.getMessage()));
+ }
+ // Perform standard decryption
+ byte[] cleartext = decrypt( cipherBytes );
+ // Perform "standard" Java encoding and return the result
+ return new String(cleartext);
+ }
+
+ public static String stripEncryptionPrefix(String ciphertext) {
+ if (ciphertext.startsWith(BasicCryptor.ENCRYPT_PREFIX)) {
+ ciphertext = ciphertext.substring(BasicCryptor.ENCRYPT_PREFIX.length());
+ } else if (ciphertext.startsWith(BasicCryptor.OLD_ENCRYPT_PREFIX)) {
+ ciphertext = ciphertext.substring(BasicCryptor.OLD_ENCRYPT_PREFIX.length());
+ }
+ return ciphertext;
+ }
+
+ /**
+ * Initialize the ciphers used for encryption and decryption. The ciphers
+ * define the algorithms to be used. They are initialized with the
+ * appropriate key to be used in the encryption or decryption operation.
+ */
+ protected void initDecryptCipher() throws CryptoException {
+
+ // Create and initialize decryption cipher
+ try {
+ decryptCipher = Cipher.getInstance( cipherAlgorithm);
+ decryptCipher.init( Cipher.DECRYPT_MODE, decryptKey );
+ } catch ( NoSuchAlgorithmException e ) {
+ throw new CryptoException( e, ErrorMessageKeys.CM_UTIL_ERR_0076, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0076, cipherAlgorithm ));
+ } catch ( NoSuchPaddingException e ) {
+ throw new CryptoException( ErrorMessageKeys.CM_UTIL_ERR_0077, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0077, cipherAlgorithm, e.getClass().getName(), e.getMessage() ));
+ } catch ( InvalidKeyException e ) {
+ throw new CryptoException( e, ErrorMessageKeys.CM_UTIL_ERR_0079, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0079, e.getClass().getName(), e.getMessage()) );
+ }
+ }
+
+ public synchronized Serializable unsealObject(Serializable object) throws CryptoException {
+
+ if (!(object instanceof SealedObject)) {
+ return object;
+ }
+
+ SealedObject so = (SealedObject)object;
+
+ try {
+ return (Serializable)so.getObject(decryptCipher);
+ } catch ( Exception e ) {
+ try {
+ initDecryptCipher();
+ } catch (CryptoException err) {
+ //shouldn't happen
+ }
+ throw new CryptoException( ErrorMessageKeys.CM_UTIL_ERR_0071, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0071, e.getClass().getName(), e.getMessage()));
+ }
+ }
+
+ /**
+ * Encrypt the cleartext in byte array format.
+ * @param cleartext The text to be encrypted, in byte form
+ * @param The encrypted ciphertext, in byte form
+ */
+ public synchronized byte[] encrypt( byte[] cleartext ) throws CryptoException {
+ try {
+ return encryptCipher.doFinal(cleartext);
+ } catch ( Exception e ) {
+ try {
+ initEncryptCipher();
+ } catch (CryptoException err) {
+ //shouldn't happen
+ }
+ throw new CryptoException(ErrorMessageKeys.CM_UTIL_ERR_0081, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0081, e.getMessage()));
+ }
+ }
+
+ public String encrypt( String cleartext ) throws CryptoException {
+ if ( cleartext == null ) {
+ throw new CryptoException( ErrorMessageKeys.CM_UTIL_ERR_0072, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0072));
+ }
+ String clearString = new String(cleartext);
+ if ( clearString.trim().length() == 0 && clearString.length() == 0 ) {
+ throw new CryptoException( ErrorMessageKeys.CM_UTIL_ERR_0073, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0073));
+ }
+ // Turn char array into string and get its bytes using "standard" encoding
+ byte[] clearBytes = clearString.getBytes();
+ // Perform standard encryption
+ byte[] cipherBytes = encrypt( clearBytes );
+ // Perform specialized encoding now, and return result
+
+ String encoded = Base64.encodeBytes( cipherBytes );
+ return BasicCryptor.ENCRYPT_PREFIX + encoded;
+ }
+
+ /**
+ * Initialize the cipher used for encryption. The cipher defines the
+ * algorithm to be used. It is initialized with the appropriate key to
+ * be used in the encryption operation.
+ */
+ protected void initEncryptCipher() throws CryptoException {
+
+ // Create and initialize encryption cipher
+ try {
+ encryptCipher = Cipher.getInstance( cipherAlgorithm );
+ encryptCipher.init( Cipher.ENCRYPT_MODE, encryptKey );
+ } catch ( NoSuchAlgorithmException e ) {
+ throw new CryptoException( e, ErrorMessageKeys.CM_UTIL_ERR_0076, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0076, cipherAlgorithm ));
+ } catch ( NoSuchPaddingException e ) {
+ throw new CryptoException(e, ErrorMessageKeys.CM_UTIL_ERR_0072, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0077, cipherAlgorithm , e.getMessage() ));
+ } catch ( InvalidKeyException e ) {
+ throw new CryptoException( e, ErrorMessageKeys.CM_UTIL_ERR_0078, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0078, e.getMessage() ));
+ }
+ }
+
+ public synchronized Serializable sealObject(Serializable object) throws CryptoException {
+ try {
+ return new SealedObject(object, encryptCipher);
+ } catch ( Exception e ) {
+ try {
+ initEncryptCipher();
+ } catch (CryptoException err) {
+ //shouldn't happen
+ }
+ throw new CryptoException(ErrorMessageKeys.CM_UTIL_ERR_0081, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0081, e.getMessage()));
+ }
+ }
+
+} // END CLASS
Property changes on: branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/BasicCryptor.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Deleted: branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/CryptoUtil.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/CryptoUtil.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/CryptoUtil.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -1,419 +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.util.crypto;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.net.URL;
-import java.util.Enumeration;
-import java.util.Properties;
-
-import com.metamatrix.common.util.PropertiesUtils;
-import com.metamatrix.common.util.crypto.cipher.BasicCryptor;
-import com.metamatrix.common.util.crypto.cipher.SymmetricCryptor;
-import com.metamatrix.core.CorePlugin;
-import com.metamatrix.core.ErrorMessageKeys;
-import com.metamatrix.core.util.Base64;
-
-/**
- * Collection of Crypto utilities and helpers for use by the server and installers.
- *
- */
-public class CryptoUtil {
- /**
- * This property indicates the encryption provider, if set to none encryption is disabled.
- */
- public static final String ENCRYPTION_ENABLED = "teiid.encryption.enabled"; //$NON-NLS-1$
-
- /** The name of the key. */
- public static final String KEY_NAME = "teiid.keystore"; //$NON-NLS-1$
- public static final URL KEY = CryptoUtil.class.getResource("/" + KEY_NAME); //$NON-NLS-1$
- public static final String OLD_ENCRYPT_PREFIX = "{mm-encrypt}"; //$NON-NLS-1$
- public static final String ENCRYPT_PREFIX = "{teiid-encrypt}"; //$NON-NLS-1$
- // Empty provider means encryption should be disabled
- public static final String NONE = "none"; //$NON-NLS-1$
-
- private static boolean encryptionEnabled = PropertiesUtils.getBooleanProperty(System.getProperties(), ENCRYPTION_ENABLED, true);
-
- private static Cryptor CRYPTOR;
-
- public static boolean isEncryptionEnabled() {
- return encryptionEnabled;
- }
-
- /**
- * Encrypts given set of property values based on occurrence of the property name in
- * the <code>match</code> collection.
- * @param match A Set of property names that, if found in <code>props</code>
- * property names, will modify the associated value in <code>props</code>. <strong>
- * Note</strong>: This is a <i><b>case insensitive</b></i> match.
- * @param props The properties whose values are to be modified in place.
- * @returns A copy of the <code>props</code> with values modified.
- * @throws CryptoException if there's an error with the <code>Cryptor</code>.
- */
- public static Properties propertyEncrypt(String match, Properties props)
- throws CryptoException {
- Cryptor theCryptor = CryptoUtil.getCryptor();
- Properties modifiedProps = new Properties();
-
- Enumeration propEnum = props.propertyNames();
-
- while (propEnum.hasMoreElements()) {
- String propName = (String) propEnum.nextElement();
- if (match.equalsIgnoreCase(propName)) {
- String propVal = props.getProperty(propName);
- if (propVal != null) {
- if (propVal.trim().length() > 0) {
- String cryptValue = theCryptor.encrypt(propVal);
- modifiedProps.setProperty(propName, cryptValue);
- } else {
- modifiedProps.setProperty(propName, propVal);
- }
- }
- } else {
- modifiedProps.setProperty(propName, props.getProperty(propName));
- }
- }
- return modifiedProps;
- }
-
- /**
- * Decrypts given set of property values based on occurrence of the property name in
- * the <code>match</code> collection.
- * @param match A Set of property names that, if found in <code>props</code>
- * property names, will modify the associated value in <code>props</code>. <strong>
- * Note</strong>: This is a <i><b>case insensitive</b></i> match.
- * @param props The properties whose values are to be modified in place.
- * @returns A copy of the <code>props</code> with values modified.
- * @throws CryptoException if there's an error with the <code>Cryptor</code>.
- */
- public static Properties propertyDecrypt(String match, Properties props)
- throws CryptoException {
- Cryptor theCryptor = CryptoUtil.getCryptor();
- Properties modifiedProps = new Properties();
-
- Enumeration propEnum = props.propertyNames();
-
- while (propEnum.hasMoreElements()) {
- String propName = (String) propEnum.nextElement();
- if (match.equalsIgnoreCase(propName)) {
- String propVal = props.getProperty(propName);
- if (propVal != null) {
- if (propVal.trim().length() > 0 && CryptoUtil.isValueEncrypted(propVal)) {
- String cryptValue = theCryptor.decrypt(propVal);
- modifiedProps.setProperty(propName, cryptValue);
-
- } else {
- modifiedProps.setProperty(propName, propVal);
- }
- }
-
- } else {
- modifiedProps.setProperty(propName, props.getProperty(propName));
- }
- }
- return modifiedProps;
- }
-
- /**
- * Encrypts given set of property values based on occurrence of the property name ending
- * in with the given pattern, using the server-side encryptor.
- * This method requires that the server keystore is available.
- * @param pattern A pattern that, if found at the end of a <code>props</code>
- * property name, will modify the associated value in <code>props</code>. <strong>
- * Note</strong>: This is a <i><b>case insensitive</b></i> match.
- * @param props The properties whose values are to be modified.
- * @returns A copy of the <code>props</code> with values modified.
- * @throws CryptoException if there's an error with the <code>Cryptor</code>.
- */
- public static Properties propertyEncryptEndsWith(String pattern, Properties props)
- throws CryptoException {
-
- return propertyEncryptEndsWith(CryptoUtil.getCryptor(), pattern, props);
- }
-
-
- /**
- * Encrypts given set of property values based on occurance of the property name ending
- * in with the given pattern, using the specified encryptor.
- * @param encryptor Encryptor to use.
- * @param pattern A pattern that, if found at the end of a <code>props</code>
- * property name, will modify the associated value in <code>props</code>. <strong>
- * Note</strong>: This is a <i><b>case insensitive</b></i> match.
- * @param props The properties whose values are to be modified.
- * @returns A copy of the <code>props</code> with values modified.
- * @throws CryptoException if there's an error with the <code>Cryptor</code>.
- */
- public static Properties propertyEncryptEndsWith(Encryptor encryptor, String pattern, Properties props)
- throws CryptoException {
- Properties modifiedProps = new Properties();
-
- Enumeration propEnum = props.propertyNames();
- pattern = pattern.toUpperCase();
- while (propEnum.hasMoreElements()) {
- String propName = (String) propEnum.nextElement();
- if (propName.toUpperCase().endsWith(pattern)) {
- String propVal = props.getProperty(propName);
- if (propVal != null) {
- if (propVal.trim().length() > 0) {
- String cryptValue = encryptor.encrypt(propVal);
- modifiedProps.setProperty(propName, cryptValue);
- } else {
- modifiedProps.setProperty(propName, propVal);
- }
- }
- } else {
- modifiedProps.setProperty(propName, props.getProperty(propName));
- }
- }
- return modifiedProps;
- }
-
- /**
- * Decrypts given set of property values based on occurance of the property name ending
- * in with the given pattern.
- * @param pattern A pattern that, if found at the end of a <code>props</code>
- * property name, will modify the associated value in <code>props</code>. <strong>
- * Note</strong>: This is a <i><b>case insensitive</b></i> match.
- * @param props The properties whose values are to be modified.
- * @returns A copy of the <code>props</code> with values modified.
- * @throws CryptoException if there's an error with the <code>Cryptor</code>.
- */
- public static Properties propertyDecryptEndsWith(String pattern, Properties props)
- throws CryptoException {
- Cryptor theCryptor = CryptoUtil.getCryptor();
- Properties modifiedProps = new Properties();
-
- Enumeration propEnum = props.propertyNames();
- pattern = pattern.toUpperCase();
- while (propEnum.hasMoreElements()) {
- String propName = (String) propEnum.nextElement();
- if (propName.toUpperCase().endsWith(pattern)) {
- String propVal = props.getProperty(propName);
- // don't try to decrypt a value that doesn't have length
- // an encrypted password would have some content
- if (propVal != null) {
- if (propVal.trim().length() > 0 && CryptoUtil.isValueEncrypted(propVal)) {
- String cryptValue = theCryptor.decrypt(propVal);
- modifiedProps.setProperty(propName, cryptValue);
- } else {
- modifiedProps.setProperty(propName, propVal);
- }
- }
- } else {
- modifiedProps.setProperty(propName, props.getProperty(propName));
- }
- }
- return modifiedProps;
- }
-
- public static boolean isValueEncrypted(String value) {
- if (value == null) {
- return false;
- }
- try {
- if (value.trim().length() == 0) {
- return false;
- }
- String strippedValue = BasicCryptor.stripEncryptionPrefix(value);
- if (strippedValue.length() != value.length()) {
- try {
- Base64.decode(strippedValue);
- } catch (IllegalArgumentException e) {
- return false;
- }
- //if we have the encrypt prefix and the rest of the string is base64 encoded, then
- //we'll assume that it's properly encrypted
- return true;
- }
- CryptoUtil.getDecryptor().decrypt(value);
- return true;
- } catch (CryptoException err) {
- return false;
- }
- }
-
- /**
- * <p>Initialize this factory, bound to a specific keystore and key
- * entry in that store.
- * <br>The keystore file name is well-known and must be in the applicaition's classpath.
- * The key entry name is well-known.
- * The keystore password is found in configuration.<\br></p>
- */
- private static synchronized void init()
- throws CryptoException {
-
- init(KEY);
- }
-
- /**
- * <p>Initialize this factory, bound to the given keystore and keystore password.
- * <br>This method <strong>will</strong> initialize the cryptor with the given
- * keystore and <strong>will not</strong> use the application classpath to find
- * the keystore to use.
- * The key entry name is well-known.
- * </br> </p>
- * @param storeFilename url to the keystore file.
- * @param storePass The password used to unlock the keystore.
- */
- public static synchronized void init(URL keyResource)
- throws CryptoException {
-
- if (CRYPTOR == null) {
- // If encryption is not enabled then do nothing.
- if (!isEncryptionEnabled() || keyResource == null) {
- CRYPTOR = new NullCryptor();
- return;
- }
-
- try {
- // Init given path to keystore, keystore pwd, name of the encrypt key
- // and flag stating NOT to retrieve keystore from classpath
- CRYPTOR = SymmetricCryptor.getSymmectricCryptor(keyResource);
- } catch ( FileNotFoundException e ) {
- throw new CryptoException(e, ErrorMessageKeys.CM_UTIL_ERR_0068, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0068, e.getMessage()));
- } catch ( IOException e ) {
- throw new CryptoException(e, ErrorMessageKeys.CM_UTIL_ERR_0068, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0068, e.getMessage()));
- }
- }
- }
-
- /**
- * Construct and return a utility that can be used for either encryption
- * or decryption.
- *
- * @return A utility that implements the <code>Cryptor</code> interface
- *
- * @throws CryptoException If there was a problem getting the keys
- * required to initialize the cipher, or if there was a
- * problem initializing the cipher utility
- */
- public static Cryptor getCryptor() throws CryptoException {
- init();
- return CRYPTOR;
- }
-
- /**
- * Construct and return a utility that can be used for only encryption.
- *
- * @return A utility that implements the <code>Encryptor</code> interface
- *
- * @throws CryptoException If there was a problem getting the key
- * required to initialize the cipher, or if there was a
- * problem initializing the cipher utility
- */
- public static Encryptor getEncryptor() throws CryptoException {
- return getCryptor();
- }
-
- /**
- * Construct and return a utility that can be used for only decryption.
- *
- * @return A utility that implements the <code>Decryptor</code> interface
- *
- * @throws CryptoException If there was a problem getting the key
- * required to initialize the cipher, or if there was a
- * problem initializing the cipher utility
- */
- public static Decryptor getDecryptor() throws CryptoException {
- return getCryptor();
- }
-
- public static String stringEncrypt(String clearText) throws CryptoException {
- return getCryptor().encrypt(clearText);
- }
-
- public static String stringDecrypt(String cipherText) throws CryptoException {
- return getCryptor().decrypt(cipherText);
- }
-
- public static boolean canDecrypt(String cipherText) {
- try {
- CryptoUtil.getDecryptor().decrypt(cipherText);
- } catch (CryptoException err) {
- return false;
- }
- return true;
- }
-
- /**
- * Allows tests to reinit if necessary
- */
- public static synchronized void reinit() {
- CRYPTOR = null;
- }
-
- public static synchronized boolean isInitialized() {
- return CRYPTOR == null;
- }
-
- public static void main(String[] args) throws Exception {
- if (args.length < 1) {
- printUsage();
- }
-
- int i = 0;
- if (args.length == 2 && args[i].equals("-genkey")) { //$NON-NLS-1$
- String keyName = args[++i];
- if (keyName == null) {
- printUsage();
- }
- SymmetricCryptor.generateAndSaveKey(keyName);
- return;
- }
- else if (args.length == 4 && args[i].equals("-key")) { //$NON-NLS-1$
- String keyFile = args[++i];
- if (keyFile == null) {
- printUsage();
- }
-
- File key = new File(keyFile);
- if (!key.exists()) {
- System.out.println("Key file does not exist at "+keyFile); //$NON-NLS-1$
- }
- else {
- CryptoUtil.init(key.toURI().toURL());
- }
-
- ++i;
- if (args[i].equals("-encrypt")) { //$NON-NLS-1$
- String clearText = args[++i];
- if (clearText == null) {
- printUsage();
- }
- System.out.println("Encypted Text:"+stringEncrypt(clearText)); //$NON-NLS-1$
- return;
- }
- }
- printUsage();
- }
-
- private static void printUsage() {
- System.out.println("java CryptoUtil <option>"); //$NON-NLS-1$
- System.out.println("options:"); //$NON-NLS-1$
- System.out.println("\t-genkey <filename> # Generates password key file"); //$NON-NLS-1$
- System.out.println("\t-key <keyfile> -encrypt <cleartext> # Encrypts the given clear text string"); //$NON-NLS-1$
- System.exit(0);
- }
-}
Modified: branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/Cryptor.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/Cryptor.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/Cryptor.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -22,10 +22,45 @@
package com.metamatrix.common.util.crypto;
+import java.io.Serializable;
+
/**
* Interface defining a utility that can perform both encryption and decryption.
- * @see Encryptor
- * @see Decryptor
*/
-public interface Cryptor extends Encryptor, Decryptor {
+public interface Cryptor {
+
+ /**
+ * Encrypt the cleartext in byte array format.
+ * @param cleartext The text to be encrypted, in byte form
+ * @param The encrypted ciphertext, in byte form
+ */
+ byte[] encrypt( byte[] cleartext ) throws CryptoException;
+
+ /**
+ * Encrypt the cleartext
+ * @param cleartext The text to be encrypted
+ * @param The encrypted ciphertext
+ */
+ String encrypt( String cleartext ) throws CryptoException;
+
+ Serializable sealObject(Serializable object) throws CryptoException;
+
+ /**
+ * Decrypt the ciphertext in byte array format to yield the original
+ * cleartext.
+ * @param ciphertext The text to be encrypted, in byte form
+ * @param The decrypted cleartext, in byte form
+ */
+ byte[] decrypt( byte[] ciphertext ) throws CryptoException;
+
+ /**
+ * Decrypt the ciphertext to yield the original
+ * cleartext.
+ * @param ciphertext The text to be encrypted
+ * @param The decrypted cleartext
+ */
+ String decrypt( String ciphertext ) throws CryptoException;
+
+ Serializable unsealObject(Serializable object) throws CryptoException;
+
}
Deleted: branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/Decryptor.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/Decryptor.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/Decryptor.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -1,51 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.common.util.crypto;
-
-import java.io.Serializable;
-
-/**
- * Interface defining a utility that can perform decryption of ciphertext to
- * yield the original cleartext.
- */
-public interface Decryptor {
-
- /**
- * Decrypt the ciphertext in byte array format to yield the original
- * cleartext.
- * @param ciphertext The text to be encrypted, in byte form
- * @param The decrypted cleartext, in byte form
- */
- byte[] decrypt( byte[] ciphertext ) throws CryptoException;
-
- /**
- * Decrypt the ciphertext to yield the original
- * cleartext.
- * @param ciphertext The text to be encrypted
- * @param The decrypted cleartext
- */
- String decrypt( String ciphertext ) throws CryptoException;
-
- Serializable unsealObject(Serializable object) throws CryptoException;
-}
-
Modified: branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/DhKeyGenerator.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/DhKeyGenerator.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/DhKeyGenerator.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -42,7 +42,6 @@
import javax.crypto.KeyAgreement;
import javax.crypto.spec.DHParameterSpec;
-import com.metamatrix.common.util.crypto.cipher.SymmetricCryptor;
import com.metamatrix.core.MetaMatrixRuntimeException;
/**
Deleted: branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/Encryptor.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/Encryptor.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/Encryptor.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -1,48 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.common.util.crypto;
-
-import java.io.Serializable;
-
-/**
- * Interface defining a utility that can perform encryption of cleartext.
- */
-public interface Encryptor {
-
- /**
- * Encrypt the cleartext in byte array format.
- * @param cleartext The text to be encrypted, in byte form
- * @param The encrypted ciphertext, in byte form
- */
- byte[] encrypt( byte[] cleartext ) throws CryptoException;
-
- /**
- * Encrypt the cleartext
- * @param cleartext The text to be encrypted
- * @param The encrypted ciphertext
- */
- String encrypt( String cleartext ) throws CryptoException;
-
- Serializable sealObject(Serializable object) throws CryptoException;
-}
-
Modified: branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/NullCryptor.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/NullCryptor.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/NullCryptor.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -24,7 +24,7 @@
import java.io.Serializable;
-public class NullCryptor implements Cryptor, Serializable {
+public class NullCryptor implements Cryptor {
public byte[] encrypt(byte[] cleartext) throws CryptoException {
return cleartext;
Deleted: branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/PasswordChangeUtility.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/PasswordChangeUtility.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/PasswordChangeUtility.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -1,274 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.common.util.crypto;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.util.Enumeration;
-import java.util.Properties;
-
-import com.metamatrix.common.util.crypto.cipher.SymmetricCryptor;
-import com.metamatrix.core.CorePlugin;
-import com.metamatrix.core.ErrorMessageKeys;
-
-/**
- * <p>Utility that allows ciphertext that was encrypted with one key
- * to be decrypted with the old key and re-encrypted with a new key</p>
- * <p><i>This utility assumes that the keys have been created and verified to work
- * correctly.</i></p>
- */
-public class PasswordChangeUtility {
-
- /** The name of the old key file name. */
- private String oldkeyName;
-
- /** The name of the new key file name. */
- private String newkeyName;
-
- /** Initailization state. */
- protected boolean initialized;
-
- /** The Cryptor to use for decrypting the old passwords. */
- protected Cryptor oldCryptor;
-
- /** The Cryptor to use for encrypting the new passwords. */
- protected Cryptor newCryptor;
-
- /**
- * Construct a <code>PasswordChangeUtility</code> with information for two different
- * keys.
- * @param oldkeyFileName The absolute path to the key with which you would like
- * to decrypt the old passwords.
- * @param newkeyFileName The absolute path to the key with which you would like
- * to encrypt the new passwords.
- * @throws IllegaArgumentException if any arguments are <code>null</code> or empty.
- */
- public PasswordChangeUtility(String oldkeyFileName,
- String newkeyFileName) {
- if (oldkeyFileName == null || oldkeyFileName.length() == 0) {
- throw new IllegalArgumentException(CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0062));
- }
- if (newkeyFileName == null || newkeyFileName.length() == 0) {
- throw new IllegalArgumentException(CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0064));
- }
-
- this.oldkeyName = oldkeyFileName;
- this.newkeyName = newkeyFileName;
- }
-
- // =========================================================================
- // I N I T I A L I Z A T I O N
- // =========================================================================
-
- /**
- * <p>Initialize this factory, bound to a specific key and key
- * entry in that store. </p>
- */
- public synchronized void init() throws CryptoException {
-
- if ( initialized == false ) {
-
- // Init and get the Cryptor for old passwords.
- try {
- this.oldCryptor = SymmetricCryptor.getSymmectricCryptor(new File(oldkeyName).toURL());
- } catch ( FileNotFoundException e ) {
- throw new CryptoException(e, ErrorMessageKeys.CM_UTIL_ERR_0066, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0066, e.getMessage()));
- } catch ( IOException e ) {
- throw new CryptoException(e, ErrorMessageKeys.CM_UTIL_ERR_0066, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0066, e.getMessage()));
- }
-
- // Init and get the Cryptor for new passwords.
- try {
- this.newCryptor = SymmetricCryptor.getSymmectricCryptor(new File(newkeyName).toURL());
- } catch ( FileNotFoundException e ) {
- throw new CryptoException(e, ErrorMessageKeys.CM_UTIL_ERR_0066, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0067, e.getMessage()));
- } catch ( IOException e ) {
- throw new CryptoException(e, ErrorMessageKeys.CM_UTIL_ERR_0066, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0067, e.getMessage()));
- }
-
- initialized = true;
- }
- }
-
- // =========================================================================
- // U T I L I T Y M E T H O D S
- // =========================================================================
-
- /**
- * Use old Cryptor to encrypt a char[].
- * @param cleartext The cleartext that you want encrypted with the
- * old Cryptor.
- * @return The encrypted ciphertext chars.
- * @throws CryptoException If an error occurs durring initialization
- * of the Cryptor or during encryption.
- */
- public String oldEncrypt( String cleartext ) throws CryptoException {
- init();
- return oldCryptor.encrypt( cleartext );
- }
-
-
- /**
- * Use old Cryptor to encrypt properties.
- * Encrypts any properties that end with <code>match</code>
- * @param match
- * @param props
- * @return Encrypted properties
- * @throws CryptoException
- * @since 4.3
- */
- public Properties oldEncrypt(String match, Properties props)
- throws CryptoException {
- init();
- return doCrypt(oldCryptor, true, match, props);
- }
-
-
-
- /**
- * Use old Cryptor to decrypt a char[].
- * @param ciphertext The ciphertext that you want decrypted with the
- * old Cryptor.
- * @return The decrypted cleartext chars.
- * @throws CryptoException If an error occurs durring initialization
- * of the Cryptor or during decryption.
- */
- public String oldDecrypt( String ciphertext ) throws CryptoException {
- init();
- return oldCryptor.decrypt( ciphertext );
- }
-
- /**
- * Use old Cryptor to decrypt properties.
- * Decrypts any properties that end with <code>match</code>
- * @param match
- * @param props
- * @return decrypted properties
- * @throws CryptoException
- * @since 4.3
- */
- public Properties oldDecrypt(String match, Properties props)
- throws CryptoException {
- init();
- return doCrypt(oldCryptor, false, match, props);
- }
-
-
- /**
- * Use new Cryptor to encrypt a char[].
- * @param cleartext The cleartext that you want encrypted with the
- * new Cryptor.
- * @return The encrypted ciphertext chars.
- * @throws CryptoException If an error occurs durring initialization
- * of the Cryptor or during encryption.
- */
- public String newEncrypt(String cleartext ) throws CryptoException {
- init();
- return newCryptor.encrypt( cleartext );
- }
-
- /**
- * Use new Cryptor to encrypt properties.
- * Encrypts any properties that end with <code>match</code>
- * @param match
- * @param props
- * @return encrypted properties
- * @throws CryptoException
- * @since 4.3
- */
- public Properties newEncrypt(String match, Properties props)
- throws CryptoException {
- init();
- return doCrypt(newCryptor, true, match, props);
- }
-
-
- /**
- * Use new Cryptor to decrypt a char[].
- * @param ciphertext The ciphertext that you want decrypted with the
- * new Cryptor.
- * @return The decrypted cleartext chars.
- * @throws CryptoException If an error occurs durring initialization
- * of the Cryptor or during decryption.
- */
- public String newDecrypt( String ciphertext ) throws CryptoException {
- init();
- return newCryptor.decrypt( ciphertext );
- }
-
- /**
- * Use new Cryptor to decrypt properties.
- * Decrypts any properties that end with <code>match</code>
- * @param match
- * @param props
- * @return decrypted properties
- * @throws CryptoException
- * @since 4.3
- */
- public Properties newDecrypt(String match, Properties props)
- throws CryptoException {
- init();
- return doCrypt(newCryptor, false, match, props);
- }
-
- /**
- * Encrypt or decrypt properties using the specified encryptor.
- * Operates on any properties that end with <code>match</code>
- * @param cryptor
- * @param encrypt If true, encrypt. If false, decrypt.
- * @param match
- * @param props
- * @return
- * @throws CryptoException
- * @since 4.3
- */
- private Properties doCrypt(Cryptor cryptor, boolean encrypt, String match, Properties props)
- throws CryptoException {
- Properties modifiedProps = new Properties();
-
- Enumeration propEnum = props.propertyNames();
-
- String matchUpper = match.toUpperCase();
- while (propEnum.hasMoreElements()) {
- String propName = (String) propEnum.nextElement();
- if (propName.toUpperCase().endsWith(matchUpper)) {
- String propVal = props.getProperty(propName);
- if (propVal != null && propVal.length() > 0) {
- String cryptValue;
- if (encrypt) {
- cryptValue = cryptor.encrypt(propVal);
- } else {
- cryptValue = cryptor.decrypt(propVal);
- }
- modifiedProps.setProperty(propName, cryptValue);
- }
- } else {
- modifiedProps.setProperty(propName, props.getProperty(propName));
- }
- }
- return modifiedProps;
- }
-
-} // END CLASS
-
Copied: branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/SymmetricCryptor.java (from rev 1884, branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/cipher/SymmetricCryptor.java)
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/SymmetricCryptor.java (rev 0)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/SymmetricCryptor.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -0,0 +1,148 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License 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.util.crypto;
+
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.security.GeneralSecurityException;
+import java.security.Key;
+import java.security.KeyStore;
+
+import javax.crypto.KeyGenerator;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.SecretKeySpec;
+
+import com.metamatrix.core.util.ArgCheck;
+
+/**
+ * Provides a symmetric cryptor using AES
+ */
+public class SymmetricCryptor extends BasicCryptor {
+
+ public static final String DEFAULT_SYM_KEY_ALGORITHM = "AES"; //$NON-NLS-1$
+ public static final String DEFAULT_SYM_ALGORITHM = "AES/ECB/PKCS5Padding"; //$NON-NLS-1$
+ public static final int DEFAULT_KEY_BITS = 128;
+ public static final String DEFAULT_STORE_PASSWORD = "changeit"; //$NON-NLS-1$
+ public static final String DEFAULT_ALIAS = "cluster_key"; //$NON-NLS-1$
+
+ private static KeyGenerator keyGen;
+
+ /**
+ * Creates a new SymmetricCryptor with a new symmetric key
+ *
+ * @return a new SymmetricCryptor
+ * @throws CryptoException
+ */
+ public static SymmetricCryptor getSymmectricCryptor() throws CryptoException {
+ Key key = generateKey();
+
+ return new SymmetricCryptor(key);
+ }
+
+ private static SecretKey generateKey() throws CryptoException {
+ try {
+ synchronized(SymmetricCryptor.class) {
+ if (keyGen == null) {
+ keyGen = KeyGenerator.getInstance(DEFAULT_SYM_KEY_ALGORITHM);
+ }
+ keyGen.init(DEFAULT_KEY_BITS);
+ return keyGen.generateKey();
+ }
+ } catch (GeneralSecurityException e) {
+ throw new CryptoException(e);
+ }
+ }
+
+ /**
+ * Creates a SymmetricCryptor using the supplied URL contents as the key
+ *
+ * @param key
+ * @return a new SymmetricCryptor
+ * @throws CryptoException
+ * @throws IOException
+ */
+ public static SymmetricCryptor getSymmectricCryptor(URL keyResource) throws CryptoException, IOException {
+ ArgCheck.isNotNull(keyResource);
+ InputStream stream = keyResource.openStream();
+ try {
+ KeyStore store = KeyStore.getInstance("JCEKS"); //$NON-NLS-1$
+ store.load(stream, DEFAULT_STORE_PASSWORD.toCharArray());
+ Key key = store.getKey(DEFAULT_ALIAS, DEFAULT_STORE_PASSWORD.toCharArray());
+ return new SymmetricCryptor(key);
+ } catch (GeneralSecurityException e) {
+ throw new CryptoException(e);
+ } finally {
+ stream.close();
+ }
+ }
+
+ /**
+ * Creates a SymmetricCryptor using the supplied byte array as the key
+ *
+ * @param key
+ * @return a new SymmetricCryptor
+ * @throws CryptoException
+ */
+ public static SymmetricCryptor getSymmectricCryptor(byte[] key) throws CryptoException {
+ Key secretKey = new SecretKeySpec(key, DEFAULT_SYM_KEY_ALGORITHM);
+ return new SymmetricCryptor(secretKey);
+ }
+
+ public static void generateAndSaveKey(String file) throws CryptoException, IOException {
+ SecretKey key = generateKey();
+ saveKey(file, key);
+ }
+
+ private static void saveKey(String file, SecretKey key) throws CryptoException, IOException {
+ ArgCheck.isNotNull(file);
+ FileOutputStream fos = new FileOutputStream(file);
+ try {
+ KeyStore store = KeyStore.getInstance("JCEKS"); //$NON-NLS-1$
+ store.load(null,null);
+ store.setKeyEntry(DEFAULT_ALIAS, key, DEFAULT_STORE_PASSWORD.toCharArray(),null);
+ store.store(fos, DEFAULT_STORE_PASSWORD.toCharArray());
+ } catch (GeneralSecurityException e) {
+ throw new CryptoException(e);
+ } finally {
+ fos.close();
+ }
+ }
+
+ SymmetricCryptor(Key key) throws CryptoException {
+ super(key, key, DEFAULT_SYM_ALGORITHM);
+ }
+
+ public byte[] getEncodedKey() {
+ return this.decryptKey.getEncoded();
+ }
+
+ public static void main(String[] args) throws Exception {
+ if (args.length != 1) {
+ System.out.println("The file to create must be supplied as the only argument."); //$NON-NLS-1$
+ System.exit(-1);
+ }
+ SymmetricCryptor.generateAndSaveKey(args[0]);
+ }
+}
Deleted: branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/cipher/BasicCryptor.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/cipher/BasicCryptor.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/cipher/BasicCryptor.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -1,231 +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.util.crypto.cipher;
-
-import java.io.Serializable;
-import java.security.InvalidKeyException;
-import java.security.Key;
-import java.security.NoSuchAlgorithmException;
-
-import javax.crypto.Cipher;
-import javax.crypto.NoSuchPaddingException;
-import javax.crypto.SealedObject;
-
-import com.metamatrix.common.util.crypto.CryptoException;
-import com.metamatrix.common.util.crypto.CryptoUtil;
-import com.metamatrix.common.util.crypto.Cryptor;
-import com.metamatrix.common.util.crypto.Decryptor;
-import com.metamatrix.common.util.crypto.Encryptor;
-import com.metamatrix.core.CorePlugin;
-import com.metamatrix.core.ErrorMessageKeys;
-import com.metamatrix.core.util.Base64;
-
-/**
- * <p>Implementation of <code>Cryptor</code> interface that can perform both
- * encryption and decryption. Instances of this class can be cast to any
- * of the following interfaces: <code>Cryptor</code>, <code>Encryptor</code>,
- * or <code>Decryptor</code>. </p>
- *
- * <p>Public methods in this class throw only <code>CryptoException</code>s. </p>
- *
- * @see Encryptor
- * @see Decryptor
- */
-public class BasicCryptor implements Cryptor {
-
- /** The key to be used for decryption. */
- protected Key decryptKey;
- /** The <code>Cipher</code> to use for decryption. */
- private Cipher decryptCipher;
- /** The key to be used for encryption. */
- private Key encryptKey;
- /** The <code>Cipher</code> to use for encryption. */
- protected Cipher encryptCipher;
- protected String cipherAlgorithm;
-
- public BasicCryptor( Key encryptKey, Key decryptKey, String algorithm) throws CryptoException {
- this.encryptKey = encryptKey;
- this.cipherAlgorithm = algorithm;
- this.decryptKey = decryptKey;
-
- initEncryptCipher();
- initDecryptCipher();
- }
-
- /**
- * Decrypt the ciphertext to yield the original cleartext.
- * @param ciphertext The text to be encrypted, in byte form
- * @param The decrypted cleartext, in byte form
- */
- public synchronized byte[] decrypt( byte[] ciphertext ) throws CryptoException {
- try {
- return decryptCipher.doFinal(ciphertext);
- } catch ( Exception e ) {
- try {
- initDecryptCipher();
- } catch (CryptoException err) {
- //shouldn't happen
- }
- throw new CryptoException( ErrorMessageKeys.CM_UTIL_ERR_0071, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0071, e.getClass().getName(), e.getMessage()));
- }
- }
-
- public String decrypt( String ciphertext ) throws CryptoException {
- if ( ciphertext == null ) {
- throw new CryptoException( ErrorMessageKeys.CM_UTIL_ERR_0074, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0074));
- }
-
- ciphertext = stripEncryptionPrefix(ciphertext);
-
- // Decode the previously encoded text into bytes...
- byte[] cipherBytes = null;
- try {
- cipherBytes = Base64.decode(ciphertext);
- } catch ( IllegalArgumentException e ) {
- throw new CryptoException( ErrorMessageKeys.CM_UTIL_ERR_0075, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0075, e.getMessage()));
- }
- // Perform standard decryption
- byte[] cleartext = decrypt( cipherBytes );
- // Perform "standard" Java encoding and return the result
- return new String(cleartext);
- }
-
- public static String stripEncryptionPrefix(String ciphertext) {
- if (ciphertext.startsWith(CryptoUtil.ENCRYPT_PREFIX)) {
- ciphertext = ciphertext.substring(CryptoUtil.ENCRYPT_PREFIX.length());
- } else if (ciphertext.startsWith(CryptoUtil.OLD_ENCRYPT_PREFIX)) {
- ciphertext = ciphertext.substring(CryptoUtil.OLD_ENCRYPT_PREFIX.length());
- }
- return ciphertext;
- }
-
- /**
- * Initialize the ciphers used for encryption and decryption. The ciphers
- * define the algorithms to be used. They are initialized with the
- * appropriate key to be used in the encryption or decryption operation.
- */
- protected void initDecryptCipher() throws CryptoException {
-
- // Create and initialize decryption cipher
- try {
- decryptCipher = Cipher.getInstance( cipherAlgorithm);
- decryptCipher.init( Cipher.DECRYPT_MODE, decryptKey );
- } catch ( NoSuchAlgorithmException e ) {
- throw new CryptoException( e, ErrorMessageKeys.CM_UTIL_ERR_0076, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0076, cipherAlgorithm ));
- } catch ( NoSuchPaddingException e ) {
- throw new CryptoException( ErrorMessageKeys.CM_UTIL_ERR_0077, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0077, cipherAlgorithm, e.getClass().getName(), e.getMessage() ));
- } catch ( InvalidKeyException e ) {
- throw new CryptoException( e, ErrorMessageKeys.CM_UTIL_ERR_0079, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0079, e.getClass().getName(), e.getMessage()) );
- }
- }
-
- public synchronized Serializable unsealObject(Serializable object) throws CryptoException {
-
- if (!(object instanceof SealedObject)) {
- return object;
- }
-
- SealedObject so = (SealedObject)object;
-
- try {
- return (Serializable)so.getObject(decryptCipher);
- } catch ( Exception e ) {
- try {
- initDecryptCipher();
- } catch (CryptoException err) {
- //shouldn't happen
- }
- throw new CryptoException( ErrorMessageKeys.CM_UTIL_ERR_0071, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0071, e.getClass().getName(), e.getMessage()));
- }
- }
-
- /**
- * Encrypt the cleartext in byte array format.
- * @param cleartext The text to be encrypted, in byte form
- * @param The encrypted ciphertext, in byte form
- */
- public synchronized byte[] encrypt( byte[] cleartext ) throws CryptoException {
- try {
- return encryptCipher.doFinal(cleartext);
- } catch ( Exception e ) {
- try {
- initEncryptCipher();
- } catch (CryptoException err) {
- //shouldn't happen
- }
- throw new CryptoException(ErrorMessageKeys.CM_UTIL_ERR_0081, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0081, e.getMessage()));
- }
- }
-
- public String encrypt( String cleartext ) throws CryptoException {
- if ( cleartext == null ) {
- throw new CryptoException( ErrorMessageKeys.CM_UTIL_ERR_0072, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0072));
- }
- String clearString = new String(cleartext);
- if ( clearString.trim().length() == 0 && clearString.length() == 0 ) {
- throw new CryptoException( ErrorMessageKeys.CM_UTIL_ERR_0073, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0073));
- }
- // Turn char array into string and get its bytes using "standard" encoding
- byte[] clearBytes = clearString.getBytes();
- // Perform standard encryption
- byte[] cipherBytes = encrypt( clearBytes );
- // Perform specialized encoding now, and return result
-
- String encoded = Base64.encodeBytes( cipherBytes );
- return CryptoUtil.ENCRYPT_PREFIX + encoded;
- }
-
- /**
- * Initialize the cipher used for encryption. The cipher defines the
- * algorithm to be used. It is initialized with the appropriate key to
- * be used in the encryption operation.
- */
- protected void initEncryptCipher() throws CryptoException {
-
- // Create and initialize encryption cipher
- try {
- encryptCipher = Cipher.getInstance( cipherAlgorithm );
- encryptCipher.init( Cipher.ENCRYPT_MODE, encryptKey );
- } catch ( NoSuchAlgorithmException e ) {
- throw new CryptoException( e, ErrorMessageKeys.CM_UTIL_ERR_0076, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0076, cipherAlgorithm ));
- } catch ( NoSuchPaddingException e ) {
- throw new CryptoException(e, ErrorMessageKeys.CM_UTIL_ERR_0072, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0077, cipherAlgorithm , e.getMessage() ));
- } catch ( InvalidKeyException e ) {
- throw new CryptoException( e, ErrorMessageKeys.CM_UTIL_ERR_0078, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0078, e.getMessage() ));
- }
- }
-
- public synchronized Serializable sealObject(Serializable object) throws CryptoException {
- try {
- return new SealedObject(object, encryptCipher);
- } catch ( Exception e ) {
- try {
- initEncryptCipher();
- } catch (CryptoException err) {
- //shouldn't happen
- }
- throw new CryptoException(ErrorMessageKeys.CM_UTIL_ERR_0081, CorePlugin.Util.getString(ErrorMessageKeys.CM_UTIL_ERR_0081, e.getMessage()));
- }
- }
-
-} // END CLASS
Deleted: branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/cipher/SymmetricCryptor.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/cipher/SymmetricCryptor.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/common/util/crypto/cipher/SymmetricCryptor.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -1,150 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.common.util.crypto.cipher;
-
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.security.GeneralSecurityException;
-import java.security.Key;
-import java.security.KeyStore;
-
-import javax.crypto.KeyGenerator;
-import javax.crypto.SecretKey;
-import javax.crypto.spec.SecretKeySpec;
-
-import com.metamatrix.common.util.crypto.CryptoException;
-import com.metamatrix.core.util.ArgCheck;
-
-/**
- * Provides a symmetric cryptor
- *
- */
-public class SymmetricCryptor extends BasicCryptor {
-
- public static final String DEFAULT_SYM_KEY_ALGORITHM = "AES"; //$NON-NLS-1$
- public static final String DEFAULT_SYM_ALGORITHM = "AES/ECB/PKCS5Padding"; //$NON-NLS-1$
- public static final int DEFAULT_KEY_BITS = 128;
- public static final String DEFAULT_STORE_PASSWORD = "changeit"; //$NON-NLS-1$
- public static final String DEFAULT_ALIAS = "cluster_key"; //$NON-NLS-1$
-
- private static KeyGenerator keyGen;
-
- /**
- * Creates a new SymmetricCryptor with a new symmetric key
- *
- * @return a new SymmetricCryptor
- * @throws CryptoException
- */
- public static SymmetricCryptor getSymmectricCryptor() throws CryptoException {
- Key key = generateKey();
-
- return new SymmetricCryptor(key);
- }
-
- private static SecretKey generateKey() throws CryptoException {
- try {
- synchronized(SymmetricCryptor.class) {
- if (keyGen == null) {
- keyGen = KeyGenerator.getInstance(DEFAULT_SYM_KEY_ALGORITHM);
- }
- keyGen.init(DEFAULT_KEY_BITS);
- return keyGen.generateKey();
- }
- } catch (GeneralSecurityException e) {
- throw new CryptoException(e);
- }
- }
-
- /**
- * Creates a SymmetricCryptor using the supplied URL contents as the key
- *
- * @param key
- * @return a new SymmetricCryptor
- * @throws CryptoException
- * @throws IOException
- */
- public static SymmetricCryptor getSymmectricCryptor(URL keyResource) throws CryptoException, IOException {
- ArgCheck.isNotNull(keyResource);
- InputStream stream = keyResource.openStream();
- try {
- KeyStore store = KeyStore.getInstance("JCEKS"); //$NON-NLS-1$
- store.load(stream, DEFAULT_STORE_PASSWORD.toCharArray());
- Key key = store.getKey(DEFAULT_ALIAS, DEFAULT_STORE_PASSWORD.toCharArray());
- return new SymmetricCryptor(key);
- } catch (GeneralSecurityException e) {
- throw new CryptoException(e);
- } finally {
- stream.close();
- }
- }
-
- /**
- * Creates a SymmetricCryptor using the supplied byte array as the key
- *
- * @param key
- * @return a new SymmetricCryptor
- * @throws CryptoException
- */
- public static SymmetricCryptor getSymmectricCryptor(byte[] key) throws CryptoException {
- Key secretKey = new SecretKeySpec(key, DEFAULT_SYM_KEY_ALGORITHM);
- return new SymmetricCryptor(secretKey);
- }
-
- public static void generateAndSaveKey(String file) throws CryptoException, IOException {
- SecretKey key = generateKey();
- saveKey(file, key);
- }
-
- private static void saveKey(String file, SecretKey key) throws CryptoException, IOException {
- ArgCheck.isNotNull(file);
- FileOutputStream fos = new FileOutputStream(file);
- try {
- KeyStore store = KeyStore.getInstance("JCEKS"); //$NON-NLS-1$
- store.load(null,null);
- store.setKeyEntry(DEFAULT_ALIAS, key, DEFAULT_STORE_PASSWORD.toCharArray(),null);
- store.store(fos, DEFAULT_STORE_PASSWORD.toCharArray());
- } catch (GeneralSecurityException e) {
- throw new CryptoException(e);
- } finally {
- fos.close();
- }
- }
-
- SymmetricCryptor(Key key) throws CryptoException {
- super(key, key, DEFAULT_SYM_ALGORITHM);
- }
-
- public byte[] getEncodedKey() {
- return this.decryptKey.getEncoded();
- }
-
- public static void main(String[] args) throws Exception {
- if (args.length != 1) {
- System.out.println("The file to create must be supplied as the only argument."); //$NON-NLS-1$
- System.exit(-1);
- }
- SymmetricCryptor.generateAndSaveKey(args[0]);
- }
-}
Deleted: branches/JCA/common-core/src/main/java/com/metamatrix/core/util/DateUtil.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/core/util/DateUtil.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/core/util/DateUtil.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -1,174 +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.core.util;
-
-import java.text.DateFormat;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.GregorianCalendar;
-
-import com.metamatrix.core.CorePlugin;
-
-public final class DateUtil {
-
- public static final String COMPLETE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS-ZZ:zz"; //$NON-NLS-1$
- public static final String TIMESTAMP_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS"; //$NON-NLS-1$
- // String indexes (useful for the logic in 'convertStringToDate')
- // Example "2001-08-07T20:44:22.911-06:00"
- // "yyyy-MM-ddTHH:mm:ss.SSS-ZZ:zz"
- // 01234567890123456789012345678
- // 1 2
-
- private static final ThreadLocal<DateFormat> DATE_FORMATTER = new ThreadLocal<DateFormat>() {
- @Override
- protected DateFormat initialValue() {
- DateFormat df = new SimpleDateFormat(TIMESTAMP_FORMAT);
- df.setLenient(false);
- return df;
- }
- };
-
- /**
- * Method to convert a string in the standard MetaMatrix pattern into a Date object.
- * The pattern is <i>yyyy-MM-dd'T'HH:mm:ss.SSS-ZZ:zz<i> where
- * <blockquote>
- * <pre>
- * Symbol Meaning Presentation Example
- * ------ ------- ------------ -------
- * y year (Number) 1996
- * M month in year (Number) 07
- * d day in month (Number) 10
- * h hour in am/pm (1~12) (Number) 12
- * H hour in day (0~23) (Number) 0
- * m minute in hour (Number) 30
- * s second in minute (Number) 55
- * S millisecond (Number) 978
- * Z zone offset hours (Number) 6
- * z zone offset minutes (Number) 30
- * ' escape for text (Delimiter)
- * '' single quote (Literal) '
- * </pre>
- * </blockquote>
- * The milliseconds, zone hour, and zone minutes are not required for parsing.
- * @param dateString the stringified date in the format described above
- * @return the Date instance
- * @throws ParseException if the string is not of the expected format
- */
- public static final Date convertStringToDate(String dateString) throws ParseException {
- ArgCheck.isNotEmpty(dateString);
- int badIndex=0;
- int millis = 0;
- try {
- // Find the year ...
- int year = Integer.parseInt( dateString.substring(0,4) );
- badIndex=5;
- int month = Integer.parseInt( dateString.substring(5,7) );
- badIndex=8;
- int day = Integer.parseInt( dateString.substring(8,10) );
- badIndex=11;
- int hours = Integer.parseInt( dateString.substring(11,13) );
- badIndex=14;
- int minutes = Integer.parseInt( dateString.substring(14,16) );
- badIndex=17;
- int seconds = Integer.parseInt( dateString.substring(17,19) );
- int len = dateString.length();
- if ( len > 19 ) {
- badIndex=20;
- millis = Integer.parseInt( dateString.substring(20,23) );
- }
- if ( len > 23 ) {
- badIndex=24;
- Integer.parseInt( dateString.substring(24,26) );
- }
- if ( len > 26 ) {
- badIndex=27;
- Integer.parseInt( dateString.substring(27,29) );
- }
-
- // Note the month is zero-based!!!!
- GregorianCalendar calendar = new GregorianCalendar(year,month-1,day,hours,minutes,seconds);
- calendar.add(Calendar.MILLISECOND,millis);
- // TODO: Unable to support different time zones!!!!
- //calendar.add(Calendar.ZONE_OFFSET,millis); throws IllegalArgument
- return calendar.getTime();
-
- // Use a java.sql.Timestamp since java.util.Date doesn't have a way to set millis!!!
- //return new Timestamp(year,month,day,hours,minutes,seconds,millis*1000);
- } catch ( IndexOutOfBoundsException ioobe ) {
- final Object[] params = new Object[]{dateString, COMPLETE_FORMAT};
- throw new ParseException(CorePlugin.Util.getString("DateUtil.The_string_is_not_of_the_expected_format_1",params),badIndex); //$NON-NLS-1$
- } catch ( NumberFormatException nfe ) {
- final Object[] params = new Object[]{dateString, COMPLETE_FORMAT};
- throw new ParseException(CorePlugin.Util.getString("DateUtil.The_string_is_not_of_the_expected_format_2",params),badIndex); //$NON-NLS-1$
- }
- }
-
- public static final String getDateAsString( Date timestamp ) {
- return formatString(timestamp);
- }
-
- public static final String getDateAsString( long timestamp ) {
- return formatString(new Date(timestamp));
- }
-
- public static final Date getDate( long timestamp ) {
- return new Date(timestamp);
- }
-
- public static final String getCurrentDateAsString() {
- return formatString(new Date());
- }
-
- public static final Date getCurrentDate() {
- return new Date();
- }
-
- private static final String formatString( Date timestamp ) {
- StringBuffer sb = new StringBuffer( DATE_FORMATTER.get().format(timestamp) );
- long offsetMillis = Calendar.getInstance().get( Calendar.ZONE_OFFSET );
- if ( offsetMillis == 0 ) {
- sb.append("+00:00"); //$NON-NLS-1$
- } else if ( offsetMillis > 0 ) {
- sb.append('+');
- } else {
- sb.append('-');
- }
- int seconds = (int)(Math.abs(offsetMillis) / 1000);
- int minutes = seconds / 60;
- int hours = minutes / 60;
- minutes = minutes % 60;
- if ( hours < 10 ) {
- sb.append('0');
- }
- sb.append( hours );
- sb.append(':');
- if ( minutes < 10 ) {
- sb.append('0');
- }
- sb.append( minutes );
- return sb.toString();
- }
-
-}
Modified: branches/JCA/common-core/src/main/java/com/metamatrix/core/util/StringUtil.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/core/util/StringUtil.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/core/util/StringUtil.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -12,8 +12,11 @@
package com.metamatrix.core.util;
+import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
+import java.io.IOException;
import java.io.PrintWriter;
+import java.io.StringReader;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
@@ -26,6 +29,7 @@
import java.util.regex.Pattern;
import com.metamatrix.core.CorePlugin;
+import com.metamatrix.core.MetaMatrixRuntimeException;
/**
* This is a common place to put String utility methods.
@@ -1043,4 +1047,20 @@
throw new IllegalArgumentException("Conversion from String to "+ type.getName() + " is not supported"); //$NON-NLS-1$ //$NON-NLS-2$
}
+
+ public static String[] getLines(final String value) {
+ StringReader stringReader = new StringReader(value);
+ BufferedReader reader = new BufferedReader(stringReader);
+ ArrayList result = new ArrayList();
+ try {
+ String line = reader.readLine();
+ while (line != null) {
+ result.add(line);
+ line = reader.readLine();
+ }
+ } catch (IOException e) {
+ throw new MetaMatrixRuntimeException(e);
+ }
+ return (String[]) result.toArray(new String[result.size()]);
+ }
}
Deleted: branches/JCA/common-core/src/main/java/com/metamatrix/core/util/StringUtilities.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/core/util/StringUtilities.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/core/util/StringUtilities.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -1,262 +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.core.util;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.IOException;
-import java.io.StringReader;
-import java.util.ArrayList;
-
-import com.metamatrix.core.MetaMatrixRuntimeException;
-
-/**
- * This class contains static utilities that return strings that are the result of manipulating other strings or objects.
- * @since 3.1
- * @version 3.1
- * @author <a href="mailto:jverhaeg@metamatrix.com">John P. A. Verhaeg</a>
- */
-public class StringUtilities {
- /**
- * The String "\n"
- */
- public static final String NEW_LINE = "\n"; //$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, NEW_LINE);
-
- //############################################################################################################################
- //# Static Methods #
- //############################################################################################################################
-
- public static String getLineSeparator() {
- return LINE_SEPARATOR;
- }
-
- /**
- * Returns the path representing the concatenation of the specified path prefix and suffix. The resulting path is guaranteed
- * to have exactly one file separator between the prefix and suffix.
- * @param prefix The path prefix
- * @param suffix The path suffix
- * @return The concatenated path prefix and suffix
- * @since 3.1
- */
- public static String buildPath(final String prefix, final String suffix) {
- final StringBuffer path = new StringBuffer(prefix);
- if (!prefix.endsWith(File.separator)) {
- path.append(File.separator);
- }
- if (suffix.startsWith(File.separator)) {
- path.append(suffix.substring(File.separator.length()));
- } else {
- path.append(suffix);
- }
- return path.toString();
- }
-
- /**
- * Returns a new string that lowercases the first character in the passed in
- * value String
- * @param value
- * @return String
- */
- public static String lowerCaseFirstChar(final String value){
- if(value == null){
- return null;
- }
-
- //Lower case the first char and try to look-up the SF
- String firstChar = new Character(value.charAt(0) ).toString();
- firstChar = firstChar.toLowerCase();
- return (firstChar + value.substring(1) );
- }
-
- /**
- * Returns a new string that uppercases the first character in the passed in
- * value String
- * @param value
- * @return String
- */
- public static String upperCaseFirstChar(final String value){
- if(value == null){
- return null;
- }
-
- //Lower case the first char and try to look-up the SF
- String firstChar = new Character(value.charAt(0) ).toString();
- firstChar = firstChar.toUpperCase();
- return (firstChar + value.substring(1) );
- }
-
- /**
- * Returns a new string that represents the last fragment of the original
- * string that begins with an uppercase char. Ex: "getSuperTypes" would
- * return "Types".
- * @param value
- * @param lastToken - the last token tried... if not null will look
- * backwards from the last token instead of the end of the value param
- * @return String
- */
- public static String getLastUpperCharToken(final String value, final String lastToken){
- if(value == null || lastToken == null){
- return value;
- }
-
- int index = value.lastIndexOf(lastToken);
- if(index == -1){
- return null;
- }
-
- StringBuffer result = new StringBuffer();
- for(int i = index - 1; i >= 0 ; i--){
- result.insert(0,value.charAt(i) );
- if(Character.isUpperCase(value.charAt(i) ) ){
- return result.toString() + lastToken;
- }
- }
-
- return result.toString() + lastToken;
- }
-
- /**
- * Returns a new string that represents the last fragment of the original
- * string that begins with an uppercase char. Ex: "getSuperTypes" would
- * return "Types".
- * @param value
- * @return String
- */
- public static String getLastUpperCharToken(final String value){
- if(value == null){
- return null;
- }
-
- StringBuffer result = new StringBuffer();
- for(int i = value.length() - 1; i >= 0; i--){
- result.insert(0, value.charAt(i) );
- if(Character.isUpperCase(value.charAt(i) ) ){
- return result.toString();
- }
- }
-
- return result.toString();
- }
-
- public static String[] getLines(final String value) {
- StringReader stringReader = new StringReader(value);
- BufferedReader reader = new BufferedReader(stringReader);
- ArrayList result = new ArrayList();
- try {
- String line = reader.readLine();
- while (line != null) {
- result.add(line);
- line = reader.readLine();
- }
- } catch (IOException e) {
- throw new MetaMatrixRuntimeException(e);
- }
- return (String[]) result.toArray(new String[result.size()]);
- }
-
- 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();
- }
-
- /** Replaces all "whitespace" characters from the specified string with space
- * characters, where whitespace includes \r\t\n and other characters
- * @param value the string to work with
- * @param stripExtras if true, replace multiple whitespace characters with a single character.
- * @see java.util.regex.Pattern
- */
- public static String replaceWhitespace(String value, boolean stripExtras) {
- return replaceWhitespace(value, " ", stripExtras); //$NON-NLS-1$
- }
-
- /** Replaces all "whitespace" characters from the specified string with space
- * characters, where whitespace includes \r\t\n and other characters
- * @param value the string to work with
- * @param replaceWith the character to replace with
- * @param stripExtras if true, replace multiple whitespace characters with a single character.
- * @see java.util.regex.Pattern
- */
- public static String replaceWhitespace(String value, String replaceWith, boolean stripExtras) {
- String rv = value.replaceAll("\\s+", replaceWith); //$NON-NLS-1$
-
- if (stripExtras) {
- rv = removeExtraWhitespace(rv);
- } // endif
-
- return rv;
- }
-
- /** Replaces multiple sequential "whitespace" characters from the specified string with
- * a single space character, where whitespace includes \r\t\n and other characters
- * @param value the string to work with
- * @see java.util.regex.Pattern
- */
- public static String removeExtraWhitespace(String value) {
- return value.replaceAll("\\s\\s+", " "); //$NON-NLS-1$//$NON-NLS-2$
- }
-
- /**
- *
- * @param originalString
- * @param maxLength
- * @param endLength
- * @param middleString
- * @return
- * @since 5.0
- */
- public static String condenseToLength(String originalString, int maxLength, int endLength, String middleString) {
- if( originalString.length() <= maxLength) {
- return originalString;
- }
- int originalLength = originalString.length();
- StringBuffer sb = new StringBuffer(maxLength);
- sb.append(originalString.substring(0, maxLength - endLength - middleString.length()));
- sb.append(middleString);
- sb.append(originalString.substring(originalLength - endLength, originalLength));
-
- return sb.toString();
- }
-}
Deleted: branches/JCA/common-core/src/main/java/com/metamatrix/core/util/ZipFileUtil.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/core/util/ZipFileUtil.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/core/util/ZipFileUtil.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -1,822 +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.core.util;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-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.Enumeration;
-import java.util.Iterator;
-import java.util.List;
-import java.util.jar.JarFile;
-import java.util.jar.Manifest;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipException;
-import java.util.zip.ZipFile;
-import java.util.zip.ZipInputStream;
-import java.util.zip.ZipOutputStream;
-
-import com.metamatrix.core.CorePlugin;
-
-/**
- * This class provides utilities to manipulate Zip files.
- */
-public final class ZipFileUtil {
-
- // ===========================================================================================================================
- // Constants
-
- // specify buffer size for extraction
- static final int BUFFER = 16384;
-
- static final String TMP_PFX = "ZipFileUtil"; //$NON-NLS-1$
- static final String TMP_SFX = ".zip"; //$NON-NLS-1$
-
- // ===========================================================================================================================
- // Static Controller Methods
-
- /**
- * Adds the file with the specified name to the zip file with the specified name.
- *
- * @param zipFileName
- * The name of the zip file to which the file with the specified name will be added.
- * @param fileName
- * The name of the file to be added.
- * @return True if the file with the specified name was successfully added to the zip file with the specified name.
- * @throws IOException
- * If an I/O error occurs updating the zip file.
- * @test {@link TestZipFileUtil#testAddRemove()}
- * @since 4.3
- */
- public static boolean add(final String zipFileName,
- final String fileName) throws IOException {
- ArgCheck.isNotEmpty(zipFileName);
- ArgCheck.isNotEmpty(fileName);
-
- List fileNames = new ArrayList();
- fileNames.add(fileName);
- return addAll(new File(zipFileName), fileNames, fileNames);
- }
-
- /**
- * Adds the file with the specified name to the zip file with the specified name.
- *
- * @param zipFileName
- * The name of the zip file to which the file with the specified name will be added.
- * @param entryName
- * The name to call the entry in the zip file.
- * @param fileName
- * The name of the file to be added.
- * @return True if the file with the specified name was successfully added to the zip file with the specified name.
- * @throws IOException
- * If an I/O error occurs updating the zip file.
- * @test {@link TestZipFileUtil#testAddRemove()}
- * @since 4.3
- */
- public static boolean add(final String zipFileName,
- final String entryName,
- final String fileName) throws IOException {
- ArgCheck.isNotEmpty(zipFileName);
- ArgCheck.isNotEmpty(entryName);
- ArgCheck.isNotEmpty(fileName);
-
- List fileNames = new ArrayList();
- fileNames.add(fileName);
- List entryNames = new ArrayList();
- entryNames.add(entryName);
- return addAll(new File(zipFileName), entryNames, fileNames);
- }
-
- /**
- * Adds the file with the specified name to the specified zip file.
- *
- * @param zipFile
- * The zip file to which the file with the specified name will be added.
- * @param fileName
- * The name of the file to be added.
- * @return True if the file with the specified name was successfully added to the specified zip file.
- * @throws IOException
- * If an I/O error occurs updating the zip file.
- * @test {@link TestZipFileUtil#testAddRemove()}
- * @since 4.3
- */
- public static boolean add(final File zipFile,
- final String fileName) throws IOException {
- ArgCheck.isNotNull(zipFile);
- ArgCheck.isNotEmpty(fileName);
-
- List fileNames = new ArrayList();
- fileNames.add(fileName);
- return addAll(zipFile, fileNames, fileNames);
- }
-
-
-
- /**
- * Adds all of the files in the specified directory to the specified zip file.
- *
- * @param zipFile
- * The zip file to which the file with the specified name will be added.
- * @param dirName
- * The name of the directory which contains the files to be added.
- * @return True if the files wes successfully added to the specified zip file.
- * @throws IOException
- * If an I/O error occurs updating the zip file.
- * @since 4.3
- */
- public static boolean addAll(final File zipFile,
- final String dirName) throws IOException {
- return addAll(zipFile, dirName, ""); //$NON-NLS-1$
- }
-
- /**
- * Adds all of the files in the specified directory to the specified zip file.
- *
- * @param zipFile
- * The zip file to which the file with the specified name will be added.
- * @param dirName
- * The name of the directory which contains the files to be added.
- * @param pathInZip
- * Path in which the files should be added in the zip.
- * @return True if the files wes successfully added to the specified zip file.
- * @throws IOException
- * If an I/O error occurs updating the zip file.
- * @since 4.3
- */
- public static boolean addAll(final File zipFile,
- final String dirName,
- String pathInZip) throws IOException {
- ArgCheck.isNotNull(zipFile);
- ArgCheck.isNotEmpty(dirName);
-
-
- File dir = new File(dirName);
- //get the entrynames (relative path)
- if (pathInZip.length() > 0) {
- pathInZip = pathInZip + File.separator;
- }
- List entryNames = listRecursively(dir, pathInZip);
- //get the filenames (full path)
- List fileNames = listRecursively(dir, dir.getAbsolutePath() + File.separator);
-
- return addAll(zipFile, entryNames, fileNames);
- }
-
-
- /**
- * List recursively from the <code>sourceDirectory</code> all its contents.
- * @param sourceDirectory
- * @param pathSoFar Path tp append to the beginning of each result.
- * @return List of Strings, the filenames of the contents of the directory.
- * @since 4.3
- */
- private static List listRecursively(File sourceDirectory, String pathSoFar) throws FileNotFoundException {
-
- if (!sourceDirectory.exists()) {
- throw new FileNotFoundException(CorePlugin.Util.getString("FileUtils.File_does_not_exist._1", sourceDirectory)); //$NON-NLS-1$
- }
- if (!sourceDirectory.isDirectory()) {
- throw new FileNotFoundException(CorePlugin.Util.getString("FileUtils.Not_a_directory", sourceDirectory)); //$NON-NLS-1$
- }
-
- return listRecursivelySub(sourceDirectory, pathSoFar);
- }
-
- private static List listRecursivelySub(File sourceDirectory, String pathSoFar) {
- List results = new ArrayList();
-
- File[] sourceFiles = sourceDirectory.listFiles();
- for (int i = 0; i < sourceFiles.length; i++) {
- File srcFile = sourceFiles[i];
- String newPathSoFar = pathSoFar + srcFile.getName();
- if (srcFile.isDirectory()) {
- results.addAll(listRecursivelySub(srcFile, newPathSoFar + File.separator));
- } else {
- results.add(newPathSoFar);
- }
- }
- return results;
- }
-
-
-
-
- /**
- * Adds the files with the specified names to the specified zip file.
- *
- * @param zipFile
- * The zip file to which the file with the specified name will be added.
- * @param entryNames
- * List of Strings. The names to call the entries in the zip file. Must be in the same order as <code>fileNames</code>.
- * @param fileNames
- * List of Files. The names of the file to be added. Must be in the same order as <code>entryNames</code>.
- * @return True if the file with the specified name was successfully added to the specified zip file.
- * @throws IOException
- * If an I/O error occurs updating the zip file.
- * @test {@link TestZipFileUtil#testAddRemove()}
- * @since 4.3
- */
- private static boolean addAll(final File zipFile,
- final List entryNames,
- final List fileNames) throws IOException {
- FileOutputStream fos = null;
- ZipOutputStream out = null;
- File tmpFile = File.createTempFile(TMP_PFX, TMP_SFX);
- try {
- // Create temp zip file
- fos = new FileOutputStream(tmpFile);
- out = new ZipOutputStream(fos);
- // Create buffer to use to write data to temp zip file
- final byte[] buf = new byte[BUFFER];
- // Copy specified zip file to temp zip file
- if (zipFile.exists()) {
- ZipFile zipFileZip = null;
- FileInputStream fis = null;
- ZipInputStream in = null;
- try {
- zipFileZip = new ZipFile(zipFile);
- fis = new FileInputStream(zipFile);
- in = new ZipInputStream(fis);
- for (ZipEntry entry = in.getNextEntry(); entry != null; entry = in.getNextEntry()) {
- writeEntry(entry, zipFileZip.getInputStream(entry), out, buf);
- }
- } catch (final ZipException ignored) {
- // Happens when zip file empty or contains no entries
- } finally {
- // Close input streams so we can later replace specified file with temp file
- if (zipFileZip != null) {
- zipFileZip.close();
- }
- cleanup(in);
- cleanup(fis);
- }
- }
-
- // Add specified entries to temp zip file
- Iterator entryNamesIter = entryNames.iterator();
- Iterator fileNamesIter = fileNames.iterator();
- while (entryNamesIter.hasNext() && fileNamesIter.hasNext()) {
- String entryName = (String) entryNamesIter.next();
- String fileName = (String) fileNamesIter.next();
- long modified = new File(fileName).lastModified();
-
- FileInputStream fis = new FileInputStream(fileName);
- ZipEntry entry = new ZipEntry(entryName);
- entry.setTime(modified);
- writeEntry(entry, fis, out, buf);
- // Close output stream so we can replace specified file with temp file
- // (Also set variable to null so we don't close again in finally block)
- cleanup(fis);
- }
-
-
- out.close();
- out = null;
- fos.close();
- fos = null;
- // Replace specified file with temp file
- FileUtils.rename(tmpFile.getAbsolutePath(), zipFile.getAbsolutePath(), true);
-
-
- return true;
- } finally {
- cleanup(out);
- cleanup(fos);
- if (tmpFile != null && tmpFile.exists() && !tmpFile.delete()) {
- Logger.getLogger("org.teiid.common-core").log(Level.INFO, "Could not delete temp file " + tmpFile.getAbsolutePath()); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
- }
-
- /**
- * Extract the given zip file to the given destination directory base.
- *
- * @param zipFileName
- * The full path and file name of the Zip file to extract.
- * @param destinationDirectory
- * The root directory to extract to.
- * @throws IOException
- */
- public static void extract(final String zipFileName,
- final String destinationDirectory) throws IOException {
- try {
- File sourceZipFile = new File(zipFileName);
- File unzipDestinationDirectory = new File(destinationDirectory);
-
- // Open Zip file for reading
- ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);
-
- // Create an enumeration of the entries in the zip file
- Enumeration zipFileEntries = zipFile.entries();
-
- // Process each entry
- while (zipFileEntries.hasMoreElements()) {
- // grab a zip file entry
- ZipEntry entry = (ZipEntry)zipFileEntries.nextElement();
-
- String currentEntry = entry.getName();
-
- File destFile = new File(unzipDestinationDirectory, currentEntry);
-
- // grab file's parent directory structure
- File destinationParent = destFile.getParentFile();
-
- // create the parent directory structure if needed
- destinationParent.mkdirs();
-
- // extract file if not a directory
- if (!entry.isDirectory()) {
- BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry));
- int currentByte;
- // establish buffer for writing file
- byte data[] = new byte[BUFFER];
-
- // write the current file to disk
- FileOutputStream fos = new FileOutputStream(destFile);
- BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
-
- // read and write until last byte is encountered
- while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
- dest.write(data, 0, currentByte);
- }
- dest.flush();
- dest.close();
- fos.close();
- is.close();
- }
- }
- zipFile.close();
- } catch (IOException ioe) {
- throw ioe;
- }
- }
-
- /**
- * Removes the file with the specified name from the zip file with the specified name.
- *
- * @param zipFileName
- * The name of the zip file from which the file with the specified name will be removed.
- * @param fileName
- * The name of the file to be removed.
- * @param ignoreCase
- * Indicates whether the case of the filename should be ignored when finding the match.
- * @return True if the file with the specified name was successfully removed from the zip file with the specified name.
- * @throws IOException
- * If an I/O error occurs updating the zip file.
- * @test {@link TestZipFileUtil#testAddRemove()}
- * @since 4.3
- */
- public static boolean remove(final String zipFileName,
- final String fileName,
- boolean ignoreCase) throws IOException {
- ArgCheck.isNotEmpty(zipFileName);
- return remove(new File(zipFileName), fileName, ignoreCase);
- }
-
- /**
- * Removes the file with the specified name from the zip file with the specified name.
- *
- * @param zipFileName
- * The name of the zip file from which the file with the specified name will be removed.
- * @param fileName
- * The name of the file to be removed.
- * @return True if the file with the specified name was successfully removed from the zip file with the specified name.
- * @throws IOException
- * If an I/O error occurs updating the zip file.
- * @test {@link TestZipFileUtil#testAddRemove()}
- * @since 4.3
- */
- public static boolean remove(final String zipFileName,
- final String fileName) throws IOException {
- ArgCheck.isNotEmpty(zipFileName);
- return remove(new File(zipFileName), fileName, false);
- }
-
- /**
- * Removes the file with the specified name to the specified zip file.
- *
- * @param zipFile
- * The zip file from which the file with the specified name will be removed.
- * @param fileName
- * The name of the file to be removed.
- * @return True if the file with the specified name was successfully removed from the specified zip file.
- * @throws IOException
- * If an I/O error occurs updating the zip file.
- * @test {@link TestZipFileUtil#testAddRemove()}
- * @since 4.3
- */
- public static boolean remove(final File zipFile,
- final String fileName) throws IOException {
- ArgCheck.isNotNull(zipFile);
- ArgCheck.isNotEmpty(fileName);
-
- return remove(zipFile, fileName, false);
- }
-
- /**
- * Removes the file with the specified name to the specified zip file.
- *
- * @param zipFile
- * The zip file from which the file with the specified name will be removed.
- * @param fileName
- * The name of the file to be removed.
- * @param ignoreCase
- * Indicates whether the case of the filename should be ignored when finding the match.
- * @return True if the file with the specified name was successfully removed from the specified zip file.
- * @throws IOException
- * If an I/O error occurs updating the zip file.
- * @test {@link TestZipFileUtil#testAddRemove()}
- * @since 4.3
- */
- public static boolean remove(final File zipFile,
- final String fileName,
- boolean ignoreCase) throws IOException {
- ArgCheck.isNotNull(zipFile);
- ArgCheck.isNotEmpty(fileName);
- FileOutputStream fos = null;
- ZipOutputStream out = null;
- File tmpFile = File.createTempFile(TMP_PFX, TMP_SFX);
- try {
- // Create temp zip file
- fos = new FileOutputStream(tmpFile);
- out = new ZipOutputStream(fos);
- // Create buffer to use to write data to temp zip file
- final byte[] buf = new byte[BUFFER];
- // Copy specified zip file to temp zip file, skipping entry with specified file name
- final ZipFile zipFileZip = new ZipFile(zipFile);
- FileInputStream fis = null;
- ZipInputStream in = null;
- try {
- fis = new FileInputStream(zipFile);
- in = new ZipInputStream(fis);
- for (ZipEntry entry = in.getNextEntry(); entry != null; entry = in.getNextEntry()) {
- if (ignoreCase) {
- if (!entry.getName().equalsIgnoreCase(fileName)) {
- writeEntry(entry, zipFileZip.getInputStream(entry), out, buf);
- }
- } else {
- if (!entry.getName().equals(fileName)) {
- writeEntry(entry, zipFileZip.getInputStream(entry), out, buf);
- }
-
- }
- }
- } finally {
- // Close input streams so we can later replace specified file with temp file
- zipFileZip.close();
- cleanup(in);
- cleanup(fis);
- }
- // Close output stream so we can replace specified file with temp file
- // (Also set variable to null so we don't close again in finally block)
- out.close();
- out = null;
- fos.close();
- fos = null;
- // Replace specified file with temp file
- FileUtils.rename(tmpFile.getAbsolutePath(), zipFile.getAbsolutePath(), true);
- return true;
-
- } finally {
- cleanup(out);
- cleanup(fos);
- }
- }
-
-
- public static boolean replace (final File zipFile, final String replaceName, InputStream replaceStream) throws IOException {
- ArgCheck.isNotNull(zipFile);
- ArgCheck.isNotEmpty(replaceName);
-
- FileOutputStream fos = null;
- ZipOutputStream out = null;
- File tmpFile = File.createTempFile(TMP_PFX, TMP_SFX);
-
- try {
- // Create temp zip file
- fos = new FileOutputStream(tmpFile);
- out = new ZipOutputStream(fos);
-
- // Create buffer to use to write data to temp zip file
- final byte[] buf = new byte[BUFFER];
-
- // Copy specified zip file to temp zip file, skipping entry with
- // specified file name
- final ZipFile zipFileZip = new ZipFile(zipFile);
- FileInputStream fis = null;
- ZipInputStream in = null;
- boolean replaced = false;
-
- try {
- fis = new FileInputStream(zipFile);
- in = new ZipInputStream(fis);
- for (ZipEntry entry = in.getNextEntry(); entry != null; entry = in.getNextEntry()) {
- boolean replace = entry.getName().equals(replaceName);
- if (replace) {
- writeEntry(new ZipEntry(entry.getName()), replaceStream, out, buf);
- replaced = true;
- } else {
- writeEntry(new ZipEntry(entry.getName()), zipFileZip.getInputStream(entry),out, buf);
- }
- }
- } finally {
- // Close input streams so we can later replace specified file
- // with temp file
- zipFileZip.close();
- cleanup(in);
- cleanup(fis);
- }
-
- // if the original was not there then add a new entry
- if (!replaced) {
- ZipEntry entry = new ZipEntry(replaceName);
- writeEntry(entry, replaceStream, out, buf);
- }
-
- // Close output stream so we can replace specified file with temp
- // file
- // (Also set variable to null so we don't close again in finally
- // block)
- out.close();
- out = null;
- fos.close();
- fos = null;
-
- // Replace specified file with temp file
- try {
- FileUtils.rename(tmpFile.getAbsolutePath(), zipFile.getAbsolutePath(), true);
- } catch (Exception e) {
- IOException ex = new IOException();
- ex.initCause(e);
- throw ex;
- }
- return true;
-
- } finally {
- cleanup(out);
- cleanup(fos);
- }
- }
-
- /**
- * Returns the file with the specified name to the specified zip file.
- *
- * @param zipFile
- * The zip file from which the file with the specified name will be retrieved from.
- * @param fileName
- * The name of the file to be returned.
- * @param ignoreCase
- * Indicates whether the case of the filename should be ignored when finding the match.
- * @return True if the file with the specified name was successfully removed from the specified zip file.
- * @throws IOException
- * If an I/O error occurs updating the zip file.
- * @test {@link TestZipFileUtil#testGet()}
- * @since 4.3
- */
- public static InputStream get(final File zipFile,
- final String fileName,
- boolean ignoreCase) throws IOException {
- ArgCheck.isNotNull(zipFile);
- ArgCheck.isNotEmpty(fileName);
- ByteArrayOutputStream out = null;
- try {
-
- out = new ByteArrayOutputStream();
- // Create temp zip file
- // Create buffer to use to write data to temp zip file
- final byte[] buf = new byte[BUFFER];
- // Copy specified zip file to temp zip file, skipping entry with specified file name
- final ZipFile zipFileZip = new ZipFile(zipFile);
- FileInputStream fis = null;
- ZipInputStream in = null;
- try {
- fis = new FileInputStream(zipFile);
- in = new ZipInputStream(fis);
- boolean match = false;
- for (ZipEntry entry = in.getNextEntry(); entry != null; entry = in.getNextEntry()) {
- if (ignoreCase) {
- if (entry.getName().equalsIgnoreCase(fileName)) {
- match = true;
- }
- } else {
- if (entry.getName().equals(fileName)) {
- match = true;
- }
- }
-
- if (match) {
- copyEntry(zipFileZip.getInputStream(entry), out, buf );
-
- byte[] data = out.toByteArray();
-
- out.close();
-
- return new ByteArrayInputStream(data);
-
- }
- }
- } finally {
- // Close input streams so we can later replace specified file with temp file
- zipFileZip.close();
- cleanup(in);
- cleanup(fis);
- }
-
- } finally {
- cleanup(out);
-
- }
-
- return null;
- }
-
- /**
- * Will find all entries in the jar based on the expression specified and based on
- * if case is ignored.
- *
- * @param zipFile
- * The zip file from which the find will be performed.
- * @param regexExpression
- * The regex expression supported by {@link java.util.regex}
- * @param ignoreCase
- * Indicates whether the case of an entry in the jar file should be ignored when finding the match.
- * @return List of entry names that were found to match the regex expression
- * @throws IOException
- * If an I/O error occurs reading the zip file.
- * @test {@link TestZipFileUtil#testFind()}
- * @test {@link TestZipFileUtil#testFindIgnoreCase()}
- * @test {@link TestZipFileUtil#testNotFind()}
- * @since 6.0
- */
- public static List<String> find(final File zipFile,
- final String regexExpression,
- boolean ignoreCase) throws IOException {
- ArgCheck.isNotNull(zipFile);
- ArgCheck.isNotNull(regexExpression);
-
- Pattern pattern = null;
- if (ignoreCase) {
- pattern = Pattern.compile(regexExpression, Pattern.CASE_INSENSITIVE);
- } else {
- pattern = Pattern.compile(regexExpression);
- }
- List<String> finds = new ArrayList();
- final ZipFile zipFileZip = new ZipFile(zipFile);
- FileInputStream fis = null;
- ZipInputStream in = null;
- try {
- fis = new FileInputStream(zipFile);
- in = new ZipInputStream(fis);
- for (ZipEntry entry = in.getNextEntry(); entry != null; entry = in.getNextEntry()) {
- Matcher matcher = pattern.matcher(entry.getName());
- if (matcher.find()) {
- finds.add(entry.getName());
- }
-
- }
- } finally {
- // Close input streams so we can later replace specified file with temp file
- zipFileZip.close();
- cleanup(in);
- cleanup(fis);
- }
- return finds;
- }
-
- /**
- * Attempts to obtain the manifest file from the specified file, which
- * must be either a .jar or .zip file.
- *
- * @param path
- * @param VENDOR
- * @return Manifest, if one exist, other returns null
- */
-
- public static Manifest getManifest(File jarfile){
- JarFile jfile = null;
- String path = jarfile.getAbsolutePath();
- if(!jarfile.isDirectory()){
- if((path.indexOf(".jar")>0) || ((path.indexOf(".zip")>0))){ //$NON-NLS-1$ //$NON-NLS-2$
- //This is a jar file so look for it's Manifest information
- try{
- jfile = new JarFile(jarfile);
- Manifest manifest = jfile.getManifest();
- if(manifest != null){
- return manifest;
- }
- } catch(IOException io){
- // ignore
- }
- }
- }
- return null;
- }
-
-
- /**
- * Writes the specified entry (including its contents) to the specified output stream.
- *
- * @param entry
- * The zip entry to be added.
- * @param in
- * The inputstream from which the zip entry's contents wil be read.
- * @param out
- * The zip output stream to which the specified zip entry will be written.
- * @param buffer
- * The buffer used to transfer data from the specified zip entry to the specified zip output stream.
- * @throws IOException
- * If an I/O error occurs writing to the specified zip output stream.
- * @since 4.3
- */
- private static void writeEntry(final ZipEntry entry,
- final InputStream in,
- final ZipOutputStream out,
- final byte[] buffer) throws IOException {
- // Add specified entry to stream
- out.putNextEntry(entry);
- // Write contents of entry to stream
- final BufferedInputStream zipEntryIn = new BufferedInputStream(in);
- for (int count = zipEntryIn.read(buffer); count >= 0; count = zipEntryIn.read(buffer)) {
- out.write(buffer, 0, count);
- }
- zipEntryIn.close();
- }
-
- private static void copyEntry(final InputStream in,
- final OutputStream out,
- final byte[] buffer) throws IOException {
- BufferedInputStream zipEntryIn = null;
- try {
- // Write contents of entry to stream
- zipEntryIn = new BufferedInputStream(in);
- for (int count = zipEntryIn.read(buffer); count >= 0; count = zipEntryIn.read(buffer)) {
- out.write(buffer, 0, count);
- }
- } finally {
- zipEntryIn.close();
- }
-
- }
-
-
- private static void cleanup(InputStream stream) {
- if (stream != null) {
- try {
- stream.close();
- } catch (Exception e) {
- }
- }
- }
- private static void cleanup(OutputStream stream) {
- if (stream != null) {
- try {
- stream.close();
- } catch (Exception e) {
- }
- }
- }
-
-
- // ===========================================================================================================================
- // Constructors
-
- /**
- * Prevent initialization
- */
- private ZipFileUtil() {
- }
-
-}
Deleted: branches/JCA/common-core/src/main/java/com/metamatrix/core/vdb/VDBStatus.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/core/vdb/VDBStatus.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/core/vdb/VDBStatus.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -1,39 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.core.vdb;
-
-
-public interface VDBStatus {
- public static final short INCOMPLETE = 1;
- public static final short INACTIVE = 2;
- public static final short ACTIVE = 3;
- public static final short DELETED = 4;
- public static final short ACTIVE_DEFAULT = 5;
-
- final static String[] VDB_STATUS_NAMES = {
- "Incomplete", //$NON-NLS-1$
- "Inactive", //$NON-NLS-1$
- "Active", //$NON-NLS-1$
- "Deleted", //$NON-NLS-1$
- "Active-Default"}; //$NON-NLS-1$
-}
Modified: branches/JCA/common-core/src/main/java/com/metamatrix/core/vdb/VdbConstants.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/core/vdb/VdbConstants.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/core/vdb/VdbConstants.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -42,16 +42,6 @@
public final static String MODEL_EXT = ".xmi"; //$NON-NLS-1$
public final static String UDF_FILE_NAME = "FunctionDefinitions.xmi"; //$NON-NLS-1$
- /**
- * These are virtual database status.
- */
- final public static class VDB_STATUS {
- public static final short INCOMPLETE = 1;
- public static final short INACTIVE = 2;
- public static final short ACTIVE = 3;
- public static final short DELETED = 4;
- }
-
public static final String VDB = ".vdb"; //$NON-NLS-1$
public static final String DEF = ".def"; //$NON-NLS-1$
Modified: branches/JCA/common-core/src/test/java/com/metamatrix/api/exception/TestExceptionHolder.java
===================================================================
--- branches/JCA/common-core/src/test/java/com/metamatrix/api/exception/TestExceptionHolder.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/test/java/com/metamatrix/api/exception/TestExceptionHolder.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -5,6 +5,7 @@
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URL;
+import java.net.URLClassLoader;
import java.sql.SQLException;
import java.util.ArrayList;
@@ -12,7 +13,6 @@
import org.junit.Test;
-import com.metamatrix.common.classloader.PostDelegatingClassLoader;
import com.metamatrix.core.MetaMatrixRuntimeException;
import com.metamatrix.core.util.ReflectionHelper;
import com.metamatrix.core.util.UnitTestUtil;
@@ -30,7 +30,7 @@
}
@Test public void testDeserializationUnknownException() throws Exception {
- ClassLoader cl = new PostDelegatingClassLoader(new URL[] {UnitTestUtil.getTestDataFile("test.jar").toURI().toURL()}); //$NON-NLS-1$
+ ClassLoader cl = new URLClassLoader(new URL[] {UnitTestUtil.getTestDataFile("test.jar").toURI().toURL()}); //$NON-NLS-1$
Object obj = ReflectionHelper.create("test.Test", null, cl); //$NON-NLS-1$
ByteArrayOutputStream baos = new ByteArrayOutputStream();
@@ -56,7 +56,7 @@
}
@Test public void testDeserializationUnknownChildException() throws Exception {
- ClassLoader cl = new PostDelegatingClassLoader(new URL[] {UnitTestUtil.getTestDataFile("test.jar").toURI().toURL()}); //$NON-NLS-1$
+ ClassLoader cl = new URLClassLoader(new URL[] {UnitTestUtil.getTestDataFile("test.jar").toURI().toURL()}); //$NON-NLS-1$
Exception obj = (Exception)ReflectionHelper.create("test.UnknownException", null, cl); //$NON-NLS-1$
obj.initCause(new SQLException("something bad happended")); //$NON-NLS-1$
@@ -78,7 +78,7 @@
}
@Test public void testDeserializationUnknownChildException2() throws Exception {
- ClassLoader cl = new PostDelegatingClassLoader(new URL[] {UnitTestUtil.getTestDataFile("test.jar").toURI().toURL()}); //$NON-NLS-1$
+ ClassLoader cl = new URLClassLoader(new URL[] {UnitTestUtil.getTestDataFile("test.jar").toURI().toURL()}); //$NON-NLS-1$
ArrayList<String> args = new ArrayList<String>();
args.add("Unknown Exception"); //$NON-NLS-1$
Exception obj = (Exception)ReflectionHelper.create("test.UnknownException", args, cl); //$NON-NLS-1$
Deleted: branches/JCA/common-core/src/test/java/com/metamatrix/common/util/TestByteArrayHelper.java
===================================================================
--- branches/JCA/common-core/src/test/java/com/metamatrix/common/util/TestByteArrayHelper.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/test/java/com/metamatrix/common/util/TestByteArrayHelper.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -1,95 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.common.util;
-
-import java.io.BufferedInputStream;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Arrays;
-
-import junit.framework.TestCase;
-
-public class TestByteArrayHelper extends TestCase {
-
- private static final byte[] TEST_ARRAY = (new String("TEST 1 2 3 4 5 TEST")).getBytes(); //$NON-NLS-1$
-
- // ################################## FRAMEWORK ################################
-
- public TestByteArrayHelper(String name) {
- super(name);
- }
-
- //===================================================================
- //ACTUAL TESTS
- //===================================================================
-
- public void testToByteArrayExactChunkSize(){
- int chunkSize = TEST_ARRAY.length+1;
- InputStream is = new ByteArrayInputStream(TEST_ARRAY);
- checkByteArrayWithChunkSize(TEST_ARRAY,chunkSize, is);
- }
-
- public void testToByteArrayBiggerChunkSize(){
- int chunkSize = 2*TEST_ARRAY.length;
- InputStream is = new ByteArrayInputStream(TEST_ARRAY);
- checkByteArrayWithChunkSize(TEST_ARRAY,chunkSize, is);
- }
-
- public void testToByteArraySmallerChunkSize(){
- int chunkSize = TEST_ARRAY.length/7;
- InputStream is = new ByteArrayInputStream(TEST_ARRAY);
- checkByteArrayWithChunkSize(TEST_ARRAY,chunkSize, is);
- }
-
- public void testToByteArrayBufferedInputStream(){
- int chunkSize = TEST_ARRAY.length+1;
- InputStream is = new ByteArrayInputStream(TEST_ARRAY);
- is = new BufferedInputStream(is);
- checkByteArrayWithChunkSize(TEST_ARRAY,chunkSize, is);
- }
-
- public void testToByteArrayFakeInputStream(){
- int chunkSize = TEST_ARRAY.length+5;
- InputStream is = new FakeInputStream(TEST_ARRAY);
- checkByteArrayWithChunkSize(TEST_ARRAY,chunkSize, is);
- }
-
-
- //===================================================================
- //TESTS HELPERS
- //===================================================================
-
- private void checkByteArrayWithChunkSize(byte[] controlData, int chunkSize, InputStream is){
- byte[] testData = null;
- try{
- testData = ByteArrayHelper.toByteArray(is, chunkSize);
- assertNotNull(testData);
- } catch (IOException e){
- fail(e.getMessage());
- }
-
- assertTrue("byte arrays are NOT same size", controlData.length == testData.length); //$NON-NLS-1$
- assertTrue("byte arrays are NOT identical", Arrays.equals(controlData, testData)); //$NON-NLS-1$
- }
-}
Modified: branches/JCA/common-core/src/test/java/com/metamatrix/common/util/crypto/TestDhKeyGenerator.java
===================================================================
--- branches/JCA/common-core/src/test/java/com/metamatrix/common/util/crypto/TestDhKeyGenerator.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/test/java/com/metamatrix/common/util/crypto/TestDhKeyGenerator.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -24,7 +24,6 @@
import junit.framework.TestCase;
-import com.metamatrix.common.util.crypto.cipher.SymmetricCryptor;
public class TestDhKeyGenerator extends TestCase {
@@ -42,7 +41,7 @@
String cleartext2 = clientCryptor.decrypt(ciphertext);
assertEquals(cleartext, cleartext2);
- assertTrue(CryptoUtil.isValueEncrypted(new String(ciphertext)));
+ assertTrue(!ciphertext.equals(cleartext));
}
}
Modified: branches/JCA/common-core/src/test/java/com/metamatrix/common/util/crypto/TestEncryptDecrypt.java
===================================================================
--- branches/JCA/common-core/src/test/java/com/metamatrix/common/util/crypto/TestEncryptDecrypt.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/test/java/com/metamatrix/common/util/crypto/TestEncryptDecrypt.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -22,24 +22,26 @@
package com.metamatrix.common.util.crypto;
+import static org.junit.Assert.*;
+
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
+import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
-import junit.framework.TestCase;
+import org.junit.BeforeClass;
+import org.junit.Test;
-import com.metamatrix.common.util.crypto.cipher.BasicCryptor;
-import com.metamatrix.common.util.crypto.cipher.SymmetricCryptor;
/**
* <p>Test cases for {@link CryptoFactory} and carious <code>Encryptor</code>
* and <code>Decryptor</code> implementations. </p>
*/
-public class TestEncryptDecrypt extends TestCase {
+public class TestEncryptDecrypt {
// Some strings for testing...
private static final String ALPHA_U = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; //$NON-NLS-1$
@@ -49,14 +51,11 @@
/** String to encrypt and decrypt. */
private static final String CLEARTEXT = ALPHA_U + ALPHA_L + NUMBERS + MISC_CHAR;
-
- // =========================================================================
- // T E S T C O N T R O L
- // =========================================================================
-
- /** Construct test case. */
- public TestEncryptDecrypt( String name ) {
- super( name );
+
+ private static Cryptor cryptor;
+
+ @BeforeClass public static void oneTimeSetup() throws CryptoException, IOException {
+ cryptor = SymmetricCryptor.getSymmectricCryptor(TestEncryptDecrypt.class.getResource("/teiid.keystore")); //$NON-NLS-1$
}
// =========================================================================
@@ -67,17 +66,11 @@
* Test encryption (and decryption) for specified string.
*/
public void helpTestEncryptDecrypt( String cleartext ) throws CryptoException {
- // Get a utility that can be used for encryption
- Encryptor encryptor = CryptoUtil.getEncryptor();
-
- // Get a utility that can be used for decryption
- Decryptor decryptor = CryptoUtil.getDecryptor();
-
// Encrypt the cleartext into ciphertext
- String ciphertext = encryptor.encrypt( cleartext );
- String cleartext2 = decryptor.decrypt( ciphertext );
+ String ciphertext = cryptor.encrypt( cleartext );
+ String cleartext2 = cryptor.decrypt( ciphertext );
- assertTrue(CryptoUtil.isValueEncrypted(ciphertext));
+ assertTrue(ciphertext.startsWith(BasicCryptor.ENCRYPT_PREFIX));
assertEquals(cleartext, cleartext2);
}
@@ -87,26 +80,26 @@
// =========================================================================
/**
- * Test the {@link BasicCryptor#encrypt} method.
+ * Test the {@link Cryptor#encrypt} method.
* @throws CryptoException
*/
- public void testPos_EncryptDecryptLongString() throws CryptoException {
+ @Test public void testPos_EncryptDecryptLongString() throws CryptoException {
helpTestEncryptDecrypt( CLEARTEXT );
}
/**
- * Test the {@link BasicCryptor#encrypt} method.
+ * Test the {@link Cryptor#encrypt} method.
* @throws CryptoException
*/
- public void testPos_EncryptDecryptHalfLongString() throws CryptoException {
+ @Test public void testPos_EncryptDecryptHalfLongString() throws CryptoException {
helpTestEncryptDecrypt( CLEARTEXT.substring(0,CLEARTEXT.length()/2) );
}
/**
- * Test the {@link BasicCryptor#encrypt} method.
+ * Test the {@link Cryptor#encrypt} method.
* @throws CryptoException
*/
- public void testPos_EncryptDecryptStringsOfVariousLengths() throws CryptoException {
+ @Test public void testPos_EncryptDecryptStringsOfVariousLengths() throws CryptoException {
for ( int k = 1; k < CLEARTEXT.length()/4; k++ ) {
// Use substring starting at index k, and 'k' characters long
String cleartext = CLEARTEXT.substring(k,k+k);
@@ -115,10 +108,10 @@
}
/**
- * Test the {@link BasicCryptor#encrypt} method.
+ * Test the {@link Cryptor#encrypt} method.
* @throws CryptoException
*/
- public void testPos_EncryptDecryptStringsOfBlanks() throws CryptoException {
+ @Test public void testPos_EncryptDecryptStringsOfBlanks() throws CryptoException {
String BLANKS = " "; //$NON-NLS-1$
for ( int k = 1; k < BLANKS.length(); k++ ) {
// Use substring starting at index 0, and 'k' characters long
@@ -128,32 +121,26 @@
}
/**
- * Test the {@link BasicCryptor#encrypt} method.
+ * Test the {@link Cryptor#encrypt} method.
* @throws CryptoException
*/
- public void testNeg_DecryptNonEncryptedStringLen10() throws CryptoException {
+ @Test public void testNeg_DecryptNonEncryptedStringLen10() throws CryptoException {
String ciphertext = "abcdefghij"; // Will not decode //$NON-NLS-1$
- // Get a utility that can be used for decryption
- Decryptor decryptor = CryptoUtil.getDecryptor();
-
try {
- decryptor.decrypt( ciphertext );
+ cryptor.decrypt( ciphertext );
fail("expected exception"); //$NON-NLS-1$
} catch ( CryptoException e ) {
}
}
/**
- * Test the {@link BasicCryptor#encrypt} method.
+ * Test the {@link Cryptor#encrypt} method.
*/
- public void testNeg_DecryptNullString() throws Exception {
- // Get a utility that can be used for decryption
- Decryptor decryptor = CryptoUtil.getDecryptor();
-
+ @Test public void testNeg_DecryptNullString() throws Exception {
// Decrypt the Base64 encoded ciphertext back to the original cleartext
try {
- decryptor.decrypt( (String)null );
+ cryptor.decrypt( (String)null );
fail("expected exception"); //$NON-NLS-1$
} catch ( CryptoException e ) {
//expected
@@ -162,16 +149,13 @@
/**
- * Test the {@link BasicCryptor#encrypt} method.
+ * Test the {@link Cryptor#encrypt} method.
* @throws CryptoException
*/
- public void testNeg_EncryptZeroLengthString() throws CryptoException {
- // Get a utility that can be used for encryption
- Encryptor encryptor = CryptoUtil.getEncryptor();
-
+ @Test public void testNeg_EncryptZeroLengthString() throws CryptoException {
// Encrypt the cleartext and leave ciphertext in Base64 encoded char array
try {
- encryptor.encrypt( "" ); //$NON-NLS-1$
+ cryptor.encrypt( "" ); //$NON-NLS-1$
fail("expected exception"); //$NON-NLS-1$
} catch ( CryptoException e ) {
assertEquals("Error Code:ERR.003.030.0073 Message:Attempt to encrypt zero-length cleartext.", e.getMessage()); //$NON-NLS-1$
@@ -179,16 +163,13 @@
}
/**
- * Test the {@link BasicCryptor#encrypt} method.
+ * Test the {@link Cryptor#encrypt} method.
* @throws CryptoException
*/
- public void testNeg_EncryptNullCharArray() throws CryptoException {
- // Get a utility that can be used for encryption
- Encryptor encryptor = CryptoUtil.getEncryptor();
-
+ @Test public void testNeg_EncryptNullCharArray() throws CryptoException {
// Encrypt the cleartext and leave ciphertext in Base64 encoded char array
try {
- encryptor.encrypt( (String)null );
+ cryptor.encrypt( (String)null );
fail("expected exception"); //$NON-NLS-1$
} catch ( CryptoException e ) {
assertEquals("Error Code:ERR.003.030.0072 Message:Attempt to encrypt null cleartext.", e.getMessage()); //$NON-NLS-1$
@@ -196,31 +177,28 @@
}
/**
- * Test the {@link BasicCryptor#encrypt} method.
+ * Test the {@link Cryptor#encrypt} method.
*/
- public void testPos_EncryptAfterException() throws Exception {
- // Get a utility that can be used for encryption
- Encryptor encryptor = CryptoUtil.getEncryptor();
-
+ @Test public void testPos_EncryptAfterException() throws Exception {
try {
- encryptor.encrypt( "" );
+ cryptor.encrypt( "" );
} catch ( CryptoException e ) {
// This valid test case should work after a failure!
helpTestEncryptDecrypt( CLEARTEXT );
}
}
- public void testLongEncryption() throws Exception {
+ @Test public void testLongEncryption() throws Exception {
helpTestEncryptDecrypt(CLEARTEXT + CLEARTEXT + CLEARTEXT);
}
- public void testSymmetricEncryptionWithRandomKey() throws Exception {
+ @Test public void testSymmetricEncryptionWithRandomKey() throws Exception {
- SymmetricCryptor cryptor = SymmetricCryptor.getSymmectricCryptor();
+ SymmetricCryptor randomSymCryptor = SymmetricCryptor.getSymmectricCryptor();
ArrayList test = new ArrayList(Arrays.asList(new String[] {ALPHA_L, ALPHA_U, CLEARTEXT, NUMBERS}));
- Serializable result = cryptor.sealObject(test);
+ Serializable result = randomSymCryptor.sealObject(test);
//ensure that we can serialize
ByteArrayOutputStream baos = new ByteArrayOutputStream();
@@ -231,21 +209,16 @@
ObjectInputStream ois = new ObjectInputStream(bais);
result = (Serializable)ois.readObject();
- ArrayList clearObject = (ArrayList)cryptor.unsealObject(result);
+ ArrayList clearObject = (ArrayList)randomSymCryptor.unsealObject(result);
assertEquals(test, clearObject);
- SymmetricCryptor cryptor1 = SymmetricCryptor.getSymmectricCryptor(cryptor.getEncodedKey());
+ SymmetricCryptor cryptor1 = SymmetricCryptor.getSymmectricCryptor(randomSymCryptor.getEncodedKey());
clearObject = (ArrayList)cryptor1.unsealObject(result);
assertEquals(test, clearObject);
}
- public void testIsEncryptedFails() {
- assertFalse(CryptoUtil.isValueEncrypted(ALPHA_U));
- assertFalse(CryptoUtil.isValueEncrypted(CryptoUtil.ENCRYPT_PREFIX + "xyz")); //$NON-NLS-1$
- }
-
}
Deleted: branches/JCA/common-core/src/test/java/com/metamatrix/common/util/crypto/TestPasswordChangeUtility.java
===================================================================
--- branches/JCA/common-core/src/test/java/com/metamatrix/common/util/crypto/TestPasswordChangeUtility.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/test/java/com/metamatrix/common/util/crypto/TestPasswordChangeUtility.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -1,131 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.common.util.crypto;
-
-import java.util.Properties;
-
-import junit.framework.TestCase;
-
-/**
- * <p>Test cases for PasswordChangeUtility
- */
-public class TestPasswordChangeUtility extends TestCase {
-
- private static final String PASSWORD = "PASSWORD"; //$NON-NLS-1$
-
- private static final String KEY1 = "key1"; //$NON-NLS-1$
- private static final String KEY2 = "password"; //$NON-NLS-1$
- private static final String KEY3 = "a.paSSword"; //$NON-NLS-1$
- private static final String KEY4 = "password.b"; //$NON-NLS-1$
-
- private static final String VALUE1 = "value1"; //$NON-NLS-1$
- private static final String VALUE2 = "value2"; //$NON-NLS-1$
- private static final String VALUE3 = "value3"; //$NON-NLS-1$
- private static final String VALUE4 = "value4"; //$NON-NLS-1$
-
-
- public static final String FAKE_DECRYPTED_OLD = "fake-decrypted-old"; //$NON-NLS-1$
- public static final String FAKE_ENCRYPTED_OLD = "fake-encrypted-old"; //$NON-NLS-1$
- public static final String FAKE_DECRYPTED_NEW = "fake-decrypted-new"; //$NON-NLS-1$
- public static final String FAKE_ENCRYPTED_NEW = "fake-encrypted-new"; //$NON-NLS-1$
-
-
-
-
- private PasswordChangeUtility utility;
- private Properties properties;
-
- /** Construct test case. */
- public TestPasswordChangeUtility(String name) {
- super(name);
- }
-
- public void setUp() {
- utility = new FakePasswordChangeUtility();
-
- properties = new Properties();
- properties.put(KEY1, VALUE1);
- properties.put(KEY2, VALUE2);
- properties.put(KEY3, VALUE3);
- properties.put(KEY4, VALUE4);
- }
-
- /**Test PasswordChangeUtility.oldEncrypt()*/
- public void testOldEncryptProperties() throws Exception {
- properties = utility.oldEncrypt(PASSWORD, properties);
-
- assertEquals(VALUE1, properties.get(KEY1));
- assertEquals(FAKE_ENCRYPTED_OLD, properties.get(KEY2));
- assertEquals(FAKE_ENCRYPTED_OLD, properties.get(KEY3));
- assertEquals(VALUE4, properties.get(KEY4));
- }
-
- /**Test PasswordChangeUtility.newEncrypt()*/
- public void testNewEncryptProperties() throws Exception {
- properties = utility.newEncrypt(PASSWORD, properties);
-
- assertEquals(VALUE1, properties.get(KEY1));
- assertEquals(FAKE_ENCRYPTED_NEW, properties.get(KEY2));
- assertEquals(FAKE_ENCRYPTED_NEW, properties.get(KEY3));
- assertEquals(VALUE4, properties.get(KEY4));
- }
-
- /**Test PasswordChangeUtility.oldDecrypt()*/
- public void testOldDecryptProperties() throws Exception {
- properties = utility.oldDecrypt(PASSWORD, properties);
-
- assertEquals(VALUE1, properties.get(KEY1));
- assertEquals(FAKE_DECRYPTED_OLD, properties.get(KEY2));
- assertEquals(FAKE_DECRYPTED_OLD, properties.get(KEY3));
- assertEquals(VALUE4, properties.get(KEY4));
- }
-
- /**Test PasswordChangeUtility.newDecrypt()*/
- public void testNewDecryptProperties() throws Exception {
- properties = utility.newDecrypt(PASSWORD, properties);
-
- assertEquals(VALUE1, properties.get(KEY1));
- assertEquals(FAKE_DECRYPTED_NEW, properties.get(KEY2));
- assertEquals(FAKE_DECRYPTED_NEW, properties.get(KEY3));
- assertEquals(VALUE4, properties.get(KEY4));
- }
-
-
-
- /**
- * Subclass of PasswordChangeUtility, extended to use fake cryptors.
- * @since 4.3
- */
- public static class FakePasswordChangeUtility extends PasswordChangeUtility {
- public FakePasswordChangeUtility() {
- super("fake", "fake"); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
- }
-
- public void init() throws CryptoException {
- this.oldCryptor = new FakeCryptor(FAKE_ENCRYPTED_OLD, FAKE_DECRYPTED_OLD);
- this.newCryptor = new FakeCryptor(FAKE_ENCRYPTED_NEW, FAKE_DECRYPTED_NEW);
- this.initialized = true;
- }
- }
-}
-
Deleted: branches/JCA/common-core/src/test/java/com/metamatrix/core/util/TestStringUtilities.java
===================================================================
--- branches/JCA/common-core/src/test/java/com/metamatrix/core/util/TestStringUtilities.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/test/java/com/metamatrix/core/util/TestStringUtilities.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -1,75 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-//################################################################################################################################
-package com.metamatrix.core.util;
-
-import junit.framework.TestCase;
-
-/**
- * @author Lance Phillips
- *
- * @since 3.1
- */
-public class TestStringUtilities extends TestCase {
-
- /**
- * Constructor for TestStringUtilities.
- * @param name
- */
- public TestStringUtilities(String name) {
- super(name);
- }
-
- /**
- * Constructor for TestStringUtilities.
- * @param name
- */
- public TestStringUtilities() {
- this("TestStringUtilities"); //$NON-NLS-1$
- }
-
- public void testGetLastUpperCharToken(){
- String testString = "getSuperDuperTypes"; //$NON-NLS-1$
- String result = StringUtilities.getLastUpperCharToken(testString);
-
- if(!result.equals("Types") ){ //$NON-NLS-1$
- fail("Expected \"Types\" but got " + result); //$NON-NLS-1$
- }
- }
-
- public void testGetLastUpperCharTokenComplex(){
- String testString = "getSuperDuperTypes"; //$NON-NLS-1$
- String result = StringUtilities.getLastUpperCharToken(testString);
-
- result = StringUtilities.getLastUpperCharToken(testString, result);
- if(!result.equals("DuperTypes") ){ //$NON-NLS-1$
- fail("Expected \"DuperTypes\" but got " + result); //$NON-NLS-1$
- }
-
- result = StringUtilities.getLastUpperCharToken(testString, result);
- if(!result.equals("SuperDuperTypes") ){ //$NON-NLS-1$
- fail("Expected \"SuperDuperTypes\" but got " + result); //$NON-NLS-1$
- }
- }
-
-}
Deleted: branches/JCA/common-core/src/test/java/com/metamatrix/core/util/TestZipFileUtil.java
===================================================================
--- branches/JCA/common-core/src/test/java/com/metamatrix/core/util/TestZipFileUtil.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/common-core/src/test/java/com/metamatrix/core/util/TestZipFileUtil.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -1,264 +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.core.util;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.List;
-import java.util.jar.Manifest;
-
-import junit.framework.TestCase;
-
-/**
- * @since 4.3
- */
-public final class TestZipFileUtil extends TestCase {
-
- // ===========================================================================================================================
- // Constants
-
- private static final String PATH = UnitTestUtil.getTestDataPath();
- private static final String EMPTIED_ZIP_FILE_NAME = PATH + "/testEmptiedZipFile.zip"; //$NON-NLS-1$
- private static final String EMPTY_ZIP_FILE_NAME = PATH + "/testEmptyZipFile.zip"; //$NON-NLS-1$
- private static final String NEW_ZIP_FILE_NAME = UnitTestUtil.getTestScratchPath() + "/testNewZipFile.zip"; //$NON-NLS-1$
- private static final String ZIP_ENTRY_NAME = PATH + "/fakeFile"; //$NON-NLS-1$
- private static final String ZIP_FILE_NAME = PATH + "/testZipFile.zip"; //$NON-NLS-1$
-
-
- public void setUp() {
- try {
- new File(NEW_ZIP_FILE_NAME).delete();
- } catch (Exception e) {
- }
- }
-
- // ===========================================================================================================================
- // Static Controller Methods
-
- /**
- * Adds a file to the specified zip file, verifies the results,
- * removes the file, verifies the results,
- * then deletes the zip file.
- *
- * @param file
- * The zip file on which to perform the add and remove test.
- * @since 4.3
- */
- private void addRemove(final File file) throws Exception {
- final long oldSize = file.length();
- try {
- //add
- assertTrue(ZipFileUtil.add(file, ZIP_ENTRY_NAME));
- assertTrue(file.exists());
- assertTrue(file.length() > oldSize);
-
- //remove
- assertTrue(ZipFileUtil.remove(file, ZIP_ENTRY_NAME));
- assertTrue(file.exists());
- assertEquals(oldSize, file.length());
-
- } finally {
- if (file.exists()) {
- file.delete();
- }
- }
- }
-
-
-
-
-
-
- /**
- * Adds a file to the specified zip file, verifies the results, then deletes the zip file.
- *
- * @param file
- * The zip file on which to perform the add and remove test.
- * @since 4.3
- */
- private void add(final File file) throws Exception {
- final long oldSize = file.length();
- try {
- assertTrue(ZipFileUtil.add(file, ZIP_ENTRY_NAME));
- assertTrue(file.exists());
- assertTrue(file.length() > oldSize);
-
- } finally {
- if (file.exists()) {
- file.delete();
- }
- }
- }
-
- /**
- * Creates a copy of the specified file.
- *
- * @param file
- * The file to copy.
- * @return
- * @throws IOException
- * @since 4.3
- */
- private static File copy(final String file) throws IOException {
- final File copy = File.createTempFile(ZipFileUtil.TMP_PFX, ZipFileUtil.TMP_SFX);
- final byte[] buf = new byte[ZipFileUtil.BUFFER];
- BufferedInputStream in = null;
- BufferedOutputStream out = null;
- try {
- in = new BufferedInputStream(new FileInputStream(file));
- out = new BufferedOutputStream(new FileOutputStream(copy));
- for (int count = in.read(buf); count >= 0; count = in.read(buf)) {
- out.write(buf, 0, count);
- }
- } finally {
- if (in != null) {
- in.close();
- }
- if (out != null) {
- out.close();
- }
- }
- return copy;
- }
-
- // ===========================================================================================================================
- // Test Methods
-
- /**
- * @tests {@link ZipFileUtil#add(String, String)}, {@link ZipFileUtil#add(File, String)},
- * {@link ZipFileUtil#remove(String, String)}, {@link ZipFileUtil#remove(File, String)}
- * @since 4.3
- */
- public void testAddRemove() throws Exception {
- final File file = new File(NEW_ZIP_FILE_NAME);
- assertTrue(!file.exists());
- add(file);
- addRemove(copy(ZIP_FILE_NAME));
- add(copy(EMPTIED_ZIP_FILE_NAME));
- add(copy(EMPTY_ZIP_FILE_NAME));
- }
-
-
- /**
- * Tests ZipFileUtil.addAll()
- * @since 4.3
- */
- public void testAddAll() throws Exception {
- final File file = new File(NEW_ZIP_FILE_NAME);
-
- assertEquals(0, file.length());
- assertTrue(ZipFileUtil.addAll(file, PATH));
- assertTrue(file.length() > 0);
-
- }
-
- /**
- * Tests ZipFileUtil.addAll()
- * @since 4.3
- */
- public void testAddAllPrefix() throws Exception {
- final File file = new File(NEW_ZIP_FILE_NAME);
-
- assertEquals(0, file.length());
- assertTrue(ZipFileUtil.addAll(file, PATH, "my/zip/path")); //$NON-NLS-1$
- assertTrue(file.length() > 0);
- }
-
- public void testGet() throws Exception {
- final File file = new File(ZIP_FILE_NAME);
- assertTrue(file.exists());
-
-
- InputStream is = ZipFileUtil.get(file, "META-INF/MANIFEST.MF", false); //$NON-NLS-1$
-
- assertNotNull(is);
-
- byte[] data = ObjectConverterUtil.convertToByteArray(is);
-
- assertNotNull(data);
-
-
- if (data.length == 0) {
- fail("No manifest file returned"); //$NON-NLS-1$
- }
-
- }
-
- public void testGetManifest() throws Exception {
- final File file = new File(ZIP_FILE_NAME);
- assertTrue(file.exists());
-
-
- Manifest m = ZipFileUtil.getManifest(file);
-
- assertNotNull(m);
-
-
- }
-
-
- public void testFind() throws Exception {
- String jarname = PATH + "/extensionmodule/testjar.jar";
- final File file = new File(jarname);
- assertTrue(file.exists());
-
-
- List<String> found = ZipFileUtil.find(file, "Class.class$", false);
- assertNotNull(found);
- assertTrue(!found.isEmpty());
-
-
- }
-
- public void testFindIgnoreCase() throws Exception {
- String jarname = PATH + "/extensionmodule/testjar.jar";
- final File file = new File(jarname);
- assertTrue(file.exists());
-
-
- List<String> found = ZipFileUtil.find(file, "class.class$", true);
- assertNotNull(found);
- assertTrue(!found.isEmpty());
-
-
- }
-
- public void testNotFind() throws Exception {
- String jarname = PATH + "/extensionmodule/testjar.jar";
- final File file = new File(jarname);
- assertTrue(file.exists());
-
-
- List<String> found = ZipFileUtil.find(file, "^Class.class", false);
- assertNotNull(found);
- assertTrue(found.isEmpty());
-
-
- }
-
-}
Modified: branches/JCA/connector-sdk/src/main/java/com/metamatrix/core/commandshell/Command.java
===================================================================
--- branches/JCA/connector-sdk/src/main/java/com/metamatrix/core/commandshell/Command.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/connector-sdk/src/main/java/com/metamatrix/core/commandshell/Command.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -27,7 +27,9 @@
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
+import java.text.DateFormat;
import java.text.ParseException;
+import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
@@ -39,7 +41,6 @@
import com.metamatrix.core.id.IDGenerator;
import com.metamatrix.core.id.InvalidIDException;
import com.metamatrix.core.id.ObjectID;
-import com.metamatrix.core.util.DateUtil;
import com.metamatrix.core.util.FileUtil;
import com.metamatrix.core.util.StringUtil;
@@ -246,7 +247,7 @@
}
if (neededType.equals(Date.class)) {
try {
- return DateUtil.convertStringToDate(target);
+ return DateFormat.getDateTimeInstance().parse(target);
} catch (ParseException e) {
throw new ArgumentConversionException(e, e.getMessage());
}
Modified: branches/JCA/connector-sdk/src/main/java/com/metamatrix/core/commandshell/ScriptReader.java
===================================================================
--- branches/JCA/connector-sdk/src/main/java/com/metamatrix/core/commandshell/ScriptReader.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/connector-sdk/src/main/java/com/metamatrix/core/commandshell/ScriptReader.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -28,7 +28,6 @@
import com.metamatrix.core.CorePlugin;
import com.metamatrix.core.MetaMatrixRuntimeException;
import com.metamatrix.core.util.StringUtil;
-import com.metamatrix.core.util.StringUtilities;
/**
* Understands how to read specific command line scripts from a String containing multiple scripts.
@@ -61,7 +60,7 @@
testScriptIndex = 0;
this.testName = scriptName;
testScript = getScriptContents();
- testLines = StringUtilities.getLines(testScript);
+ testLines = StringUtil.getLines(testScript);
}
/**
@@ -140,7 +139,7 @@
private String getScriptContents() {
boolean readyForNewScript = true;
- String[] scriptLines = StringUtilities.getLines(script);
+ String[] scriptLines = StringUtil.getLines(script);
for (int i=0; i<scriptLines.length; i++) {
if (readyForNewScript) {
boolean openingBraceFound = false;
@@ -195,7 +194,7 @@
List subStrings = StringUtil.split(script, "{"); //$NON-NLS-1$
for (int i = 0; i < subStrings.size()-1; i++) {
String fragment = ((String) subStrings.get(i)).trim();
- String[] lines = StringUtilities.getLines(fragment);
+ String[] lines = StringUtil.getLines(fragment);
String testName = lines[lines.length-1];
if (!containsWhitespace(testName)) {
if (testName.length() > 0) {
Modified: branches/JCA/connector-sdk/src/test/java/com/metamatrix/core/commandshell/TestShell.java
===================================================================
--- branches/JCA/connector-sdk/src/test/java/com/metamatrix/core/commandshell/TestShell.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/connector-sdk/src/test/java/com/metamatrix/core/commandshell/TestShell.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -24,7 +24,7 @@
import junit.framework.TestCase;
import com.metamatrix.core.MetaMatrixRuntimeException;
-import com.metamatrix.core.util.StringUtilities;
+import com.metamatrix.core.util.StringUtil;
import com.metamatrix.core.util.UnitTestUtil;
public class TestShell extends TestCase {
@@ -45,13 +45,13 @@
public void testHelp() {
assertEquals("checkin String byte[] java.util.Date " //$NON-NLS-1$
- + StringUtilities.LINE_SEPARATOR + "exit " //$NON-NLS-1$
- + StringUtilities.LINE_SEPARATOR + "getLatest String " //$NON-NLS-1$
- + StringUtilities.LINE_SEPARATOR + "getTrace " //$NON-NLS-1$
- + StringUtilities.LINE_SEPARATOR + "help " //$NON-NLS-1$
- + StringUtilities.LINE_SEPARATOR + "method0 String[] " //$NON-NLS-1$
- + StringUtilities.LINE_SEPARATOR + "method1 String int[] " //$NON-NLS-1$
- + StringUtilities.LINE_SEPARATOR + "quit" //$NON-NLS-1$
+ + StringUtil.LINE_SEPARATOR + "exit " //$NON-NLS-1$
+ + StringUtil.LINE_SEPARATOR + "getLatest String " //$NON-NLS-1$
+ + StringUtil.LINE_SEPARATOR + "getTrace " //$NON-NLS-1$
+ + StringUtil.LINE_SEPARATOR + "help " //$NON-NLS-1$
+ + StringUtil.LINE_SEPARATOR + "method0 String[] " //$NON-NLS-1$
+ + StringUtil.LINE_SEPARATOR + "method1 String int[] " //$NON-NLS-1$
+ + StringUtil.LINE_SEPARATOR + "quit" //$NON-NLS-1$
, shell.execute("help").trim() ); //$NON-NLS-1$
}
Modified: branches/JCA/engine/src/main/java/com/metamatrix/common/buffer/impl/MemoryStorageManager.java
===================================================================
--- branches/JCA/engine/src/main/java/com/metamatrix/common/buffer/impl/MemoryStorageManager.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/engine/src/main/java/com/metamatrix/common/buffer/impl/MemoryStorageManager.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -23,7 +23,6 @@
package com.metamatrix.common.buffer.impl;
import java.nio.ByteBuffer;
-import java.util.Properties;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.common.buffer.FileStore;
Modified: branches/JCA/engine/src/test/java/com/metamatrix/query/analysis/TestAnalysisRecord.java
===================================================================
--- branches/JCA/engine/src/test/java/com/metamatrix/query/analysis/TestAnalysisRecord.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/engine/src/test/java/com/metamatrix/query/analysis/TestAnalysisRecord.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -24,7 +24,7 @@
import java.util.*;
-import com.metamatrix.core.util.StringUtilities;
+import com.metamatrix.core.util.StringUtil;
import junit.framework.TestCase;
@@ -75,7 +75,7 @@
rec.println("b"); //$NON-NLS-1$
String log = rec.getDebugLog();
- assertEquals("a" + StringUtilities.LINE_SEPARATOR + "b" + StringUtilities.LINE_SEPARATOR, log); //$NON-NLS-1$ //$NON-NLS-2$
+ assertEquals("a" + StringUtil.LINE_SEPARATOR + "b" + StringUtil.LINE_SEPARATOR, log); //$NON-NLS-1$ //$NON-NLS-2$
}
}
Modified: branches/JCA/engine/src/test/java/com/metamatrix/query/processor/proc/TestProcedureProcessor.java
===================================================================
--- branches/JCA/engine/src/test/java/com/metamatrix/query/processor/proc/TestProcedureProcessor.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/engine/src/test/java/com/metamatrix/query/processor/proc/TestProcedureProcessor.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -22,8 +22,7 @@
package com.metamatrix.query.processor.proc;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.Assert.*;
import java.sql.SQLException;
import java.util.ArrayList;
@@ -46,7 +45,6 @@
import com.metamatrix.common.types.DataTypeManager;
import com.metamatrix.common.types.XMLType;
import com.metamatrix.core.MetaMatrixCoreException;
-import com.metamatrix.core.util.StringUtilities;
import com.metamatrix.dqp.message.ParameterInfo;
import com.metamatrix.query.analysis.AnalysisRecord;
import com.metamatrix.query.mapping.relational.QueryNode;
@@ -2355,7 +2353,7 @@
FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
String resultFile = "TestXMLProcessor-testNested2WithContextCriteria5d.xml"; //$NON-NLS-1$
String expectedDoc = TestXMLProcessor.readFile(resultFile);
- expectedDoc = StringUtilities.removeChars(expectedDoc, new char[] {'\r'});
+ expectedDoc = expectedDoc.replaceAll("\\r", ""); //$NON-NLS-1$ //$NON-NLS-2$
FakeMetadataObject pm1 = metadata.getStore().findObject("xqttest",FakeMetadataObject.MODEL); //$NON-NLS-1$
FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs2", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.XML }); //$NON-NLS-1$ //$NON-NLS-2$
Modified: branches/JCA/test-integration/common/src/test/java/com/metamatrix/cdk/TestConnectorShell.java
===================================================================
--- branches/JCA/test-integration/common/src/test/java/com/metamatrix/cdk/TestConnectorShell.java 2010-03-03 19:53:45 UTC (rev 1892)
+++ branches/JCA/test-integration/common/src/test/java/com/metamatrix/cdk/TestConnectorShell.java 2010-03-03 21:54:32 UTC (rev 1893)
@@ -31,7 +31,6 @@
import com.metamatrix.core.commandshell.CommandShell;
import com.metamatrix.core.commandshell.CommandShellTest;
import com.metamatrix.core.util.StringUtil;
-import com.metamatrix.core.util.StringUtilities;
import com.metamatrix.core.util.UnitTestUtil;
public class TestConnectorShell extends CommandShellTest {
@@ -203,11 +202,11 @@
start();
String loadedProperties = connectorShell.execute("getProperties"); //$NON-NLS-1$
String expected = new StringBuffer("property1=PropVal1") //$NON-NLS-1$
- .append(StringUtilities.LINE_SEPARATOR)
+ .append(StringUtil.LINE_SEPARATOR)
.append("property2=PropVal2") //$NON-NLS-1$
- .append(StringUtilities.LINE_SEPARATOR)
+ .append(StringUtil.LINE_SEPARATOR)
.append("property3=com.metamatrix.cdk.propertyVal") //$NON-NLS-1$
- .append(StringUtilities.LINE_SEPARATOR)
+ .append(StringUtil.LINE_SEPARATOR)
.toString();
assertEquals(expected, loadedProperties);
}
@@ -219,11 +218,11 @@
String loadedProperties = connectorShell.execute("getProperties"); //$NON-NLS-1$
assertNotNull(loadedProperties);
String expected = new StringBuffer("property1=PropVal1") //$NON-NLS-1$
- .append(StringUtilities.LINE_SEPARATOR)
+ .append(StringUtil.LINE_SEPARATOR)
.append("property2=PropVal2") //$NON-NLS-1$
- .append(StringUtilities.LINE_SEPARATOR)
+ .append(StringUtil.LINE_SEPARATOR)
.append("property3=com.metamatrix.cdk.propertyVal") //$NON-NLS-1$
- .append(StringUtilities.LINE_SEPARATOR)
+ .append(StringUtil.LINE_SEPARATOR)
.toString();
assertEquals(expected, loadedProperties);
}
14 years, 2 months
teiid SVN: r1891 - in branches/JCA: client/src/main/java/com/metamatrix/common/comm/platform/socket/client and 18 other directories.
by teiid-commits@lists.jboss.org
Author: shawkins
Date: 2010-03-03 13:56:39 -0500 (Wed, 03 Mar 2010)
New Revision: 1891
Added:
branches/JCA/engine/src/main/java/com/metamatrix/dqp/message/RequestID.java
Removed:
branches/JCA/client/src/main/java/com/metamatrix/dqp/message/RequestID.java
Modified:
branches/JCA/client-jdbc/src/main/java/com/metamatrix/jdbc/MMDatabaseMetaData.java
branches/JCA/client/src/main/java/com/metamatrix/common/comm/platform/socket/Handshake.java
branches/JCA/client/src/main/java/com/metamatrix/common/comm/platform/socket/client/ServiceInvocationStruct.java
branches/JCA/client/src/main/java/com/metamatrix/dqp/client/MetadataResult.java
branches/JCA/client/src/main/java/org/teiid/adminapi/impl/RequestMetadata.java
branches/JCA/common-core/src/main/java/com/metamatrix/core/CoreConstants.java
branches/JCA/common-core/src/main/java/com/metamatrix/core/util/ExternalizeUtil.java
branches/JCA/documentation/reference/src/main/docbook/en-US/content/datatypes.xml
branches/JCA/documentation/reference/src/main/docbook/en-US/content/procedures.xml
branches/JCA/engine/src/main/java/com/metamatrix/query/processor/proc/ExecDynamicSqlInstruction.java
branches/JCA/engine/src/main/java/com/metamatrix/query/resolver/command/DynamicCommandResolver.java
branches/JCA/engine/src/main/java/com/metamatrix/query/sql/ProcedureReservedWords.java
branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/Request.java
branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/validator/AuthorizationValidationVisitor.java
branches/JCA/engine/src/main/javacc/com/metamatrix/query/parser/SQLParser.jj
branches/JCA/engine/src/test/java/com/metamatrix/query/validator/TestValidator.java
branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCoreRequestHandling.java
branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/validator/TestAuthorizationValidationVisitor.java
branches/JCA/metadata/src/main/resources/System.vdb
Log:
TEIID-1005 changing system schema to sys and adding DVARS as the using clause group for dynamic sql
Modified: branches/JCA/client/src/main/java/com/metamatrix/common/comm/platform/socket/Handshake.java
===================================================================
--- branches/JCA/client/src/main/java/com/metamatrix/common/comm/platform/socket/Handshake.java 2010-03-03 18:45:43 UTC (rev 1890)
+++ branches/JCA/client/src/main/java/com/metamatrix/common/comm/platform/socket/Handshake.java 2010-03-03 18:56:39 UTC (rev 1891)
@@ -22,14 +22,17 @@
package com.metamatrix.common.comm.platform.socket;
-import java.io.Serializable;
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
import com.metamatrix.common.util.ApplicationInfo;
/**
* Represents the information needed in a socket connection handshake
*/
-public class Handshake implements Serializable {
+public class Handshake implements Externalizable {
private static final long serialVersionUID = 7839271224736355515L;
@@ -63,6 +66,18 @@
public void setPublicKey(byte[] key) {
this.publicKey = key;
}
-
+ @Override
+ public void readExternal(ObjectInput in) throws IOException,
+ ClassNotFoundException {
+ version = (String)in.readObject();
+ publicKey = (byte[])in.readObject();
+ }
+
+ @Override
+ public void writeExternal(ObjectOutput out) throws IOException {
+ out.writeObject(version);
+ out.writeObject(publicKey);
+ }
+
}
Modified: branches/JCA/client/src/main/java/com/metamatrix/common/comm/platform/socket/client/ServiceInvocationStruct.java
===================================================================
--- branches/JCA/client/src/main/java/com/metamatrix/common/comm/platform/socket/client/ServiceInvocationStruct.java 2010-03-03 18:45:43 UTC (rev 1890)
+++ branches/JCA/client/src/main/java/com/metamatrix/common/comm/platform/socket/client/ServiceInvocationStruct.java 2010-03-03 18:56:39 UTC (rev 1891)
@@ -31,6 +31,7 @@
import java.io.ObjectOutput;
import com.metamatrix.core.util.ArgCheck;
+import com.metamatrix.core.util.ExternalizeUtil;
public final class ServiceInvocationStruct implements Externalizable {
private static final long serialVersionUID = 1207674062670068350L;
@@ -43,7 +44,7 @@
}
public ServiceInvocationStruct(Object[] args, String methodName,
- Class targetClass) {
+ Class<?> targetClass) {
ArgCheck.isNotNull(methodName);
ArgCheck.isNotNull(targetClass);
this.args = args;
@@ -55,12 +56,12 @@
ClassNotFoundException {
this.targetClass = (String)in.readObject();
this.methodName = (String)in.readObject();
- this.args = (Object[])in.readObject();
+ this.args = ExternalizeUtil.readArray(in, Object.class);
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(targetClass);
out.writeObject(methodName);
- out.writeObject(args);
+ ExternalizeUtil.writeArray(out, args);
}
}
\ No newline at end of file
Modified: branches/JCA/client/src/main/java/com/metamatrix/dqp/client/MetadataResult.java
===================================================================
--- branches/JCA/client/src/main/java/com/metamatrix/dqp/client/MetadataResult.java 2010-03-03 18:45:43 UTC (rev 1890)
+++ branches/JCA/client/src/main/java/com/metamatrix/dqp/client/MetadataResult.java 2010-03-03 18:56:39 UTC (rev 1891)
@@ -22,10 +22,15 @@
package com.metamatrix.dqp.client;
-import java.io.Serializable;
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
import java.util.Map;
-public class MetadataResult implements Serializable {
+import com.metamatrix.core.util.ExternalizeUtil;
+
+public class MetadataResult implements Externalizable {
private static final long serialVersionUID = -1520482281079030324L;
private Map[] columnMetadata;
private int parameterCount;
@@ -42,6 +47,17 @@
return parameterCount;
}
+ @Override
+ public void readExternal(ObjectInput in) throws IOException,
+ ClassNotFoundException {
+ columnMetadata = ExternalizeUtil.readArray(in, Map.class);
+ parameterCount = in.readInt();
+ }
+ @Override
+ public void writeExternal(ObjectOutput out) throws IOException {
+ ExternalizeUtil.writeArray(out, columnMetadata);
+ out.writeInt(parameterCount);
+ }
}
Deleted: branches/JCA/client/src/main/java/com/metamatrix/dqp/message/RequestID.java
===================================================================
--- branches/JCA/client/src/main/java/com/metamatrix/dqp/message/RequestID.java 2010-03-03 18:45:43 UTC (rev 1890)
+++ branches/JCA/client/src/main/java/com/metamatrix/dqp/message/RequestID.java 2010-03-03 18:56:39 UTC (rev 1891)
@@ -1,175 +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.message;
-
-import java.io.Externalizable;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-
-/**
- * <p>This class represents an identifier for a request. However, there are some
- * differences in what constitutes "uniqueness" for a given RequestID that
- * is based on context (where the id is used). The RequestID has 2 parts:
- * connectionID, and executionIDFor the purposes of the RequestID, the combined
- * representation is "connectionID.executionID" - this implies a scoping
- * for the name parts. The connectionID specifies a particular connection that
- * is making requests. Each connection generates a unique executionID for each
- * request execution, so the executionID is only unique in the context of a
- * connectionID. </p>
- *
- * <p>When this class is used between client and server, the connectionID is implied
- * and thus only the executionID part will be used. The server will qualify the
- * executionID with a connectionID when it reaches the server. </p>
- *
- * <p>RequestIDs are immutable so no setters exist. This allows hashcodes to be
- * pre-computed for faster comparison in equals.</p>
- */
-public class RequestID implements Externalizable {
-
- static final long serialVersionUID = -2888539138291776071L;
-
- public static final String NO_CONNECTION_STR = "C"; //$NON-NLS-1$
- private static final String SEPARATOR = "."; //$NON-NLS-1$
-
- // Basic state
- private String connectionID;
- private long executionID;
-
- // Derived state
- private String combinedID;
- private int hash;
-
- /**
- * Necessary for implementing Externalizable
- */
- public RequestID() {
- }
-
- /**
- * Create a RequestID using all of the ID parts.
- * @param connectionID Identifies a connection, may be null
- * @param executionID Identifies an execution, cannot be null
- */
- public RequestID(String connectionID, long executionID) {
- this.connectionID = connectionID;
- this.executionID = executionID;
-
- createCombinedID();
- computeHashCode();
- }
-
- public RequestID(long connectionID, long executionID) {
- this.connectionID = String.valueOf(connectionID);
- this.executionID = executionID;
-
- createCombinedID();
- computeHashCode();
- }
-
- /**
- * Create a RequestID for an execution where the connection is
- * not specified.
- * @param executionID Identifies an execution, cannot be null
- */
- public RequestID(long executionID) {
- this(null, executionID);
- }
-
-
- /**
- * Return connectionID, may be null if connection has not been specified.
- * @return Connection ID, may be null
- */
- public String getConnectionID() {
- return this.connectionID;
- }
-
- /**
- * Return executionID, which identifies a per-connection execution.
- * @return Execution ID
- */
- public long getExecutionID() {
- return this.executionID;
- }
-
- /**
- * Create a unique combined ID string from the RequestID parts.
- */
- private void createCombinedID() {
- StringBuffer combinedStr = new StringBuffer();
- if(this.connectionID != null) {
- combinedStr.append(this.connectionID);
- } else {
- combinedStr.append(NO_CONNECTION_STR);
- }
- combinedStr.append(SEPARATOR);
- combinedStr.append(this.executionID);
-
- this.combinedID = combinedStr.toString();
- }
-
- private void computeHashCode() {
- this.hash = combinedID.hashCode();
- }
-
- public int hashCode() {
- return this.hash;
- }
-
- public boolean equals(Object obj) {
- if(obj == this) {
- return true;
- } else if(obj == null || !(obj instanceof RequestID) || obj.hashCode() != this.hashCode()) {
- return false;
- } else {
- return this.toString().equals(obj.toString());
- }
- }
-
- /**
- * Return a combined string for the ID.
- */
- public String toString() {
- return this.combinedID;
- }
-
- /**
- * @see java.io.Externalizable#readExternal(java.io.ObjectInput)
- */
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
- connectionID = (String)in.readObject();
- executionID = in.readLong();
-
- createCombinedID();
- computeHashCode();
- }
-
- /**
- * @see java.io.Externalizable#writeExternal(java.io.ObjectOutput)
- */
- public void writeExternal(ObjectOutput out) throws IOException {
- out.writeObject(connectionID);
- out.writeLong(executionID);
- }
-}
Modified: branches/JCA/client/src/main/java/org/teiid/adminapi/impl/RequestMetadata.java
===================================================================
--- branches/JCA/client/src/main/java/org/teiid/adminapi/impl/RequestMetadata.java 2010-03-03 18:45:43 UTC (rev 1890)
+++ branches/JCA/client/src/main/java/org/teiid/adminapi/impl/RequestMetadata.java 2010-03-03 18:56:39 UTC (rev 1891)
@@ -28,7 +28,7 @@
import org.jboss.metatype.api.annotations.MetaMapping;
import org.teiid.adminapi.Request;
-import com.metamatrix.dqp.message.RequestID;
+import com.metamatrix.core.util.HashCodeUtil;
@MetaMapping(RequestMetadataMapper.class)
@@ -45,9 +45,6 @@
private int nodeID = Integer.MIN_VALUE;
private String transactionId;
- // Derived state
- private RequestID requestId;
-
@Override
@ManagementProperty(description="Unique Identifier for Request", readOnly=true)
public long getExecutionId() {
@@ -118,13 +115,6 @@
this.transactionId = id;
}
- public RequestID getRequestId() {
- if (this.requestId == null) {
- this.requestId = new RequestID(this.sessionId, this.executionId);
- }
- return this.requestId;
- }
-
@Override
public boolean equals(Object obj) {
if (!(obj instanceof RequestMetadata)) {
@@ -138,7 +128,7 @@
}
public int hashCode() {
- return getRequestId().hashCode();
+ return HashCodeUtil.hashCode((int)executionId, (int)sessionId);
}
public String toString() {
Modified: branches/JCA/client-jdbc/src/main/java/com/metamatrix/jdbc/MMDatabaseMetaData.java
===================================================================
--- branches/JCA/client-jdbc/src/main/java/com/metamatrix/jdbc/MMDatabaseMetaData.java 2010-03-03 18:45:43 UTC (rev 1890)
+++ branches/JCA/client-jdbc/src/main/java/com/metamatrix/jdbc/MMDatabaseMetaData.java 2010-03-03 18:56:39 UTC (rev 1891)
@@ -46,6 +46,7 @@
import com.metamatrix.common.types.DataTypeManager;
import com.metamatrix.common.types.MMJDBCSQLTypeInfo;
import com.metamatrix.common.util.SqlUtil;
+import com.metamatrix.core.CoreConstants;
import com.metamatrix.core.MetaMatrixRuntimeException;
import com.metamatrix.dqp.message.ResultsMessage;
import com.metamatrix.dqp.metadata.ResultsMetadataConstants;
@@ -63,6 +64,8 @@
*/
public class MMDatabaseMetaData extends WrapperImpl implements com.metamatrix.jdbc.api.DatabaseMetaData {
+ private static final String DATA_TYPES = "DataTypes"; //$NON-NLS-1$
+
private static Logger logger = Logger.getLogger("org.teiid.jdbc"); //$NON-NLS-1$
/** CONSTANTS */
@@ -122,7 +125,7 @@
private final static String LIKE_ESCAPE = " LIKE ? ESCAPE '" + ESCAPE_SEARCH_STRING + "' ";//$NON-NLS-1$//$NON-NLS-2$
final private static class RUNTIME_MODEL{
- public final static String VIRTUAL_MODEL_NAME = "System"; //$NON-NLS-1$
+ public final static String VIRTUAL_MODEL_NAME = CoreConstants.SYSTEM_MODEL;
}
private static final String TYPE_MAPPING;
@@ -1786,24 +1789,24 @@
Map[] metadataList = new Map[18];
- metadataList[0] = getColumnMetadata("System.DataTypes", JDBCColumnNames.TYPE_INFO.TYPE_NAME, MMJDBCSQLTypeInfo.STRING, ResultsMetadataConstants.NULL_TYPES.NOT_NULL, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE);//$NON-NLS-1$
- metadataList[1] = getColumnMetadata("System.DataTypes", JDBCColumnNames.TYPE_INFO.DATA_TYPE, MMJDBCSQLTypeInfo.INTEGER, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
- metadataList[2] = getColumnMetadata("System.DataTypes", JDBCColumnNames.TYPE_INFO.PRECISION, MMJDBCSQLTypeInfo.INTEGER, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
- metadataList[3] = getColumnMetadata("System.DataTypes", JDBCColumnNames.TYPE_INFO.LITERAL_PREFIX, MMJDBCSQLTypeInfo.STRING, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
- metadataList[4] = getColumnMetadata("System.DataTypes", JDBCColumnNames.TYPE_INFO.LITERAL_SUFFIX, MMJDBCSQLTypeInfo.STRING, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
- metadataList[5] = getColumnMetadata("System.DataTypes", JDBCColumnNames.TYPE_INFO.CREATE_PARAMS, MMJDBCSQLTypeInfo.STRING, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
- metadataList[6] = getColumnMetadata("System.DataTypes", JDBCColumnNames.TYPE_INFO.NULLABLE, MMJDBCSQLTypeInfo.SHORT, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
- metadataList[7] = getColumnMetadata("System.DataTypes", JDBCColumnNames.TYPE_INFO.CASE_SENSITIVE, MMJDBCSQLTypeInfo.BOOLEAN, ResultsMetadataConstants.NULL_TYPES.NOT_NULL, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE);//$NON-NLS-1$
- metadataList[8] = getColumnMetadata("System.DataTypes", JDBCColumnNames.TYPE_INFO.SEARCHABLE, MMJDBCSQLTypeInfo.SHORT, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
- metadataList[9] = getColumnMetadata("System.DataTypes", JDBCColumnNames.TYPE_INFO.UNSIGNED_ATTRIBUTE, MMJDBCSQLTypeInfo.BOOLEAN, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
- metadataList[10] = getColumnMetadata("System.DataTypes", JDBCColumnNames.TYPE_INFO.FIXED_PREC_SCALE, MMJDBCSQLTypeInfo.BOOLEAN, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
- metadataList[11] = getColumnMetadata("System.DataTypes", JDBCColumnNames.TYPE_INFO.AUTOINCREMENT, MMJDBCSQLTypeInfo.BOOLEAN, ResultsMetadataConstants.NULL_TYPES.NOT_NULL, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.FALSE, Boolean.TRUE, Boolean.TRUE);//$NON-NLS-1$
- metadataList[12] = getColumnMetadata("System.DataTypes", JDBCColumnNames.TYPE_INFO.LOCAL_TYPE_NAME, MMJDBCSQLTypeInfo.STRING, ResultsMetadataConstants.NULL_TYPES.NOT_NULL, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE);//$NON-NLS-1$
- metadataList[13] = getColumnMetadata("System.DataTypes", JDBCColumnNames.TYPE_INFO.MINIMUM_SCALE, MMJDBCSQLTypeInfo.SHORT, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
- metadataList[14] = getColumnMetadata("System.DataTypes", JDBCColumnNames.TYPE_INFO.MAXIMUM_SCALE, MMJDBCSQLTypeInfo.SHORT, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
- metadataList[15] = getColumnMetadata("System.DataTypes", JDBCColumnNames.TYPE_INFO.SQL_DATA_TYPE, MMJDBCSQLTypeInfo.INTEGER, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
- metadataList[16] = getColumnMetadata("System.DataTypes", JDBCColumnNames.TYPE_INFO.SQL_DATETIME_SUB, MMJDBCSQLTypeInfo.INTEGER, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
- metadataList[17] = getColumnMetadata("System.DataTypes", JDBCColumnNames.TYPE_INFO.NUM_PREC_RADIX, MMJDBCSQLTypeInfo.INTEGER, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE);//$NON-NLS-1$
+ metadataList[0] = getColumnMetadata(CoreConstants.SYSTEM_MODEL + "." + DATA_TYPES, JDBCColumnNames.TYPE_INFO.TYPE_NAME, MMJDBCSQLTypeInfo.STRING, ResultsMetadataConstants.NULL_TYPES.NOT_NULL, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE);//$NON-NLS-1$
+ metadataList[1] = getColumnMetadata(CoreConstants.SYSTEM_MODEL + "." + DATA_TYPES, JDBCColumnNames.TYPE_INFO.DATA_TYPE, MMJDBCSQLTypeInfo.INTEGER, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
+ metadataList[2] = getColumnMetadata(CoreConstants.SYSTEM_MODEL + "." + DATA_TYPES, JDBCColumnNames.TYPE_INFO.PRECISION, MMJDBCSQLTypeInfo.INTEGER, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
+ metadataList[3] = getColumnMetadata(CoreConstants.SYSTEM_MODEL + "." + DATA_TYPES, JDBCColumnNames.TYPE_INFO.LITERAL_PREFIX, MMJDBCSQLTypeInfo.STRING, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
+ metadataList[4] = getColumnMetadata(CoreConstants.SYSTEM_MODEL + "." + DATA_TYPES, JDBCColumnNames.TYPE_INFO.LITERAL_SUFFIX, MMJDBCSQLTypeInfo.STRING, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
+ metadataList[5] = getColumnMetadata(CoreConstants.SYSTEM_MODEL + "." + DATA_TYPES, JDBCColumnNames.TYPE_INFO.CREATE_PARAMS, MMJDBCSQLTypeInfo.STRING, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
+ metadataList[6] = getColumnMetadata(CoreConstants.SYSTEM_MODEL + "." + DATA_TYPES, JDBCColumnNames.TYPE_INFO.NULLABLE, MMJDBCSQLTypeInfo.SHORT, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
+ metadataList[7] = getColumnMetadata(CoreConstants.SYSTEM_MODEL + "." + DATA_TYPES, JDBCColumnNames.TYPE_INFO.CASE_SENSITIVE, MMJDBCSQLTypeInfo.BOOLEAN, ResultsMetadataConstants.NULL_TYPES.NOT_NULL, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE);//$NON-NLS-1$
+ metadataList[8] = getColumnMetadata(CoreConstants.SYSTEM_MODEL + "." + DATA_TYPES, JDBCColumnNames.TYPE_INFO.SEARCHABLE, MMJDBCSQLTypeInfo.SHORT, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
+ metadataList[9] = getColumnMetadata(CoreConstants.SYSTEM_MODEL + "." + DATA_TYPES, JDBCColumnNames.TYPE_INFO.UNSIGNED_ATTRIBUTE, MMJDBCSQLTypeInfo.BOOLEAN, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
+ metadataList[10] = getColumnMetadata(CoreConstants.SYSTEM_MODEL + "." + DATA_TYPES, JDBCColumnNames.TYPE_INFO.FIXED_PREC_SCALE, MMJDBCSQLTypeInfo.BOOLEAN, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
+ metadataList[11] = getColumnMetadata(CoreConstants.SYSTEM_MODEL + "." + DATA_TYPES, JDBCColumnNames.TYPE_INFO.AUTOINCREMENT, MMJDBCSQLTypeInfo.BOOLEAN, ResultsMetadataConstants.NULL_TYPES.NOT_NULL, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.FALSE, Boolean.TRUE, Boolean.TRUE);//$NON-NLS-1$
+ metadataList[12] = getColumnMetadata(CoreConstants.SYSTEM_MODEL + "." + DATA_TYPES, JDBCColumnNames.TYPE_INFO.LOCAL_TYPE_NAME, MMJDBCSQLTypeInfo.STRING, ResultsMetadataConstants.NULL_TYPES.NOT_NULL, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE);//$NON-NLS-1$
+ metadataList[13] = getColumnMetadata(CoreConstants.SYSTEM_MODEL + "." + DATA_TYPES, JDBCColumnNames.TYPE_INFO.MINIMUM_SCALE, MMJDBCSQLTypeInfo.SHORT, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
+ metadataList[14] = getColumnMetadata(CoreConstants.SYSTEM_MODEL + "." + DATA_TYPES, JDBCColumnNames.TYPE_INFO.MAXIMUM_SCALE, MMJDBCSQLTypeInfo.SHORT, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
+ metadataList[15] = getColumnMetadata(CoreConstants.SYSTEM_MODEL + "." + DATA_TYPES, JDBCColumnNames.TYPE_INFO.SQL_DATA_TYPE, MMJDBCSQLTypeInfo.INTEGER, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
+ metadataList[16] = getColumnMetadata(CoreConstants.SYSTEM_MODEL + "." + DATA_TYPES, JDBCColumnNames.TYPE_INFO.SQL_DATETIME_SUB, MMJDBCSQLTypeInfo.INTEGER, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE);//$NON-NLS-1$
+ metadataList[17] = getColumnMetadata(CoreConstants.SYSTEM_MODEL + "." + DATA_TYPES, JDBCColumnNames.TYPE_INFO.NUM_PREC_RADIX, MMJDBCSQLTypeInfo.INTEGER, ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE);//$NON-NLS-1$
ResultSetMetaData rmetadata = ResultsMetadataWithProvider.newInstance(StaticMetadataProvider.createWithData(metadataList, 0));
Modified: branches/JCA/common-core/src/main/java/com/metamatrix/core/CoreConstants.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/core/CoreConstants.java 2010-03-03 18:45:43 UTC (rev 1890)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/core/CoreConstants.java 2010-03-03 18:56:39 UTC (rev 1891)
@@ -51,17 +51,10 @@
String PROXIES = "proxies"; //$NON-NLS-1$
}
- public static final String SYSTEM_MODEL = "System"; //$NON-NLS-1$
+ public static final String SYSTEM_MODEL = "SYS"; //$NON-NLS-1$
public static final String SYSTEM_VDB = "System.vdb"; //$NON-NLS-1$
- public static final String SYSTEM_PHYSICAL_MODEL_NAME = "SystemPhysical"; //$NON-NLS-1$
-
- public static final String SYSTEM_ADMIN_MODEL_NAME = "SystemAdmin"; //$NON-NLS-1$
-
- public static final String SYSTEM_ADMIN_PHYSICAL_MODEL_NAME = "SystemAdminPhysical"; //$NON-NLS-1$
-
-
public static final String EXPORTED_VDB_FILE_EXTENSION = VdbConstants.VDB_DEF_FILE_EXTENSION;
public static final String VDB_ARCHIVE_EXTENSION = VdbConstants.VDB_ARCHIVE_EXTENSION;
Modified: branches/JCA/common-core/src/main/java/com/metamatrix/core/util/ExternalizeUtil.java
===================================================================
--- branches/JCA/common-core/src/main/java/com/metamatrix/core/util/ExternalizeUtil.java 2010-03-03 18:45:43 UTC (rev 1890)
+++ branches/JCA/common-core/src/main/java/com/metamatrix/core/util/ExternalizeUtil.java 2010-03-03 18:56:39 UTC (rev 1891)
@@ -25,10 +25,10 @@
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
+import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -66,36 +66,22 @@
* @param coll reference to a Collection. Can be null.
* @throws IOException
*/
- public static void writeCollection(ObjectOutput out, Collection coll) throws IOException {
+ public static void writeCollection(ObjectOutput out, Collection<?> coll) throws IOException {
if (coll == null) {
out.writeInt(0);
} else {
final int size = coll.size();
if (size > 0) {
out.writeInt(coll.size());
- for (Iterator i = coll.iterator(); i.hasNext();) {
- out.writeObject(i.next());
+ for (Object object : coll) {
+ out.writeObject(object);
}
}
}
}
- /**
- * Writes a List to the output using its indexes.
- * @param out the output instance
- * @param list reference to a List. Can be null.
- * @throws IOException
- */
- public static void writeList(ObjectOutput out, List list) throws IOException {
- if (list == null) {
- out.writeInt(0);
- } else {
- final int size = list.size();
- out.writeInt(size);
- for (int i = 0; i < size; i++) {
- out.writeObject(list.get(i));
- }
- }
+ public static void writeList(ObjectOutput out, List<?> coll) throws IOException {
+ writeCollection(out, coll);
}
/**
@@ -104,14 +90,12 @@
* @param list reference to a Map. Can be null.
* @throws IOException
*/
- public static void writeMap(ObjectOutput out, Map map) throws IOException {
+ public static void writeMap(ObjectOutput out, Map<?, ?> map) throws IOException {
if (map == null) {
out.writeInt(0);
} else {
out.writeInt(map.size());
- Map.Entry entry = null;
- for (Iterator i = map.entrySet().iterator(); i.hasNext();) {
- entry = (Map.Entry)i.next();
+ for (Map.Entry<?, ?> entry : map.entrySet()) {
out.writeObject(entry.getKey());
out.writeObject(entry.getValue());
}
@@ -119,21 +103,26 @@
}
/**
- * Reads an array of String that was written to the ouput by this utility class
+ * Reads an array of String that was written to the output by this utility class
* @param in
* @return a non-null String[]
* @throws IOException
* @throws ClassNotFoundException
*/
- public static String[] readStringArray(ObjectInput in) throws IOException, ClassNotFoundException {
+ @SuppressWarnings("unchecked")
+ public static <T> T[] readArray(ObjectInput in, Class<T> type) throws IOException, ClassNotFoundException {
final int length = in.readInt();
- String[] strings = new String[length];
+ T[] result = (T[])Array.newInstance(type, length);
for (int i = 0; i < length; i++) {
- strings[i] = (String)in.readObject();
+ result[i] = type.cast(in.readObject());
}
- return strings;
+ return result;
}
+ public static String[] readStringArray(ObjectInput in) throws IOException, ClassNotFoundException {
+ return readArray(in, String.class);
+ }
+
/**
* Reads a List that was written by this utility class.
* @param in
@@ -141,15 +130,14 @@
* @throws IOException
* @throws ClassNotFoundException
*/
- public static List readList(ObjectInput in) throws IOException, ClassNotFoundException {
- final int size = in.readInt();
- Object [] array = new Object[size];
- for (int i = 0; i < size; i++) {
- array[i] = in.readObject();
- }
- return Arrays.asList(array);
+ public static <T> List<T> readList(ObjectInput in, Class<T> type) throws IOException, ClassNotFoundException {
+ return Arrays.asList(readArray(in, type));
}
+ public static List<?> readList(ObjectInput in) throws IOException, ClassNotFoundException {
+ return readList(in, Object.class);
+ }
+
/**
* Reads a Map that was written by this utility class
* @param in
@@ -157,11 +145,12 @@
* @throws IOException
* @throws ClassNotFoundException
*/
- public static Map readMap(ObjectInput in) throws IOException, ClassNotFoundException {
+ @SuppressWarnings("unchecked")
+ public static <K, V> Map<K, V> readMap(ObjectInput in) throws IOException, ClassNotFoundException {
final int size = in.readInt();
- HashMap map = new HashMap(size + 1, 1);
+ HashMap<K, V> map = new HashMap<K, V>(size);
for (int i = 0; i < size; i++) {
- map.put(in.readObject(), in.readObject());
+ map.put((K)in.readObject(), (V)in.readObject());
}
return map;
}
Modified: branches/JCA/documentation/reference/src/main/docbook/en-US/content/datatypes.xml
===================================================================
--- branches/JCA/documentation/reference/src/main/docbook/en-US/content/datatypes.xml 2010-03-03 18:45:43 UTC (rev 1890)
+++ branches/JCA/documentation/reference/src/main/docbook/en-US/content/datatypes.xml 2010-03-03 18:56:39 UTC (rev 1891)
@@ -28,9 +28,9 @@
</thead>
<tbody>
<row>
- <entry>string</entry>
+ <entry>string or varchar</entry>
<entry>variable length character string with a
- maximum length of 4000</entry>
+ maximum length of 4000. Note that the length cannot be explicitly set with the type literal, e.g. varchar(100).</entry>
<entry>java.lang.String</entry>
<entry>VARCHAR</entry>
<entry>VARCHAR</entry>
@@ -51,14 +51,14 @@
<entry>SMALLINT</entry>
</row>
<row>
- <entry>byte</entry>
+ <entry>byte or tinyint</entry>
<entry>numeric, integral type, signed 8-bit</entry>
<entry>java.lang.Byte</entry>
<entry>TINYINT</entry>
<entry>SMALLINT</entry>
</row>
<row>
- <entry>short</entry>
+ <entry>short or smallint</entry>
<entry>numeric, integral type, signed 16-bit</entry>
<entry>java.lang.Short</entry>
<entry>SMALLINT</entry>
@@ -72,7 +72,7 @@
<entry>INTEGER</entry>
</row>
<row>
- <entry>long</entry>
+ <entry>long or bigint</entry>
<entry>numeric, integral type, signed 64-bit</entry>
<entry>java.lang.Long</entry>
<entry>BIGINT</entry>
@@ -87,7 +87,7 @@
<entry>NUMERIC</entry>
</row>
<row>
- <entry>float</entry>
+ <entry>float or real</entry>
<entry>numeric, floating point type, 32-bit IEEE 754
floating-point numbers</entry>
<entry>java.lang.Float</entry>
@@ -103,9 +103,9 @@
<entry>DOUBLE</entry>
</row>
<row>
- <entry>bigdecimal</entry>
+ <entry>bigdecimal or decimal</entry>
<entry>numeric, floating point type, arbitrary
- precision of up to 1000 digits</entry>
+ precision of up to 1000 digits. Note that the precision and scale cannot be explicitly set with the type literal, e.g. decimal(38, 2).</entry>
<entry>java.math.BigDecimal</entry>
<entry>NUMERIC</entry>
<entry>NUMERIC</entry>
Modified: branches/JCA/documentation/reference/src/main/docbook/en-US/content/procedures.xml
===================================================================
--- branches/JCA/documentation/reference/src/main/docbook/en-US/content/procedures.xml 2010-03-03 18:45:43 UTC (rev 1890)
+++ branches/JCA/documentation/reference/src/main/docbook/en-US/content/procedures.xml 2010-03-03 18:56:39 UTC (rev 1891)
@@ -49,7 +49,7 @@
</para>
</listitem>
<listitem>
- <para>The "USING" clause allows the dynamic SQL string to contain variable references that are bound at runtime to specified values. This allows for some independence of the SQL string from the surrounding procedure variable names and input names. In the dynamic command "USING" clause, each variable is specified by short name only. However in the dynamic SQL the "USING" variable must be fully qualified to "USING.". The "USING" clause is only for values that will be used in the dynamic SQL as legal expressions. It is not possible to use the "USING" clause to replace table names, keywords, etc. This makes using symbols equivalent in power to normal bind (?) expressions in prepared statements. The "USING" clause helps reduce the amount of string manipulation needed. If a reference is made to a USING symbol in the SQL string that is not bound to a value in the "USING" clause, an exception will occur.
+ <para>The "USING" clause allows the dynamic SQL string to contain variable references that are bound at runtime to specified values. This allows for some independence of the SQL string from the surrounding procedure variable names and input names. In the dynamic command "USING" clause, each variable is specified by short name only. However in the dynamic SQL the "USING" variable must be fully qualified to "UVAR.". The "USING" clause is only for values that will be used in the dynamic SQL as legal expressions. It is not possible to use the "USING" clause to replace table names, keywords, etc. This makes using symbols equivalent in power to normal bind (?) expressions in prepared statements. The "USING" clause helps reduce the amount of string manipulation needed. If a reference is made to a USING symbol in the SQL string that is not bound to a value in the "USING" clause, an exception will occur.
</para>
</listitem>
<listitem>
@@ -63,7 +63,7 @@
/* Typically complex criteria would be formed based upon inputs to the procedure.
In this simple example the criteria is references the using clause to isolate
the SQL string from referencing a value from the procedure directly */
-DECLARE string criteria = 'Customer.Accounts.Last = USING.LastName';
+DECLARE string criteria = 'Customer.Accounts.Last = DVARS.LastName';
/* Now we create the desired SQL string */
DECLARE string sql_string = 'SELECT ID, First || ‘‘ ‘‘ || Last AS Name, Birthdate FROM Customer.Accounts WHERE ' || criteria;
/* The execution of the SQL string will create the #temp table with the columns (ID, Name, Birthdate).
@@ -81,17 +81,17 @@
<programlisting>...
DECLARE string crit = null;
IF (AccountAccess.GetAccounts.ID IS NOT NULL)
- crit = ‘(Customer.Accounts.ID = using.ID)’;
+ crit = ‘(Customer.Accounts.ID = DVARS.ID)’;
ELSE IF (AccountAccess.GetAccounts.LastName IS NOT NULL)
BEGIN
IF (AccountAccess.GetAccounts.LastName == ‘%’)
ERROR "Last name cannot be %";
ELSE IF (LOCATE(‘%’, AccountAccess.GetAccounts.LastName) < 0)
- crit = ‘(Customer.Accounts.Last = using.LastName)’;
+ crit = ‘(Customer.Accounts.Last = DVARS.LastName)’;
ELSE
- crit = ‘(Customer.Accounts.Last LIKE using.LastName)’;
+ crit = ‘(Customer.Accounts.Last LIKE DVARS.LastName)’;
IF (AccountAccess.GetAccounts.bday IS NOT NULL)
- crit = ‘(‘ || crit || ‘ and (Customer.Accounts.Birthdate = using.BirthDay))’;
+ crit = ‘(‘ || crit || ‘ and (Customer.Accounts.Birthdate = DVARS.BirthDay))’;
END
ELSE
ERROR "ID or LastName must be specified.";
@@ -118,7 +118,7 @@
<title>Example Dangerous NULL handling
</title>
<programlisting>...
-criteria = ‘(‘ || criteria || ‘ and (Customer.Accounts.Birthdate = using.BirthDay))’;</programlisting>
+criteria = ‘(‘ || criteria || ‘ and (Customer.Accounts.Birthdate = DVARS.BirthDay))’;</programlisting>
</example>
<para>The preferred approach is for the user to ensure the criteria is not NULL prior its usage. If this is not possible, a good approach is to specify a default as shown in the following example.
</para>
@@ -126,7 +126,7 @@
<title>Example NULL handling
</title>
<programlisting>...
-criteria = ‘(‘ || nvl(criteria, ‘(1 = 1)’) || ‘ and (Customer.Accounts.Birthdate = using.BirthDay))’;</programlisting>
+criteria = ‘(‘ || nvl(criteria, ‘(1 = 1)’) || ‘ and (Customer.Accounts.Birthdate = DVARS.BirthDay))’;</programlisting>
</example>
</listitem>
<listitem>
Copied: branches/JCA/engine/src/main/java/com/metamatrix/dqp/message/RequestID.java (from rev 1884, branches/JCA/client/src/main/java/com/metamatrix/dqp/message/RequestID.java)
===================================================================
--- branches/JCA/engine/src/main/java/com/metamatrix/dqp/message/RequestID.java (rev 0)
+++ branches/JCA/engine/src/main/java/com/metamatrix/dqp/message/RequestID.java 2010-03-03 18:56:39 UTC (rev 1891)
@@ -0,0 +1,175 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License 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.message;
+
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+
+/**
+ * <p>This class represents an identifier for a request. However, there are some
+ * differences in what constitutes "uniqueness" for a given RequestID that
+ * is based on context (where the id is used). The RequestID has 2 parts:
+ * connectionID, and executionIDFor the purposes of the RequestID, the combined
+ * representation is "connectionID.executionID" - this implies a scoping
+ * for the name parts. The connectionID specifies a particular connection that
+ * is making requests. Each connection generates a unique executionID for each
+ * request execution, so the executionID is only unique in the context of a
+ * connectionID. </p>
+ *
+ * <p>When this class is used between client and server, the connectionID is implied
+ * and thus only the executionID part will be used. The server will qualify the
+ * executionID with a connectionID when it reaches the server. </p>
+ *
+ * <p>RequestIDs are immutable so no setters exist. This allows hashcodes to be
+ * pre-computed for faster comparison in equals.</p>
+ */
+public class RequestID implements Externalizable {
+
+ static final long serialVersionUID = -2888539138291776071L;
+
+ public static final String NO_CONNECTION_STR = "C"; //$NON-NLS-1$
+ private static final String SEPARATOR = "."; //$NON-NLS-1$
+
+ // Basic state
+ private String connectionID;
+ private long executionID;
+
+ // Derived state
+ private String combinedID;
+ private int hash;
+
+ /**
+ * Necessary for implementing Externalizable
+ */
+ public RequestID() {
+ }
+
+ /**
+ * Create a RequestID using all of the ID parts.
+ * @param connectionID Identifies a connection, may be null
+ * @param executionID Identifies an execution, cannot be null
+ */
+ public RequestID(String connectionID, long executionID) {
+ this.connectionID = connectionID;
+ this.executionID = executionID;
+
+ createCombinedID();
+ computeHashCode();
+ }
+
+ public RequestID(long connectionID, long executionID) {
+ this.connectionID = String.valueOf(connectionID);
+ this.executionID = executionID;
+
+ createCombinedID();
+ computeHashCode();
+ }
+
+ /**
+ * Create a RequestID for an execution where the connection is
+ * not specified.
+ * @param executionID Identifies an execution, cannot be null
+ */
+ public RequestID(long executionID) {
+ this(null, executionID);
+ }
+
+
+ /**
+ * Return connectionID, may be null if connection has not been specified.
+ * @return Connection ID, may be null
+ */
+ public String getConnectionID() {
+ return this.connectionID;
+ }
+
+ /**
+ * Return executionID, which identifies a per-connection execution.
+ * @return Execution ID
+ */
+ public long getExecutionID() {
+ return this.executionID;
+ }
+
+ /**
+ * Create a unique combined ID string from the RequestID parts.
+ */
+ private void createCombinedID() {
+ StringBuffer combinedStr = new StringBuffer();
+ if(this.connectionID != null) {
+ combinedStr.append(this.connectionID);
+ } else {
+ combinedStr.append(NO_CONNECTION_STR);
+ }
+ combinedStr.append(SEPARATOR);
+ combinedStr.append(this.executionID);
+
+ this.combinedID = combinedStr.toString();
+ }
+
+ private void computeHashCode() {
+ this.hash = combinedID.hashCode();
+ }
+
+ public int hashCode() {
+ return this.hash;
+ }
+
+ public boolean equals(Object obj) {
+ if(obj == this) {
+ return true;
+ } else if(obj == null || !(obj instanceof RequestID) || obj.hashCode() != this.hashCode()) {
+ return false;
+ } else {
+ return this.toString().equals(obj.toString());
+ }
+ }
+
+ /**
+ * Return a combined string for the ID.
+ */
+ public String toString() {
+ return this.combinedID;
+ }
+
+ /**
+ * @see java.io.Externalizable#readExternal(java.io.ObjectInput)
+ */
+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+ connectionID = (String)in.readObject();
+ executionID = in.readLong();
+
+ createCombinedID();
+ computeHashCode();
+ }
+
+ /**
+ * @see java.io.Externalizable#writeExternal(java.io.ObjectOutput)
+ */
+ public void writeExternal(ObjectOutput out) throws IOException {
+ out.writeObject(connectionID);
+ out.writeLong(executionID);
+ }
+}
Modified: branches/JCA/engine/src/main/java/com/metamatrix/query/processor/proc/ExecDynamicSqlInstruction.java
===================================================================
--- branches/JCA/engine/src/main/java/com/metamatrix/query/processor/proc/ExecDynamicSqlInstruction.java 2010-03-03 18:45:43 UTC (rev 1890)
+++ branches/JCA/engine/src/main/java/com/metamatrix/query/processor/proc/ExecDynamicSqlInstruction.java 2010-03-03 18:56:39 UTC (rev 1891)
@@ -159,10 +159,14 @@
if (dynamicCommand.getUsing() != null
&& !dynamicCommand.getUsing().isEmpty()) {
- metadataStore.addTempGroup(ProcedureReservedWords.USING, new LinkedList(dynamicCommand.getUsing().getClauseMap().keySet()));
- GroupSymbol using = new GroupSymbol(ProcedureReservedWords.USING);
- using.setMetadataID(metadataStore.getTempGroupID(ProcedureReservedWords.USING));
+ metadataStore.addTempGroup(SQLReservedWords.USING, new LinkedList(dynamicCommand.getUsing().getClauseMap().keySet()));
+ GroupSymbol using = new GroupSymbol(SQLReservedWords.USING);
+ using.setMetadataID(metadataStore.getTempGroupID(SQLReservedWords.USING));
command.addExternalGroupToContext(using);
+ metadataStore.addTempGroup(ProcedureReservedWords.DVARS, new LinkedList(dynamicCommand.getUsing().getClauseMap().keySet()));
+ using = new GroupSymbol(ProcedureReservedWords.DVARS);
+ using.setMetadataID(metadataStore.getTempGroupID(ProcedureReservedWords.DVARS));
+ command.addExternalGroupToContext(using);
}
// Resolve any groups
@@ -235,8 +239,8 @@
LogManager.logTrace(LogConstants.CTX_DQP,
new Object[] { this, " The using variable ", //$NON-NLS-1$
setClause.getSymbol(), " has value :", assignment }); //$NON-NLS-1$
- localContext.setValue(setClause.getSymbol(),
- assignment);
+ localContext.setValue(setClause.getSymbol(), assignment);
+ localContext.setValue(new ElementSymbol(SQLReservedWords.USING + ElementSymbol.SEPARATOR + setClause.getSymbol().getShortName()), assignment);
}
}
}
Modified: branches/JCA/engine/src/main/java/com/metamatrix/query/resolver/command/DynamicCommandResolver.java
===================================================================
--- branches/JCA/engine/src/main/java/com/metamatrix/query/resolver/command/DynamicCommandResolver.java 2010-03-03 18:45:43 UTC (rev 1890)
+++ branches/JCA/engine/src/main/java/com/metamatrix/query/resolver/command/DynamicCommandResolver.java 2010-03-03 18:56:39 UTC (rev 1891)
@@ -27,8 +27,6 @@
import java.util.List;
import java.util.Set;
-import org.teiid.connector.language.SQLReservedWords;
-
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.query.QueryMetadataException;
import com.metamatrix.api.exception.query.QueryResolverException;
@@ -87,8 +85,8 @@
if (dynamicCmd.getUsing() != null && !dynamicCmd.getUsing().isEmpty()) {
for (SetClause clause : dynamicCmd.getUsing().getClauses()) {
ElementSymbol id = clause.getSymbol();
- id.setName(ProcedureReservedWords.USING + SingleElementSymbol.SEPARATOR + id.getShortName());
- id.setGroupSymbol(new GroupSymbol(ProcedureReservedWords.USING));
+ id.setName(ProcedureReservedWords.DVARS + SingleElementSymbol.SEPARATOR + id.getShortName());
+ id.setGroupSymbol(new GroupSymbol(ProcedureReservedWords.DVARS));
id.setType(clause.getValue().getType());
id.setMetadataID(new TempMetadataID(id.getCanonicalName(), id.getType()));
}
Modified: branches/JCA/engine/src/main/java/com/metamatrix/query/sql/ProcedureReservedWords.java
===================================================================
--- branches/JCA/engine/src/main/java/com/metamatrix/query/sql/ProcedureReservedWords.java 2010-03-03 18:45:43 UTC (rev 1890)
+++ branches/JCA/engine/src/main/java/com/metamatrix/query/sql/ProcedureReservedWords.java 2010-03-03 18:56:39 UTC (rev 1891)
@@ -44,7 +44,7 @@
public static final String VARIABLES = "VARIABLES"; //$NON-NLS-1$
- public static final String USING = SQLReservedWords.USING;
+ public static final String DVARS = "DVARS"; //$NON-NLS-1$
/**
* Set of CAPITALIZED reserved words for checking whether a string is a reserved word.
Modified: branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/Request.java
===================================================================
--- branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/Request.java 2010-03-03 18:45:43 UTC (rev 1890)
+++ branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/Request.java 2010-03-03 18:56:39 UTC (rev 1891)
@@ -573,7 +573,7 @@
protected void validateAccess(Command command) throws QueryValidatorException, MetaMatrixComponentException {
// See if entitlement checking is turned on
- AuthorizationValidationVisitor visitor = new AuthorizationValidationVisitor(this.authService);
+ AuthorizationValidationVisitor visitor = new AuthorizationValidationVisitor(this.authService, this.workContext.getVDB());
validateWithVisitor(visitor, this.metadata, command);
}
}
Modified: branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/validator/AuthorizationValidationVisitor.java
===================================================================
--- branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/validator/AuthorizationValidationVisitor.java 2010-03-03 18:45:43 UTC (rev 1890)
+++ branches/JCA/engine/src/main/java/org/teiid/dqp/internal/process/validator/AuthorizationValidationVisitor.java 2010-03-03 18:56:39 UTC (rev 1891)
@@ -33,6 +33,7 @@
import org.teiid.adminapi.Visibility;
import org.teiid.adminapi.impl.ModelMetaData;
+import org.teiid.adminapi.impl.VDBMetaData;
import org.teiid.dqp.internal.process.DQPWorkContext;
import org.teiid.dqp.internal.process.multisource.MultiSourceElement;
@@ -61,9 +62,11 @@
public class AuthorizationValidationVisitor extends AbstractValidationVisitor {
private AuthorizationService authInterface;
+ private VDBMetaData vdb;
- public AuthorizationValidationVisitor(AuthorizationService authInterface) {
+ public AuthorizationValidationVisitor(AuthorizationService authInterface, VDBMetaData vdb) {
this.authInterface = authInterface;
+ this.vdb = vdb;
}
// ############### Visitor methods for language objects ##################
@@ -298,7 +301,7 @@
}
try {
String modelName = getMetadata().getFullName(modelID);
- ModelMetaData model = DQPWorkContext.getWorkContext().getVDB().getModel(modelName);
+ ModelMetaData model = vdb.getModel(modelName);
if(model.getVisibility() != Visibility.PUBLIC) {
handleValidationError(DQPPlugin.Util.getString("ERR.018.005.0088", getMetadata().getFullName(group.getMetadataID()))); //$NON-NLS-1$
}
Modified: branches/JCA/engine/src/main/javacc/com/metamatrix/query/parser/SQLParser.jj
===================================================================
--- branches/JCA/engine/src/main/javacc/com/metamatrix/query/parser/SQLParser.jj 2010-03-03 18:45:43 UTC (rev 1890)
+++ branches/JCA/engine/src/main/javacc/com/metamatrix/query/parser/SQLParser.jj 2010-03-03 18:56:39 UTC (rev 1891)
@@ -302,6 +302,39 @@
| <YEAR: "year">
}
+TOKEN : /* SQL/XML Reserved words */
+{
+ <XMLAGG: "xmlagg">
+| <XMLATTRIBUTES: "xmlattributes">
+| <XMLBINARY: "xmlbinary">
+| <XMLCONCAT: "xmlconcat">
+| <XMLCOMMENT: "xmlcomment">
+| <XMLELEMENT: "xmlelement">
+| <XMLFOREST: "xmlforest">
+| <XMLNAMESPACES: "xmlnamespaces">
+| <XMLPARSE: "xmlparse">
+| <XMLPI: "xmlpi">
+| <XMLROOT: "xmlroot">
+| <XMLSERIALIZE: "xmlserialize">
+}
+
+TOKEN : /* SQL/MED Reserved words */
+{
+ <DATALINK: "datalink">
+| <DLNEWCOPY: "dlnewcopy">
+| <DLPREVIOUSCOPY: "dlpreviouscopy">
+| <DLURLCOMPLETE: "dlurlcomplete">
+| <DLURLCOMPLETEWRITE: "dlurlcompletewrite">
+| <DLURLCOMPLETEONLY: "dlurlcompleteonly">
+| <DLURLPATH: "dlurlpath">
+| <DLURLPATHWRITE: "dlurlpathwrite">
+| <DLURLPATHONLY: "dlurlpathonly">
+| <DLURLSCHEME: "dlurlscheme">
+| <DLURLSERVER: "dlurlserver">
+| <DLVALUE: "dlvalue">
+| <IMPORT: "import">
+}
+
TOKEN : /* Special function words */
{
<SQL_TSI_FRAC_SECOND: "SQL_TSI_FRAC_SECOND">
Modified: branches/JCA/engine/src/test/java/com/metamatrix/query/validator/TestValidator.java
===================================================================
--- branches/JCA/engine/src/test/java/com/metamatrix/query/validator/TestValidator.java 2010-03-03 18:45:43 UTC (rev 1890)
+++ branches/JCA/engine/src/test/java/com/metamatrix/query/validator/TestValidator.java 2010-03-03 18:56:39 UTC (rev 1891)
@@ -1716,7 +1716,7 @@
// Validate
ValidatorReport report = helpValidateInModeler("pm1.vsp36", sql, metadata); //$NON-NLS-1$
assertEquals(1, report.getItems().size());
- assertEquals("Elements cannot appear more than once in a SET or USING clause. The following elements are duplicated: [\"USING\".id]", report.toString()); //$NON-NLS-1$
+ assertEquals("Elements cannot appear more than once in a SET or USING clause. The following elements are duplicated: [DVARS.id]", report.toString()); //$NON-NLS-1$
}
@Test public void testValidateAssignmentWithFunctionOnParameter_InModeler() throws Exception{
Modified: branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCoreRequestHandling.java
===================================================================
--- branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCoreRequestHandling.java 2010-03-03 18:45:43 UTC (rev 1890)
+++ branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCoreRequestHandling.java 2010-03-03 18:56:39 UTC (rev 1891)
@@ -53,7 +53,7 @@
private void compareReqInfos(Collection<RequestID> reqs1, Collection<RequestMetadata> reqs2) {
Set reqIDs2 = new HashSet();
for (RequestMetadata requestInfo : reqs2) {
- reqIDs2.add(requestInfo.getRequestId());
+ reqIDs2.add(new RequestID(requestInfo.getSessionId(), requestInfo.getExecutionId()));
}
assertEquals("Collections of request infos are not the same: ", new HashSet(reqs1), reqIDs2); //$NON-NLS-1$
Modified: branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/validator/TestAuthorizationValidationVisitor.java
===================================================================
--- branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/validator/TestAuthorizationValidationVisitor.java 2010-03-03 18:45:43 UTC (rev 1890)
+++ branches/JCA/engine/src/test/java/org/teiid/dqp/internal/process/validator/TestAuthorizationValidationVisitor.java 2010-03-03 18:56:39 UTC (rev 1891)
@@ -32,7 +32,6 @@
import org.mockito.Mockito;
import org.teiid.adminapi.Visibility;
import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.dqp.internal.process.DQPWorkContext;
import org.teiid.dqp.internal.process.Request;
import com.metamatrix.api.exception.MetaMatrixComponentException;
@@ -126,11 +125,7 @@
vdb.addAttchment(QueryMetadataInterface.class, metadata);
- DQPWorkContext context = new DQPWorkContext();
- context.setVdb(vdb);
- DQPWorkContext.setWorkContext(context);
-
- AuthorizationValidationVisitor visitor = new AuthorizationValidationVisitor(svc); //$NON-NLS-1$ //$NON-NLS-2$
+ AuthorizationValidationVisitor visitor = new AuthorizationValidationVisitor(svc, vdb);
ValidatorReport report = Validator.validate(command, metadata, visitor);
if(report.hasItems()) {
ValidatorFailure firstFailure = (ValidatorFailure) report.getItems().iterator().next();
@@ -247,13 +242,11 @@
}
private void helpTestLookupVisibility(boolean visible) throws QueryParserException, QueryValidatorException, MetaMatrixComponentException {
- AuthorizationValidationVisitor mvvv = new AuthorizationValidationVisitor(Mockito.mock(AuthorizationService.class));
-
- DQPWorkContext workContext = FakeMetadataFactory.buildWorkContext(FakeMetadataFactory.example1Cached(), FakeMetadataFactory.example1VDB());
+ VDBMetaData vdb = FakeMetadataFactory.example1VDB();
if (!visible) {
- workContext.getVDB().getModel("pm1").setVisibility(Visibility.PRIVATE);
+ vdb.getModel("pm1").setVisibility(Visibility.PRIVATE); //$NON-NLS-1$
}
-
+ AuthorizationValidationVisitor mvvv = new AuthorizationValidationVisitor(Mockito.mock(AuthorizationService.class), vdb);
String sql = "select lookup('pm1.g1', 'e1', 'e2', 1)"; //$NON-NLS-1$
Command command = QueryParser.getQueryParser().parseCommand(sql);
Request.validateWithVisitor(mvvv, FakeMetadataFactory.example1Cached(), command);
Modified: branches/JCA/metadata/src/main/resources/System.vdb
===================================================================
(Binary files differ)
14 years, 2 months
teiid SVN: r1890 - in branches/JCA/console/src: main/java/org/teiid/rhq/plugin and 3 other directories.
by teiid-commits@lists.jboss.org
Author: tejones
Date: 2010-03-03 13:45:43 -0500 (Wed, 03 Mar 2010)
New Revision: 1890
Modified:
branches/JCA/console/src/main/java/org/teiid/rhq/admin/DQPManagementView.java
branches/JCA/console/src/main/java/org/teiid/rhq/plugin/PlatformComponent.java
branches/JCA/console/src/main/java/org/teiid/rhq/plugin/PlatformDiscoveryComponent.java
branches/JCA/console/src/main/java/org/teiid/rhq/plugin/VDBComponent.java
branches/JCA/console/src/main/java/org/teiid/rhq/plugin/objects/ExecutedOperationResultImpl.java
branches/JCA/console/src/main/java/org/teiid/rhq/plugin/util/PluginConstants.java
branches/JCA/console/src/main/java/org/teiid/rhq/plugin/util/ProfileServiceUtil.java
branches/JCA/console/src/resources/embedded/META-INF/rhq-plugin.xml
Log:
Add operations and metrics to VDB and engine. Also restructure tree.
Modified: branches/JCA/console/src/main/java/org/teiid/rhq/admin/DQPManagementView.java
===================================================================
--- branches/JCA/console/src/main/java/org/teiid/rhq/admin/DQPManagementView.java 2010-03-03 04:42:56 UTC (rev 1889)
+++ branches/JCA/console/src/main/java/org/teiid/rhq/admin/DQPManagementView.java 2010-03-03 18:45:43 UTC (rev 1890)
@@ -4,24 +4,21 @@
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
-import java.util.Collections;
-import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import java.util.Properties;
import javax.naming.NamingException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.jboss.managed.api.ComponentType;
import org.jboss.managed.api.ManagedComponent;
import org.jboss.managed.api.ManagedOperation;
import org.jboss.metatype.api.types.MetaType;
import org.jboss.metatype.api.values.CollectionValueSupport;
import org.jboss.metatype.api.values.MetaValue;
+import org.jboss.metatype.api.values.MetaValueFactory;
import org.teiid.adminapi.impl.RequestMetadata;
import org.teiid.adminapi.impl.RequestMetadataMapper;
import org.teiid.adminapi.impl.SessionMetadata;
@@ -30,15 +27,16 @@
import org.teiid.rhq.plugin.util.PluginConstants;
import org.teiid.rhq.plugin.util.ProfileServiceUtil;
import org.teiid.rhq.plugin.util.PluginConstants.ComponentType.Platform;
-import org.teiid.rhq.plugin.util.PluginConstants.ComponentType.Platform.Metrics;
-import org.teiid.rhq.plugin.util.PluginConstants.ComponentType.Platform.Operations;
+import org.teiid.rhq.plugin.util.PluginConstants.ComponentType.VDB;
-import com.metamatrix.core.MetaMatrixRuntimeException;
-public class DQPManagementView implements PluginConstants{
+public class DQPManagementView implements PluginConstants {
+
private static ManagedComponent mc = null;
private static final Log LOG = LogFactory.getLog(DQPManagementView.class);
+ private static final MetaValueFactory metaValueFactory = MetaValueFactory
+ .getInstance();
public DQPManagementView() {
@@ -62,7 +60,7 @@
}
private Object getPlatformMetric(String componentType, String metric,
- Map valueMap) {
+ Map<String, Object> valueMap) {
Object resultObject = new Object();
@@ -78,8 +76,7 @@
.equals(PluginConstants.ComponentType.Platform.Metrics.LONG_RUNNING_QUERIES)) {
Integer longRunningQueryLimit = (Integer) valueMap
.get(PluginConstants.Operation.Value.LONG_RUNNING_QUERY_LIMIT);
- Collection<RequestMetadata> longRunningQueries = getLongRunningQueries(
- longRunningQueryLimit);
+ Collection<RequestMetadata> longRunningQueries = getLongRunningQueries(longRunningQueryLimit);
resultObject = new Double(longRunningQueries.size());
}
}
@@ -89,7 +86,7 @@
}
private Object getVdbMetric(String componentType, String identifier,
- String metric, Map valueMap) {
+ String metric, Map<String, Object> valueMap) {
Object resultObject = new Object();
@@ -111,118 +108,148 @@
PluginConstants.ComponentType.Platform.NAME)) {
executePlatformOperation(operationResult, operationResult
.getOperationName(), valueMap);
+ } else if (operationResult.getComponentType().equals(
+ PluginConstants.ComponentType.VDB.NAME)) {
+ executeVdbOperation(operationResult, operationResult
+ .getOperationName(), valueMap);
}
- // else if
- // (operationResult.getComponentType().equals(ConnectionConstants.ComponentType.Runtime.System.TYPE))
- // {
- // executeSystemOperation(operationResult,
- // operationResult.getOperationName(), valueMap);
- // } else if (operationResult.getComponentType().equals(
- // Runtime.Process.TYPE)) {
- // executeProcessOperation(operationResult,
- // operationResult.getOperationName(), valueMap);
- // } else if
- // (operationResult.getComponentType().equals(com.metamatrix.rhq.comm.ConnectionConstants.ComponentType.Runtime.Host.TYPE))
- // {
- // executeHostOperation(operationResult,
- // operationResult.getOperationName(), valueMap);
- // } else if
- // (operationResult.getComponentType().equals(com.metamatrix.rhq.comm.ConnectionConstants.ComponentType.Runtime.Session.TYPE))
- // {
- // executeSessionOperation(operationResult,
- // operationResult.getOperationName(), valueMap);
- // } else if
- // (operationResult.getComponentType().equals(com.metamatrix.rhq.comm.ConnectionConstants.ComponentType.Runtime.Queries.TYPE))
- // {
- // executeQueriesOperation(operationResult,
- // operationResult.getOperationName(), valueMap);
- // }
}
private void executePlatformOperation(ExecutedResult operationResult,
final String operationName, final Map<String, Object> valueMap) {
Collection<RequestMetadata> resultObject = new ArrayList<RequestMetadata>();
+ Collection<SessionMetadata> activeSessionsCollection = new ArrayList<SessionMetadata>();
if (operationName.equals(Platform.Operations.GET_LONGRUNNINGQUERIES)) {
Integer longRunningValue = (Integer) valueMap
.get(Operation.Value.LONG_RUNNING_QUERY_LIMIT);
List<String> fieldNameList = operationResult.getFieldNameList();
resultObject = getLongRunningQueries(longRunningValue);
- operationResult.setContent(createReportResultList(fieldNameList, resultObject.iterator()));
- }
-
-// else if (operationName.equals(ComponentType.Operation.KILL_REQUEST)) {
-// String requestID = (String) valueMap
-// .get(ConnectionConstants.ComponentType.Operation.Value.REQUEST_ID);
-// cancelRequest(requestID);
-// } else if (operationName.equals(ComponentType.Operation.GET_VDBS)) {
-// List fieldNameList = operationResult.getFieldNameList();
-// resultObject = getVDBs(fieldNameList);
-// operationResult.setContent((List) resultObject);
-// } else if (operationName.equals(ComponentType.Operation.GET_PROPERTIES)) {
-// String identifier = (String) valueMap
-// .get(ConnectionConstants.IDENTIFIER);
-// Properties props = getProperties(
-// ConnectionConstants.ComponentType.Runtime.System.TYPE,
-// identifier);
-// resultObject = createReportResultList(props);
-// operationResult.setContent((List) resultObject);
-// }
+ operationResult.setContent(createReportResultList(fieldNameList,
+ resultObject.iterator()));
+ } else if (operationName.equals(Platform.Operations.GET_SESSIONS)) {
+ List<String> fieldNameList = operationResult.getFieldNameList();
+ MetaValue sessionMetaValue = getSessions();
+ getSessionCollectionValue(sessionMetaValue,
+ activeSessionsCollection);
+ operationResult.setContent(createReportResultList(fieldNameList,
+ activeSessionsCollection.iterator()));
+ } else if (operationName.equals(Platform.Operations.GET_REQUESTS)) {
+ List<String> fieldNameList = operationResult.getFieldNameList();
+ MetaValue requestMetaValue = getRequests();
+ getRequestCollectionValue(requestMetaValue, resultObject);
+ operationResult.setContent(createReportResultList(fieldNameList,
+ resultObject.iterator()));
+ } else if (operationName.equals(Platform.Operations.KILL_SESSION)) {
+ Long sessionID = (Long) valueMap.get(Operation.Value.SESSION_ID);
+ MetaValue[] args = new MetaValue[] {metaValueFactory.create(sessionID) };
+ try {
+ executeManagedOperation(mc, Platform.Operations.KILL_SESSION, args);
+ } catch (Exception e) {
+ final String msg = "Exception executing operation: " + Platform.Operations.KILL_SESSION; //$NON-NLS-1$
+ LOG.error(msg, e);
+ }
+ } else if (operationName.equals(Platform.Operations.KILL_REQUEST)) {
+ Long requestID = (Long) valueMap.get(Operation.Value.REQUEST_ID);
+ Long sessionID = (Long) valueMap.get(Operation.Value.SESSION_ID);
+ MetaValue[] args = new MetaValue[] {
+ metaValueFactory.create(requestID),
+ metaValueFactory.create(sessionID) };
+ try {
+ executeManagedOperation(mc, Platform.Operations.KILL_REQUEST, args);
+ } catch (Exception e) {
+ final String msg = "Exception executing operation: " + Platform.Operations.KILL_REQUEST; //$NON-NLS-1$
+ LOG.error(msg, e);
+ }
+ }
+ }
+ private void executeVdbOperation(ExecutedResult operationResult,
+ final String operationName, final Map<String, Object> valueMap) {
+ Collection<RequestMetadata> resultObject = new ArrayList<RequestMetadata>();
+ Collection<SessionMetadata> activeSessionsCollection = new ArrayList<SessionMetadata>();
+
+ if (operationName.equals(VDB.Operations.GET_PROPERTIES)) {
+ List<String> fieldNameList = operationResult.getFieldNameList();
+ getProperties(PluginConstants.ComponentType.VDB.NAME);
+ operationResult.setContent(createReportResultList(fieldNameList,
+ resultObject.iterator()));
+ }else if (operationName.equals(VDB.Operations.GET_SESSIONS)) {
+ List<String> fieldNameList = operationResult.getFieldNameList();
+ MetaValue sessionMetaValue = getSessions();
+ getSessionCollectionValue(sessionMetaValue,
+ activeSessionsCollection);
+ operationResult.setContent(createReportResultList(fieldNameList,
+ activeSessionsCollection.iterator()));
+ } else if (operationName.equals(VDB.Operations.GET_REQUESTS)) {
+ List<String> fieldNameList = operationResult.getFieldNameList();
+ MetaValue requestMetaValue = getRequests();
+ getRequestCollectionValue(requestMetaValue, resultObject);
+ operationResult.setContent(createReportResultList(fieldNameList,
+ resultObject.iterator()));
+ }
+
}
/*
* Helper methods
*/
- protected MetaValue getRequests(List<String> fieldNameList) {
+ public MetaValue getProperties(final String component) {
+ MetaValue propertyValue = null;
+ MetaValue args = null;
+
+ try {
+ propertyValue = executeManagedOperation(mc,
+ PluginConstants.Operation.GET_PROPERTIES, args);
+ } catch (Exception e) {
+ final String msg = "Exception executing operation: " + Platform.Operations.GET_PROPERTIES; //$NON-NLS-1$
+ LOG.error(msg, e);
+ }
+
+ return propertyValue;
+
+ }
+
+ protected MetaValue getRequests() {
+
MetaValue requestsCollection = null;
MetaValue args = null;
- requestsCollection = executeManagedOperation(mc,
- PluginConstants.Operation.GET_REQUESTS, args);
+ try {
+ requestsCollection = executeManagedOperation(mc,
+ PluginConstants.Operation.GET_REQUESTS, args);
+ } catch (Exception e) {
+ final String msg = "Exception executing operation: " + Platform.Operations.GET_REQUESTS; //$NON-NLS-1$
+ LOG.error(msg, e);
+ }
return requestsCollection;
- // if (fieldNameList != null) {
- // Collection reportResultCollection = createReportResultList(
- // fieldNameList, requestsCollection.iterator());
- // return reportResultCollection;
- // } else {
- // return requestsCollection;
- // }
}
- public MetaValue getSessions(List<String> fieldNameList) {
+ public MetaValue getSessions() {
MetaValue sessionCollection = null;
MetaValue args = null;
- sessionCollection = executeManagedOperation(mc,
- PluginConstants.Operation.GET_SESSIONS, args);
+ try {
+ sessionCollection = executeManagedOperation(mc,
+ PluginConstants.Operation.GET_SESSIONS, args);
+ } catch (Exception e) {
+ final String msg = "Exception executing operation: " + Platform.Operations.GET_SESSIONS; //$NON-NLS-1$
+ LOG.error(msg, e);
+ }
return sessionCollection;
- // if (fieldNameList != null) {
- // Collection reportResultCollection = createReportResultList(
- // fieldNameList, requestsCollection.iterator());
- // return reportResultCollection;
- // } else {
- // return requestsCollection;
- // }
}
public static MetaValue executeManagedOperation(ManagedComponent mc,
- String operation, MetaValue... args) {
+ String operation, MetaValue... args) throws Exception {
- try {
- mc = ProfileServiceUtil.getDQPManagementView();
- } catch (NamingException e) {
- LOG.error(e);
- } catch (Exception e1) {
- LOG.error(e1);
- }
+ mc = getDQPManagementView(mc);
for (ManagedOperation mo : mc.getOperations()) {
String opName = mo.getName();
@@ -239,19 +266,52 @@
}
}
}
- throw new MetaMatrixRuntimeException(
+ throw new Exception(
"No operation found with given name =" + operation);
}
+ /**
+ * @param mc
+ * @return
+ */
+ private static ManagedComponent getDQPManagementView(ManagedComponent mc) {
+ try {
+ mc = ProfileServiceUtil.getDQPManagementView();
+ } catch (NamingException e) {
+ final String msg = "NamingException getting the DQPManagementView"; //$NON-NLS-1$
+ LOG.error(msg, e);
+ } catch (Exception e1) {
+ final String msg = "Exception getting the DQPManagementView"; //$NON-NLS-1$
+ LOG.error(msg, e1);
+ }
+ return mc;
+ }
+
+ public static MetaValue getManagedProperty(ManagedComponent mc,
+ String property, MetaValue... args) throws Exception {
+
+ mc = getDQPManagementView(mc);
+
+ try {
+ mc.getProperty(property);
+ } catch (Exception e) {
+ final String msg = "Exception getting the AdminApi in " + property; //$NON-NLS-1$
+ LOG.error(msg, e);
+ }
+
+ throw new Exception(
+ "No property found with given name =" + property);
+ }
+
private Integer getQueryCount() {
Integer count = new Integer(0);
MetaValue requests = null;
- Collection<RequestMetadata> requestsCollection = new ArrayList();
+ Collection<RequestMetadata> requestsCollection = new ArrayList<RequestMetadata>();
- requests = getRequests(null);
+ requests = getRequests();
getRequestCollectionValue(requests, requestsCollection);
@@ -265,7 +325,7 @@
private Integer getSessionCount() {
Collection<SessionMetadata> activeSessionsCollection = new ArrayList<SessionMetadata>();
- MetaValue sessionMetaValue = getSessions(null);
+ MetaValue sessionMetaValue = getSessions();
getSessionCollectionValue(sessionMetaValue, activeSessionsCollection);
return activeSessionsCollection.size();
}
@@ -278,7 +338,7 @@
double longRunningQueryTimeDouble = new Double(longRunningValue);
- requestsCollection = getRequests(null);
+ requestsCollection = getRequests();
getRequestCollectionValue(requestsCollection, list);
@@ -294,10 +354,10 @@
requestsIter.remove();
}
}
-
+
return list;
}
-
+
public static <T> void getRequestCollectionValue(MetaValue pValue,
Collection<RequestMetadata> list) {
MetaType metaType = pValue.getMetaType();
@@ -335,10 +395,11 @@
}
}
}
-
- private Collection createReportResultList(List fieldNameList, Iterator objectIter) {
+
+ private Collection createReportResultList(List fieldNameList,
+ Iterator objectIter) {
Collection reportResultList = new ArrayList();
-
+
while (objectIter.hasNext()) {
Object object = objectIter.next();
@@ -347,10 +408,10 @@
cls = object.getClass();
Iterator methodIter = fieldNameList.iterator();
Map reportValueMap = new HashMap<String, String>();
- while (methodIter.hasNext()) {
+ while (methodIter.hasNext()) {
String fieldName = (String) methodIter.next();
String methodName = fieldName;
- Method meth = cls.getMethod(methodName, (Class[]) null);
+ Method meth = cls.getMethod(methodName, (Class[]) null);
Object retObj = meth.invoke(object, (Object[]) null);
reportValueMap.put(fieldName, retObj);
}
Modified: branches/JCA/console/src/main/java/org/teiid/rhq/plugin/PlatformComponent.java
===================================================================
--- branches/JCA/console/src/main/java/org/teiid/rhq/plugin/PlatformComponent.java 2010-03-03 04:42:56 UTC (rev 1889)
+++ branches/JCA/console/src/main/java/org/teiid/rhq/plugin/PlatformComponent.java 2010-03-03 18:45:43 UTC (rev 1890)
@@ -31,7 +31,6 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.jboss.managed.api.ManagedComponent;
import org.jboss.managed.api.RunState;
import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.domain.configuration.PropertySimple;
@@ -51,10 +50,9 @@
public class PlatformComponent extends Facet implements PluginConstants {
private final Log LOG = LogFactory.getLog(PlatformComponent.class);
-
/**
* @see org.teiid.rhq.plugin.Facet#getComponentType()
- * @since 4.3
+ * @since 7.0
*/
@Override
String getComponentType() {
@@ -63,14 +61,10 @@
@Override
public AvailabilityType getAvailability() {
- RunState runState = null;
- ManagedComponent mc;
+
+ RunState runState;
try {
- mc = ProfileServiceUtil.getManagedComponent(new org.jboss.managed.api.ComponentType(
- ComponentType.Platform.TYPE,
- ComponentType.Platform.SUBTYPE),
- ComponentType.Platform.TEIID_RUNTIME_ENGINE);
- runState = mc.getRunState();
+ runState = ProfileServiceUtil.getDQPManagementView().getRunState();
} catch (NamingException e) {
LOG
.error("Naming exception getting: "
@@ -82,35 +76,40 @@
+ PluginConstants.ComponentType.Platform.TEIID_RUNTIME_ENGINE);
return AvailabilityType.DOWN;
}
-
- return (runState == RunState.RUNNING) ? AvailabilityType.UP
- : AvailabilityType.DOWN;
-
+ return (runState == RunState.RUNNING) ? AvailabilityType.UP :
+ AvailabilityType.DOWN;
+
}
@Override
protected void setOperationArguments(String name,
Configuration configuration, Map<String, Object> valueMap) {
// Parameter logic for System Operations
- if (name.equals(Platform.Operations.GET_QUERIES) ||
- name.equals(Platform.Operations.GET_LONGRUNNINGQUERIES)) {
- Integer long_running_value = getResourceConfiguration().getSimple(Operation.Value.LONG_RUNNING_QUERY_LIMIT).getIntegerValue();
- valueMap.put(Operation.Value.LONG_RUNNING_QUERY_LIMIT, long_running_value);
+ if (name.equals(Platform.Operations.GET_QUERIES)
+ || name.equals(Platform.Operations.GET_LONGRUNNINGQUERIES)) {
+ Integer long_running_value = getResourceConfiguration().getSimple(
+ Operation.Value.LONG_RUNNING_QUERY_LIMIT).getIntegerValue();
+ valueMap.put(Operation.Value.LONG_RUNNING_QUERY_LIMIT,
+ long_running_value);
} else if (name.equals(Platform.Operations.KILL_REQUEST)) {
- String key = Operation.Value.REQUEST_ID;
- valueMap.put(key, configuration.getSimple(key).getStringValue());
- }
-// else if (name.equals(ConnectionConstants.ComponentType.Operation.GET_PROPERTIES) ) {
-// String key = ConnectionConstants.IDENTIFIER;
-// valueMap.put(key, getComponentIdentifier());
-// }
+ valueMap.put(Operation.Value.REQUEST_ID, configuration.getSimple(
+ Operation.Value.REQUEST_ID).getLongValue());
+ valueMap.put(Operation.Value.SESSION_ID, configuration.getSimple(
+ Operation.Value.SESSION_ID).getLongValue());
+ } else if (name.equals(Platform.Operations.KILL_SESSION)) {
+ valueMap.put(Operation.Value.SESSION_ID, configuration.getSimple(
+ Operation.Value.SESSION_ID).getLongValue());
+ } else if (name.equals(Platform.Operations.GET_PROPERTIES)) {
+ // String key = ConnectionConstants.IDENTIFIER;
+ // valueMap.put(key, getComponentIdentifier());
+ }
}
@Override
public void getValues(MeasurementReport report,
Set<MeasurementScheduleRequest> requests) throws Exception {
-
+
DQPManagementView view = new DQPManagementView();
Map<String, Object> valueMap = new HashMap<String, Object>();
@@ -121,31 +120,46 @@
// Initialize any parameters to be used in the retrieval of metric
// values
- if (request.getName().equals(PluginConstants.ComponentType.Platform.Metrics.LONG_RUNNING_QUERIES)) {
+ if (request
+ .getName()
+ .equals(
+ PluginConstants.ComponentType.Platform.Metrics.LONG_RUNNING_QUERIES)) {
Integer value = getResourceConfiguration()
.getSimple(
PluginConstants.Operation.Value.LONG_RUNNING_QUERY_LIMIT)
.getIntegerValue();
- valueMap.put(PluginConstants.Operation.Value.LONG_RUNNING_QUERY_LIMIT, value);
+ valueMap
+ .put(
+ PluginConstants.Operation.Value.LONG_RUNNING_QUERY_LIMIT,
+ value);
}
Object metricReturnObject = view.getMetric(getComponentType(), this
.getComponentIdentifier(), name, valueMap);
try {
- if (request.getName().equals(PluginConstants.ComponentType.Platform.Metrics.QUERY_COUNT)) {
+ if (request
+ .getName()
+ .equals(
+ PluginConstants.ComponentType.Platform.Metrics.QUERY_COUNT)) {
report.addData(new MeasurementDataNumeric(request,
(Double) metricReturnObject));
} else {
- if (request.getName().equals(PluginConstants.ComponentType.Platform.Metrics.SESSION_COUNT)) {
+ if (request
+ .getName()
+ .equals(
+ PluginConstants.ComponentType.Platform.Metrics.SESSION_COUNT)) {
report.addData(new MeasurementDataNumeric(request,
(Double) metricReturnObject));
} else {
- if (request.getName().equals(
- PluginConstants.ComponentType.Platform.Metrics.LONG_RUNNING_QUERIES)) {
+ if (request
+ .getName()
+ .equals(
+ PluginConstants.ComponentType.Platform.Metrics.LONG_RUNNING_QUERIES)) {
report.addData(new MeasurementDataNumeric(request,
(Double) metricReturnObject));
}
+
}
}
@@ -177,7 +191,7 @@
props.put(pluginProp.getName(), pluginProp.getStringValue());
}
- //SingletonConnectionManager.getInstance().initialize(props);
+ // SingletonConnectionManager.getInstance().initialize(props);
super.updateResourceConfiguration(report);
}
Modified: branches/JCA/console/src/main/java/org/teiid/rhq/plugin/PlatformDiscoveryComponent.java
===================================================================
--- branches/JCA/console/src/main/java/org/teiid/rhq/plugin/PlatformDiscoveryComponent.java 2010-03-03 04:42:56 UTC (rev 1889)
+++ branches/JCA/console/src/main/java/org/teiid/rhq/plugin/PlatformDiscoveryComponent.java 2010-03-03 18:45:43 UTC (rev 1890)
@@ -38,7 +38,7 @@
import org.teiid.rhq.plugin.util.ProfileServiceUtil;
/**
- * This is the parent node for a MetaMatrix system
+ * This is the parent node for a Teiid system
*/
public class PlatformDiscoveryComponent implements ResourceDiscoveryComponent {
@@ -58,8 +58,8 @@
Set<DiscoveredResourceDetails> discoveredResources = new HashSet<DiscoveredResourceDetails>();
ManagedComponent mc = ProfileServiceUtil.getManagedComponent(
- new ComponentType(PluginConstants.ComponentType.Platform.TYPE,
- PluginConstants.ComponentType.Platform.SUBTYPE),
+ new ComponentType("teiid",
+ "dqp"),
PluginConstants.ComponentType.Platform.TEIID_RUNTIME_ENGINE);
Configuration c = new Configuration();
Modified: branches/JCA/console/src/main/java/org/teiid/rhq/plugin/VDBComponent.java
===================================================================
--- branches/JCA/console/src/main/java/org/teiid/rhq/plugin/VDBComponent.java 2010-03-03 04:42:56 UTC (rev 1889)
+++ branches/JCA/console/src/main/java/org/teiid/rhq/plugin/VDBComponent.java 2010-03-03 18:45:43 UTC (rev 1890)
@@ -21,18 +21,24 @@
*/
package org.teiid.rhq.plugin;
+import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.hyperic.sigar.test.GetPass;
import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.domain.measurement.MeasurementDataNumeric;
import org.rhq.core.domain.measurement.MeasurementReport;
import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
import org.rhq.core.pluginapi.measurement.MeasurementFacet;
+import org.teiid.rhq.admin.DQPManagementView;
import org.teiid.rhq.comm.ConnectionConstants;
import org.teiid.rhq.plugin.util.PluginConstants;
+import org.teiid.rhq.plugin.util.PluginConstants.Operation;
+import org.teiid.rhq.plugin.util.PluginConstants.ComponentType.Platform;
+import org.teiid.rhq.plugin.util.PluginConstants.ComponentType.VDB;
/**
@@ -51,53 +57,79 @@
public String getComponentName() {
return PluginConstants.ComponentType.VDB.NAME;
}
+
+ @Override
+ protected void setOperationArguments(String name,
+ Configuration configuration, Map<String, Object> valueMap) {
+ // Parameter logic for VDB Operations
+ if (name.equals(VDB.Operations.KILL_REQUEST)) {
+ valueMap.put(Operation.Value.REQUEST_ID, configuration.getSimple(
+ Operation.Value.REQUEST_ID).getLongValue());
+ valueMap.put(Operation.Value.SESSION_ID, configuration.getSimple(
+ Operation.Value.SESSION_ID).getLongValue());
+ } else if (name.equals(Platform.Operations.KILL_SESSION)) {
+ valueMap.put(Operation.Value.SESSION_ID, configuration.getSimple(
+ Operation.Value.SESSION_ID).getLongValue());
+ } else if (name.equals(Platform.Operations.GET_PROPERTIES)) {
+ String key = ConnectionConstants.IDENTIFIER;
+ valueMap.put(key, getComponentIdentifier());
+ }
- /**
- * The plugin container will call this method when your resource component
- * has been scheduled to collect some measurements now. It is within this
- * method that you actually talk to the managed resource and collect the
- * measurement data that is has emitted.
- *
- * @see MeasurementFacet#getValues(MeasurementReport, Set)
- */
+ }
+
+ @Override
public void getValues(MeasurementReport report,
- Set<MeasurementScheduleRequest> requests) {
+ Set<MeasurementScheduleRequest> requests) throws Exception {
+
+ DQPManagementView view = new DQPManagementView();
+
+ Map<String, Object> valueMap = new HashMap<String, Object>();
+
for (MeasurementScheduleRequest request : requests) {
String name = request.getName();
+ LOG.debug("Measurement name = " + name); //$NON-NLS-1$
- // TODO: based on the request information, you must collect the
- // requested measurement(s)
- // you can use the name of the measurement to determine what you
- // actually need to collect
+ Object metricReturnObject = view.getMetric(getComponentType(), this
+ .getComponentIdentifier(), name, valueMap);
+
try {
- Number value = new Integer(1); // dummy measurement value -
- // this should come from the
- // managed resource
- report.addData(new MeasurementDataNumeric(request, value
- .doubleValue()));
+ if (request
+ .getName()
+ .equals(
+ PluginConstants.ComponentType.Platform.Metrics.QUERY_COUNT)) {
+ report.addData(new MeasurementDataNumeric(request,
+ (Double) metricReturnObject));
+ } else {
+ if (request
+ .getName()
+ .equals(
+ PluginConstants.ComponentType.Platform.Metrics.SESSION_COUNT)) {
+ report.addData(new MeasurementDataNumeric(request,
+ (Double) metricReturnObject));
+ } else {
+ if (request
+ .getName()
+ .equals(
+ PluginConstants.ComponentType.Platform.Metrics.LONG_RUNNING_QUERIES)) {
+ report.addData(new MeasurementDataNumeric(request,
+ (Double) metricReturnObject));
+ }
+
+ }
+ }
+
} catch (Exception e) {
LOG.error("Failed to obtain measurement [" + name //$NON-NLS-1$
+ "]. Cause: " + e); //$NON-NLS-1$
+ // throw(e);
}
}
- return;
}
-
- protected void setOperationArguments(String name, Configuration configuration,
- Map argumentMap) {
- if (name.equals(ConnectionConstants.ComponentType.Operation.GET_PROPERTIES)){
- String key = ConnectionConstants.IDENTIFIER;
- //argumentMap.put(key, getComponentIdentifier());
- }
-
- }
-
@Override
String getComponentType() {
- // TODO Auto-generated method stub
- return null;
+ return PluginConstants.ComponentType.VDB.NAME;
}
}
Modified: branches/JCA/console/src/main/java/org/teiid/rhq/plugin/objects/ExecutedOperationResultImpl.java
===================================================================
--- branches/JCA/console/src/main/java/org/teiid/rhq/plugin/objects/ExecutedOperationResultImpl.java 2010-03-03 04:42:56 UTC (rev 1889)
+++ branches/JCA/console/src/main/java/org/teiid/rhq/plugin/objects/ExecutedOperationResultImpl.java 2010-03-03 18:45:43 UTC (rev 1890)
@@ -21,6 +21,7 @@
*/
package org.teiid.rhq.plugin.objects;
+import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
@@ -28,6 +29,8 @@
import java.util.Map;
import java.util.Set;
+import javax.persistence.Transient;
+
import org.rhq.core.domain.configuration.PropertyList;
import org.rhq.core.domain.configuration.PropertyMap;
import org.rhq.core.domain.configuration.PropertySimple;
@@ -52,8 +55,6 @@
final static String MAPNAME = "map"; //$NON-NLS-1$
-// String mapName;
-
Object result;
Object content;
@@ -131,6 +132,8 @@
OperationDefinition opDef = (OperationDefinition) operationsIter
.next();
if (opDef.getName().equals(operationName)) {
+ if (opDef.getResultsConfigurationDefinition()==null) break;
+
Map propDefs = opDef.getResultsConfigurationDefinition()
.getPropertyDefinitions();
PropertyDefinition listPropDefinition = (PropertyDefinition) propDefs
@@ -142,7 +145,7 @@
.getPropertyDefinitions();
Iterator simplePropertiesIter = simpleProperties.values()
.iterator();
-
+
while (simplePropertiesIter.hasNext()) {
PropertyDefinition simpleProp = (PropertyDefinition) simplePropertiesIter
.next();
@@ -154,5 +157,5 @@
break;
}
}
- }
+ }
}
Modified: branches/JCA/console/src/main/java/org/teiid/rhq/plugin/util/PluginConstants.java
===================================================================
--- branches/JCA/console/src/main/java/org/teiid/rhq/plugin/util/PluginConstants.java 2010-03-03 04:42:56 UTC (rev 1889)
+++ branches/JCA/console/src/main/java/org/teiid/rhq/plugin/util/PluginConstants.java 2010-03-03 18:45:43 UTC (rev 1890)
@@ -37,12 +37,11 @@
// In embedded, its a predefined value
// In enterprise, its the installation directory
// public final static String INSTALL_DIR = "install.dir"; //$NON-NLS-1$
-
/**
* These are global properties used by all components
*/
public final static String PROFILE_SERVICE = "ProfileService"; //$NON-NLS-1$
-
+
/**
* These properties are exposed via the #getProperty method call.
*/
@@ -56,26 +55,28 @@
* @since 1.0
*/
public interface ComponentType {
-
+
public interface Platform {
public final static String NAME = "Platform"; //$NON-NLS-1$
+ public final static String TEIID_TYPE = "teiid"; //$NON-NLS-1$
+ public final static String TEIID_SUB_TYPE = "dqp"; //$NON-NLS-1$
public final static String TYPE = "ConnectionFactory"; //$NON-NLS-1$
public final static String SUBTYPE = "NoTx"; //$NON-NLS-1$
- public final static String TEIID_RUNTIME_ENGINE = "teiid/runtime-engine"; //$NON-NLS-1$
+ public final static String TEIID_RUNTIME_ENGINE = "org.teiid.jboss.deployers.RuntimeEngineDeployer"; //$NON-NLS-1$
public final static String TEIID_ENGINE_RESOURCE_NAME = "Data Service Runtime Engine"; //$NON-NLS-1$
public final static String TEIID_ENGINE_RESOURCE_DESCRIPTION = "JBoss Enterprise Data Service Runtime Engine"; //$NON-NLS-1$
-
public static interface Operations {
public final static String GET_QUERIES = "listQueries"; //$NON-NLS-1$
public final static String GET_LONGRUNNINGQUERIES = "listLongRunningQueries"; //$NON-NLS-1$
- public final static String KILL_REQUEST = "killRequest"; //$NON-NLS-1$
+ public final static String KILL_REQUEST = "cancelRequest"; //$NON-NLS-1$
+ public final static String KILL_SESSION = "terminateSession"; //$NON-NLS-1$
public final static String GET_PROPERTIES = "getProperties"; //$NON-NLS-1$
public final static String GET_REQUESTS = "getRequests"; //$NON-NLS-1$
- public final static String GET_SESSIONS = "getActiveSessions"; //$NON-NLS-1$
-
+ public final static String GET_SESSIONS = "getSessions"; //$NON-NLS-1$
+
}
public static interface Metrics {
@@ -94,8 +95,20 @@
public final static String NAME = "Enterprise Virtual Database"; //$NON-NLS-1$
public final static String DESCRIPTION = "JBoss Enterprise Virtual Database (VDB)"; //$NON-NLS-1$
+ public static interface Operations {
+
+ public final static String GET_QUERIES = "listQueries"; //$NON-NLS-1$
+ public final static String GET_LONGRUNNINGQUERIES = "listLongRunningQueries"; //$NON-NLS-1$
+ public final static String KILL_REQUEST = "cancelRequest"; //$NON-NLS-1$
+ public final static String KILL_SESSION = "terminateSession"; //$NON-NLS-1$
+ public final static String GET_PROPERTIES = "getProperties"; //$NON-NLS-1$
+ public final static String GET_REQUESTS = "getRequests"; //$NON-NLS-1$
+ public final static String GET_SESSIONS = "getSessions"; //$NON-NLS-1$
+
+ }
+
}
-
+
public interface Model {
public final static String TYPE = "teiid"; //$NON-NLS-1$
@@ -105,7 +118,6 @@
}
-
public interface Connector {
public final static String TYPE = "ConnectionFactory"; //$NON-NLS-1$
@@ -113,7 +125,7 @@
public final static String SUBTYPE_TX = "Tx"; //$NON-NLS-1$
public final static String NAME = "Enterprise Connector"; //$NON-NLS-1$
public final static String DESCRIPTION = "JBoss Enterprise Connector Binding"; //$NON-NLS-1$
-
+
public static interface Operations {
public final static String RESTART_CONNECTOR = "restart"; //$NON-NLS-1$
@@ -143,20 +155,6 @@
}
}
- public interface Service {
-
- public final static String TYPE = "Resource.Service"; //$NON-NLS-1$
-
- public static interface Operations {
-
- }
-
- public static interface Query {
-
- }
-
- }
-
}
/**
@@ -182,7 +180,7 @@
public final static String GET_PROPERTIES = "getProperties"; //$NON-NLS-1$
public final static String GET_REQUESTS = "getRequests"; //$NON-NLS-1$
public final static String GET_SESSIONS = "getActiveSessions"; //$NON-NLS-1$
-
+
/**
* Use these value names when calling executeOperation() on the
* connection interface. These will correlate with parameters used in
@@ -201,6 +199,7 @@
public final static String FIELD_LIST = "fieldList"; //$NON-NLS-1$
public final static String REQUEST_ID = "requestID"; //$NON-NLS-1$
+ public final static String SESSION_ID = "sessionID"; //$NON-NLS-1$
public final static String NAME = "Name"; //$NON-NLS-1$
public final static String VALUE = "Value"; //$NON-NLS-1$
Modified: branches/JCA/console/src/main/java/org/teiid/rhq/plugin/util/ProfileServiceUtil.java
===================================================================
--- branches/JCA/console/src/main/java/org/teiid/rhq/plugin/util/ProfileServiceUtil.java 2010-03-03 04:42:56 UTC (rev 1889)
+++ branches/JCA/console/src/main/java/org/teiid/rhq/plugin/util/ProfileServiceUtil.java 2010-03-03 18:45:43 UTC (rev 1890)
@@ -24,15 +24,13 @@
import org.jboss.metatype.api.values.SimpleValue;
import org.jboss.profileservice.spi.ProfileService;
-import com.metamatrix.core.MetaMatrixRuntimeException;
public class ProfileServiceUtil {
protected final Log LOG = LogFactory.getLog(ProfileServiceUtil.class);
private static ComponentType DQPTYPE = new ComponentType("teiid", "dqp");
- private static String DQPNAME = "org.teiid.dqp.internal.process.DQPManagementView";
+ private static String DQPNAME = "org.teiid.jboss.deployers.RuntimeEngineDeployer";
-
/**
* Get the passed in {@link ManagedComponent}
*
@@ -47,6 +45,7 @@
ManagementView mv = getManagementView(ps, true);
ManagedComponent mc = mv.getComponent(componentName, componentType);
+
return mc;
}
@@ -148,14 +147,14 @@
return getManagedComponent(DQPTYPE, DQPNAME);
}
- public static String stringValue(MetaValue v1) {
+ public static String stringValue(MetaValue v1) throws Exception {
if (v1 != null) {
MetaType type = v1.getMetaType();
if (type instanceof SimpleMetaType) {
SimpleValue simple = (SimpleValue)v1;
return simple.getValue().toString();
}
- throw new MetaMatrixRuntimeException("Failed to convert value to string value");
+ throw new Exception("Failed to convert value to string value");
}
return null;
}
Modified: branches/JCA/console/src/resources/embedded/META-INF/rhq-plugin.xml
===================================================================
--- branches/JCA/console/src/resources/embedded/META-INF/rhq-plugin.xml 2010-03-03 04:42:56 UTC (rev 1889)
+++ branches/JCA/console/src/resources/embedded/META-INF/rhq-plugin.xml 2010-03-03 18:45:43 UTC (rev 1890)
@@ -27,16 +27,16 @@
<depends plugin="JBossAS5" useClasses="true" />
<server name="Data Services" description="JBoss Enterprise Data Services"
- class="PlatformComponent" discovery="PlatformDiscoveryComponent">
+ class="PlatformComponent" discovery="PlatformDiscoveryComponent"
+ singleton="true">
<runs-inside>
<parent-resource-type name="JBossAS Server"
plugin="JBossAS5" />
</runs-inside>
-
- <operation name="listLongRunningQueries"
- displayName="View current long running queries"
- description="List current queries executing against the JBEDSP System that have surpassed the long running query threshhold">
+
+ <operation name="listLongRunningQueries" displayName="View current long running queries"
+ description="List current queries executing against the Teiid System that have surpassed the long running query threshhold">
<results>
<c:list-property name="list">
<c:map-property name="map">
@@ -44,11 +44,9 @@
name="getSessionId" type="string"
description="The name of the resource whose availability is being reported" />
<c:simple-property displayName="Request ID"
- name="getRequestId" type="string"
- description="The id for the request" />
+ name="getRequestId" type="string" description="The id for the request" />
<c:simple-property displayName="SQL String"
- name="getCommand" type="string"
- description="The SQL string for this query" />
+ name="getCommand" type="string" description="The SQL string for this query" />
<c:simple-property displayName="Source Request"
name="sourceRequest" type="string"
description="If false,this is the top level query. If true, this a physical source query." />
@@ -56,31 +54,106 @@
name="getExecutionId" type="string"
description="The execution id for this request (if this is a physical source query)" />
<c:simple-property displayName="Start Time"
- name="getCreatedTime" type="string"
- description="The time this query began" />
+ name="getCreatedTime" type="string" description="The time this query began" />
<c:simple-property displayName="Start Time"
- name="getProcessingTime" type="string"
- description="Processing time for this request" />
+ name="getProcessingTime" type="string" description="Processing time for this request" />
<c:simple-property displayName="Transaction ID"
name="getTransactionId" type="string"
description="The transaction XID if there is a transaction involved" />
- <c:simple-property displayName="Node ID"
- name="getNodeId" type="string"
- description="The node ID of this query" />
- </c:map-property>
+ <c:simple-property displayName="Node ID" name="getNodeId"
+ type="string" description="The node ID of this query" />
+ </c:map-property>
</c:list-property>
</results>
</operation>
- <operation name="killRequest" displayName="Terminate query"
- description="Terminate the processing of a query and it's source queries">
+ <operation name="getSessions" displayName="View current sessions"
+ description="Get current sessions connected to the Teiid instance">
+ <results>
+
+ <c:list-property name="list" displayName="Current Sessions"
+ description="Sessions currently connected to the Teiid system"
+ required="false">
+ <c:map-property name="map">
+ <c:simple-property displayName="Session ID"
+ name="getSessionId" type="string" description="The identifier for this session" />
+ <c:simple-property displayName="Application Name"
+ name="getApplicationName" type="string"
+ description="The application associated with Session" />
+ <c:simple-property displayName="Created Time"
+ name="getCreatedTime" type="string" description="When the session was created" />
+ <c:simple-property displayName="Client Host"
+ name="getClientHostName" type="string"
+ description="Host name from where the session created" />
+ <c:simple-property displayName="IP Address"
+ name="getIPAddress" type="string"
+ description="IP address from where this session was created" />
+ <c:simple-property displayName="Last ping time"
+ name="getLastPingTime" type="string" description="Last ping time" />
+ <c:simple-property displayName="User Name" name="getUserName"
+ type="string" description="User associated with this session" />
+ <c:simple-property displayName="VDB Name" name="getVDBName"
+ type="string" description="VDB associated with this session" />
+ <c:simple-property displayName="Security Domain"
+ name="getSecurityDomain" type="string"
+ description="Security Domain that session logged into" />
+ </c:map-property>
+ </c:list-property>
+ </results>
+ </operation>
+
+ <operation name="getRequests" displayName="View current requests"
+ description="Get current requests executing against this Teiid instance">
+ <results>
+
+ <c:list-property name="list" displayName="Current Request"
+ description="Requests currently executing against the Teiid system"
+ required="false">
+ <c:map-property name="map">
+ <c:simple-property displayName="Request ID"
+ name="getRequestId" type="string" description="The request identifier" />
+ <c:simple-property displayName="Session ID"
+ name="getSessionId" type="string" description="Session identifier" />
+ <c:simple-property displayName="Execution ID"
+ name="getExecutionId" type="string" description="Unique Identifier for Request" />
+ <c:simple-property displayName="Created Time"
+ name="getCreatedTime" type="string" description="Time when request submitted" />
+ <c:simple-property displayName="Processing Time"
+ name="getProcessingTime" type="string" description="Processing time for the request" />
+ <c:simple-property displayName="Last ping time"
+ name="getCommand" type="string" description="SQL Command" />
+ <c:simple-property displayName="Connector level request?"
+ name="sourceRequest" type="string"
+ description="True if this is a connector level request" />
+ <c:simple-property displayName="Node ID" name="getNodeId"
+ type="string" description="The node identifier" />
+ <c:simple-property displayName="Tansaction identifier"
+ name="getTransactionId" type="string"
+ description="Transaction XID if a transaction is involved" />
+ </c:map-property>
+ </c:list-property>
+ </results>
+ </operation>
+
+ <operation name="cancelRequest" displayName="Terminate request"
+ description="Terminate the processing of a query and its source queries">
<parameters>
- <c:simple-property displayName="SessionID|RequestID"
- name="requestID" type="string" required="true"
- description="The IDs of the session|request to terminate (use format = sessionID|requestID)" />
+ <c:simple-property displayName="Session ID" name="sessionID"
+ type="long" required="true"
+ description="The ID of the session that the request to cancel is associated with" />
+ <c:simple-property displayName="Request ID" name="requestID"
+ type="long" required="true" description="The ID of the request to cancel" />
</parameters>
</operation>
+ <operation name="terminateSession" displayName="Terminate Session"
+ description="Terminate a specified session">
+ <parameters>
+ <c:simple-property displayName="SessionID" name="sessionID"
+ type="long" required="true" description="The ID of the session to terminate" />
+ </parameters>
+ </operation>
+
<metric displayName="Query Count" defaultOn="true" displayType="detail"
category="throughput" property="queryCount"
description="The number of queries for a given point in time" />
@@ -99,7 +172,7 @@
<c:description>Query Configuration</c:description>
<c:simple-property name="longRunningQueryLimit"
type="integer" activationPolicy="immediate" units="seconds"
- default="600" displayName="Long Running Query limit"
+ default="600" required="true" displayName="Long Running Query limit"
description="The value (in seconds) to use to determine if a query is to be considered 'long running'.">
<c:constraint>
<c:integer-constraint minimum="0" maximum="999999" />
@@ -107,18 +180,81 @@
</c:simple-property>
</c:group>
</resource-configuration>
-
+
<service name="Virtual Database (VDB)s"
description="JBoss Enterprise Data Services Virtual Databases" class="VDBComponent"
discovery="VDBDiscoveryComponent" createDeletePolicy="both"
creationDataType="content">
+ <operation name="getSessions" displayName="View VDB Sessions"
+ description="Get current sessions currently connected to this VDB">
+ <results>
+
+ <c:list-property name="list" displayName="Current VDB Sessions"
+ description="Sessions currently connected to this VDB" required="false">
+ <c:map-property name="map">
+ <c:simple-property displayName="Session ID"
+ name="getSessionId" type="string" description="The identifier for this session" />
+ <c:simple-property displayName="Application Name"
+ name="getApplicationName" type="string"
+ description="The application associated with Session" />
+ <c:simple-property displayName="Created Time"
+ name="getCreatedTime" type="string" description="When the session was created" />
+ <c:simple-property displayName="Client Host"
+ name="getClientHostName" type="string"
+ description="Host name from where the session created" />
+ <c:simple-property displayName="IP Address"
+ name="getIPAddress" type="string"
+ description="IP address from where this session was created" />
+ <c:simple-property displayName="Last ping time"
+ name="getLastPingTime" type="string" description="Last ping time" />
+ <c:simple-property displayName="User Name"
+ name="getUserName" type="string" description="User associated with this session" />
+ <c:simple-property displayName="Security Domain"
+ name="getSecurityDomain" type="string"
+ description="Security Domain that session logged into" />
+ </c:map-property>
+ </c:list-property>
+ </results>
+ </operation>
+
+ <operation name="getRequests" displayName="View VDB requests"
+ description="Get current requests executing against this VDB">
+ <results>
+
+ <c:list-property name="list" displayName="Current Request"
+ description="Requests currently executing against the Teiid system"
+ required="false">
+ <c:map-property name="map">
+ <c:simple-property displayName="Request ID"
+ name="getRequestId" type="string" description="The request identifier" />
+ <c:simple-property displayName="Session ID"
+ name="getSessionId" type="string" description="Session identifier" />
+ <c:simple-property displayName="Execution ID"
+ name="getExecutionId" type="string" description="Unique Identifier for Request" />
+ <c:simple-property displayName="Created Time"
+ name="getCreatedTime" type="string" description="Time when request submitted" />
+ <c:simple-property displayName="Processing Time"
+ name="getProcessingTime" type="string" description="Processing time for the request" />
+ <c:simple-property displayName="Last ping time"
+ name="getCommand" type="string" description="SQL Command" />
+ <c:simple-property displayName="Connector level request?"
+ name="sourceRequest" type="string"
+ description="True if this is a connector level request" />
+ <c:simple-property displayName="Node ID" name="getNodeId"
+ type="string" description="The node identifier" />
+ <c:simple-property displayName="Tansaction identifier"
+ name="getTransactionId" type="string"
+ description="Transaction XID if a transaction is involved" />
+ </c:map-property>
+ </c:list-property>
+ </results>
+ </operation>
+
<content name="vdb" displayName="VDB Archive" category="deployable"
isCreationType="true">
-
</content>
-
<resource-configuration>
<c:group name="general" displayName="General"
hiddenByDefault="false">
@@ -150,6 +286,15 @@
</c:group>
</resource-configuration>
+ <!--
+ <operation name="getProperties" displayName="View VDB properties"
+ description="List the properties of this VDB"> <results>
+ <c:list-property name="list"> <c:map-property name="map">
+ <c:simple-property name="Name" type="string" description="The name
+ of this property" /> <c:simple-property name="Value" type="string"
+ description="The value of this property" /> </c:map-property>
+ </c:list-property> </results> </operation>
+ -->
<service name="Models" description="Models that map to a datasource"
class="ModelComponent" discovery="ModelDiscoveryComponent"
14 years, 2 months
teiid SVN: r1889 - in trunk/engine/src: test/java/com/metamatrix/query/processor and 1 other directory.
by teiid-commits@lists.jboss.org
Author: shawkins
Date: 2010-03-02 23:42:56 -0500 (Tue, 02 Mar 2010)
New Revision: 1889
Modified:
trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleAssignOutputElements.java
trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleMergeVirtual.java
trunk/engine/src/test/java/com/metamatrix/query/processor/TestProcessor.java
Log:
TEIID-989 expanding on the last fix to ensure that only source supporting unrelated seach will get the pushdown.
Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleAssignOutputElements.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleAssignOutputElements.java 2010-03-03 03:29:06 UTC (rev 1888)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleAssignOutputElements.java 2010-03-03 04:42:56 UTC (rev 1889)
@@ -38,6 +38,7 @@
import com.metamatrix.query.metadata.QueryMetadataInterface;
import com.metamatrix.query.metadata.SupportConstants;
import com.metamatrix.query.optimizer.capabilities.CapabilitiesFinder;
+import com.metamatrix.query.optimizer.capabilities.SourceCapabilities.Capability;
import com.metamatrix.query.optimizer.relational.OptimizerRule;
import com.metamatrix.query.optimizer.relational.RuleStack;
import com.metamatrix.query.optimizer.relational.plantree.NodeConstants;
@@ -160,7 +161,7 @@
assignOutputElements(root.getLastChild(), outputElements, metadata, capFinder, rules, analysisRecord, context);
break;
case NodeConstants.Types.SOURCE: {
- outputElements = (List<SingleElementSymbol>)determineSourceOutput(root, outputElements);
+ outputElements = (List<SingleElementSymbol>)determineSourceOutput(root, outputElements, metadata, capFinder);
root.setProperty(NodeConstants.Info.OUTPUT_COLS, outputElements);
List<SingleElementSymbol> childElements = filterVirtualElements(root, outputElements, metadata);
SymbolMap symbolMap = (SymbolMap)root.getProperty(NodeConstants.Info.SYMBOL_MAP);
@@ -237,9 +238,13 @@
* So, in this case filtering should not occur. In fact the output columns
* that were set on root above are filtered, but we actually want all the
* virtual elements - so just reset it and proceed as before
+ * @throws MetaMatrixComponentException
+ * @throws QueryMetadataException
*/
static List<? extends SingleElementSymbol> determineSourceOutput(PlanNode root,
- List<SingleElementSymbol> outputElements) {
+ List<SingleElementSymbol> outputElements,
+ QueryMetadataInterface metadata,
+ CapabilitiesFinder capFinder) throws QueryMetadataException, MetaMatrixComponentException {
PlanNode virtualRoot = root.getLastChild();
if(hasDupRemoval(virtualRoot)) {
@@ -247,7 +252,39 @@
SymbolMap symbolMap = (SymbolMap) root.getProperty(NodeConstants.Info.SYMBOL_MAP);
return symbolMap.getKeys();
}
- return outputElements;
+ PlanNode limit = NodeEditor.findNodePreOrder(root, NodeConstants.Types.TUPLE_LIMIT, NodeConstants.Types.PROJECT);
+ if (limit == null) {
+ return outputElements;
+ }
+ //reset the output elements to be the output columns + what's required by the sort
+ PlanNode sort = NodeEditor.findNodePreOrder(limit, NodeConstants.Types.SORT, NodeConstants.Types.PROJECT);
+ if (sort == null) {
+ return outputElements;
+ }
+ PlanNode access = NodeEditor.findParent(sort, NodeConstants.Types.ACCESS);
+ if (sort.hasBooleanProperty(NodeConstants.Info.UNRELATED_SORT) ||
+ (access != null && capFinder != null && CapabilitiesUtil.supports(Capability.QUERY_ORDERBY_UNRELATED, RuleRaiseAccess.getModelIDFromAccess(access, metadata), metadata, capFinder))) {
+ return outputElements;
+ }
+ OrderBy sortOrder = (OrderBy)sort.getProperty(NodeConstants.Info.SORT_ORDER);
+ List<SingleElementSymbol> topCols = FrameUtil.findTopCols(sort);
+
+ SymbolMap symbolMap = (SymbolMap)root.getProperty(NodeConstants.Info.SYMBOL_MAP);
+
+ List<ElementSymbol> symbolOrder = symbolMap.getKeys();
+
+ for (OrderByItem item : sortOrder.getOrderByItems()) {
+ final Expression expr = item.getSymbol();
+ int index = topCols.indexOf(expr);
+ if (index < 0) {
+ continue;
+ }
+ ElementSymbol symbol = symbolOrder.get(index);
+ if (!outputElements.contains(symbol)) {
+ outputElements.add(symbol);
+ }
+ }
+ return outputElements;
}
/**
Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleMergeVirtual.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleMergeVirtual.java 2010-03-03 03:29:06 UTC (rev 1888)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleMergeVirtual.java 2010-03-03 04:42:56 UTC (rev 1889)
@@ -78,7 +78,7 @@
static PlanNode doMerge(PlanNode frame,
PlanNode root,
- QueryMetadataInterface metadata) throws QueryPlannerException {
+ QueryMetadataInterface metadata) throws QueryPlannerException, QueryMetadataException, MetaMatrixComponentException {
GroupSymbol virtualGroup = frame.getGroups().iterator().next();
@@ -178,11 +178,13 @@
/**
* Removes source layers that only do a simple projection of the elements below.
+ * @throws MetaMatrixComponentException
+ * @throws QueryMetadataException
*/
private static PlanNode checkForSimpleProjection(PlanNode frame,
PlanNode root,
PlanNode parentProject,
- QueryMetadataInterface metadata) {
+ QueryMetadataInterface metadata) throws QueryMetadataException, MetaMatrixComponentException {
// check that the parent only performs projection
PlanNode nodeToCheck = parentProject.getFirstChild();
while (nodeToCheck != frame) {
@@ -200,7 +202,7 @@
return root;
}
- List<? extends SingleElementSymbol> requiredElements = getNecessaryOutput(frame);
+ List<? extends SingleElementSymbol> requiredElements = RuleAssignOutputElements.determineSourceOutput(frame, new ArrayList<SingleElementSymbol>(), metadata, null);
List<SingleElementSymbol> selectSymbols = (List<SingleElementSymbol>)parentProject.getProperty(NodeConstants.Info.PROJECT_COLS);
// check that it only performs simple projection and that all required symbols are projected
@@ -273,42 +275,6 @@
return root;
}
- private static List<? extends SingleElementSymbol> getNecessaryOutput(PlanNode root) {
- List<SingleElementSymbol> outputElements = new ArrayList<SingleElementSymbol>();
- List<? extends SingleElementSymbol> result = RuleAssignOutputElements.determineSourceOutput(root, outputElements);
- if (!result.isEmpty()) {
- return result;
- }
- PlanNode limit = NodeEditor.findNodePreOrder(root, NodeConstants.Types.TUPLE_LIMIT, NodeConstants.Types.PROJECT);
- if (limit == null) {
- return outputElements;
- }
- //reset the output elements to be the output columns + what's required by the sort
- PlanNode sort = NodeEditor.findNodePreOrder(limit, NodeConstants.Types.SORT, NodeConstants.Types.PROJECT);
- if (sort == null) {
- return outputElements;
- }
- OrderBy sortOrder = (OrderBy)sort.getProperty(NodeConstants.Info.SORT_ORDER);
- List<SingleElementSymbol> topCols = FrameUtil.findTopCols(sort);
-
- SymbolMap symbolMap = (SymbolMap)root.getProperty(NodeConstants.Info.SYMBOL_MAP);
-
- List<ElementSymbol> symbolOrder = symbolMap.getKeys();
-
- for (OrderByItem item : sortOrder.getOrderByItems()) {
- final Expression expr = item.getSymbol();
- int index = topCols.indexOf(expr);
- if (index < 0) {
- continue;
- }
- ElementSymbol symbol = symbolOrder.get(index);
- if (!outputElements.contains(symbol)) {
- outputElements.add(symbol);
- }
- }
- return outputElements;
- }
-
/**
* Check to ensure that we are not projecting a subquery or null dependent expressions
*/
Modified: trunk/engine/src/test/java/com/metamatrix/query/processor/TestProcessor.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/processor/TestProcessor.java 2010-03-03 03:29:06 UTC (rev 1888)
+++ trunk/engine/src/test/java/com/metamatrix/query/processor/TestProcessor.java 2010-03-03 04:42:56 UTC (rev 1889)
@@ -6990,7 +6990,27 @@
sampleData1(manager);
helpProcess(plan, manager, expected);
}
+
+ @Test public void testSortWithLimit4() {
+ String sql = "select c from (select pm1.g1.e1 a, pm1.g1.e2 b, pm1.g1.e3 c from pm1.g1 order by b limit 1) x"; //$NON-NLS-1$
+
+ FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY_UNRELATED, false);
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, new DefaultCapabilitiesFinder(caps));
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { Boolean.FALSE }),
+ };
+ FakeDataManager manager = new FakeDataManager();
+ sampleData1(manager);
+ helpProcess(plan, manager, expected);
+ assertEquals("SELECT g_0.e3 AS c_0, g_0.e2 AS c_1 FROM pm1.g1 AS g_0 ORDER BY c_1", manager.getQueries().iterator().next()); //$NON-NLS-1$
+ }
+
@Test public void testCountWithHaving() {
String sql = "select e1, count(*) from pm1.g1 group by e1 having count(*) > 1"; //$NON-NLS-1$
14 years, 2 months