You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airavata.apache.org by sh...@apache.org on 2015/06/11 23:34:44 UTC
[3/8] airavata git commit: moved commons-utils to commons module
http://git-wip-us.apache.org/repos/asf/airavata/blob/8d16d0ec/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/DBUtil.java
----------------------------------------------------------------------
diff --git a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/DBUtil.java b/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/DBUtil.java
deleted file mode 100644
index bb2ff1d..0000000
--- a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/DBUtil.java
+++ /dev/null
@@ -1,334 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.airavata.common.utils;
-
-import org.apache.airavata.common.exception.ApplicationSettingsException;
-import org.apache.commons.dbcp.BasicDataSource;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.sql.DataSource;
-import java.sql.*;
-import java.util.Properties;
-
-/**
- * Database lookup. Abstracts out JDBC operations.
- */
-public class DBUtil {
-
- private String jdbcUrl;
- private String databaseUserName;
- private String databasePassword;
- private String driverName;
-
- protected static Logger log = LoggerFactory.getLogger(DBUtil.class);
-
- private Properties properties;
-
- public DBUtil(String jdbcUrl, String userName, String password, String driver) throws InstantiationException,
- IllegalAccessException, ClassNotFoundException {
-
- this.jdbcUrl = jdbcUrl;
- this.databaseUserName = userName;
- this.databasePassword = password;
- this.driverName = driver;
-
- init();
- }
-
- /**
- * Initializes and load driver. Must be called this before calling anyother method.
- *
- * @throws ClassNotFoundException
- * If DB driver is not found.
- * @throws InstantiationException
- * If unable to create driver class.
- * @throws IllegalAccessException
- * If security does not allow users to instantiate driver object.
- */
- private void init() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
- properties = new Properties();
-
- properties.put("user", databaseUserName);
- properties.put("password", databasePassword);
- properties.put("characterEncoding", "ISO-8859-1");
- properties.put("useUnicode", "true");
-
- loadDriver();
- }
-
- /**
- * Generic method to query values in the database.
- *
- * @param tableName
- * Table name to query
- * @param selectColumn
- * The column selecting
- * @param whereValue
- * The condition query
- * @return The value appropriate to the query.
- * @throws SQLException
- * If an error occurred while querying
- */
- public String getMatchingColumnValue(String tableName, String selectColumn, String whereValue) throws SQLException {
- return getMatchingColumnValue(tableName, selectColumn, selectColumn, whereValue);
- }
-
- /**
- * Generic method to query values in the database.
- *
- * @param tableName
- * Table name to query
- * @param selectColumn
- * The column selecting
- * @param whereColumn
- * The column which condition should apply
- * @param whereValue
- * The condition query
- * @return The value appropriate to the query.
- * @throws SQLException
- * If an error occurred while querying
- */
- public String getMatchingColumnValue(String tableName, String selectColumn, String whereColumn, String whereValue)
- throws SQLException {
-
- StringBuilder stringBuilder = new StringBuilder();
-
- stringBuilder.append("SELECT ").append(selectColumn).append(" FROM ").append(tableName).append(" WHERE ")
- .append(whereColumn).append(" = ?");
-
- String sql = stringBuilder.toString();
-
- Connection connection = getConnection();
-
- PreparedStatement ps = connection.prepareStatement(sql);
- ResultSet rs = null;
-
- try {
- ps.setString(1, whereValue);
- rs = ps.executeQuery();
-
- if (rs.next()) {
- return rs.getString(1);
- }
-
- } finally {
- try {
- if (rs != null) {
- rs.close();
- }
-
- ps.close();
- connection.close();
-
- } catch (Exception ignore) {
- log.error("An error occurred while closing database connections ", ignore);
- }
- }
-
- return null;
- }
-
- /**
- * Create table utility method.
- *
- * @param sql
- * SQL to be executed.
- * @throws SQLException
- * If an error occurred while creating the table.
- */
- public void executeSQL(String sql) throws SQLException {
-
- Connection connection = getConnection();
-
- PreparedStatement ps = connection.prepareStatement(sql);
-
- try {
- ps.executeUpdate();
- connection.commit();
- } finally {
- try {
- if (ps != null) {
- ps.close();
- }
-
- connection.close();
-
- } catch (Exception ignore) {
- log.error("An error occurred while closing database connections ", ignore);
- }
- }
-
- }
-
- private void loadDriver() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
- Class.forName(driverName).newInstance();
- }
-
- /**
- * Gets a new DBCP data source.
- *
- * @return A new data source.
- */
- public DataSource getDataSource() {
- BasicDataSource ds = new BasicDataSource();
- ds.setDriverClassName(this.driverName);
- ds.setUsername(this.databaseUserName);
- ds.setPassword(this.databasePassword);
- ds.setUrl(this.jdbcUrl);
-
- return ds;
- }
-
- /**
- * Creates a new JDBC connections based on provided DBCP properties.
- *
- * @return A new DB connection.
- * @throws SQLException
- * If an error occurred while creating the connection.
- */
- public Connection getConnection() throws SQLException {
- Connection connection = DriverManager.getConnection(jdbcUrl, properties);
- connection.setAutoCommit(false);
- return connection;
- }
-
- /**
- * Utility method to close statements and connections.
- *
- * @param preparedStatement
- * The prepared statement to close.
- * @param connection
- * The connection to close.
- */
- public static void cleanup(PreparedStatement preparedStatement, Connection connection) {
- if (preparedStatement != null) {
- try {
- preparedStatement.close();
- } catch (SQLException e) {
- log.error("Error closing prepared statement.", e);
- }
- }
- if (connection != null) {
- try {
- connection.close();
- } catch (SQLException e) {
- log.error("Error closing database connection.", e);
- }
- }
- }
-
- /**
- * Utility method to close statements and connections.
- *
- * @param preparedStatement
- * The prepared statement to close.
- */
- public static void cleanup(PreparedStatement preparedStatement) {
- if (preparedStatement != null) {
- try {
- preparedStatement.close();
- } catch (SQLException e) {
- log.error("Error closing prepared statement.", e);
- }
- }
- }
-
- /**
- * Utility method to close statements and connections.
- *
- * @param preparedStatement
- * The prepared statement to close.
- */
- public static void cleanup(PreparedStatement preparedStatement, ResultSet resultSet) {
- if (resultSet != null) {
- try {
- resultSet.close();
- } catch (SQLException e) {
- log.error("Error closing prepared statement.", e);
- }
- }
-
- cleanup(preparedStatement);
- }
-
- /**
- * Cleanup the connection.
- * @param connection The connection to close.
- */
- public static void cleanup(Connection connection) {
- if (connection != null) {
- try {
- connection.close();
- } catch (SQLException e) {
- log.debug("Error closing connection.", e);
- log.warn("Error closing connection.");
- }
- }
- }
-
- /**
- * Mainly useful for tests.
- *
- * @param tableName
- * The table name.
- * @param connection
- * The connection to be used.
- */
- public static void truncate(String tableName, Connection connection) throws SQLException {
-
- String sql = "delete from " + tableName;
-
- PreparedStatement preparedStatement = connection.prepareStatement(sql);
- preparedStatement.executeUpdate();
-
- connection.commit();
-
- }
-
- /**
- * Creates a DBUtil object based on servlet context configurations.
- *
- * @return DBUtil object.
- * @throws Exception
- * If an error occurred while reading configurations or while creating database object.
- */
- public static DBUtil getCredentialStoreDBUtil() throws ApplicationSettingsException, IllegalAccessException,
- ClassNotFoundException, InstantiationException {
- String jdbcUrl = ServerSettings.getCredentialStoreDBURL();
- String userName = ServerSettings.getCredentialStoreDBUser();
- String password = ServerSettings.getCredentialStoreDBPassword();
- String driverName = ServerSettings.getCredentialStoreDBDriver();
-
- StringBuilder stringBuilder = new StringBuilder("Starting credential store, connecting to database - ");
- stringBuilder.append(jdbcUrl).append(" DB user - ").append(userName).append(" driver name - ")
- .append(driverName);
-
- log.debug(stringBuilder.toString());
-
- DBUtil dbUtil = new DBUtil(jdbcUrl, userName, password, driverName);
- dbUtil.init();
-
- return dbUtil;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/airavata/blob/8d16d0ec/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/DatabaseTestCases.java
----------------------------------------------------------------------
diff --git a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/DatabaseTestCases.java b/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/DatabaseTestCases.java
deleted file mode 100644
index 6ff528d..0000000
--- a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/DatabaseTestCases.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.airavata.common.utils;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.sql.Connection;
-import java.sql.SQLException;
-
-/**
- * An abstraction for database specific test classes. This will create a database and provides methods to execute SQLs.
- */
-public class DatabaseTestCases {
-
- private static final Logger logger = LoggerFactory.getLogger(DatabaseTestCases.class);
-
- protected static String hostAddress = "localhost";
- protected static int port = 20000;
- protected static String userName = "admin";
- protected static String password = "admin";
- protected static String driver = "org.apache.derby.jdbc.ClientDriver";
-
- public static String getHostAddress() {
- return hostAddress;
- }
-
- public static int getPort() {
- return port;
- }
-
- public static String getUserName() {
- return userName;
- }
-
- public static String getPassword() {
- return password;
- }
-
- public static String getDriver() {
- return driver;
- }
-
- public static String getJDBCUrl() {
- return new StringBuilder().append("jdbc:derby://").append(getHostAddress()).append(":").append(getPort())
- .append("/experiment_catalog;create=true;user=").append(getUserName()).append(";password=")
- .append(getPassword()).toString();
- }
-
- public static void waitTillServerStarts() {
- DBUtil dbUtil = null;
-
- try {
- dbUtil = new DBUtil(getJDBCUrl(), getUserName(), getPassword(), getDriver());
- } catch (Exception e) {
- // ignore
- }
-
- Connection connection = null;
- try {
- if (dbUtil != null) {
- connection = dbUtil.getConnection();
- }
- } catch (Throwable e) {
- // ignore
- }
-
- while (connection == null) {
- try {
- Thread.sleep(1000);
- try {
- if (dbUtil != null) {
- connection = dbUtil.getConnection();
- }
- } catch (SQLException e) {
- // ignore
- }
- } catch (InterruptedException e) {
- // ignore
- }
- }
-
- }
-
- public static void executeSQL(String sql) throws Exception {
- DBUtil dbUtil = new DBUtil(getJDBCUrl(), getUserName(), getPassword(), getDriver());
- dbUtil.executeSQL(sql);
- }
-
- public DBUtil getDbUtil () throws Exception {
- return new DBUtil(getJDBCUrl(), getUserName(), getPassword(), getDriver());
-
- }
-
- public Connection getConnection() throws Exception {
-
- DBUtil dbUtil = getDbUtil ();
- Connection connection = dbUtil.getConnection();
- connection.setAutoCommit(true);
- return connection;
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/airavata/blob/8d16d0ec/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/DefaultKeyStorePasswordCallback.java
----------------------------------------------------------------------
diff --git a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/DefaultKeyStorePasswordCallback.java b/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/DefaultKeyStorePasswordCallback.java
deleted file mode 100644
index fc7792b..0000000
--- a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/DefaultKeyStorePasswordCallback.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.airavata.common.utils;
-
-import org.apache.airavata.common.exception.ApplicationSettingsException;
-
-/**
- * User: AmilaJ (amilaj@apache.org)
- * Date: 12/29/13
- * Time: 12:10 PM
- */
-
-public class DefaultKeyStorePasswordCallback implements KeyStorePasswordCallback {
-
- public DefaultKeyStorePasswordCallback(){
-
- }
-
- @Override
- public char[] getStorePassword() {
- try {
- return ApplicationSettings.getCredentialStoreKeyStorePassword().toCharArray();
- } catch (ApplicationSettingsException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public char[] getSecretKeyPassPhrase(String keyAlias) {
- try {
- return ApplicationSettings.getCredentialStoreKeyStorePassword().toCharArray();
- } catch (ApplicationSettingsException e) {
- throw new RuntimeException(e);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/airavata/blob/8d16d0ec/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/DerbyUtil.java
----------------------------------------------------------------------
diff --git a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/DerbyUtil.java b/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/DerbyUtil.java
deleted file mode 100644
index 4fb35b9..0000000
--- a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/DerbyUtil.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.airavata.common.utils;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.net.InetAddress;
-import java.sql.DriverManager;
-import org.apache.derby.drda.NetworkServerControl;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.sql.SQLException;
-
-/**
- * This class includes methods to start stop Derby database. Mainly user for tests.
- */
-public class DerbyUtil {
-
- private static NetworkServerControl server;
-
- private static final Logger logger = LoggerFactory.getLogger(DerbyUtil.class);
-
- public static final String DERBY_SERVER_MODE_SYS_PROPERTY = "derby.drda.startNetworkServer";
-
- /**
- * Starts new derby server instance with given configurations.
- *
- * @param hostAddress
- * The host address start the server.
- * @param port
- * The port number which server is starting.
- * @param user
- * JDBC user name.
- * @param password
- * JDBC password.
- * @throws Exception
- * If an error occurred while starting the server.
- */
- public static void startDerbyInServerMode(String hostAddress, int port, String user, String password)
- throws Exception {
- PrintWriter consoleWriter = null;
-
- try {
- System.setProperty(DERBY_SERVER_MODE_SYS_PROPERTY, "true");
- server = new NetworkServerControl(InetAddress.getByName(hostAddress), port, user, password);
- consoleWriter = new PrintWriter(System.out, true);
- server.start(consoleWriter);
-
- } catch (IOException e) {
- logger.error("Unable to start Apache derby in the server mode! Check whether "
- + "specified port is available", e);
- throw e;
- } catch (Exception e) {
- logger.error("Unable to start Apache derby in the server mode! Check whether "
- + "specified port is available", e);
- throw e;
- } finally {
-
- if (consoleWriter != null) {
- consoleWriter.close();
- }
-
- }
-
- }
-
- /**
- * Starts derby server in embedded mode.
- *
- * @throws ClassNotFoundException
- * If specified driver not found in the class path.
- * @throws SQLException
- * If an error occurred while creat
- */
- public static void startDerbyInEmbeddedMode() throws ClassNotFoundException, SQLException {
- Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
- DriverManager.getConnection("jdbc:derby:memory:unit-testing-jpa;create=true").close();
- }
-
- /**
- * Shuts down the server.
- *
- * @throws Exception
- * If an error occurred while shutting down.
- */
- public static void stopDerbyServer() throws Exception {
- try {
- server.shutdown();
- } catch (Exception e) {
- logger.error("Error shutting down derby server.", e);
- throw e;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/airavata/blob/8d16d0ec/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/ExecutionMode.java
----------------------------------------------------------------------
diff --git a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/ExecutionMode.java b/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/ExecutionMode.java
deleted file mode 100644
index cf17ef0..0000000
--- a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/ExecutionMode.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.airavata.common.utils;
-
-public enum ExecutionMode {
- CLIENT,
- SERVER,
- UNKNOWN
-}
http://git-wip-us.apache.org/repos/asf/airavata/blob/8d16d0ec/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/IOUtil.java
----------------------------------------------------------------------
diff --git a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/IOUtil.java b/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/IOUtil.java
deleted file mode 100644
index 9d1d7dd..0000000
--- a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/IOUtil.java
+++ /dev/null
@@ -1,209 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.airavata.common.utils;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.io.Writer;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class IOUtil {
-
- private static final Logger logger = LoggerFactory.getLogger(IOUtil.class);
-
- /**
- * @param path
- * @param content
- * @throws IOException
- */
- public static void writeToFile(String content, String path) throws IOException {
- logger.debug("Path:" + path + " Content:" + content);
-
- FileWriter fw = new FileWriter(path);
- writeToWriter(content, fw);
- }
-
- /**
- * @param content
- * @param file
- * @throws IOException
- */
- public static void writeToFile(String content, File file) throws IOException {
- FileWriter fw = new FileWriter(file);
- writeToWriter(content, fw);
- }
-
- /**
- * @param inputStream
- * @param file
- * @throws IOException
- */
- public static void writeToFile(InputStream inputStream, File file) throws IOException {
- FileOutputStream outputStream = new FileOutputStream(file);
- byte[] bytes = new byte[1024];
- int len;
- while ((len = inputStream.read(bytes)) != -1) {
- outputStream.write(bytes, 0, len);
- }
- outputStream.close();
- }
-
- /**
- * Writes a specified String to a specified Writer.
- *
- * @param content
- * The content to write
- * @param writer
- * The specified Writer
- *
- * @throws IOException
- */
- public static void writeToWriter(String content, Writer writer) throws IOException {
- writer.write(content);
- writer.close();
- }
-
- /**
- * Returns the content of a specified file as a String.
- *
- * @param path
- * @return the content of a specified file as a String
- * @throws IOException
- */
- public static String readFileToString(String path) throws IOException {
- FileReader read = new FileReader(path);
- return readToString(read);
- }
-
- /**
- * Returns the content of a specified file as a String.
- *
- * @param file
- * @return the content of a specified file as a String
- * @throws IOException
- */
- public static String readFileToString(File file) throws IOException {
- FileReader reader = new FileReader(file);
- return readToString(reader);
- }
-
- /**
- * Returns a String read from a specified InputStream.
- *
- * @param stream
- * The specified InputStream
- * @return The String read from the specified InputStream
- * @throws IOException
- */
- public static String readToString(InputStream stream) throws IOException {
- return readToString(new InputStreamReader(stream));
- }
-
- /**
- * Returns a String read from a specified Reader.
- *
- * @param reader
- * The specified Reader
- * @return The String read from the specified Reader
- * @throws IOException
- */
- public static String readToString(Reader reader) throws IOException {
- char[] cbuf = new char[1024];
- StringBuilder sbuf = new StringBuilder();
- int len;
- while ((len = reader.read(cbuf)) != -1) {
- sbuf.append(cbuf, 0, len);
- }
- return sbuf.toString();
- }
-
- /**
- * @param file
- * @return The byte array
- * @throws IOException
- */
- public static byte[] readToByteArray(File file) throws IOException {
- return readToByteArray(new FileInputStream(file));
- }
-
- /**
- * @param inputStream
- * @return The byte array.
- * @throws IOException
- */
- public static byte[] readToByteArray(InputStream inputStream) throws IOException {
- byte[] buf = new byte[1024];
- ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
- int len;
- while ((len = inputStream.read(buf)) != -1) {
- byteArrayStream.write(buf, 0, len);
- }
- return byteArrayStream.toByteArray();
- }
-
- /**
- * @param path
- * @return <code>true</code> if and only if the file or directory is successfully deleted; <code>false</code>
- * otherwise
- */
- public static boolean deleteDirectory(File path) {
- if (path.exists()) {
- File[] files = path.listFiles();
- for (File file : files) {
- if (file.isDirectory()) {
- deleteDirectory(file);
- } else {
- file.delete();
- }
- }
- }
- return path.delete();
- }
-
- /**
- * Gets the extension of a specified file.
- *
- * @param file
- * the specified file.
- * @return the extension of the file in lower case if there is an extension; null otherwise
- */
- public static String getExtension(File file) {
- String ext = null;
- String name = file.getName();
-
- int index = name.lastIndexOf('.');
- if (index > 0 && index < name.length() - 1) {
- ext = name.substring(index + 1).toLowerCase();
- }
- return ext;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/airavata/blob/8d16d0ec/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/IServer.java
----------------------------------------------------------------------
diff --git a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/IServer.java b/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/IServer.java
deleted file mode 100644
index 867eb45..0000000
--- a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/IServer.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.airavata.common.utils;
-
-import java.util.Calendar;
-import java.util.Date;
-
-public interface IServer {
- public enum ServerStatus{
- STOPING,
- STOPPED,
- STARTING,
- STARTED,
- FAILED;
- public void updateTime(){
- now=Calendar.getInstance().getTime();
- }
- private Date now;
- public Date getTime(){
- return now;
- }
- }
- public String getName();
- public String getVersion();
- public void start() throws Exception;
- public void stop() throws Exception;
- public void restart() throws Exception;
- public void configure() throws Exception;
- public ServerStatus getStatus() throws Exception;
-// public void waitForServerToStart() throws Exception;
-// public void waitForServerToStop() throws Exception;
-}
http://git-wip-us.apache.org/repos/asf/airavata/blob/8d16d0ec/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/JSONUtil.java
----------------------------------------------------------------------
diff --git a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/JSONUtil.java b/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/JSONUtil.java
deleted file mode 100644
index 7946acc..0000000
--- a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/JSONUtil.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.airavata.common.utils;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
-import com.google.gson.JsonPrimitive;
-import com.google.gson.stream.JsonReader;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.Reader;
-import java.util.Map;
-import java.util.Set;
-
-public class JSONUtil {
-
-
- public static void saveJSON(JsonElement jsonElement, File file) throws IOException {
- IOUtil.writeToFile(jsonElementToString(jsonElement), file);
- }
-
- public static JsonObject stringToJSONObject(String workflowString) {
- JsonParser parser = new JsonParser();
- return (JsonObject) parser.parse(workflowString);
- }
-
- public static JsonObject loadJSON(File file) throws IOException {
- return loadJSON(new FileReader(file));
- }
-
- public static JsonObject loadJSON(Reader reader) throws IOException {
- JsonParser parser = new JsonParser();
- JsonElement jsonElement = parser.parse(reader);
- if (jsonElement instanceof JsonObject) {
- return (JsonObject) jsonElement;
- } else {
- throw new RuntimeException("Error while loading Json from file");
- }
-
- }
-
- public static String jsonElementToString(JsonElement jsonElement) {
- Gson gson = new GsonBuilder().setPrettyPrinting().create();
- return gson.toJson(jsonElement);
- }
-
- public static boolean isEqual(JsonObject originalJsonObject, JsonObject newJsonObject) {
- // TODO - Implement this method
- if (originalJsonObject == null && newJsonObject == null) {
- return true;
- }else if (originalJsonObject == null || newJsonObject == null) {
- return false;
- } else {
- // check the number of childs
- Set<Map.Entry<String , JsonElement>> entrySetOfOriginalJson = originalJsonObject.entrySet();
- Set<Map.Entry<String , JsonElement>> entrySetOfNewJson = newJsonObject.entrySet();
- if (entrySetOfOriginalJson.size() != entrySetOfNewJson.size()) {
- return false;
- }
-
- for (Map.Entry<String, JsonElement> keyString : entrySetOfOriginalJson) {
- JsonElement valueOrig = keyString.getValue();
- JsonElement valueNew = newJsonObject.get(keyString.getKey());
- if (valueOrig instanceof JsonObject && valueNew instanceof JsonObject &&
- !isEqual((JsonObject) valueOrig, (JsonObject) valueNew)) {
- return false;
- }else if (valueOrig instanceof JsonArray && valueNew instanceof JsonArray &&
- !isEqual((JsonArray) valueOrig, (JsonArray) valueNew)) {
- return false;
- }else if (valueOrig instanceof JsonPrimitive && valueNew instanceof JsonPrimitive &&
- !isEqual((JsonPrimitive) valueOrig, (JsonPrimitive) valueNew)) {
- return false;
- }
- }
- }
- return true;
- }
-
- private static boolean isEqual(JsonArray arrayOriginal, JsonArray arrayNew) {
- if (arrayOriginal == null && arrayNew == null) {
- return true;
- }else if (arrayOriginal == null || arrayNew == null) {
- return false;
- }else {
- // check the number of element
- if (arrayOriginal.size() != arrayNew.size()) {
- return false;
- }else if (arrayOriginal.size() == 0) {
- return true;
- } else {
- for (int i = 0; i < arrayOriginal.size(); i++) {
- JsonElement valueOrig = arrayOriginal.get(i);
- JsonElement valueNew = arrayNew.get(i);
- if (valueOrig instanceof JsonObject && valueNew instanceof JsonObject) {
- if (!isEqual((JsonObject) valueOrig, (JsonObject) valueNew)) {
- return false;
- }
- }else if (valueOrig instanceof JsonPrimitive && valueNew instanceof JsonPrimitive) {
- if (!isEqual((JsonPrimitive) valueOrig, (JsonPrimitive) valueNew)) {
- return false;
- }
- }
- }
- }
- }
- return true;
- }
-
- private static boolean isEqual(JsonPrimitive primitiveOrig, JsonPrimitive primitiveNew) {
- if (primitiveOrig == null && primitiveNew == null) {
- return true;
- }else if (primitiveOrig == null || primitiveNew == null) {
- return false;
- } else {
- if (primitiveOrig.isString() && primitiveNew.isString()){
- if(!primitiveOrig.getAsString().equals(primitiveNew.getAsString())) {
- return false;
- }
- }else if (primitiveOrig.isBoolean() && primitiveNew.isBoolean()) {
- if ((Boolean.valueOf(primitiveOrig.getAsBoolean()).compareTo(primitiveNew.getAsBoolean()) != 0)) {
- return false;
- }
- }else if (primitiveOrig.isNumber() && primitiveNew.isNumber() ) {
- if (new Double(primitiveOrig.getAsDouble()).compareTo(primitiveNew.getAsDouble()) != 0) {
- return false;
- }
- }else {
- return primitiveOrig.isJsonNull() && primitiveNew.isJsonNull();
- }
- }
- return true;
- }
-}
http://git-wip-us.apache.org/repos/asf/airavata/blob/8d16d0ec/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/KeyStorePasswordCallback.java
----------------------------------------------------------------------
diff --git a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/KeyStorePasswordCallback.java b/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/KeyStorePasswordCallback.java
deleted file mode 100644
index bafaff3..0000000
--- a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/KeyStorePasswordCallback.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package org.apache.airavata.common.utils;/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-/**
- * User: AmilaJ (amilaj@apache.org)
- * Date: 10/11/13
- * Time: 11:30 AM
- */
-
-/**
- * An interface to get keystore password in a form of a callback.
- */
-public interface KeyStorePasswordCallback {
-
- /**
- * Caller should implement the interface. Should return the password for
- * the keystore. This should return the keystore password. i.e. password used to open the keystore.
- * Instead of the actual file.
- * @return The password to open the keystore.
- */
- char[] getStorePassword() throws RuntimeException;
-
- /**
- * Caller should implement the interface. Should return the pass phrase for
- * the secret key.
- * Instead of the actual file.
- * @param keyAlias The alias of the key
- * @return The pass phrase for the secret key.
- */
- char[] getSecretKeyPassPhrase(String keyAlias);
-
-}
http://git-wip-us.apache.org/repos/asf/airavata/blob/8d16d0ec/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/MonitorPublisher.java
----------------------------------------------------------------------
diff --git a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/MonitorPublisher.java b/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/MonitorPublisher.java
deleted file mode 100644
index 7f64e86..0000000
--- a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/MonitorPublisher.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-package org.apache.airavata.common.utils;
-
-import com.google.common.eventbus.EventBus;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class MonitorPublisher{
- private final static Logger logger = LoggerFactory.getLogger(MonitorPublisher.class);
- private EventBus eventBus;
-
- public MonitorPublisher(EventBus eventBus) {
- this.eventBus = eventBus;
- }
-
- public void registerListener(Object listener) {
- eventBus.register(listener);
- }
-
- public void unregisterListener(Object listener) {
- eventBus.unregister(listener);
- }
-
- public void publish(Object o) {
- eventBus.post(o);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/airavata/blob/8d16d0ec/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/NameValidator.java
----------------------------------------------------------------------
diff --git a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/NameValidator.java b/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/NameValidator.java
deleted file mode 100644
index 98530cf..0000000
--- a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/NameValidator.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.airavata.common.utils;
-
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public class NameValidator {
-
- /**
- * @param name
- * @return Is it valid name?
- */
- public static boolean validate(String name) {
- // Set the name pattern string
- Pattern p = Pattern.compile("([a-zA-Z]){1,}([0-9]|_|\\.|[a-zA-Z]){0,}$");
-
- // Match the given string with the pattern
- Matcher m = p.matcher(name);
-
- // Check whether match is found
- boolean matchFound = m.matches();
-
- return matchFound;
- }
-
- /**
- * @param args
- * @Description some quick tests
- */
- public static void main(String[] args) {
- System.out.println(validate("abc90_90abc")); // true
-
- System.out.println(validate("abc_abc_123")); // true
-
- System.out.println(validate("abc_abc_")); // true
-
- System.out.println(validate("abc_abc")); // true
-
- System.out.println(validate("abc.abc")); // true
-
- System.out.println(validate("9abc_abc")); // false, name cannot start with number
-
- System.out.println(validate("_abc_abc")); // false, name cannot start with "_"
-
- System.out.println(validate("\\abc_abc")); // false, name cannot start with "\"
-
- System.out.println(validate("abc\\_abc")); // false, name cannot contain "\"
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/airavata/blob/8d16d0ec/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/Pair.java
----------------------------------------------------------------------
diff --git a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/Pair.java b/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/Pair.java
deleted file mode 100644
index ee24360..0000000
--- a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/Pair.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.airavata.common.utils;
-
-public class Pair<L, R> {
-
- private L left;
-
- private R right;
-
- /**
- * Constructs a Pair.
- *
- * @param left
- * @param right
- */
- public Pair(L left, R right) {
- this.left = left;
- this.right = right;
- }
-
- /**
- * Returns the left.
- *
- * @return The left
- */
- public L getLeft() {
- return this.left;
- }
-
- /**
- * Sets left.
- *
- * @param left
- * The left to set.
- */
- public void setLeft(L left) {
- this.left = left;
- }
-
- /**
- * Returns the right.
- *
- * @return The right
- */
- public R getRight() {
- return this.right;
- }
-
- /**
- * Sets right.
- *
- * @param right
- * The right to set.
- */
- public void setRight(R right) {
- this.right = right;
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/airavata/blob/8d16d0ec/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/SecurityUtil.java
----------------------------------------------------------------------
diff --git a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/SecurityUtil.java b/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/SecurityUtil.java
deleted file mode 100644
index aeec807..0000000
--- a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/SecurityUtil.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.airavata.common.utils;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.crypto.Cipher;
-import javax.crypto.spec.IvParameterSpec;
-import javax.crypto.spec.SecretKeySpec;
-import java.io.*;
-import java.security.*;
-import java.security.cert.CertificateException;
-
-/**
- * Class which includes security utilities.
- */
-public class SecurityUtil {
-
- public static final String PASSWORD_HASH_METHOD_PLAINTEXT = "PLAINTEXT";
-
- public static final String CHARSET_ENCODING = "UTF-8";
- public static final String ENCRYPTION_ALGORITHM = "AES";
- public static final String PADDING_MECHANISM = "AES/CBC/PKCS5Padding";
-
- private static final Logger logger = LoggerFactory.getLogger(SecurityUtil.class);
-
- /**
- * Creates a hash of given string with the given hash algorithm.
- *
- * @param stringToDigest
- * The string to digest.
- * @param digestingAlgorithm
- * Hash algorithm.
- * @return The digested string.
- * @throws NoSuchAlgorithmException
- * If given hash algorithm doesnt exists.
- */
- public static String digestString(String stringToDigest, String digestingAlgorithm) throws NoSuchAlgorithmException {
-
- if (digestingAlgorithm == null || digestingAlgorithm.equals(PASSWORD_HASH_METHOD_PLAINTEXT)) {
- return stringToDigest;
- }
-
- MessageDigest messageDigest = MessageDigest.getInstance(digestingAlgorithm);
- try {
- return new String(messageDigest.digest(stringToDigest.getBytes("UTF-8")));
- } catch (UnsupportedEncodingException e) {
- logger.error("Error encoding password string when creating digest", e);
- throw new RuntimeException("Error encoding password string when creating digest", e);
- }
- }
-
- /**
- * Sets the truststore for application. Useful when communicating over HTTPS.
- *
- * @param trustStoreFilePath
- * Where trust store is located.
- * @param trustStorePassword
- * The trust store password.
- */
- public static void setTrustStoreParameters(String trustStoreFilePath, String trustStorePassword) {
-
- if (System.getProperty("javax.net.ssl.trustStrore") == null) {
- logger.info("Setting Java trust store to " + trustStoreFilePath);
- System.setProperty("javax.net.ssl.trustStrore", trustStoreFilePath);
- }
-
- if (System.getProperty("javax.net.ssl.trustStorePassword") == null) {
- System.setProperty("javax.net.ssl.trustStorePassword", trustStoreFilePath);
- }
-
- }
-
- public static byte[] encryptString(String keyStorePath, String keyAlias,
- KeyStorePasswordCallback passwordCallback, String value)
- throws GeneralSecurityException, IOException {
- return encrypt(keyStorePath, keyAlias, passwordCallback, value.getBytes(CHARSET_ENCODING));
- }
-
- public static byte[] encrypt(String keyStorePath, String keyAlias,
- KeyStorePasswordCallback passwordCallback, byte[] value)
- throws GeneralSecurityException, IOException {
-
- Key secretKey = getSymmetricKey(keyStorePath, keyAlias, passwordCallback);
-
- Cipher cipher = Cipher.getInstance(PADDING_MECHANISM);
- cipher.init(Cipher.ENCRYPT_MODE, secretKey,
- new IvParameterSpec(new byte[16]));
- return cipher.doFinal(value);
- }
-
- private static Key getSymmetricKey(String keyStorePath, String keyAlias,
- KeyStorePasswordCallback passwordCallback)
- throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException,
- UnrecoverableKeyException {
-
- KeyStore ks = SecurityUtil.loadKeyStore(keyStorePath, "jceks", passwordCallback);
-
- if (ks == null) {
- throw new IOException("Unable to load Java keystore " + keyStorePath);
- }
-
- return ks.getKey(keyAlias, passwordCallback.getSecretKeyPassPhrase(keyAlias));
-
- }
-
- public static byte[] decrypt(String keyStorePath, String keyAlias,
- KeyStorePasswordCallback passwordCallback, byte[] encrypted)
- throws GeneralSecurityException, IOException {
-
- Key secretKey = getSymmetricKey(keyStorePath, keyAlias, passwordCallback);
-
- Cipher cipher = Cipher.getInstance(PADDING_MECHANISM);
- cipher.init(Cipher.DECRYPT_MODE, secretKey,
- new IvParameterSpec(new byte[16]));
-
- return cipher.doFinal(encrypted);
- }
-
- public static String decryptString(String keyStorePath, String keyAlias,
- KeyStorePasswordCallback passwordCallback, byte[] encrypted)
- throws GeneralSecurityException, IOException {
-
- byte[] decrypted = decrypt(keyStorePath, keyAlias, passwordCallback, encrypted);
- return new String(decrypted, CHARSET_ENCODING);
- }
-
- public static KeyStore loadKeyStore(String keyStoreFilePath, String keyStoreType,
- KeyStorePasswordCallback passwordCallback)
- throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
-
- java.io.FileInputStream fis = null;
- try {
- fis = new java.io.FileInputStream(keyStoreFilePath);
- return loadKeyStore(fis, keyStoreType, passwordCallback);
- } finally {
- if (fis != null) {
- fis.close();
- }
- }
- }
-
- public static KeyStore loadKeyStore(InputStream inputStream, String keyStoreType,
- KeyStorePasswordCallback passwordCallback)
- throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
-
- if (keyStoreType == null) {
- keyStoreType = KeyStore.getDefaultType();
- }
-
- KeyStore ks = KeyStore.getInstance(keyStoreType);
- ks.load(inputStream, passwordCallback.getStorePassword());
-
- return ks;
- }
-
-
-
-
-
-}
http://git-wip-us.apache.org/repos/asf/airavata/blob/8d16d0ec/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/ServerSettings.java
----------------------------------------------------------------------
diff --git a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/ServerSettings.java b/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/ServerSettings.java
deleted file mode 100644
index 8370e40..0000000
--- a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/ServerSettings.java
+++ /dev/null
@@ -1,270 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.airavata.common.utils;
-
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-
-import org.apache.airavata.common.exception.ApplicationSettingsException;
-
-public class ServerSettings extends ApplicationSettings {
-
- private static final String DEFAULT_USER = "default.registry.user";
- private static final String DEFAULT_USER_PASSWORD = "default.registry.password";
- private static final String DEFAULT_USER_GATEWAY = "default.registry.gateway";
-
- private static final String SERVER_CONTEXT_ROOT = "server.context-root";
- public static final String EMBEDDED_ZK = "embedded.zk";
- public static final String IP = "ip";
-
- private static final String CREDENTIAL_STORE_DB_URL = "credential.store.jdbc.url";
- private static final String CREDENTIAL_STORE_DB_USER = "credential.store.jdbc.user";
- private static final String CREDENTIAL_STORE_DB_PASSWORD = "credential.store.jdbc.password";
- private static final String CREDENTIAL_STORE_DB_DRIVER = "credential.store.jdbc.driver";
-
- private static final String REGISTRY_DB_URL = "registry.jdbc.url";
- private static final String REGISTRY_DB_USER = "registry.jdbc.user";
- private static final String REGISTRY_DB_PASSWORD = "registry.jdbc.password";
- private static final String REGISTRY_DB_DRIVER = "registry.jdbc.driver";
- private static final String ENABLE_HTTPS = "enable.https";
- private static final String HOST_SCHEDULER = "host.scheduler";
- private static final String MY_PROXY_SERVER = "myproxy.server";
- private static final String MY_PROXY_USER = "myproxy.user";
- private static final String MY_PROXY_PASSWORD = "myproxy.password";
- private static final String MY_PROXY_LIFETIME = "myproxy.life";
- private static final String STATUS_PUBLISHER = "status.publisher";
- private static final String TASK_LAUNCH_PUBLISHER = "task.launch.publisher";
- private static final String ACTIVITY_LISTENERS = "activity.listeners";
- public static final String JOB_NOTIFICATION_ENABLE = "job.notification.enable";
- public static final String JOB_NOTIFICATION_EMAILIDS = "job.notification.emailids";
- public static final String JOB_NOTIFICATION_FLAGS = "job.notification.flags";
- public static final String GFAC_PASSIVE = "gfac.passive"; // by default this is desabled
- public static final String LAUNCH_QUEUE_NAME = "launch.queue.name";
- public static final String CANCEL_QUEUE_NAME = "cancel.queue.name";
-
-
- // Workflow Enactment Service component configuration.
- private static final String ENACTMENT_THREAD_POOL_SIZE = "enactment.thread.pool.size";
- private static final int DEFAULT_ENACTMENT_THREAD_POOL_SIZE = 10;
- private static final String WORKFLOW_PARSER = "workflow.parser";
-
- // email based monitoring configurations
- private static final String EMAIL_BASED_MONITORING_PERIOD = "email.based.monitoring.period";
- private static final String EMAIL_BASED_MONITOR_HOST = "email.based.monitor.host";
- private static final String EMAIL_BASED_MONITOR_ADDRESS = "email.based.monitor.address";
- private static final String EMAIL_BASED_MONITOR_PASSWORD = "email.based.monitor.password";
- private static final String EMAIL_BASED_MONITOR_FOLDER_NAME = "email.based.monitor.folder.name";
- private static final String EMAIL_BASED_MONITOR_STORE_PROTOCOL = "email.based.monitor.store.protocol";
- private static final String ENABLE_EMAIL_BASED_MONITORING = "enable.email.based.monitoring";
-
- private static boolean stopAllThreads = false;
- private static boolean emailBaseNotificationEnable;
-
- public static String getDefaultUser() throws ApplicationSettingsException {
- return getSetting(DEFAULT_USER);
- }
-
- public static String getLaunchQueueName() {
- return getSetting(LAUNCH_QUEUE_NAME, "launch.queue");
- }
-
-
- public static String getCancelQueueName() {
- return getSetting(CANCEL_QUEUE_NAME, "cancel.queue");
- }
-
- public static String getDefaultUserPassword() throws ApplicationSettingsException {
- return getSetting(DEFAULT_USER_PASSWORD);
- }
-
- public static String getDefaultUserGateway() throws ApplicationSettingsException {
- return getSetting(DEFAULT_USER_GATEWAY);
- }
-
- public static String getServerContextRoot() {
- return getSetting(SERVER_CONTEXT_ROOT, "axis2");
- }
-
- public static String getCredentialStoreDBUser() throws ApplicationSettingsException {
- try {
- return getSetting(CREDENTIAL_STORE_DB_USER);
- } catch (ApplicationSettingsException e) {
- return getSetting(REGISTRY_DB_USER);
- }
- }
-
- public static String getCredentialStoreDBPassword() throws ApplicationSettingsException {
- try {
- return getSetting(CREDENTIAL_STORE_DB_PASSWORD);
- } catch (ApplicationSettingsException e) {
- return getSetting(REGISTRY_DB_PASSWORD);
- }
- }
-
- public static String getCredentialStoreDBDriver() throws ApplicationSettingsException {
- try {
- return getSetting(CREDENTIAL_STORE_DB_DRIVER);
- } catch (ApplicationSettingsException e) {
- return getSetting(REGISTRY_DB_DRIVER);
- }
- }
-
- public static String getCredentialStoreDBURL() throws ApplicationSettingsException {
- try {
- return getSetting(CREDENTIAL_STORE_DB_URL);
- } catch (ApplicationSettingsException e) {
- return getSetting(REGISTRY_DB_URL);
- }
-
- }
-
- public static boolean isEnableHttps() {
- try {
- return Boolean.parseBoolean(getSetting(ENABLE_HTTPS));
- } catch (ApplicationSettingsException e) {
- return false;
- }
- }
-
-
- public static String getHostScheduler() throws ApplicationSettingsException {
- return getSetting(HOST_SCHEDULER);
- }
-
- public static boolean isStopAllThreads() {
- return stopAllThreads;
- }
-
- public static void setStopAllThreads(boolean stopAllThreads) {
- ServerSettings.stopAllThreads = stopAllThreads;
- }
-
- public static String getMyProxyServer() throws ApplicationSettingsException {
- return getSetting(MY_PROXY_SERVER);
- }
-
- public static String getMyProxyUser() throws ApplicationSettingsException {
- return getSetting(MY_PROXY_USER);
- }
-
- public static String getMyProxyPassword() throws ApplicationSettingsException {
- return getSetting(MY_PROXY_PASSWORD);
- }
-
- public static int getMyProxyLifetime() throws ApplicationSettingsException {
- return Integer.parseInt(getSetting(MY_PROXY_LIFETIME));
- }
-
- public static String[] getActivityListeners() throws ApplicationSettingsException {
- return getSetting(ACTIVITY_LISTENERS).split(",");
- }
-
- public static String getStatusPublisher() throws ApplicationSettingsException {
- return getSetting(STATUS_PUBLISHER);
- }
-
- public static String getTaskLaunchPublisher() throws ApplicationSettingsException {
- return getSetting(TASK_LAUNCH_PUBLISHER);
- }
-
- public static boolean isGFacPassiveMode()throws ApplicationSettingsException {
- String setting = getSetting(GFAC_PASSIVE);
- return Boolean.parseBoolean(setting);
- }
-
- public static boolean isEmbeddedZK() {
- return Boolean.parseBoolean(getSetting(EMBEDDED_ZK, "true"));
- }
-
- public static String getIp() {
- try {
- return getSetting(IP);
- } catch (ApplicationSettingsException e) {
- try {
- return InetAddress.getLocalHost().getHostAddress();
- } catch (UnknownHostException e1) {
- e1.printStackTrace();
- }
- }
- return null;
- }
-
- public static int getEnactmentThreadPoolSize() {
- String threadPoolSize = null;
- try {
- threadPoolSize = getSetting(ENACTMENT_THREAD_POOL_SIZE);
- } catch (ApplicationSettingsException e) {
- return DEFAULT_ENACTMENT_THREAD_POOL_SIZE;
- }
- return Integer.valueOf(threadPoolSize);
- }
-
- public static String getWorkflowParser() throws ApplicationSettingsException {
- return getSetting(WORKFLOW_PARSER);
- }
-
-
- public static int getEmailMonitorPeriod() throws ApplicationSettingsException {
- return Integer.valueOf(getSetting(EMAIL_BASED_MONITORING_PERIOD, "100000"));
-
- }
-
- public static String getEmailBasedMonitorHost() throws ApplicationSettingsException {
- return getSetting(EMAIL_BASED_MONITOR_HOST);
- }
-
- public static String getEmailBasedMonitorAddress() throws ApplicationSettingsException {
- return getSetting(EMAIL_BASED_MONITOR_ADDRESS);
- }
-
- public static String getEmailBasedMonitorPassword() throws ApplicationSettingsException {
- return getSetting(EMAIL_BASED_MONITOR_PASSWORD);
- }
-
- public static String getEmailBasedMonitorFolderName() throws ApplicationSettingsException {
- return getSetting(EMAIL_BASED_MONITOR_FOLDER_NAME);
- }
-
- public static String getEmailBasedMonitorStoreProtocol() throws ApplicationSettingsException {
- return getSetting(EMAIL_BASED_MONITOR_STORE_PROTOCOL);
- }
-
- public static boolean isEmailBasedNotificationEnable() {
- return Boolean.valueOf(getSetting(ENABLE_EMAIL_BASED_MONITORING, "false"));
- }
-
- public static boolean isAPISecured() throws ApplicationSettingsException {
- return Boolean.valueOf(getSetting(Constants.IS_API_SECURED));
- }
-
- public static String getRemoteOauthServerUrl() throws ApplicationSettingsException {
- return getSetting(Constants.REMOTE_OAUTH_SERVER_URL);
- }
-
- public static String getAdminUsername() throws ApplicationSettingsException {
- return getSetting(Constants.ADMIN_USERNAME);
- }
-
- public static String getAdminPassword() throws ApplicationSettingsException {
- return getSetting(Constants.ADMIN_PASSWORD);
- }
-}
http://git-wip-us.apache.org/repos/asf/airavata/blob/8d16d0ec/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/ServiceUtils.java
----------------------------------------------------------------------
diff --git a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/ServiceUtils.java b/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/ServiceUtils.java
deleted file mode 100644
index 0c54053..0000000
--- a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/ServiceUtils.java
+++ /dev/null
@@ -1,93 +0,0 @@
-///*
-// *
-// * Licensed to the Apache Software Foundation (ASF) under one
-// * or more contributor license agreements. See the NOTICE file
-// * distributed with this work for additional information
-// * regarding copyright ownership. The ASF licenses this file
-// * to you under the Apache License, Version 2.0 (the
-// * "License"); you may not use this file except in compliance
-// * with the License. You may obtain a copy of the License at
-// *
-// * http://www.apache.org/licenses/LICENSE-2.0
-// *
-// * Unless required by applicable law or agreed to in writing,
-// * software distributed under the License is distributed on an
-// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// * KIND, either express or implied. See the License for the
-// * specific language governing permissions and limitations
-// * under the License.
-// *
-// */
-//
-//package org.apache.airavata.common.utils;
-//
-//import java.io.IOException;
-//import java.net.SocketException;
-//
-//import org.apache.airavata.common.exception.ApplicationSettingsException;
-//import org.apache.axis2.context.ConfigurationContext;
-//import org.apache.axis2.description.TransportInDescription;
-//import org.apache.axis2.util.Utils;
-//import org.slf4j.Logger;
-//import org.slf4j.LoggerFactory;
-//
-//public class ServiceUtils {
-// private static final Logger log = LoggerFactory.getLogger(ServiceUtils.class);
-//// private static final String REPOSITORY_PROPERTIES = "airavata-server.properties";
-// public static final String IP = "ip";
-// public static final String PORT = "port";
-//
-// public static String generateServiceURLFromConfigurationContext(
-// ConfigurationContext context, String serviceName) throws IOException, ApplicationSettingsException {
-//// URL url = ServiceUtils.class.getClassLoader()
-//// .getResource(REPOSITORY_PROPERTIES);
-// String localAddress = null;
-// String port = null;
-//// Properties properties = new Properties();
-// try {
-// localAddress = ServerSettings.getSetting(IP);
-// } catch (ApplicationSettingsException e) {
-// //we will ignore this exception since the properties file will not contain the values
-// //when it is ok to retrieve them from the axis2 context
-// }
-// if(localAddress == null){
-// try {
-// localAddress = Utils.getIpAddress(context
-// .getAxisConfiguration());
-// } catch (SocketException e) {
-// e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
-// }
-// }
-// String protocol="http";
-// if(ServerSettings.isEnableHttps()){
-// protocol="https";
-// }
-//
-// try {
-// port = ServerSettings.getTomcatPort(protocol);
-// } catch (ApplicationSettingsException e) {
-// //we will ignore this exception since the properties file will not contain the values
-// //when it is ok to retrieve them from the axis2 context
-// }
-// if (port == null) {
-// TransportInDescription transportInDescription = context
-// .getAxisConfiguration().getTransportsIn()
-// .get(protocol);
-// if (transportInDescription != null
-// && transportInDescription.getParameter(PORT) != null) {
-// port = (String) transportInDescription
-// .getParameter(PORT).getValue();
-// }
-// }
-// localAddress = protocol+"://" + localAddress + ":" + port;
-// localAddress = localAddress + "/"
-// //We are not using axis2 config context to get the context root because it is invalid
-// //+ context.getContextRoot() + "/"
-// //FIXME: the context root will be correct after updating the web.xml
-// + ServerSettings.getServerContextRoot() + "/"
-// + context.getServicePath() + "/"
-// + serviceName;
-// log.debug("Service Address Configured:" + localAddress);
-// return localAddress;
-// }
-//}
http://git-wip-us.apache.org/repos/asf/airavata/blob/8d16d0ec/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/StringUtil.java
----------------------------------------------------------------------
diff --git a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/StringUtil.java b/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/StringUtil.java
deleted file mode 100644
index 3ce5cda..0000000
--- a/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/StringUtil.java
+++ /dev/null
@@ -1,480 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.airavata.common.utils;
-
-import java.io.ByteArrayOutputStream;
-import java.io.PrintStream;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.CommandLineParser;
-import org.apache.commons.cli.Option;
-import org.apache.commons.cli.Options;
-import org.apache.commons.cli.ParseException;
-import org.apache.commons.cli.PosixParser;
-
-public class StringUtil {
- public static final String DELIMETER=",";
- public static final String QUOTE="\"";
-
- public static Map<Integer, String> getContainedParameters(String s) {
- Map<Integer,String> parameterMap=new HashMap<Integer,String>();
- int i=0;
- for(i=0;i<s.length();i++){
- if (s.charAt(i)=='$' && (i+1)<s.length() && s.charAt(i+1)=='{'){
- int i2=s.indexOf('{', i+2);
- int e=s.indexOf('}', i+2);
- if (e!=-1){
- if (i2==-1 || e<i2){
- parameterMap.put(i, s.substring(i,e+1));
- i=e;
- }
- }
- }
- }
- return parameterMap;
- }
-
- // Merits for the following function should go to
- // http://blog.houen.net/java-get-url-from-string/
- public static List<String> getURLS(String text) {
- List<String> links = new ArrayList<String>();
- String regex = "\\(?\\b((http|https|ftp)://|www[.])[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]";
- Pattern p = Pattern.compile(regex);
- Matcher m = p.matcher(text);
- while (m.find()) {
- String urlStr = m.group();
- if (urlStr.startsWith("(") && urlStr.endsWith(")")) {
- urlStr = urlStr.substring(1, urlStr.length() - 1);
- }
- if (!links.contains(urlStr)) {
- links.add(urlStr);
- }
- }
- return links;
- }
-
- public static String createHTMLUrlTaggedString2(String value, List<String> pullLinks) {
- for (String url : pullLinks) {
- String hyperlinkString="<a href='"+url+"'>"+url+"</a>";
- value=value.replaceAll(Pattern.quote(url), hyperlinkString);
- }
- return value;
- }
- public static String createHTMLUrlTaggedString(String value) {
- String urledString = "";
- int lastIndex=0,index=0;
- while(index!=-1){
- index=value.toLowerCase().indexOf("://",lastIndex);
- if (index!=-1){
- int beginIndex=value.lastIndexOf(" ",index);
- urledString+=value.substring(lastIndex,beginIndex+1);
- int endIndex=value.indexOf(" ",index);
- if (beginIndex==-1){
- beginIndex=0;
- }else{
- beginIndex++;
- }
- if (endIndex==-1){
- endIndex=value.length();
- }
- String url=value.substring(beginIndex, endIndex);
- urledString+="<a href='"+url+"'>"+url+"</a>";
- lastIndex=endIndex;
- }
- }
- urledString+=value.substring(lastIndex, value.length());
- return urledString;
- }
-
- private static boolean isQuoted(String s, String delimiter){
- //Check if we need quotes
- if (s.contains(delimiter)){
- //Check if its already quoted
- s=s.replaceAll("\"\"", "");
- return (s.substring(0,1).equals(QUOTE) && s.subSequence(s.length()-1, s.length()).equals(QUOTE));
- }
- //no delimiters present, so already in proper form
- return true;
- }
-
- private static boolean isQuoted(String s){
- return isQuoted(s, DELIMETER);
- }
-
- /**
- * Create a delimiter separated string out of a list
- * @param list
- * @return
- */
- public static String createDelimiteredString(String[] list) {
- return createDelimiteredString(list, DELIMETER);
- }
-
-
- /**
- * Create a delimiter separated string out of a list
- * @param list
- * @return
- */
- public static String createDelimiteredString(String[] list,String delimiter){
- String s=null;
- for (String ss : list) {
- ss=quoteString(ss, delimiter);
- if (s==null){
- s=ss;
- }else{
- s+=delimiter +ss;
- }
- }
- return s;
- }
-
- /**
- * Return a proper quoted string if the string contains the delimiter character
- * @param s
- * @return
- */
- public static String quoteString(String s) {
- return quoteString(s, DELIMETER);
- }
-
-
- /**
- * Return a proper quoted string if the string contains the delimiter character
- * @param s
- * @return
- */
- public static String quoteString(String s,String delimiter){
- if (isQuoted(s,delimiter)){
- return s;
- }else{
- return QUOTE+s.replaceAll(QUOTE, QUOTE+QUOTE)+QUOTE;
- }
- }
-
- /**
- * Parse the delimitered string and return elements as a string array
- * @param s
- * @return
- */
- public static String[] getElementsFromString(String s, String delimeter, String quote) {
- List<String> list=new ArrayList<String>();
- String currentItem="";
- String previousChar=null;
- boolean insideQuote=false;
- for(int i=0;i<s.length();i++){
- String c=s.substring(i,i+1);
- if (c.equals(delimeter)){
- //if not inside a quoted string ignore the delimiter character
- if (insideQuote) {
- currentItem+=c;
- }else{
- list.add(currentItem);
- currentItem = "";
- }
- }else if (c.equals(quote)){
- if (quote.equals(previousChar)){
- //which means previousChar was an escape character, not a quote for the string
- currentItem+=quote;
- if (insideQuote){
- //mistakenly thought previous char was opening quote char, thus need to make this false
- insideQuote=false;
- }else{
- //mistakenly thought previous char was closing quote char, thus need to make this true
- insideQuote=true;
- }
- } else{
- if (insideQuote){
- //quote ended
- insideQuote=false;
- }else{
- //quote beginning
- insideQuote=true;
- }
- }
- }else{
- currentItem+=c;
- }
- previousChar=c;
- }
- list.add(currentItem);
- return list.toArray(new String[]{});
- }
-
- /**
- * Parse the delimitered string and return elements as a string array
- * @param s
- * @return
- */
- public static String[] getElementsFromString(String s) {
- return getElementsFromString(s, DELIMETER, QUOTE);
- }
-
- /**
- * Converts object to String without worrying about null check.
- *
- * @param object
- * @return The object.toString if object is not null; "" otherwise.
- */
- public static String toString(Object object) {
- if (object == null) {
- return "";
- } else {
- return object.toString();
- }
- }
-
- /**
- * Trims a specified string, and makes it null if the result is empty string.
- *
- * @param string
- * @return the string processed
- */
- public static String trimAndNullify(String string) {
- if (string != null) {
- string = string.trim();
- if (string.equals("")) {
- string = null;
- }
- }
- return string;
- }
-
- /**
- * @param oldName
- * @return Trimmed String
- */
- public static String trimSpaceInString(String oldName) {
- if (oldName == null) {
- return "";
- }
- return oldName.replace(" ", "");
- }
-
- /**
- * Converts a specified string to a Java identifier.
- *
- * @param name
- * @return the Java identifier
- */
- public static String convertToJavaIdentifier(String name) {
-
- final char REPLACE_CHAR = '_';
-
- if (name == null || name.length() == 0) {
- return "" + REPLACE_CHAR;
- }
-
- StringBuilder buf = new StringBuilder();
-
- char c = name.charAt(0);
- if (!Character.isJavaIdentifierStart(c)) {
- // Add _ at the beggining instead of replacing it to _. This is
- // more readable if the name is like 3D_Model.
- buf.append(REPLACE_CHAR);
- }
-
- for (int i = 0; i < name.length(); i++) {
- c = name.charAt(i);
- if (Character.isJavaIdentifierPart(c)) {
- buf.append(c);
- } else {
- buf.append(REPLACE_CHAR);
- }
- }
-
- return buf.toString();
- }
-
- /**
- * Creates a new name by incrementing the number after the underscore at the end of the old name. If there is no
- * underscore and number at the end, put "_2" at the end.
- *
- * @param oldName
- * @return the new name
- */
- public static String incrementName(String oldName) {
-
- final char PREFIX = '_';
-
- String newName;
- if (oldName == null || oldName.length() == 0) {
- newName = "noName";
- } else {
- int lastDashIndex = oldName.lastIndexOf(PREFIX);
- if (lastDashIndex < 0) {
- newName = oldName + PREFIX + 2;
- } else {
- String suffix = oldName.substring(lastDashIndex + 1);
- try {
- int number = Integer.parseInt(suffix);
- int newNumber = number + 1;
- newName = oldName.substring(0, lastDashIndex + 1) + newNumber;
- } catch (RuntimeException e) {
- // It was not a number
- newName = oldName + PREFIX + 2;
- }
- }
- }
- return newName;
- }
-
- /**
- * Returns the local class name of a specified class.
- *
- * @param klass
- * The specified class
- * @return The local class name
- */
- public static String getClassName(Class klass) {
- String fullName = klass.getName();
- int index = fullName.lastIndexOf(".");
- if (index < 0) {
- return fullName;
- } else {
- return fullName.substring(index + 1);
- }
- }
-
- /**
- * @param throwable
- * @return The stackTrace in String
- */
- public static String getStackTraceInString(Throwable throwable) {
- ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
- PrintStream printStream = new PrintStream(byteArrayOutputStream);
- throwable.printStackTrace(printStream);
- printStream.flush();
- return byteArrayOutputStream.toString();
- }
-
- private static Options deriveCommandLineOptions(String[] args){
- Options options = new Options();
- String[] argCopy = getChangedList(args);
- int i=0;
- for (String arg : argCopy) {
- if (arg.startsWith("--")){
- arg=arg.substring(2);
- int pos = arg.indexOf('=');
- String opt;
- boolean hasArgs=true;
- if (pos==-1){ //if not of the form --arg=value
- if (i==argCopy.length-1 || argCopy[i+1].startsWith("-")){ // no value specified
- hasArgs=false;
- }
- opt=arg;
- }else{
- opt=arg.substring(0, pos);
- }
- options.addOption(opt, hasArgs, "");
- }
- i++;
- }
- return options;
- }
-
- public static Map<String, String> parseCommandLineOptions(String[] args) {
- Map<String,String> commandLineOptions=new HashMap<String,String>();
- try {
- CommandLineParameters cmdParameters = getCommandLineParser(args);
- Map<String, String> parameters = cmdParameters.getParameters();
- for (String s : parameters.keySet()) {
- commandLineOptions.put(s, parameters.get(s)==null? "":parameters.get(s));
- }
- } catch (ParseException e1) {
- e1.printStackTrace();
- }
- return commandLineOptions;
- }
-
- public static CommandLineParameters getCommandLineParser(String[] args)
- throws ParseException {
- String[] argCopy = getChangedList(args);
- CommandLineParser parser = new DynamicOptionPosixParser();
- CommandLine cmdLine = parser.parse(deriveCommandLineOptions(argCopy), argCopy);
- return new CommandLineParameters(cmdLine);
- }
-
-
- //commons-cli does not support arg names having the period (".")
- private static final String ARG_DOT_REPLACE="dot_replacement_value";
-
- private static String[] getChangedList(String[] args) {
- String[] argCopy = Arrays.asList(args).toArray(new String []{});
- for (int i=0;i<argCopy.length; i++) {
- argCopy[i]=changeOption(argCopy[i]);
- }
- return argCopy;
- }
-
- private static String revertOption(String option){
- return option==null? option : option.replaceAll(Pattern.quote(ARG_DOT_REPLACE), ".");
- }
-
- private static String changeOption(String option){
- return option==null? option : option.replaceAll(Pattern.quote("."), ARG_DOT_REPLACE);
- }
-
- private static class DynamicOptionPosixParser extends PosixParser{
- @Override
- protected void processOption(String arg0, @SuppressWarnings("rawtypes") ListIterator arg1)
- throws ParseException {
- if (getOptions().hasOption(arg0)){
- super.processOption(arg0, arg1);
- }
- }
- }
-
- public static class CommandLineParameters{
- private Map<String,String> parameters=new HashMap<String, String>();
- private List<String> arguments=new ArrayList<String>();
- protected CommandLineParameters(CommandLine cmd){
- for(Option opt:cmd.getOptions()){
- parameters.put(revertOption(opt.getOpt()), revertOption(opt.getValue()));
- }
- for(String arg:cmd.getArgs()){
- arguments.add(revertOption(arg));
- }
- }
- public List<String> getArguments() {
- return arguments;
- }
- public void setArguments(List<String> arguments) {
- this.arguments = arguments;
- }
- public Map<String,String> getParameters() {
- return parameters;
- }
- public void setParameters(Map<String,String> parameters) {
- this.parameters = parameters;
- }
- }
-
-}
\ No newline at end of file