http://git-wip-us.apache.org/repos/asf/airavata-php-gateway/blob/488b772f/modules/commons/src/main/java/org/apache/airavata/common/utils/ApplicationSettings.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/ApplicationSettings.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/ApplicationSettings.java deleted file mode 100644 index 3c3eed7..0000000 --- a/modules/commons/src/main/java/org/apache/airavata/common/utils/ApplicationSettings.java +++ /dev/null @@ -1,455 +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.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class ApplicationSettings { - public static final String SERVER_PROPERTIES="airavata-server.properties"; - public static final String AIRAVATA_CONFIG_DIR = "airavata.config.dir"; - - public static String ADDITIONAL_SETTINGS_FILES = "external.settings"; - - protected Properties properties = new Properties(); - - private Exception propertyLoadException; - - - protected static final String TRUST_STORE_PATH="trust.store"; - protected static final String TRUST_STORE_PASSWORD="trust.store.password"; - - private static final String REGULAR_EXPRESSION = "\\$\\{[a-zA-Z.-]*\\}"; - - private final static Logger logger = LoggerFactory.getLogger(ApplicationSettings.class); - - private static final String SHUTDOWN_STATEGY_STRING="shutdown.strategy"; - - protected static ApplicationSettings INSTANCE; - public static enum ShutdownStrategy{ - NONE, - SELF_TERMINATE - } - { - loadProperties(); - } - - private void loadProperties() { - URL url = getPropertyFileURL(); - try { - properties.load(url.openStream()); - logger.info("Settings loaded from "+url.toString()); - URL[] externalSettingsFileURLs = getExternalSettingsFileURLs(); - for (URL externalSettings : externalSettingsFileURLs) { - mergeSettingsImpl(externalSettings.openStream()); - logger.info("External settings merged from "+url.toString()); - } - } catch (Exception e) { - propertyLoadException=e; - } - } - - protected URL getPropertyFileURL() { - return ApplicationSettings.loadFile(SERVER_PROPERTIES); - } - - protected URL[] getExternalSettingsFileURLs(){ - try { - List<URL> externalSettingsFileURLs=new ArrayList<URL>(); - String externalSettingsFileNames = getSettingImpl(ADDITIONAL_SETTINGS_FILES); - String[] externalSettingFiles = externalSettingsFileNames.split(","); - for (String externalSettingFile : externalSettingFiles) { - URL externalSettingFileURL = ApplicationSettings.loadFile(externalSettingFile); - if (externalSettingFileURL==null){ - logger.warn("Could not file external settings file "+externalSettingFile); - }else{ - externalSettingsFileURLs.add(externalSettingFileURL); - } - } - return externalSettingsFileURLs.toArray(new URL[]{}); - } catch (ApplicationSettingsException e) { - return new URL[]{}; - } - } - protected static ApplicationSettings getInstance(){ - if (INSTANCE==null){ - INSTANCE=new ApplicationSettings(); - } - return INSTANCE; - } - - protected static void setInstance(ApplicationSettings settingsInstance){ - INSTANCE=settingsInstance; - } - - private void saveProperties() throws ApplicationSettingsException{ - URL url = getPropertyFileURL(); - if (url.getProtocol().equalsIgnoreCase("file")){ - try { - properties.store(new FileOutputStream(url.getPath()), Calendar.getInstance().toString()); - } catch (Exception e) { - throw new ApplicationSettingsException(url.getPath(), e); - } - }else{ - logger.warn("Properties cannot be updated to location "+url.toString()); - } - } - - private void validateSuccessfulPropertyFileLoad() throws ApplicationSettingsException{ - if (propertyLoadException!=null){ - throw new ApplicationSettingsException(propertyLoadException.getMessage(), propertyLoadException); - } - } - - /** - * Returns the configuration value relevant for the given key. - * If configuration value contains references to other configuration values they will also - * be replaced. E.g :- If configuration key reads http://${ip}:${port}/axis2/services/RegistryService?wsdl, - * the variables ip and port will get replaced by their appropriated values in the configuration. - * @param key The configuration key to read value of - * @return The configuration value. For above example caller will get a value like - * http://192.2.33.12:8080/axis2/services/RegistryService?wsdl - * @throws ApplicationSettingsException If an error occurred while reading configurations. - * @deprecated use #getSetting(String) instead - */ - public String getAbsoluteSetting(String key) throws ApplicationSettingsException { - - String configurationValueWithVariables = ApplicationSettings.getSetting(key); - - List<String> variableList - = getAllMatches(configurationValueWithVariables, REGULAR_EXPRESSION); - - if (variableList == null || variableList.isEmpty()) { - return configurationValueWithVariables; - } - - for(String variableIdentifier : variableList) { - String variableName = getVariableNameOnly(variableIdentifier); - String value = getAbsoluteSetting(variableName); - - configurationValueWithVariables = configurationValueWithVariables.replace(variableIdentifier, value); - } - - return configurationValueWithVariables; - - } - - private static String getVariableNameOnly(String variableWithIdentifiers) { - return variableWithIdentifiers.substring(2, (variableWithIdentifiers.length() - 1)); - } - - private static List<String> getAllMatches(String text, String regex) { - List<String> matches = new ArrayList<String>(); - Matcher m = Pattern.compile("(?=(" + regex + "))").matcher(text); - while(m.find()) { - matches.add(m.group(1)); - } - return matches; - } - - public String getSettingImpl(String key) throws ApplicationSettingsException{ - String rawValue=null; - if (System.getProperties().containsKey(key)){ - rawValue=System.getProperties().getProperty(key); - }else{ - validateSuccessfulPropertyFileLoad(); - if (properties.containsKey(key)){ - rawValue=properties.getProperty(key); - }else{ - throw new ApplicationSettingsException(key); - } - } - return deriveAbsoluteValueImpl(rawValue); - } - - public String getSettingImpl(String key, String defaultValue){ - try { - return getSettingImpl(key); - } catch (ApplicationSettingsException e) { - //we'll ignore this error since a default value is provided - } - return defaultValue; - } - - private String deriveAbsoluteValueImpl(String property){ - if (property!=null){ - Map<Integer, String> containedParameters = StringUtil.getContainedParameters(property); - List<String> parametersAlreadyProcessed=new ArrayList<String>(); - for (String parameter : containedParameters.values()) { - if (!parametersAlreadyProcessed.contains(parameter)) { - String parameterName = parameter.substring(2,parameter.length() - 1); - String parameterValue = getSetting(parameterName,parameter); - property = property.replaceAll(Pattern.quote(parameter), parameterValue); - parametersAlreadyProcessed.add(parameter); - } - } - } - return property; - } - - public void setSettingImpl(String key, String value) throws ApplicationSettingsException{ - properties.setProperty(key, value); - saveProperties(); - } - - public boolean isSettingDefinedImpl(String key) throws ApplicationSettingsException{ - validateSuccessfulPropertyFileLoad(); - return properties.containsKey(key); - } - - public String getTrustStorePathImpl() throws ApplicationSettingsException { - return getSetting(TRUST_STORE_PATH); - } - - public String getTrustStorePasswordImpl() throws ApplicationSettingsException { - return getSetting(TRUST_STORE_PASSWORD); - } - - public String getCredentialStoreKeyStorePathImpl() throws ApplicationSettingsException { - return getSetting("credential.store.keystore.url"); - } - - public String getCredentialStoreKeyAliasImpl() throws ApplicationSettingsException { - return getSetting("credential.store.keystore.alias"); - } - - public String getCredentialStoreKeyStorePasswordImpl() throws ApplicationSettingsException { - return getSetting("credential.store.keystore.password"); - } - - public String getCredentialStoreNotifierEnabledImpl() throws ApplicationSettingsException { - return getSetting("notifier.enabled"); - } - - public String getCredentialStoreNotifierDurationImpl() throws ApplicationSettingsException { - return getSetting("notifier.duration"); - } - - public String getCredentialStoreEmailServerImpl() throws ApplicationSettingsException { - return getSetting("email.server"); - } - - public String getCredentialStoreEmailServerPortImpl() throws ApplicationSettingsException { - return getSetting("email.server.port"); - } - - public String getCredentialStoreEmailUserImpl() throws ApplicationSettingsException { - return getSetting("email.user"); - } - - public String getCredentialStoreEmailPasswordImpl() throws ApplicationSettingsException { - return getSetting("email.password"); - } - - public String getCredentialStoreEmailSSLConnectImpl() throws ApplicationSettingsException { - return getSetting("email.ssl"); - } - - public String getCredentialStoreEmailFromEmailImpl() throws ApplicationSettingsException { - return getSetting("email.from"); - } - - /** - * @deprecated use {{@link #getSetting(String)}} - * @return - */ - public Properties getPropertiesImpl() { - return properties; - } - - public void mergeSettingsImpl(Map<String,String> props){ - properties.putAll(props); - } - - public void mergeSettingsImpl(InputStream stream) throws IOException{ - Properties tmpProp = new Properties(); - tmpProp.load(stream); - properties.putAll(tmpProp); - } - - public void mergeSettingsCommandLineArgsImpl(String[] args){ - properties.putAll(StringUtil.parseCommandLineOptions(args)); - } - - public ShutdownStrategy getShutdownStrategyImpl() throws Exception{ - String strategy = null; - try { - strategy = getSetting(SHUTDOWN_STATEGY_STRING, ShutdownStrategy.SELF_TERMINATE.toString()); - return ShutdownStrategy.valueOf(strategy); - } catch (Exception e) { - //if the string mentioned in config is invalid - throw new Exception("Invalid shutdown strategy configured : "+strategy); - } - } - - /* - * Static methods which will be used by the users - */ - - public static String getSetting(String key) throws ApplicationSettingsException { - return getInstance().getSettingImpl(key); - } - - public static String getSetting(String key, String defaultValue) { - return getInstance().getSettingImpl(key,defaultValue); - - } - - public static void setSetting(String key, String value) throws ApplicationSettingsException{ - getInstance().properties.setProperty(key, value); - getInstance().saveProperties(); - } - - public static boolean isSettingDefined(String key) throws ApplicationSettingsException{ - return getInstance().properties.containsKey(key); - } - - public static String getTrustStorePath() throws ApplicationSettingsException { - return getSetting(TRUST_STORE_PATH); - } - - public static String getTrustStorePassword() throws ApplicationSettingsException { - return getSetting(TRUST_STORE_PASSWORD); - } - - public static void initializeTrustStore() throws ApplicationSettingsException { - SecurityUtil.setTrustStoreParameters(getTrustStorePath(), getTrustStorePassword()); - } - - public static String getCredentialStoreKeyStorePath() throws ApplicationSettingsException { - return getSetting("credential.store.keystore.url"); - } - - public static String getCredentialStoreKeyAlias() throws ApplicationSettingsException { - return getSetting("credential.store.keystore.alias"); - } - - public static String getCredentialStoreKeyStorePassword() throws ApplicationSettingsException { - return getSetting("credential.store.keystore.password"); - } - - public static String getCredentialStoreServerHost() throws ApplicationSettingsException { - return getSetting("credential.store.server.host"); - } - - public static String getCredentialStoreServerPort() throws ApplicationSettingsException { - return getSetting("credential.store.server.port"); - } - public static String getCredentialStoreNotifierEnabled() throws ApplicationSettingsException { - return getSetting("notifier.enabled"); - } - - public static String getCredentialStoreNotifierDuration() throws ApplicationSettingsException { - return getSetting("notifier.duration"); - } - - public static String getCredentialStoreEmailServer() throws ApplicationSettingsException { - return getSetting("email.server"); - } - - public static String getCredentialStoreEmailServerPort() throws ApplicationSettingsException { - return getSetting("email.server.port"); - } - - public static String getCredentialStoreEmailUser() throws ApplicationSettingsException { - return getSetting("email.user"); - } - - public static String getCredentialStoreEmailPassword() throws ApplicationSettingsException { - return getSetting("email.password"); - } - - public static String getCredentialStoreEmailSSLConnect() throws ApplicationSettingsException { - return getSetting("email.ssl"); - } - - public static String getCredentialStoreEmailFromEmail() throws ApplicationSettingsException { - return getSetting("email.from"); - } - - public static String getRegistryServerPort() throws ApplicationSettingsException { - return getSetting("regserver.server.port"); - } - - public static String getRegistryServerHost() throws ApplicationSettingsException { - return getSetting("regserver.server.host"); - } - - public static String getSuperTenantGatewayId() throws ApplicationSettingsException { - return getSetting("super.tenant.gatewayId"); - } - - public static String getClusterStatusMonitoringRepatTime() throws ApplicationSettingsException { - return getSetting("cluster.status.monitoring.repeat.time"); - } - - /** - * @deprecated use {{@link #getSetting(String)}} - * @return - * @throws ApplicationSettingsException - */ - public static Properties getProperties() throws ApplicationSettingsException { - return getInstance().properties; - } - - public static void mergeSettings(Map<String,String> props) { - getInstance().mergeSettingsImpl(props); - } - - public static void mergeSettings(InputStream stream) throws IOException{ - getInstance().mergeSettingsImpl(stream); - } - - public static void mergeSettingsCommandLineArgs(String[] args){ - getInstance().mergeSettingsCommandLineArgsImpl(args); - } - - public static ShutdownStrategy getShutdownStrategy() throws Exception{ - return getInstance().getShutdownStrategyImpl(); - } - - public static URL loadFile(String fileName) { - final URL resource = ApplicationSettings.class.getClassLoader().getResource(fileName); - if(resource == null) { - if(System.getProperty(AIRAVATA_CONFIG_DIR) != null) { - final String airavataConfigDir = System.getProperty(AIRAVATA_CONFIG_DIR); - try { - return new File(airavataConfigDir + File.separator + fileName).toURI().toURL(); - } catch (MalformedURLException e) { - logger.error("Error parsing the file from airavata.config.dir", airavataConfigDir); - } - } - } - return resource; - } -}
http://git-wip-us.apache.org/repos/asf/airavata-php-gateway/blob/488b772f/modules/commons/src/main/java/org/apache/airavata/common/utils/AwsMetadata.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/AwsMetadata.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/AwsMetadata.java deleted file mode 100644 index f9b4a65..0000000 --- a/modules/commons/src/main/java/org/apache/airavata/common/utils/AwsMetadata.java +++ /dev/null @@ -1,137 +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.base.Preconditions; -import com.google.common.net.InetAddresses; -import com.google.gson.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.net.InetAddress; -import java.net.URI; -import java.net.URISyntaxException; - -public class AwsMetadata { - private static final Logger log = LoggerFactory.getLogger(AwsMetadata.class); - private static final String METADATA_URI_BASE = "http://169.254.169.254/"; - private static final String REGION_SUFFIX = "/latest/dynamic/instance-identity/document"; - private static final String ZONE_SUFFIX = "/latest/meta-data/placement/availability-zone"; - private static final String PUBLIC_IPV4_SUFFIX = "/latest/meta-data/public-ipv4"; - private static final String PRIVATE_IPV4_SUFFIX = "latest/meta-data/local-ipv4"; - private static final String HOSTNAME_SUFFIX = "/latest/meta-data/hostname"; - private static final String ID_SUFFIX = "/latest/meta-data/instance-id"; - - private final URI baseUri; - - private String id; - private String region; - private String hostname; - private String zone; - private InetAddress publicIp; - private InetAddress privateIp; - - public AwsMetadata() { - try { - baseUri = new URI(METADATA_URI_BASE); - } catch (URISyntaxException e) { - Preconditions.checkState(false, "Unexpected URI Syntax Exception: {}", e); - throw new RuntimeException(e); - } - } - - public String getRegion() { - if (region == null) { - try { - String dynamicData = getMetadataAt(REGION_SUFFIX); - if (dynamicData != null) { - final JsonObject asJsonObject = new JsonParser().parse(dynamicData).getAsJsonObject(); - region = asJsonObject.get("region").getAsString(); - } - } catch (ClassCastException e) { - log.error("Unable to get region, expecting a JSON Object", e); - } - } - return region; - } - - public String getZoneName() { - if (zone == null) { - zone = getMetadataAt(ZONE_SUFFIX); - } - return zone; - } - - public String getId() { - if (id == null) { - id = getMetadataAt(ID_SUFFIX); - } - - return id; - } - - public String getHostname() { - if (hostname == null) { - hostname = getMetadataAt(HOSTNAME_SUFFIX); - } - return hostname; - } - - public InetAddress getPublicIpAddress() { - if (publicIp == null) { - String ip = getMetadataAt(PUBLIC_IPV4_SUFFIX); - if (ip != null) { - publicIp = InetAddresses.forString(ip); - } - } - return publicIp; - } - - public InetAddress getInternalIpAddress() { - if (privateIp == null) { - String ip = getMetadataAt(PRIVATE_IPV4_SUFFIX); - if (ip != null) { - privateIp = InetAddresses.forString(ip); - } - } - return privateIp; - } - - private String getMetadataAt(String suffix) { - try { - URI resolved = baseUri.resolve(suffix); - StringBuilder builder = new StringBuilder(); - String line = null; - try (BufferedReader reader = new BufferedReader(new InputStreamReader(resolved.toURL().openStream()))) { - while ((line = reader.readLine()) != null) { - builder.append(line); - } - return builder.toString(); - } - } catch (Exception e) { - // ignore for now to make sure local servers don't go verbose - } - return null; - } -} http://git-wip-us.apache.org/repos/asf/airavata-php-gateway/blob/488b772f/modules/commons/src/main/java/org/apache/airavata/common/utils/BrowserLauncher.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/BrowserLauncher.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/BrowserLauncher.java deleted file mode 100644 index 3ac6d4e..0000000 --- a/modules/commons/src/main/java/org/apache/airavata/common/utils/BrowserLauncher.java +++ /dev/null @@ -1,98 +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.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; - -import org.apache.airavata.common.exception.AiravataException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Opens URLs with the OS-specific browser. - */ -public class BrowserLauncher { - - private static final String ERROR_MESSAGE = "Error while attempting to launch web browser"; - - private static Logger logger = LoggerFactory.getLogger(BrowserLauncher.class); - - /** - * Opens a specified URL with the browser. - * - * @param url - * The specified URL. - * @throws AiravataException - */ - public static void openURL(URL url) throws AiravataException { - openURL(url.toString()); - } - - /** - * Opens a specified URL with the browser. - * - * @param url - * The specified URL. - * @throws AiravataException - */ - public static void openURL(String url) throws AiravataException { - logger.debug("Enter:" + url); - String osName = System.getProperty("os.name"); - try { - if (osName.startsWith("Mac OS")) { - Class macUtils = Class.forName("com.apple.mrj.MRJFileUtils"); - Method openURL = macUtils.getDeclaredMethod("openURL", new Class[] { String.class }); - openURL.invoke(null, new Object[] { url }); - } else if (osName.startsWith("Windows")) - Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url); - else { // assume Unix or Linux - String[] browsers = { "firefox", "mozilla", "netscape", "opera", "konqueror" }; - String browser = null; - for (int count = 0; count < browsers.length && browser == null; count++) - if (Runtime.getRuntime().exec(new String[] { "which", browsers[count] }).waitFor() == 0) - browser = browsers[count]; - if (browser == null) { - throw new AiravataException("Could not find web browser."); - } else { - Runtime.getRuntime().exec(new String[] { browser, url }); - } - } - } catch (ClassNotFoundException e) { - throw new AiravataException(ERROR_MESSAGE, e); - } catch (NoSuchMethodException e) { - throw new AiravataException(ERROR_MESSAGE, e); - } catch (IllegalAccessException e) { - throw new AiravataException(ERROR_MESSAGE, e); - } catch (InvocationTargetException e) { - throw new AiravataException(ERROR_MESSAGE, e); - } catch (IOException e) { - throw new AiravataException(ERROR_MESSAGE, e); - } catch (InterruptedException e) { - throw new AiravataException(ERROR_MESSAGE, e); - } catch (RuntimeException e) { - throw new AiravataException(ERROR_MESSAGE, e); - } - } -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/airavata-php-gateway/blob/488b772f/modules/commons/src/main/java/org/apache/airavata/common/utils/ClientSettings.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/ClientSettings.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/ClientSettings.java deleted file mode 100644 index 5373772..0000000 --- a/modules/commons/src/main/java/org/apache/airavata/common/utils/ClientSettings.java +++ /dev/null @@ -1,27 +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 ClientSettings extends ApplicationSettings { - -} http://git-wip-us.apache.org/repos/asf/airavata-php-gateway/blob/488b772f/modules/commons/src/main/java/org/apache/airavata/common/utils/Constants.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/Constants.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/Constants.java deleted file mode 100644 index b5fbd4b..0000000 --- a/modules/commons/src/main/java/org/apache/airavata/common/utils/Constants.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; - -/** - * Constants used in Airavata should go here. - */ -public final class Constants { - - public static final String USER_IN_SESSION = "userName"; - - - public static final String STAT = "stat"; - public static final String JOB = "job"; - //API security relates property names - public static final String IS_API_SECURED = "api.secured"; - public static final String SECURITY_MANAGER_CLASS = "security.manager.class"; - public static final String REMOTE_OAUTH_SERVER_URL = "remote.oauth.authorization.server"; - public static final String IS_TLS_ENABLED = "TLS.enabled"; - public static final String TLS_SERVER_PORT = "TLS.api.server.port"; - public static final String KEYSTORE_PATH = "keystore.path"; - public static final String KEYSTORE_PASSWORD = "keystore.password"; - public static final String TLS_CLIENT_TIMEOUT = "TLS.client.timeout"; - - public static final String API_METHOD_NAME = "api.method.name"; - - //constants in XACML authorization response. - public static final String NOT_APPLICABLE = "NotApplicable"; - public static final String INDETERMINATE = "Indeterminate"; - public static final String DENY = "Deny"; - public static final String PERMIT = "Permit"; - - public static final String AUTHORIZATION_POLICY_NAME = "authorization.policy"; - - public static final String AUTHZ_CACHE_MANAGER_CLASS = "authz.cache.manager.class"; - - public static final String AUTHZ_CACHE_ENABLED = "authz.cache.enabled"; - - public static final String IN_MEMORY_CACHE_SIZE = "in.memory.cache.size"; - - //Names of the attributes that could be passed in the AuthzToken's claims map. - public static final String USER_NAME = "userName"; - public static final String GATEWAY_ID = "gatewayID"; - public static final String EMAIL = "email"; - public static final String ROLE = "role"; - - public static final String TRUSTED_CERT_LOCATION = "trusted.cert.location"; - public static final String TRUSTED_CERTIFICATE_SYSTEM_PROPERTY = "X509_CERT_DIR"; - - public static final String NEWLINE = System.getProperty("line.separator"); -} http://git-wip-us.apache.org/repos/asf/airavata-php-gateway/blob/488b772f/modules/commons/src/main/java/org/apache/airavata/common/utils/DBUtil.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/DBUtil.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/DBUtil.java deleted file mode 100644 index bb2ff1d..0000000 --- a/modules/commons/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-php-gateway/blob/488b772f/modules/commons/src/main/java/org/apache/airavata/common/utils/DatabaseTestCases.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/DatabaseTestCases.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/DatabaseTestCases.java deleted file mode 100644 index 6ff528d..0000000 --- a/modules/commons/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-php-gateway/blob/488b772f/modules/commons/src/main/java/org/apache/airavata/common/utils/DefaultKeyStorePasswordCallback.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/DefaultKeyStorePasswordCallback.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/DefaultKeyStorePasswordCallback.java deleted file mode 100644 index fc7792b..0000000 --- a/modules/commons/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 ([email protected]) - * 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-php-gateway/blob/488b772f/modules/commons/src/main/java/org/apache/airavata/common/utils/DerbyUtil.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/DerbyUtil.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/DerbyUtil.java deleted file mode 100644 index 4fb35b9..0000000 --- a/modules/commons/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-php-gateway/blob/488b772f/modules/commons/src/main/java/org/apache/airavata/common/utils/ExecutionMode.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/ExecutionMode.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/ExecutionMode.java deleted file mode 100644 index cf17ef0..0000000 --- a/modules/commons/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-php-gateway/blob/488b772f/modules/commons/src/main/java/org/apache/airavata/common/utils/IOUtil.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/IOUtil.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/IOUtil.java deleted file mode 100644 index 9d1d7dd..0000000 --- a/modules/commons/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-php-gateway/blob/488b772f/modules/commons/src/main/java/org/apache/airavata/common/utils/IServer.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/IServer.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/IServer.java deleted file mode 100644 index 867eb45..0000000 --- a/modules/commons/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-php-gateway/blob/488b772f/modules/commons/src/main/java/org/apache/airavata/common/utils/JSONUtil.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/JSONUtil.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/JSONUtil.java deleted file mode 100644 index 222e5a2..0000000 --- a/modules/commons/src/main/java/org/apache/airavata/common/utils/JSONUtil.java +++ /dev/null @@ -1,158 +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.FileReader; -import java.io.IOException; -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-php-gateway/blob/488b772f/modules/commons/src/main/java/org/apache/airavata/common/utils/KeyStorePasswordCallback.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/KeyStorePasswordCallback.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/KeyStorePasswordCallback.java deleted file mode 100644 index bafaff3..0000000 --- a/modules/commons/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 ([email protected]) - * 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-php-gateway/blob/488b772f/modules/commons/src/main/java/org/apache/airavata/common/utils/LocalEventPublisher.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/LocalEventPublisher.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/LocalEventPublisher.java deleted file mode 100644 index 2b5a1d8..0000000 --- a/modules/commons/src/main/java/org/apache/airavata/common/utils/LocalEventPublisher.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 LocalEventPublisher { - private final static Logger logger = LoggerFactory.getLogger(LocalEventPublisher.class); - private EventBus eventBus; - - public LocalEventPublisher(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-php-gateway/blob/488b772f/modules/commons/src/main/java/org/apache/airavata/common/utils/NameValidator.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/NameValidator.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/NameValidator.java deleted file mode 100644 index 98530cf..0000000 --- a/modules/commons/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-php-gateway/blob/488b772f/modules/commons/src/main/java/org/apache/airavata/common/utils/Pair.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/Pair.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/Pair.java deleted file mode 100644 index ee24360..0000000 --- a/modules/commons/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
