http://git-wip-us.apache.org/repos/asf/airavata/blob/8d16d0ec/modules/commons/src/main/java/org/apache/airavata/common/utils/SecurityUtil.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/SecurityUtil.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/SecurityUtil.java new file mode 100644 index 0000000..845a040 --- /dev/null +++ b/modules/commons/src/main/java/org/apache/airavata/common/utils/SecurityUtil.java @@ -0,0 +1,180 @@ +/* + * + * 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 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/src/main/java/org/apache/airavata/common/utils/ServerSettings.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/ServerSettings.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/ServerSettings.java new file mode 100644 index 0000000..8370e40 --- /dev/null +++ b/modules/commons/src/main/java/org/apache/airavata/common/utils/ServerSettings.java @@ -0,0 +1,270 @@ +/* + * + * 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/src/main/java/org/apache/airavata/common/utils/ServiceUtils.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/ServiceUtils.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/ServiceUtils.java new file mode 100644 index 0000000..0c54053 --- /dev/null +++ b/modules/commons/src/main/java/org/apache/airavata/common/utils/ServiceUtils.java @@ -0,0 +1,93 @@ +///* +// * +// * 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/src/main/java/org/apache/airavata/common/utils/StringUtil.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/StringUtil.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/StringUtil.java new file mode 100644 index 0000000..3ce5cda --- /dev/null +++ b/modules/commons/src/main/java/org/apache/airavata/common/utils/StringUtil.java @@ -0,0 +1,480 @@ +/* + * + * 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 http://git-wip-us.apache.org/repos/asf/airavata/blob/8d16d0ec/modules/commons/src/main/java/org/apache/airavata/common/utils/SwingUtil.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/SwingUtil.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/SwingUtil.java new file mode 100644 index 0000000..dc9a7e2 --- /dev/null +++ b/modules/commons/src/main/java/org/apache/airavata/common/utils/SwingUtil.java @@ -0,0 +1,358 @@ +/* + * + * 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.awt.Color; +import java.awt.Component; +import java.awt.Container; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Image; +import java.awt.Insets; +import java.awt.Toolkit; +import java.awt.event.FocusEvent; +import java.awt.event.FocusListener; +import java.net.URL; +import java.util.List; + +import javax.swing.ImageIcon; +import javax.swing.JTextField; +import javax.swing.Spring; +import javax.swing.SpringLayout; + +public class SwingUtil { + + /** + * Minimum size, zero. + */ + public static final Dimension MINIMUM_SIZE = new Dimension(0, 0); + + /** + * The default distance between components. + */ + public static final int PAD = 6; + + /** + * Default cursor. + */ + public static final Cursor DEFAULT_CURSOR = new Cursor(Cursor.DEFAULT_CURSOR); + + /** + * Hand cursor. + */ + public static final Cursor HAND_CURSOR = new Cursor(Cursor.HAND_CURSOR); + + /** + * Cross hair cursor. + */ + public static final Cursor CROSSHAIR_CURSOR = new Cursor(Cursor.CROSSHAIR_CURSOR); + + /** + * Move cursor. + */ + public static final Cursor MOVE_CURSOR = new Cursor(Cursor.MOVE_CURSOR); + + /** + * Wait cursor. + */ + public static final Cursor WAIT_CURSOR = new Cursor(Cursor.WAIT_CURSOR); + + /** + * Creates an icon from an image contained in the "images" directory. + * + * @param filename + * @return the ImageIcon created + */ + public static ImageIcon createImageIcon(String filename) { + ImageIcon icon = null; + URL imgURL = getImageURL(filename); + if (imgURL != null) { + icon = new ImageIcon(imgURL); + } + return icon; + } + + /** + * Creates an image from an image contained in the "images" directory. + * + * @param filename + * @return the Image created + */ + public static Image createImage(String filename) { + Image icon = null; + URL imgURL = getImageURL(filename); + if (imgURL != null) { + icon = Toolkit.getDefaultToolkit().getImage(imgURL); + } + return icon; + } + + public static URL getImageURL(String filename) { + String path = "/images/" + filename; + URL imgURL = SwingUtil.class.getResource(path); + return imgURL; + } + + /** + * Return the Frame of a specified component if any. + * + * @param component + * the specified component + * + * @return the Frame of a specified component if any; otherwise null + */ + public static Frame getFrame(Component component) { + Frame frame; + Component parent; + while ((parent = component.getParent()) != null) { + component = parent; + } + if (component instanceof Frame) { + frame = (Frame) component; + } else { + frame = null; + } + return frame; + } + + /** + * Wight none of rows or eolumns. Used by layoutToGrid(). + */ + public final static int WEIGHT_NONE = -1; + + /** + * Weight all rows or columns equally. Used by layoutToGrid(). + */ + public final static int WEIGHT_EQUALLY = -2; + + /** + * Layouts the child components of a specified parent component using GridBagLayout. + * + * @param parent + * The specified parent component + * @param numRow + * The number of rows + * @param numColumn + * The number of columns + * @param weightedRow + * The row to weight + * @param weightedColumn + * The column to weight + */ + public static void layoutToGrid(Container parent, int numRow, int numColumn, int weightedRow, int weightedColumn) { + GridBagLayout layout = new GridBagLayout(); + parent.setLayout(layout); + GridBagConstraints constraints = new GridBagConstraints(); + + constraints.fill = GridBagConstraints.BOTH; + constraints.insets = new Insets(SwingUtil.PAD, SwingUtil.PAD, SwingUtil.PAD, SwingUtil.PAD); + + for (int row = 0; row < numRow; row++) { + constraints.gridy = row; + if (weightedRow == WEIGHT_EQUALLY) { + constraints.weighty = 1; + } else if (row == weightedRow) { + constraints.weighty = 1; + } else { + constraints.weighty = 0; + } + for (int column = 0; column < numColumn; column++) { + constraints.gridx = column; + if (weightedColumn == WEIGHT_EQUALLY) { + constraints.weightx = 1; + } else if (column == weightedColumn) { + constraints.weightx = 1; + } else { + constraints.weightx = 0; + } + Component component = parent.getComponent(row * numColumn + column); + layout.setConstraints(component, constraints); + } + } + } + + /** + * @param parent + * @param rowWeights + * @param columnWeights + */ + public static void layoutToGrid(Container parent, double[] rowWeights, double[] columnWeights) { + GridBagLayout layout = new GridBagLayout(); + parent.setLayout(layout); + GridBagConstraints constraints = new GridBagConstraints(); + + constraints.fill = GridBagConstraints.BOTH; + constraints.insets = new Insets(SwingUtil.PAD, SwingUtil.PAD, SwingUtil.PAD, SwingUtil.PAD); + + for (int row = 0; row < rowWeights.length; row++) { + constraints.gridy = row; + constraints.weighty = rowWeights[row]; + for (int column = 0; column < columnWeights.length; column++) { + constraints.gridx = column; + constraints.weightx = columnWeights[column]; + Component component = parent.getComponent(row * columnWeights.length + column); + layout.setConstraints(component, constraints); + } + } + } + + /** + * @param parent + * @param rowWeights + * @param columnWeights + */ + @SuppressWarnings("boxing") + public static void layoutToGrid(Container parent, List<Double> rowWeights, List<Double> columnWeights) { + GridBagLayout layout = new GridBagLayout(); + parent.setLayout(layout); + GridBagConstraints constraints = new GridBagConstraints(); + + constraints.fill = GridBagConstraints.BOTH; + constraints.insets = new Insets(SwingUtil.PAD, SwingUtil.PAD, SwingUtil.PAD, SwingUtil.PAD); + + for (int row = 0; row < rowWeights.size(); row++) { + constraints.gridy = row; + constraints.weighty = rowWeights.get(row); + for (int column = 0; column < columnWeights.size(); column++) { + constraints.gridx = column; + constraints.weightx = columnWeights.get(column); + Component component = parent.getComponent(row * columnWeights.size() + column); + layout.setConstraints(component, constraints); + } + } + } + + /** + * Aligns the first <code>rows</code> * <code>cols</code> components of <code>parent</code> in a grid. Each + * component in a column is as wide as the maximum preferred width of the components in that column; height is + * similarly determined for each row. The parent is made just big enough to fit them all. + * + * @param parent + * + * @param rows + * number of rows + * @param cols + * number of columns + */ + public static void makeSpringCompactGrid(Container parent, int rows, int cols) { + makeSpringCompactGrid(parent, rows, cols, PAD, PAD, PAD, PAD); + } + + /** + * Aligns the first <code>rows</code> * <code>cols</code> components of <code>parent</code> in a grid. Each + * component in a column is as wide as the maximum preferred width of the components in that column; height is + * similarly determined for each row. The parent is made just big enough to fit them all. + * + * @param parent + * + * @param rows + * number of rows + * @param cols + * number of columns + * @param initialX + * x location to start the grid at + * @param initialY + * y location to start the grid at + * @param xPad + * x padding between cells + * @param yPad + * y padding between cells + */ + private static void makeSpringCompactGrid(Container parent, int rows, int cols, int initialX, int initialY, + int xPad, int yPad) { + + SpringLayout layout = new SpringLayout(); + parent.setLayout(layout); + + // Align all cells in each column and make them the same width. + Spring x = Spring.constant(initialX); + for (int c = 0; c < cols; c++) { + Spring width = Spring.constant(0); + for (int r = 0; r < rows; r++) { + width = Spring.max(width, getConstraintsForCell(r, c, parent, cols).getWidth()); + } + for (int r = 0; r < rows; r++) { + SpringLayout.Constraints constraints = getConstraintsForCell(r, c, parent, cols); + constraints.setX(x); + constraints.setWidth(width); + } + x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad))); + } + + // Align all cells in each row and make them the same height. + Spring y = Spring.constant(initialY); + for (int r = 0; r < rows; r++) { + Spring height = Spring.constant(0); + for (int c = 0; c < cols; c++) { + height = Spring.max(height, getConstraintsForCell(r, c, parent, cols).getHeight()); + } + for (int c = 0; c < cols; c++) { + SpringLayout.Constraints constraints = getConstraintsForCell(r, c, parent, cols); + constraints.setY(y); + constraints.setHeight(height); + } + y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad))); + } + + // Set the parent's size. + SpringLayout.Constraints pCons = layout.getConstraints(parent); + pCons.setConstraint(SpringLayout.SOUTH, y); + pCons.setConstraint(SpringLayout.EAST, x); + } + + /* Used by makeCompactGrid. */ + private static SpringLayout.Constraints getConstraintsForCell(int row, int col, Container parent, int cols) { + SpringLayout layout = (SpringLayout) parent.getLayout(); + Component c = parent.getComponent(row * cols + col); + return layout.getConstraints(c); + } + + public static void addPlaceHolder(final JTextField field,final String placeHolderText){ + field.addFocusListener(new FocusListener(){ + private Color fontColor=field.getForeground(); +// private String previousText=field.getText(); + + public void focusGained(FocusEvent arg0) { + if (field.getText().equals(placeHolderText)){ + field.setText(""); + } + field.setForeground(fontColor); + } + + public void focusLost(FocusEvent arg0) { + if (field.getText().trim().equals("")){ + fontColor=field.getForeground(); + field.setForeground(Color.GRAY); + field.setText(placeHolderText); + } + } + }); + if (field.getText().trim().equals("")){ + field.setText(placeHolderText); + field.setForeground(Color.GRAY); + } + } + +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/airavata/blob/8d16d0ec/modules/commons/src/main/java/org/apache/airavata/common/utils/ThriftUtils.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/ThriftUtils.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/ThriftUtils.java new file mode 100644 index 0000000..ee86f74 --- /dev/null +++ b/modules/commons/src/main/java/org/apache/airavata/common/utils/ThriftUtils.java @@ -0,0 +1,37 @@ +/* + * + * 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.thrift.TBase; +import org.apache.thrift.TDeserializer; +import org.apache.thrift.TException; +import org.apache.thrift.TSerializer; + +public class ThriftUtils { + public static byte[] serializeThriftObject(TBase object) throws TException { + return new TSerializer().serialize(object); + } + + public static void createThriftFromBytes(byte []bytes, TBase object) throws TException { + new TDeserializer().deserialize(object, bytes); + } +} http://git-wip-us.apache.org/repos/asf/airavata/blob/8d16d0ec/modules/commons/src/main/java/org/apache/airavata/common/utils/Version.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/Version.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/Version.java new file mode 100644 index 0000000..fe34bb1 --- /dev/null +++ b/modules/commons/src/main/java/org/apache/airavata/common/utils/Version.java @@ -0,0 +1,120 @@ +/* + * + * 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 javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement +public class Version { + public String PROJECT_NAME; + private Integer majorVersion=0; + private Integer minorVersion=0; + private Integer maintenanceVersion; + private String versionData; + private BuildType buildType; + + public static enum BuildType{ + ALPHA, + BETA, + RC + } + + public Version() { + } + + public Version(String PROJECT_NAME,Integer majorVersion,Integer minorVersion,Integer maintenanceVersion,String versionData,BuildType buildType) { + this.PROJECT_NAME=PROJECT_NAME; + this.majorVersion=majorVersion; + this.minorVersion=minorVersion; + this.maintenanceVersion=maintenanceVersion; + this.versionData=versionData; + this.buildType=buildType; + } + + public Integer getMajorVersion() { + return majorVersion; + } + + public Integer getMinorVersion() { + return minorVersion; + } + + public Integer getMaintenanceVersion() { + return maintenanceVersion; + } + + public String getVersionData() { + return versionData; + } + + public BuildType getBuildType() { + return buildType; + } + + public String getVersion(){ + String version = getBaseVersion(); + version = attachVersionData(version); + return version; + } + + private String attachVersionData(String version) { + if (getVersionData()!=null){ + version+="-"+getVersionData(); + } + return version; + } + + public String getBaseVersion() { + String version=getMajorVersion().toString()+"."+getMinorVersion(); + return version; + } + + public String getFullVersion(){ + String version = getBaseVersion(); + version = attachMaintainanceVersion(version); + version = attachVersionData(version); + version = attachBuildType(version); + return version; + } + + private String attachMaintainanceVersion(String version) { + if (getMaintenanceVersion()!=null){ + version+="."+getMaintenanceVersion(); + } + return version; + } + + private String attachBuildType(String version) { + if (getBuildType()!=null){ + version+="-"+getBuildType().name(); + } + return version; + } + + @Override + public String toString() { + return getVersion(); + } +} http://git-wip-us.apache.org/repos/asf/airavata/blob/8d16d0ec/modules/commons/src/main/java/org/apache/airavata/common/utils/WSConstants.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/WSConstants.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/WSConstants.java new file mode 100644 index 0000000..9737ac4 --- /dev/null +++ b/modules/commons/src/main/java/org/apache/airavata/common/utils/WSConstants.java @@ -0,0 +1,187 @@ +/* + * + * 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 javax.xml.namespace.QName; + +import org.xmlpull.infoset.XmlNamespace; + +public interface WSConstants { + + /** + * xmlns + */ + public final static String XMLNS = "xmlns"; + + /** + * XML Schema prefix, xsd + */ + public static final String XSD_NS_PREFIX = "xsd"; + + /** + * XML Schema URI. + */ + public static final String XSD_NS_URI = "http://www.w3.org/2001/XMLSchema"; + +// /** +// * XML Schema Namespace +// */ +// public static final XmlNamespace XSD_NS = XmlConstants.BUILDER.newNamespace(XSD_NS_PREFIX, XSD_NS_URI); + + /** + * The any type. + */ + public static final QName XSD_ANY_TYPE = new QName(XSD_NS_URI, "any", XSD_NS_PREFIX); + + /** + * xsd:anyURI + */ + public static final QName XSD_ANY_URI = new QName(XSD_NS_URI, "anyURI", XSD_NS_PREFIX); + + /** + * tns + */ + public static final String TARGET_NS_PREFIX = "tns"; + + /** + * typens + */ + public static final String TYPE_NS_PREFIX = "typens"; + + /** + * schema + */ + public static final String SCHEMA_TAG = "schema"; + + /** + * Element name for annotation, annotation + */ + public static final String ANNOTATION_TAG = "annotation"; + + /** + * Element name for documentation, documentation + */ + public static final String DOCUMENTATION_TAG = "documentation"; + + /** + * appinfo + */ + public static final String APPINFO_TAG = "appinfo"; + + /** + * element + */ + public static final String ELEMENT_TAG = "element"; + + /** + * sequence + */ + public static final String SEQUENCE_TAG = "sequence"; + + /** + * complexType + */ + public static final String COMPLEX_TYPE_TAG = "complexType"; + + /** + * simpleType + */ + public static final String SIMPLE_TYPE_TAG = "simpleType"; + + /** + * name + */ + public static final String NAME_ATTRIBUTE = "name"; + + /** + * type + */ + public static final String TYPE_ATTRIBUTE = "type"; + + /** + * targetNamespace + */ + public static final String TARGET_NAMESPACE_ATTRIBUTE = "targetNamespace"; + + /** + * elementFormDefault + */ + public final static String ELEMENT_FORM_DEFAULT_ATTRIBUTE = "elementFormDefault"; + + /** + * unqualified + */ + public final static String UNQUALIFIED_VALUE = "unqualified"; + + /** + * default + */ + public static final String DEFAULT_ATTRIBUTE = "default"; + + /** + * UsingAddressing + */ + public static final String USING_ADDRESSING_TAG = "UsingAddressing"; + + /** + * <appinfo xmlns="http://www.w3.org/2001/XMLSchema"> + * + * </appinfo> + */ +// public static final String EMPTY_APPINFO = "<appinfo xmlns=\"http://www.w3.org/2001/XMLSchema\">\n\n</appinfo>"; + public static final String EMPTY_APPINFO = "{'appinfo': '' }"; + + /** + * minOccurs + */ + public static final String MIN_OCCURS_ATTRIBUTE = "minOccurs"; + + /** + * maxOccurs + */ + public static final String MAX_OCCURS_ATTRIBUTE = "maxOccurs"; + + /** + * unbounded + */ + public static final String UNBOUNDED_VALUE = "unbounded"; + + /** + * import + */ + public static final String IMPORT_TAG = "import"; + + /** + * schemaLocation + */ + public static final String SCHEMA_LOCATION_ATTRIBUTE = "schemaLocation"; + + public static final String LEAD_NS_URI = "http://www.extreme.indiana.edu/lead"; + + /** + * The any type. + */ + public static final QName LEAD_ANY_TYPE = new QName(LEAD_NS_URI, "any", + XSD_NS_PREFIX); + + +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/airavata/blob/8d16d0ec/modules/commons/src/main/java/org/apache/airavata/common/utils/WSDLUtil.java ---------------------------------------------------------------------- diff --git a/modules/commons/src/main/java/org/apache/airavata/common/utils/WSDLUtil.java b/modules/commons/src/main/java/org/apache/airavata/common/utils/WSDLUtil.java new file mode 100644 index 0000000..81c8d93 --- /dev/null +++ b/modules/commons/src/main/java/org/apache/airavata/common/utils/WSDLUtil.java @@ -0,0 +1,546 @@ +/* + * + * 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.URI; +import java.util.LinkedList; +import java.util.List; + +import org.apache.airavata.common.exception.UtilsException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.xmlpull.infoset.XmlAttribute; +import org.xmlpull.infoset.XmlBuilderException; +import org.xmlpull.infoset.XmlElement; +import org.xmlpull.infoset.XmlNamespace; + +//import xsul.XmlConstants; +//import xsul5.wsdl.WsdlBinding; +//import xsul5.wsdl.WsdlDefinitions; +//import xsul5.wsdl.WsdlPortType; +//import xsul5.wsdl.WsdlPortTypeOperation; +//import xsul5.wsdl.WsdlUtil; + +public class WSDLUtil { + + private static final Logger logger = LoggerFactory.getLogger(WSDLUtil.class); + +// /** +// * @param wsdlString +// * @return The WSDL +// * @throws UtilsException +// */ +// public static WsdlDefinitions stringToWSDL(String wsdlString) throws UtilsException { +// try { +// XmlElement wsdlElement = XMLUtil.stringToXmlElement(wsdlString); +// WsdlDefinitions definitions = new WsdlDefinitions(wsdlElement); +// return definitions; +// } catch (RuntimeException e) { +// throw new UtilsException(e); +// } +// } +// +// /** +// * @param definitions3 +// * @return The WsdlDefinitions (XSUL5) +// */ +// public static xsul5.wsdl.WsdlDefinitions wsdlDefinitions3ToWsdlDefintions5(xsul.wsdl.WsdlDefinitions definitions3) { +// +// return new xsul5.wsdl.WsdlDefinitions(XMLUtil.xmlElement3ToXmlElement5(definitions3)); +// } +// +// /** +// * @param definitions5 +// * @return The WsdlDefinitions (XSUL3) +// */ +// public static xsul.wsdl.WsdlDefinitions wsdlDefinitions5ToWsdlDefintions3(xsul5.wsdl.WsdlDefinitions definitions5) { +// +// return new xsul.wsdl.WsdlDefinitions(XMLUtil.xmlElement5ToXmlElement3(definitions5.xml())); +// } +// +// /** +// * @param definitions +// * @return The name of the WSDL. +// */ +// public static String getWSDLName(WsdlDefinitions definitions) { +// String wsdlName = definitions.xml().attributeValue(WSConstants.NAME_ATTRIBUTE); +// if (wsdlName == null) { +// // name is optional. +// wsdlName = ""; +// } +// return wsdlName; +// } +// +// /** +// * @param definitions +// * @return The QName of the WSDL. +// */ +// public static QName getWSDLQName(WsdlDefinitions definitions) { +// String targetNamespace = definitions.getTargetNamespace(); +// String wsdlName = getWSDLName(definitions); +// return new QName(targetNamespace, wsdlName); +// } +// +// /** +// * @param definitions +// * @return The first portType +// * @throws UtilsException +// */ +// public static WsdlPortType getFirstPortType(WsdlDefinitions definitions) throws UtilsException { +// for (WsdlPortType portType : definitions.portTypes()) { +// return portType; +// } +// throw new UtilsException("No portType is defined in WSDL"); +// } +// +// public static WsdlPortTypeOperation getFirstOperation(WsdlDefinitions definitions) throws UtilsException { +// for (WsdlPortTypeOperation operation : getFirstPortType(definitions).operations()) { +// return operation; +// } +// throw new UtilsException("No portType is defined in WSDL"); +// } +// +// /** +// * @param definitions +// * @return The QName of the first portType. +// * @throws UtilsException +// */ +// public static QName getFirstPortTypeQName(WsdlDefinitions definitions) throws UtilsException { +// String targetNamespace = definitions.getTargetNamespace(); +// for (WsdlPortType portType : definitions.portTypes()) { +// String portTypeName = portType.getName(); +// QName portTypeQName = new QName(targetNamespace, portTypeName); +// return portTypeQName; +// } +// throw new UtilsException("No portType is defined."); +// } +// +// /** +// * @param definitions +// * @param portTypeQName +// * @return The name of the first operation in a given portType. +// * @throws UtilsException +// */ +// public static String getFirstOperationName(WsdlDefinitions definitions, QName portTypeQName) throws UtilsException { +// WsdlPortType portType = definitions.getPortType(portTypeQName.getLocalPart()); +// for (WsdlPortTypeOperation operation : portType.operations()) { +// String operationName = operation.getOperationName(); +// +// // XXX Temporary solution to skip some GFac specific operations. +// if ("Shutdown".equals(operationName)) { +// continue; +// } else if ("Kill".equals(operationName)) { +// continue; +// } else if ("Ping".equals(operationName)) { +// continue; +// } +// +// return operationName; +// } +// throw new UtilsException("No operation is defined"); +// } +// +// /** +// * @param definitions +// * @return The cloned WsdlDefinitions +// */ +// public static WsdlDefinitions deepClone(WsdlDefinitions definitions) throws UtilsException { +// return new WsdlDefinitions(XMLUtil.deepClone(definitions.xml())); +// } +// +// /** +// * @param definitions +// * @param paramType +// * @return The schema that includes the type definition +// */ +// public static XmlElement getSchema(WsdlDefinitions definitions, QName paramType) throws UtilsException { +// XmlElement types = definitions.getTypes(); +// +// Iterable<XmlElement> schemas = types.elements(WSConstants.XSD_NS, WSConstants.SCHEMA_TAG); +// for (XmlElement schema : schemas) { +// if (isTypeDefinedInSchema(paramType, schema)) { +// return schema; +// } +// } +// +// // ok we didnt find the type in the schema in first level +// // now we try try to see if it exist in schema imports. +// // we loop in two step because its better to avoid the network +// // connection if possible +// for (XmlElement schema : schemas) { +// Iterable<XmlElement> imports = schema.elements(WSConstants.XSD_NS, WSConstants.IMPORT_TAG); +// for (XmlElement importEle : imports) { +// String schemaLocation = importEle.attributeValue(WSConstants.SCHEMA_LOCATION_ATTRIBUTE); +// if (null != schemaLocation && !"".equals(schemaLocation)) { +// try { +// // connect using a url connection +// URL url = new URL(schemaLocation); +// URLConnection connection = url.openConnection(); +// connection.connect(); +// XmlElement importedSchema = xsul5.XmlConstants.BUILDER.parseFragmentFromInputStream(connection +// .getInputStream()); +// if (isTypeDefinedInSchema(paramType, importedSchema)) { +// // still return the parent schema +// return schema; +// } +// } catch (MalformedURLException e) { +// throw new UtilsException(e); +// } catch (XmlBuilderException e) { +// throw new UtilsException(e); +// } catch (IOException e) { +// throw new UtilsException(e); +// } +// } +// } +// } +// +// return null; +// } +// +// private static boolean isTypeDefinedInSchema(QName paramType, XmlElement schema) { +// String schemaTargetNamespace = schema.attributeValue(WSConstants.TARGET_NAMESPACE_ATTRIBUTE); +// if (schemaTargetNamespace.equals(paramType.getNamespaceURI())) { +// for (XmlElement complexType : schema.elements(WSConstants.XSD_NS, WSConstants.COMPLEX_TYPE_TAG)) { +// String complexTypeName = complexType.attributeValue(WSConstants.NAME_ATTRIBUTE); +// if (complexTypeName.equals(paramType.getLocalPart())) { +// return true; +// } +// } +// for (XmlElement simpleType : schema.elements(WSConstants.XSD_NS, WSConstants.SIMPLE_TYPE_TAG)) { +// String simpleTypeName = simpleType.attributeValue(WSConstants.NAME_ATTRIBUTE); +// if (simpleTypeName.equals(paramType.getLocalPart())) { +// return true; +// } +// } +// } +// return false; +// } +// +// /** +// * @param definitions +// * @param paramType +// * @return The type definition +// */ +// public static XmlElement getTypeDefinition(WsdlDefinitions definitions, QName paramType) throws UtilsException { +// XmlElement types = definitions.getTypes(); +// XmlElement returnType = null; +// types.element(null, WSConstants.SCHEMA_TAG); +// Iterable<XmlElement> schemas = types.elements(null, WSConstants.SCHEMA_TAG); +// for (XmlElement schema : schemas) { +// +// returnType = findTypeInSchema(paramType, schema); +// if (returnType != null) { +// return returnType; +// } +// } +// // ok we didnt find the type in the schemas +// // try to find it in the schema imports. +// +// // if not found it will return null so we would return null +// return findTypeDefinitionInImports(definitions, paramType); +// +// } +// +// /** +// * +// * @param definitions +// * @param paramType +// * @return +// */ +// +// public static XmlElement getImportContainingTypeDefinition(WsdlDefinitions definitions, QName paramType) +// throws UtilsException { +// XmlElement types = definitions.getTypes(); +// XmlElement returnType = null; +// Iterable<XmlElement> schemas = types.elements(WSConstants.XSD_NS, WSConstants.SCHEMA_TAG); +// for (XmlElement schema : schemas) { +// Iterable<XmlElement> imports = schema.elements(WSConstants.XSD_NS, WSConstants.IMPORT_TAG); +// for (XmlElement importEle : imports) { +// String schemaLocation = importEle.attributeValue(WSConstants.SCHEMA_LOCATION_ATTRIBUTE); +// if (null != schemaLocation && !"".equals(schemaLocation)) { +// try { +// // connect using a url connection +// URL url = new URL(schemaLocation); +// URLConnection connection = url.openConnection(); +// connection.connect(); +// XmlElement importedSchema = xsul5.XmlConstants.BUILDER.parseFragmentFromInputStream(connection +// .getInputStream()); +// returnType = findTypeInSchema(paramType, importedSchema); +// if (returnType != null) { +// return importEle; +// } +// +// } catch (MalformedURLException e) { +// throw new UtilsException(e); +// } catch (XmlBuilderException e) { +// throw new UtilsException(e); +// } catch (IOException e) { +// throw new UtilsException(e); +// } +// } +// } +// } +// return null; +// } +// +// /** +// * +// * @param definitions +// * @param paramType +// * @return +// */ +// +// public static XmlElement findTypeDefinitionInImports(WsdlDefinitions definitions, QName paramType) +// throws UtilsException { +// XmlElement types = definitions.getTypes(); +// XmlElement returnType = null; +// Iterable<XmlElement> schemas = types.elements(null, WSConstants.SCHEMA_TAG); +// for (XmlElement schema : schemas) { +// Iterable<XmlElement> imports = schema.elements(WSConstants.XSD_NS, WSConstants.IMPORT_TAG); +// for (XmlElement importEle : imports) { +// String schemaLocation = importEle.attributeValue(WSConstants.SCHEMA_LOCATION_ATTRIBUTE); +// if (null != schemaLocation && !"".equals(schemaLocation)) { +// try { +// // connect using a url connection +// URL url = new URL(schemaLocation); +// URLConnection connection = url.openConnection(); +// connection.connect(); +// XmlElement importedSchema = xsul5.XmlConstants.BUILDER.parseFragmentFromInputStream(connection +// .getInputStream()); +// returnType = findTypeInSchema(paramType, importedSchema); +// if (returnType != null) { +// return returnType; +// } +// +// } catch (MalformedURLException e) { +// throw new UtilsException(e); +// } catch (XmlBuilderException e) { +// throw new UtilsException(e); +// } catch (IOException e) { +// throw new UtilsException(e); +// } +// } +// } +// } +// return null; +// +// } +// +// private static XmlElement findTypeInSchema(QName paramType, XmlElement schema) { +// String schemaTargetNamespace = schema.attributeValue(WSConstants.TARGET_NAMESPACE_ATTRIBUTE); +// if (null != schemaTargetNamespace && schemaTargetNamespace.equals(paramType.getNamespaceURI())) { +// for (XmlElement complexType : schema.elements(WSConstants.XSD_NS, WSConstants.COMPLEX_TYPE_TAG)) { +// String complexTypeName = complexType.attributeValue(WSConstants.NAME_ATTRIBUTE); +// if (complexTypeName.equals(paramType.getLocalPart())) { +// return complexType; +// +// } +// } +// for (XmlElement simpleType : schema.elements(WSConstants.XSD_NS, WSConstants.SIMPLE_TYPE_TAG)) { +// String simpleTypeName = simpleType.attributeValue(WSConstants.NAME_ATTRIBUTE); +// if (simpleTypeName.equals(paramType.getLocalPart())) { +// return simpleType; +// } +// } +// } +// return null; +// } +// +// /** +// * @param wsdl +// * @return true if the WSDL is AWSDL; false otherwise. +// */ +// public static boolean isAWSDL(WsdlDefinitions wsdl) { +// if (wsdl.services().iterator().hasNext()) { +// return false; +// } +// return true; +// } +// +// /** +// * @param definitions +// * @return true if the service supports asynchronous invocation; false otherwise; +// */ +// public static boolean isAsynchronousSupported(WsdlDefinitions definitions) { +// for (WsdlBinding binding : definitions.bindings()) { +// XmlElement element = binding.xml().element(WSConstants.USING_ADDRESSING_TAG); +// if (element != null) { +// return true; +// } +// } +// return false; +// } +// +// /** +// * Converts a specified AWSDL to CWSDL using DSC URI. +// * +// * @param definitions +// * The specified AWSDL. This will be modified. +// * @param url +// * The URL of the service +// * @return The CWSDL converted. +// */ +// public static WsdlDefinitions convertToCWSDL(WsdlDefinitions definitions, URI url) { +// for (WsdlPortType portType : definitions.portTypes()) { +// WsdlUtil.createCWSDL(definitions, portType, url); +// } +// return definitions; +// } + + /** + * @param uri + * @return The URI with "?wsdl" at the end. + */ + public static String appendWSDLQuary(String uri) { + URI wsdlURI = appendWSDLQuary(URI.create(uri)); + return wsdlURI.toString(); + } + + public static List<XmlNamespace> getNamespaces(XmlElement element) { + LinkedList<XmlNamespace> namespaces = new LinkedList<XmlNamespace>(); + namespaces.add(element.getNamespace()); + Iterable<XmlAttribute> attributes = element.attributes(); + for (XmlAttribute xmlAttribute : attributes) { + if (xmlAttribute.getNamespace() != null && !namespaces.contains(xmlAttribute.getNamespace())) { + namespaces.add(xmlAttribute.getNamespace()); + } + int index = xmlAttribute.getValue().indexOf(':'); + if (-1 != index) { + String prefix = xmlAttribute.getValue().substring(0, index); + if (element.lookupNamespaceByPrefix(prefix) != null) { + namespaces.add(element.lookupNamespaceByPrefix(prefix)); + } + } + } + Iterable children = element.children(); + for (Object object : children) { + if (object instanceof XmlElement) { + List<XmlNamespace> newNSs = getNamespaces((XmlElement) object); + for (XmlNamespace xmlNamespace : newNSs) { + if (!namespaces.contains(xmlNamespace)) { + namespaces.add(xmlNamespace); + } + } + } + } + return namespaces; + } + + /** + * @param uri + * @return The URI with "?wsdl" at the end. + */ + public static URI appendWSDLQuary(URI uri) { + if (uri.toString().endsWith("?wsdl")) { + logger.warn("URL already has ?wsdl at the end: " + uri.toString()); + // Don't throw exception to be more error tolerant. + return uri; + } + String path = uri.getPath(); + if (path == null || path.length() == 0) { + uri = uri.resolve("/"); + } + uri = URI.create(uri.toString() + "?wsdl"); + return uri; + } + +// /** +// * @param valueElement +// * @return +// */ +// public static org.xmlpull.v1.builder.XmlElement xmlElement5ToXmlElementv1(XmlElement valueElement) { +// +// return XmlConstants.BUILDER.parseFragmentFromReader(new StringReader(xsul5.XmlConstants.BUILDER +// .serializeToStringPretty(valueElement))); +// } + + /** + * + * @param vals + * @param <T> + * @return + */ + public static <T extends Object> T getfirst(Iterable<T> vals) { + for (T class1 : vals) { + return class1; + } + throw new RuntimeException("Iterator empty"); + + } + +// /** +// * @param serviceSchema +// */ +// public static void print(XmlElement serviceSchema) { +// System.out.println(xsul5.XmlConstants.BUILDER.serializeToStringPretty(serviceSchema)); +// } + + /** + * @param workflowID + * @return + */ + public static String findWorkflowName(URI workflowID) { + String[] splits = workflowID.toString().split("/"); + return splits[splits.length - 1]; + + } + + /** + * + * @param element + * @param name + * @param oldValue + * @param newValue + */ + public static void replaceAttributeValue(XmlElement element, String name, String oldValue, String newValue) { + XmlAttribute attribute = element.attribute(name); + if (null != attribute && oldValue.equals(attribute.getValue())) { + element.removeAttribute(attribute); + element.setAttributeValue(name, newValue); + } + Iterable iterator = element.children(); + for (Object object : iterator) { + if (object instanceof XmlElement) { + replaceAttributeValue((XmlElement) object, name, oldValue, newValue); + } + } + + } + + public static boolean attributeExist(XmlElement element, String name, String value) { + XmlAttribute attribute = element.attribute(name); + if (null != attribute && value.equals(attribute.getValue())) { + return true; + } + Iterable iterator = element.children(); + boolean ret = false; + for (Object object : iterator) { + if (object instanceof XmlElement) { + ret = ret || attributeExist((XmlElement) object, name, value); + } + } + return ret; + + } + + +} \ No newline at end of file
