[teiid-commits] teiid SVN: r1893 - in branches/JCA: common-core/src/main/java/com/metamatrix/common/protocol and 17 other directories.
teiid-commits at lists.jboss.org
teiid-commits at lists.jboss.org
Wed Mar 3 16:54:34 EST 2010
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 at 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);
}
More information about the teiid-commits
mailing list