airavata-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ramin...@apache.org
Subject svn commit: r1139850 [3/7] - in /incubator/airavata/services/trunk/xregistry/src: ./ main/ main/java/ main/java/org/ main/java/org/apache/ main/java/org/apache/airavata/ main/java/org/apache/airavata/xregistry/ main/java/org/apache/airavata/xregistry/a...
Date Sun, 26 Jun 2011 17:50:31 GMT
Added: incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/db/ConfigurationParamsReader.java
URL: http://svn.apache.org/viewvc/incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/db/ConfigurationParamsReader.java?rev=1139850&view=auto
==============================================================================
--- incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/db/ConfigurationParamsReader.java (added)
+++ incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/db/ConfigurationParamsReader.java Sun Jun 26 17:50:29 2011
@@ -0,0 +1,936 @@
+/*
+* 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.xregistry.db;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.LineNumberReader;
+import java.io.UnsupportedEncodingException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.Properties;
+import java.util.StringTokenizer;
+import java.util.Vector;
+
+import xsul.MLogger;
+
+
+public class ConfigurationParamsReader implements Configuration {
+
+    private final static MLogger log = MLogger.getLogger();
+
+	public final String FILE_SEPARATOR = "/";
+
+	public final String DELIMITER = ",";
+
+	private final int INITIAL_LIST_SIZE = 3;
+
+	private String basePath = null;
+
+	private ArrayList keysList = new ArrayList();
+
+	protected Configuration defaults = null;
+
+	protected Hashtable store = new Hashtable();
+
+	public ConfigurationParamsReader() {
+	}
+
+	public ConfigurationParamsReader(String file) {
+		try {
+			load(file);
+		} catch (IOException ioe) {
+			ioe.printStackTrace();
+			log.info(ioe.getMessage());
+		}
+	}
+
+	public ConfigurationParamsReader(Configuration defaults) {
+		this.defaults = defaults;
+	}
+
+	/**
+	 * Load the properties from the given file
+	 * 
+	 * @param file
+	 *            The properties file to load
+	 * @throws IOException
+	 */
+	public void load(String file) throws IOException {
+		load(this.getClass().getClassLoader().getResourceAsStream(file));
+	}
+
+	/**
+	 * Load the properties from the given input stream.
+	 * 
+	 * @param input
+	 *            An InputStream on the properties file
+	 * @throws IOException
+	 */
+	public void load(InputStream input) throws IOException {
+		load(input, null);
+	}
+
+	/**
+	 * Load the properties from the given input stream and using the specified
+	 * encoding.
+	 * 
+	 * @param input
+	 *            An InputStream.
+	 * @param enc
+	 *            An encoding.
+	 * @exception IOException
+	 */
+	public synchronized void load(InputStream input, String enc)
+			throws IOException {
+
+		LineNumberReader reader = null;
+
+		if (enc != null) {
+			try {
+				reader = new LineNumberReader(new InputStreamReader(input, enc));
+			} catch (UnsupportedEncodingException e) {
+				// Get one with the default encoding...
+			}
+		}
+		if (reader == null) {
+			reader = new LineNumberReader(new InputStreamReader(input));
+		}
+
+		StringBuffer sb = new StringBuffer();
+		while (true) {
+
+			String line = reader.readLine();
+			if (line == null) {
+				break; // EOF
+			}
+
+			line = line.trim();
+			if (line.startsWith("#")) {
+				continue;
+
+			} else if (line.equals("")) {
+				continue;
+
+			} else if (line.endsWith("\\")) {
+				sb.append(line.substring(0, line.length() - 1));
+				continue;
+
+			} else {
+				line = sb.append(line).toString();
+				sb = new StringBuffer();
+
+				int equalIndex = line.indexOf('=');
+				/**
+				 * fix commons.configuration bug
+				 * 
+				 * @see BasePropertiesConfiguration#load we not only make sure
+				 *      there is an equal sign, but also there is something
+				 *      after the equal sign
+				 */
+				if (equalIndex > 0 && (equalIndex + 1) < line.length()) {
+					String key = line.substring(0, equalIndex).trim();
+					String value = line.substring(equalIndex + 1).trim();
+
+					addProperty(key, value);
+
+				}
+			}
+		}
+	}
+
+	/**
+	 * @param The
+	 *            file name with which to get InputStream
+	 * @return An InputStream
+	 * @throws IOException
+	 */
+	public InputStream getPropertyStream(String resourceName)
+			throws IOException {
+
+		InputStream resource = null;
+		File file = null;
+
+		if (resourceName.startsWith(FILE_SEPARATOR)) {
+			// an absolute path
+			file = new File(resourceName);
+			log.info("configuration: load " + resourceName);
+		} else if (basePath == null || basePath.equals("")) {
+
+			file = new File(resourceName);
+			String canonName = file.getCanonicalPath();
+			file = new File(canonName);
+			log.info("configuration: load " + canonName);
+		} else {
+			StringBuffer fileName = new StringBuffer();
+
+			if (!basePath.endsWith(FILE_SEPARATOR)) {
+				basePath = basePath + FILE_SEPARATOR;
+			}
+			fileName.append(basePath).append(resourceName);
+			file = new File(fileName.toString());
+			String canonName = file.getCanonicalPath();
+			file = new File(canonName);
+			log.info("configuration: load " + canonName);
+		}
+
+		if (file == null || !file.exists()) {
+			throw new FileNotFoundException("File not exists " + resourceName);
+
+		} else if (!file.canRead()) {
+			throw new IOException("File " + resourceName
+					+ " exists but could not be read.");
+
+		} else {
+			resource = new FileInputStream(file);
+		}
+
+		return resource;
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public void addProperty(String key, Object token) {
+
+		List tokenAdd = null;
+
+		if (token instanceof String) {
+			tokenAdd = processString((String) token);
+
+		} else if (token instanceof Collection) {
+
+			for (Iterator it = ((Collection) token).iterator(); it.hasNext();) {
+				addProperty(key, it.next());
+			}
+			return;
+
+		} else {
+			tokenAdd = new Vector(1);
+			tokenAdd.add(token);
+		}
+
+		Object o = store.get(key);
+		if (o instanceof Vector) {
+			for (Iterator it = tokenAdd.iterator(); it.hasNext();) {
+				((Vector) o).add(it.next());
+			}
+
+		} else {
+			Vector v = new Vector();
+			if (o != null) {
+				v.add(o);
+			}
+			for (Iterator it = tokenAdd.iterator(); it.hasNext();) {
+				v.add(it.next());
+			}
+
+			if (o == null && v.size() == 1) {
+				addPropertyDirect(key, v.get(0));
+
+			} else {
+				addPropertyDirect(key, v);
+			}
+		}
+	}
+
+	/**
+	 * @param token
+	 *            A String token
+	 * @return A List of Strings
+	 */
+	protected List processString(String token) {
+		List l = new ArrayList(INITIAL_LIST_SIZE);
+
+		if (token.indexOf(DELIMITER) > 0) {
+			StringTokenizer tokenizer = new StringTokenizer(token, DELIMITER);
+
+			while (tokenizer.hasMoreTokens()) {
+				String value = tokenizer.nextToken();
+				/**
+				 * fix commons.configuration bug
+				 * 
+				 * @see PropertiesConfiguration#processString() more trim() call
+				 *      allows both comma "," AND whitespace between values
+				 */
+				l.add(value.trim());
+			}
+		} else {
+			l.add(token);
+		}
+
+		return l;
+	}
+
+	/**
+	 * @param key
+	 *            key to use for mapping
+	 * @param obj
+	 *            object to store
+	 */
+	protected void addPropertyDirect(String key, Object obj) {
+
+		if (!store.containsKey(key)) {
+			keysList.add(key);
+		}
+
+		store.put(key, obj);
+	}
+
+	/**
+	 * Map <code> true </code>, <code> on </code>, <code> yes </code> to true;
+	 * <code> false </code>, <code> off </code>, <code> no </code> to false.
+	 * 
+	 * @param value
+	 *            The value to test for boolean state.
+	 * @return String of true, false or null
+	 */
+	public String testBoolean(String value) {
+
+		String val = value.toLowerCase();
+
+		if (val.equals("true") || val.equals("on") || val.equals("yes")) {
+			return "true";
+
+		} else if (val.equals("false") || val.equals("off") || val.equals("no")) {
+			return "false";
+
+		} else {
+			return null;
+		}
+
+	}
+
+	/**
+	 * 
+	 * @see Configuration
+	 */
+	public Configuration subset(String prefix) {
+
+		Configuration pc = new ConfigurationParamsReader();
+		Iterator keys = this.getKeys();
+		boolean valid = false;
+
+		while (keys.hasNext()) {
+			Object key = keys.next();
+
+			if (key instanceof String && ((String) key).startsWith(prefix)) {
+				if (!valid) {
+					valid = true;
+				}
+
+				String newKey = null;
+				if (((String) key).length() == prefix.length()) {
+					newKey = prefix;
+
+				} else {
+					newKey = ((String) key).substring(prefix.length() + 1);
+				}
+
+				Object value = store.get(key);
+				((ConfigurationParamsReader) pc).addPropertyDirect(newKey,
+						value);
+
+			}
+		}
+
+		if (valid) {
+			return pc;
+		} else {
+			return null;
+		}
+
+	}
+
+	/**
+	 * @see Configuration#isEmpty
+	 */
+	public boolean isEmpty() {
+		return store.isEmpty();
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public boolean containsKey(String key) {
+		return store.containsKey(key);
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public void setProperty(String key, Object value) {
+		clearProperty(key);
+		addProperty(key, value);
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public void clearProperty(String key) {
+
+		if (containsKey(key)) {
+			for (int i = 0; i < keysList.size(); i++) {
+				if (((String) keysList.get(i)).equals(key)) {
+					keysList.remove(i);
+					break;
+				}
+			}
+			store.remove(key);
+		}
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public Iterator getKeys() {
+		return keysList.iterator();
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public Iterator getKeys(String prefix) {
+		Iterator keys = getKeys();
+		ArrayList matchingKeys = new ArrayList();
+
+		while (keys.hasNext()) {
+			Object key = keys.next();
+
+			if (key instanceof String && ((String) key).startsWith(prefix)) {
+				matchingKeys.add(key);
+			}
+		}
+		return matchingKeys.iterator();
+	}
+
+	/**
+	 * Returns all the properties that have been read from the specified
+	 * configuration file
+	 */
+	public Properties getProperties(Properties _defaults) {
+		Properties props = new Properties(_defaults);
+
+		Enumeration e = store.keys();
+		while (e.hasMoreElements()) {
+			String _key = (String) e.nextElement();
+			String _value = store.get(_key).toString();
+			props.setProperty(_key, _value);
+		}
+		return props;
+
+	}
+
+	/**
+	 * @see Configuration
+	 * @see #getProperties(String, Properties)
+	 */
+	public Properties getProperties(String key) {
+		return getProperties(key, null);
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public Properties getProperties(String key, Properties defaults) {
+
+		String[] tokens = getStringArray(key);
+
+		/*
+		 * Each token is of the form 'key=value'.
+		 */
+		Properties props = (defaults == null ? new Properties()
+				: new Properties(defaults));
+
+		for (int i = 0; i < tokens.length; i++) {
+			String token = tokens[i];
+			int equalIndex = token.indexOf('=');
+			if (equalIndex > 0) {
+				String pkey = token.substring(0, equalIndex).trim();
+				String pvalue = token.substring(equalIndex + 1).trim();
+				props.put(pkey, pvalue);
+			} else if (tokens.length == 1 && token.equals("")) {
+				// Semantically equivalent to an empty Properties
+				// object.
+				break;
+			} else {
+				throw new IllegalArgumentException('\'' + token
+						+ "' does not contain an equals sign");
+			}
+		}
+		return props;
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public String getProperty(String key) {
+
+		Object o = store.get(key);
+
+		if (o == null) {
+			if (defaults != null) {
+				o = defaults.getProperty(key);
+			}
+		}
+		return o.toString();
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public boolean getBoolean(String key) {
+		Boolean b = getBoolean(key, (Boolean) null);
+		if (b != null) {
+			return b.booleanValue();
+
+		} else {
+			throw new NoSuchElementException('\'' + key
+					+ "' doesn't map to an existing object");
+		}
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public boolean getBoolean(String key, boolean defaultValue) {
+		return getBoolean(key, new Boolean(defaultValue)).booleanValue();
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public Boolean getBoolean(String key, Boolean defaultValue) {
+		Object value = resolveVectorStore(key);
+
+		if (value instanceof Boolean) {
+			return (Boolean) value;
+		} else if (value instanceof String) {
+			String s = testBoolean((String) value);
+			Boolean b = new Boolean(s);
+			return b;
+		} else if (value == null) {
+			if (defaults != null) {
+				return defaults.getBoolean(key, defaultValue);
+			} else {
+				return defaultValue;
+			}
+		} else {
+			throw new ClassCastException('\'' + key
+					+ "' doesn't map to a Boolean object");
+		}
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public byte getByte(String key) {
+		Byte b = getByte(key, null);
+		if (b != null) {
+			return b.byteValue();
+		} else {
+			throw new NoSuchElementException('\'' + key
+					+ " doesn't map to an existing object");
+		}
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public byte getByte(String key, byte defaultValue) {
+		return getByte(key, new Byte(defaultValue)).byteValue();
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public Byte getByte(String key, Byte defaultValue) {
+		Object value = resolveVectorStore(key);
+
+		if (value instanceof Byte) {
+			return (Byte) value;
+		} else if (value instanceof String) {
+			Byte b = new Byte((String) value);
+			return b;
+		} else if (value == null) {
+			if (defaults != null) {
+				return defaults.getByte(key, defaultValue);
+			} else {
+				return defaultValue;
+			}
+		} else {
+			throw new ClassCastException('\'' + key
+					+ "' doesn't map to a Byte object");
+		}
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public double getDouble(String key) {
+		Double d = getDouble(key, null);
+		if (d != null) {
+			return d.doubleValue();
+		} else {
+			throw new NoSuchElementException('\'' + key
+					+ "' doesn't map to an existing object");
+		}
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public double getDouble(String key, double defaultValue) {
+		return getDouble(key, new Double(defaultValue)).doubleValue();
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public Double getDouble(String key, Double defaultValue) {
+		Object value = resolveVectorStore(key);
+
+		if (value instanceof Double) {
+			return (Double) value;
+		} else if (value instanceof String) {
+			Double d = new Double((String) value);
+			return d;
+		} else if (value == null) {
+			if (defaults != null) {
+				return defaults.getDouble(key, defaultValue);
+			} else {
+				return defaultValue;
+			}
+		} else {
+			throw new ClassCastException('\'' + key
+					+ "' doesn't map to a Double object");
+		}
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public float getFloat(String key) {
+		Float f = getFloat(key, null);
+		if (f != null) {
+			return f.floatValue();
+		} else {
+			throw new NoSuchElementException('\'' + key
+					+ "' doesn't map to an existing object");
+		}
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public float getFloat(String key, float defaultValue) {
+		return getFloat(key, new Float(defaultValue)).floatValue();
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public Float getFloat(String key, Float defaultValue) {
+		Object value = resolveVectorStore(key);
+
+		if (value instanceof Float) {
+			return (Float) value;
+		} else if (value instanceof String) {
+			Float f = new Float((String) value);
+			return f;
+		} else if (value == null) {
+			if (defaults != null) {
+				return defaults.getFloat(key, defaultValue);
+			} else {
+				return defaultValue;
+			}
+		} else {
+			throw new ClassCastException('\'' + key
+					+ "' doesn't map to a Float object");
+		}
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public int getInt(String key) {
+		Integer i = getInteger(key, null);
+		if (i != null) {
+			return i.intValue();
+		} else {
+			throw new NoSuchElementException('\'' + key
+					+ "' doesn't map to an existing object");
+		}
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public int getInt(String key, int defaultValue) {
+		Integer i = getInteger(key, null);
+
+		if (i == null) {
+			return defaultValue;
+		}
+
+		return i.intValue();
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public Integer getInteger(String key, Integer defaultValue) {
+		Object value = resolveVectorStore(key);
+
+		if (value instanceof Integer) {
+			return (Integer) value;
+		} else if (value instanceof String) {
+			Integer i = new Integer((String) value);
+			return i;
+		} else if (value == null) {
+			if (defaults != null) {
+				return defaults.getInteger(key, defaultValue);
+			} else {
+				return defaultValue;
+			}
+		} else {
+			throw new ClassCastException('\'' + key
+					+ "' doesn't map to a Integer object");
+		}
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public long getLong(String key) {
+		Long l = getLong(key, null);
+		if (l != null) {
+			return l.longValue();
+		} else {
+			throw new NoSuchElementException('\'' + key
+					+ "' doesn't map to an existing object");
+		}
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public long getLong(String key, long defaultValue) {
+		return getLong(key, new Long(defaultValue)).longValue();
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public Long getLong(String key, Long defaultValue) {
+		Object value = resolveVectorStore(key);
+
+		if (value instanceof Long) {
+			return (Long) value;
+		} else if (value instanceof String) {
+			Long l = new Long((String) value);
+			return l;
+		} else if (value == null) {
+			if (defaults != null) {
+				return defaults.getLong(key, defaultValue);
+			} else {
+				return defaultValue;
+			}
+		} else {
+			throw new ClassCastException('\'' + key
+					+ "' doesn't map to a Long object");
+		}
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public short getShort(String key) {
+		Short s = getShort(key, null);
+		if (s != null) {
+			return s.shortValue();
+		} else {
+			throw new NoSuchElementException('\'' + key
+					+ "' doesn't map to an existing object");
+		}
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public short getShort(String key, short defaultValue) {
+		return getShort(key, new Short(defaultValue)).shortValue();
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public Short getShort(String key, Short defaultValue) {
+		Object value = resolveVectorStore(key);
+
+		if (value instanceof Short) {
+			return (Short) value;
+		} else if (value instanceof String) {
+			Short s = new Short((String) value);
+			return s;
+		} else if (value == null) {
+			if (defaults != null) {
+				return defaults.getShort(key, defaultValue);
+			} else {
+				return defaultValue;
+			}
+		} else {
+			throw new ClassCastException('\'' + key
+					+ "' doesn't map to a Short object");
+		}
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public String getString(String key) {
+		return getString(key, null);
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public String getString(String key, String defaultValue) {
+		Object value = resolveVectorStore(key);
+
+		if (value instanceof String) {
+			return (String) value;
+
+		} else if (value == null) {
+			if (defaults != null) {
+				return defaults.getString(key, defaultValue);
+			} else {
+				return defaultValue;
+			}
+		} else {
+			throw new ClassCastException('\'' + key
+					+ "' doesn't map to a String object");
+		}
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public String[] getStringArray(String key) {
+		Object value = store.get(key);
+
+		String[] tokens;
+
+		if (value instanceof String) {
+			tokens = new String[1];
+			tokens[0] = (String) value;
+
+		} else if (value instanceof Vector) {
+			tokens = new String[((Vector) value).size()];
+
+			for (int i = 0; i < tokens.length; i++) {
+
+				tokens[i] = (String) ((Vector) value).get(i);
+			}
+
+		} else if (value == null) {
+			if (defaults != null) {
+				tokens = defaults.getStringArray(key);
+			} else {
+				tokens = new String[0];
+			}
+		} else {
+			throw new ClassCastException('\'' + key
+					+ "' doesn't map to a String/Vector object");
+		}
+		return tokens;
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public Vector getVector(String key) {
+		return getVector(key, null);
+	}
+
+	/**
+	 * @see Configuration
+	 */
+	public Vector getVector(String key, Vector defaultValue) {
+		Object value = store.get(key);
+		Vector v = null;
+
+		if (value instanceof String) {
+			v = new Vector(1);
+			v.addElement((String) value);
+
+		} else if (value == null) {
+			if (defaults != null) {
+				v = defaults.getVector(key, defaultValue);
+			} else {
+				v = ((defaultValue == null) ? new Vector() : defaultValue);
+			}
+		} else {
+			throw new ClassCastException('\'' + key
+					+ "' doesn't map to a Vector object: " + value + ", a "
+					+ value.getClass().getName());
+		}
+		return v;
+	}
+
+	/**
+	 * 
+	 */
+	public String getBasePath() {
+		return this.basePath;
+	}
+
+	/**
+	 * 
+	 */
+	public void setBasePath(String path) {
+		this.basePath = path;
+	}
+
+	/**
+	 * Returns an object from the store described by the key. If the value is a
+	 * Vector object, replace it with the first object in the container
+	 * 
+	 * @param key
+	 *            The property key.
+	 * 
+	 * @return value Value, transparently resolving a possible Vector
+	 *         dependency.
+	 */
+	private Object resolveVectorStore(String key) {
+		Object value = store.get(key);
+		if (value != null && value instanceof Vector) {
+			value = ((Vector) value).get(0);
+		}
+		return value;
+	}
+
+}

Added: incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/db/ConnectionPool.java
URL: http://svn.apache.org/viewvc/incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/db/ConnectionPool.java?rev=1139850&view=auto
==============================================================================
--- incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/db/ConnectionPool.java (added)
+++ incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/db/ConnectionPool.java Sun Jun 26 17:50:29 2011
@@ -0,0 +1,409 @@
+/*
+* 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.
+*/
+/**
+ * ConnectionPool.java
+ * @author Yi Huang (yihuan@cs.indiana.edu)
+ * Created:Dec 14, 2005 5:00:43 PM
+ */
+
+package org.apache.airavata.xregistry.db;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Vector;
+
+import javax.sql.DataSource;
+
+/**
+ * A class for preallocating, recycling, and managing JDBC connections.
+ */
+public class ConnectionPool implements Runnable {
+	private long MAX_IDLE_TIME=5*60*1000; //5 minutes
+	private String driver, url, username, password, jdbcUrl;
+
+	private int initialConnections, maxConnections;
+
+	private boolean waitIfBusy;
+
+	private Vector availableConnections, busyConnections;
+
+	private boolean connectionPending = false;
+	
+	private HashMap lastAccessTimeRecord=new HashMap();
+	
+	private String urlType="";
+	
+	private DataSource datasource;
+    
+    private boolean autoCommit = false;
+    
+    private int transactionIsolation = Connection.TRANSACTION_NONE;
+
+	public ConnectionPool(String driver, String url, String username,
+			String password, int initialConnections, int maxConnections,
+			boolean waitIfBusy) throws SQLException {
+		this(initialConnections,maxConnections,waitIfBusy);
+		this.driver = driver;
+		this.url = url;
+		this.username = username;
+		this.password = password;
+		urlType="speratedURL";
+		createConnectionPool();
+	}
+    public ConnectionPool(String driver, String jdbcUrl,
+            int initialConnections, int maxConnections, boolean waitIfBusy, boolean autoCommit, int transactionIsolation)
+            throws SQLException {
+        this(initialConnections,maxConnections,waitIfBusy);
+        this.driver = driver;
+        this.jdbcUrl=jdbcUrl;
+        urlType="simpleURL";
+        this.autoCommit = autoCommit;
+        this.transactionIsolation = transactionIsolation;
+        createConnectionPool();
+        
+        
+    }
+
+	public ConnectionPool(String driver, String jdbcUrl,
+			int initialConnections, int maxConnections, boolean waitIfBusy)
+			throws SQLException {
+		this(initialConnections,maxConnections,waitIfBusy);
+		this.driver = driver;
+		this.jdbcUrl=jdbcUrl;
+		urlType="simpleURL";
+		createConnectionPool();
+	}
+
+	public ConnectionPool(DataSource dataSource, int initialConnections,
+			int maxConnections, boolean waitIfBusy) throws SQLException {
+		this(initialConnections,maxConnections,waitIfBusy);
+		urlType="dataSource";
+		this.datasource=dataSource;
+		createConnectionPool();
+	}
+	
+	protected ConnectionPool(int initialConnections, int maxConnections,boolean waitIfBusy) throws SQLException{
+		this.initialConnections=initialConnections;
+		this.maxConnections = maxConnections;
+		this.waitIfBusy = waitIfBusy;
+		if (initialConnections > maxConnections) {
+			initialConnections = maxConnections;
+		}
+		availableConnections = new Vector(initialConnections);
+		busyConnections = new Vector();		
+	    CleanUpThread cleanUpThread = new CleanUpThread();
+		new Thread(cleanUpThread).start();	 
+	}
+	
+	private void createConnectionPool() throws SQLException{
+		for (int i = 0; i < initialConnections; i++) {
+			availableConnections.addElement(makeNewConnection());
+		}
+	}
+
+	public synchronized Connection getConnection() throws SQLException {
+		if (!availableConnections.isEmpty()) {
+			Connection existingConnection = (Connection) availableConnections
+					.lastElement();
+			int lastIndex = availableConnections.size() - 1;
+		//	System.out.println("ConnectionNo="+lastIndex);
+			availableConnections.removeElementAt(lastIndex);
+			
+			long lastAccess=((Long)lastAccessTimeRecord.get(existingConnection)).longValue();			
+			// If connection on available list is closed (e.g.,
+			// it timed out), then remove it from available list
+			// and repeat the process of obtaining a connection.
+			// Also wake up threads that were waiting for a
+			// connection because maxConnection limit was reached.
+			if (existingConnection.isClosed() ) {
+				notifyAll(); // Freed up a spot for anybody waiting
+				Connection connection=getConnection();
+				setTimeStamp(connection);
+				return (connection);
+			} else {
+				busyConnections.addElement(existingConnection);
+				setTimeStamp(existingConnection);
+				return existingConnection;
+			}
+		} else {
+			// Three possible cases:
+			// 1) You haven't reached maxConnections limit. So
+			// establish one in the background if there isn't
+			// already one pending, then wait for
+			// the next available connection (whether or not
+			// it was the newly established one).
+			// 2) You reached maxConnections limit and waitIfBusy
+			// flag is false. Throw SQLException in such a case.
+			// 3) You reached maxConnections limit and waitIfBusy
+			// flag is true. Then do the same thing as in second
+			// part of step 1: wait for next available connection.
+			if ((totalConnections() < maxConnections) && !connectionPending) {
+				makeBackgroundConnection();
+			} else if (!waitIfBusy) {
+				throw new SQLException("Connection limit reached");
+			}
+			// Wait for either a new connection to be established
+			// (if you called makeBackgroundConnection) or for
+			// an existing connection to be freed up.
+			try {
+				wait();
+			} catch (InterruptedException ie) {
+			}
+			// Someone freed up a connection, so try again.
+			Connection connection=getConnection();
+			setTimeStamp(connection);
+			return connection;
+		}
+	}
+
+	// You can't just make a new connection in the foreground
+	// when none are available, since this can take several
+	// seconds with a slow network connection. Instead,
+	// start a thread that establishes a new connection,
+	// then wait. You get woken up either when the new connection
+	// is established or if someone finishes with an existing
+	// connection.
+	private void makeBackgroundConnection() {
+		connectionPending = true;
+		try {
+			Thread connectThread = new Thread(this);
+			connectThread.start();
+		} catch (OutOfMemoryError oome) {
+			// Give up on new connection
+		}
+	}
+
+	public void run() {
+		try {
+			Connection connection = makeNewConnection();
+			synchronized (this) {
+				availableConnections.addElement(connection);
+				connectionPending = false;
+				notifyAll();
+			}
+		} catch (Exception e) { // SQLException or OutOfMemory
+		// Give up on new connection and wait for existing one
+		// to free up.
+		}
+	}
+
+	// This explicitly makes a new connection. Called in
+	// the foreground when initializing the ConnectionPool,
+	// and called in the background when running.
+	private Connection makeNewConnection() throws SQLException {
+		try {
+			// Load database driver if not already loaded
+			Class.forName(driver);
+			Connection connection;
+			// Establish network connection to database
+			if(urlType.equals("speratedURL")){
+			  connection = DriverManager.getConnection(url, username,
+					password);
+			}else if(urlType.equals("simpleURL")){
+				connection = DriverManager.getConnection(jdbcUrl);
+			}else {   //if(urlType.equals("dataSource")){
+				connection = datasource.getConnection();
+                
+			}
+                        if(this.transactionIsolation != Connection.TRANSACTION_NONE){
+                            connection.setTransactionIsolation(this.transactionIsolation);
+                        }
+                        connection.setAutoCommit(this.autoCommit);
+			setTimeStamp(connection);
+			return connection;
+		} catch (ClassNotFoundException cnfe) {
+			// Simplify try/catch blocks of people using this by
+			// throwing only one exception type.
+			throw new SQLException("Can't find class for driver: " + driver);
+		}
+	}
+
+
+	
+	private void setTimeStamp(Connection connection){
+		lastAccessTimeRecord.put(connection, Long.valueOf(System.currentTimeMillis()));
+	}
+	
+	//The database connection cannot be left idle for too long, otherwise TCP connection will be broken.
+	/**
+	 * From http://forums.mysql.com/read.php?39,28450,57460#msg-57460
+	 * Okay, then it looks like wait_timeout on the server is killing your connection 
+	 * (it is set to 8 hours of idle time by default). Either set that value higher on your server, 
+	 * or configure your connection pool to not hold connections idle that long (I prefer the latter). 
+	 * Most folks I know that run MySQL with a connection pool in high-load production environments only 
+	 * let connections sit idle for a matter of minutes, since it only takes a few milliseconds to open a connection, 
+	 * and the longer one sits idle the more chance it will go "bad" because of a network hiccup or the MySQL server 
+	 * being restarted. 
+	 * @throws SQLException 
+	 */
+	private boolean isConnectionStale(Connection connection) throws SQLException{	
+	   long currentTime=System.currentTimeMillis();
+	   long lastAccess=((Long)lastAccessTimeRecord.get(connection)).longValue();
+	   if(currentTime-lastAccess>MAX_IDLE_TIME){
+//		   connection.close();
+	//	   System.out.println("*************JDBC Connection Stale!");
+		   return true;
+	   }
+	   else
+		   return false;
+	}
+	
+	private void closeStaleConnections() throws SQLException{
+       //close idle connections
+		Iterator iter= availableConnections.iterator();
+       while(iter.hasNext()){
+    	   Connection existingConnection = (Connection) iter.next();
+    	   if(isConnectionStale(existingConnection)){
+    		   existingConnection.close();
+    		   iter.remove();
+    	   }
+       }
+       //close busy connections that have been checked out for too long. 
+       //This should not happen sinc ethis means program has bug for not releasing connections .
+       iter= busyConnections.iterator();
+       while(iter.hasNext()){
+    	   Connection busyConnection = (Connection) iter.next();
+    	   if(isConnectionStale(busyConnection)){
+    		   iter.remove();
+    		   busyConnection.close();
+    		   System.out.println("****Connection has checked out too long. Forced release. Check the program for unReleased connection.");
+    	   }
+       }
+	}
+
+	public synchronized void free(Connection connection) {
+		busyConnections.removeElement(connection);
+		availableConnections.addElement(connection);
+		// Wake up threads that are waiting for a connection
+		notifyAll();
+	}
+
+	public synchronized int totalConnections() {
+		return (availableConnections.size() + busyConnections.size());
+	}
+
+	/**
+	 * Close all the connections. Use with caution: be sure no connections are
+	 * in use before calling. Note that you are not <I>required</I> to call
+	 * this when done with a ConnectionPool, since connections are guaranteed to
+	 * be closed when garbage collected. But this method gives more control
+	 * regarding when the connections are closed.
+	 */
+	public synchronized void closeAllConnections() {
+		closeConnections(availableConnections);
+		availableConnections = new Vector();
+		closeConnections(busyConnections);
+		busyConnections = new Vector();
+		lastAccessTimeRecord.clear();
+	}
+
+	private void closeConnections(Vector connections) {
+		try {
+			for (int i = 0; i < connections.size(); i++) {
+				Connection connection = (Connection) connections.elementAt(i);
+				if (!connection.isClosed()) {
+					connection.close();
+				}
+			}
+		} catch (SQLException sqle) {
+			// Ignore errors; garbage collect anyhow
+		}
+	}
+
+	public synchronized String toString() {
+		String info = "ConnectionPool(" + url + "," + username + ")"
+				+ ", available=" + availableConnections.size() + ", busy="
+				+ busyConnections.size() + ", max=" + maxConnections;
+		return (info);
+	}
+	
+    class CleanUpThread implements Runnable{
+  	  public void run(){
+		  while(true){
+		      try {
+					Thread.sleep(MAX_IDLE_TIME);
+				} catch (InterruptedException e) {
+					// TODO Auto-generated catch block
+					e.printStackTrace();
+				}
+				try {
+					closeStaleConnections();
+				} catch (SQLException e) {
+					// TODO Auto-generated catch block
+					e.printStackTrace();
+				}
+  		  }
+		  }
+  	  }
+	
+	
+}
+
+/*
+ * Indiana University Extreme! Lab Software License, Version 1.2
+ * 
+ * Copyright (c) 2002-2004 The Trustees of Indiana University. All rights
+ * reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * 
+ * 1) All redistributions of source code must retain the above copyright notice,
+ * the list of authors in the original source code, this list of conditions and
+ * the disclaimer listed in this license;
+ * 
+ * 2) All redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the disclaimer listed in this license in
+ * the documentation and/or other materials provided with the distribution;
+ * 
+ * 3) Any documentation included with all redistributions must include the
+ * following acknowledgement:
+ * 
+ * "This product includes software developed by the Indiana University Extreme!
+ * Lab. For further information please visit http://www.extreme.indiana.edu/"
+ * 
+ * Alternatively, this acknowledgment may appear in the software itself, and
+ * wherever such third-party acknowledgments normally appear.
+ * 
+ * 4) The name "Indiana University" or "Indiana University Extreme! Lab" shall
+ * not be used to endorse or promote products derived from this software without
+ * prior written permission from Indiana University. For written permission,
+ * please contact http://www.extreme.indiana.edu/.
+ * 
+ * 5) Products derived from this software may not use "Indiana University" name
+ * nor may "Indiana University" appear in their name, without prior written
+ * permission of the Indiana University.
+ * 
+ * Indiana University provides no reassurances that the source code provided
+ * does not infringe the patent or any other intellectual property rights of any
+ * other entity. Indiana University disclaims any liability to any recipient for
+ * claims brought by any other entity based on infringement of intellectual
+ * property rights or otherwise.
+ * 
+ * LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO
+ * WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
+ * NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF
+ * INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS.
+ * INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS",
+ * "VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.
+ * LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR
+ * ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION
+ * GENERATED USING SOFTWARE.
+ */

Added: incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/db/DBConstants.java
URL: http://svn.apache.org/viewvc/incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/db/DBConstants.java?rev=1139850&view=auto
==============================================================================
--- incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/db/DBConstants.java (added)
+++ incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/db/DBConstants.java Sun Jun 26 17:50:29 2011
@@ -0,0 +1,42 @@
+/*
+* 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.xregistry.db;
+
+public abstract class DBConstants {
+
+    /****************************************************************
+     *               Summary Table Information                      *
+     ****************************************************************/
+    public static final String T_SUMMARY_NAME = "summary";
+    public static final String T_SUMMARY_WORKFLOW_ID = "workflowid";
+    public static final String T_SUMMARY_TEMPLATE_ID = "templateid";
+    public static final String T_SUMMARY_STATUS = "status";
+    public static final String T_SUMMARY_END_TIME = "endTime";
+    public static final String T_SUMMARY_START_TIME = "startTime";
+
+    /****************************************************************
+     *               Faults Table Information                      *
+     ****************************************************************/
+    public static final String T_FAULTS_NAME = "faults";
+    public static final String T_FAULTS_ID = "id";
+    public static final String T_FAULTS_XML = "xml";
+    public static final String T_FAULTS_WORKFLOW_ID = "workflowid";
+
+}
+
+ 
+

Added: incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/db/JdbcStorage.java
URL: http://svn.apache.org/viewvc/incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/db/JdbcStorage.java?rev=1139850&view=auto
==============================================================================
--- incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/db/JdbcStorage.java (added)
+++ incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/db/JdbcStorage.java Sun Jun 26 17:50:29 2011
@@ -0,0 +1,164 @@
+/*
+* 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.xregistry.db;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+
+import org.apache.airavata.xregistry.XregistryException;
+
+
+public class JdbcStorage {
+   // private ConfigurationParamsReader config;
+
+    // private String jdbcUrl=
+    // "jdbc:mysql://156.56.104.175:3306/wsnt?user=root";
+    private String jdbcUrl = null;;
+    
+
+    private PreparedStatement stmt = null;
+
+    private ResultSet rs = null;
+
+    private ResultSetMetaData rsmd = null;
+
+    // private Connection conn = null;
+   // private ConnectionPool connectionPool;
+
+    private String jdbcDriver;
+    
+    
+
+        
+        public JdbcStorage(String fileName, boolean enableTransactions) {
+            ConfigurationParamsReader config = new ConfigurationParamsReader(fileName);
+            jdbcUrl = config.getProperty("jdbcUrl");
+            jdbcDriver = config.getProperty("jdbcDriver");
+            
+        }
+
+    
+        
+        public JdbcStorage(String jdbcUrl,String jdbcDriver) throws XregistryException {
+//            try {
+                this.jdbcDriver = jdbcDriver;
+                this.jdbcUrl = jdbcUrl;
+//                connectionPool = new ConnectionPool(jdbcDriver, jdbcUrl, 10,
+//                            50, true);
+//            } catch (SQLException e) {
+//                throw new XregistryException(e);
+//            }
+        }
+
+    public JdbcStorage(String fileName) {
+        this(fileName, false);
+
+    }
+
+    public Connection connect() throws XregistryException {
+
+        //Connection conn = connectionPool.getConnection();
+        return makeNewConnection();
+    }
+
+    public void closeConnection(Connection conn) throws java.sql.SQLException {
+        conn.setAutoCommit(true);
+        //connectionPool.free(conn);
+        conn.close();
+    }
+
+//    public int update(String query) throws java.sql.SQLException {
+//        int result = 0;
+//        // connect();
+//        Connection conn = connectionPool.getConnection();
+//        stmt = conn.prepareStatement(query);
+//        result = stmt.executeUpdate();
+//        stmt.close();
+//        connectionPool.free(conn);
+//
+//        return result;
+//    }
+//
+//    /**
+//     * This method is provided so that yo can have better control over the
+//     * statement. For example: You can use stmt.setString to convert quotation
+//     * mark automatically in an INSERT statement
+//     */
+//    public int insert(PreparedStatement stmt) throws java.sql.SQLException {
+//        int rows = 0;
+//
+//        rows = stmt.executeUpdate();
+//        stmt.close();
+//        return rows;
+//    }
+//
+//    public int insert(String query) throws java.sql.SQLException {
+//        int rows = 0;
+//
+//        Connection conn = connectionPool.getConnection();
+//        stmt = conn.prepareStatement(query);
+//        rows = stmt.executeUpdate();
+//        stmt.close();
+//        connectionPool.free(conn);
+//
+//        return rows;
+//    }
+//
+//    public ResultSet query(String query) throws SQLException {
+//        Connection conn = connectionPool.getConnection();
+//        // Create a scrollable ResultSet so that I can use rs.last() to get
+//        // total number of rows without using another COUNT in SQL query
+//        Statement lstmt = conn.createStatement(
+//                ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
+//        ResultSet rs = lstmt.executeQuery(query);
+//        connectionPool.free(conn);
+//        return rs;
+//    }
+//
+//    public int countRow(String tableName, String columnName)
+//            throws java.sql.SQLException {
+//        String query = new String("SELECT COUNT(" + columnName + ") FROM "
+//                + tableName);
+//        Connection conn = connectionPool.getConnection();
+//        stmt = conn.prepareStatement(query);
+//        rs = stmt.executeQuery();
+//        rs.next();
+//        int count = rs.getInt(1);
+//        stmt.close();
+//        connectionPool.free(conn);
+//        return count;
+//    }
+    
+    private Connection makeNewConnection() throws XregistryException  {
+                try {
+                    // Load database driver if not already loaded
+                    Class.forName(jdbcDriver);
+                    Connection connection;
+                            connection = DriverManager.getConnection(jdbcUrl);
+                    return connection;
+                } catch (ClassNotFoundException e) {
+                    throw new XregistryException(e);                    
+                } catch (SQLException e) {
+                    throw new XregistryException(e);
+                }
+}
+
+}

Added: incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/doc/AppData.java
URL: http://svn.apache.org/viewvc/incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/doc/AppData.java?rev=1139850&view=auto
==============================================================================
--- incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/doc/AppData.java (added)
+++ incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/doc/AppData.java Sun Jun 26 17:50:29 2011
@@ -0,0 +1,30 @@
+/*
+* 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.xregistry.doc;
+
+import javax.xml.namespace.QName;
+
+public class AppData extends DocData{
+    public String secondryName;
+
+    public AppData(QName name, String owner,String secondryName) {
+        super(name, owner);
+        this.secondryName = secondryName;
+    }
+}
+

Added: incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/doc/DocData.java
URL: http://svn.apache.org/viewvc/incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/doc/DocData.java?rev=1139850&view=auto
==============================================================================
--- incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/doc/DocData.java (added)
+++ incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/doc/DocData.java Sun Jun 26 17:50:29 2011
@@ -0,0 +1,149 @@
+/*
+* 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.xregistry.doc;
+
+import java.util.Calendar;
+
+import javax.xml.namespace.QName;
+
+import org.apache.airavata.xregistry.XregistryConstants;
+
+
+public class DocData {
+	public QName resourceID;
+	public QName name;
+    public String resourcename;
+    public String owner;
+    public String resourcetype;
+    public String resourcedesc;
+    public Calendar created;
+    public String allowedAction = XregistryConstants.Action.All.toString();
+    
+    public DocData(QName name, String owner) {
+        this.name = name;
+        this.owner = owner;
+    }
+    public DocData(QName name, String owner, String resourceType) {
+        this.name = name;
+        this.owner = owner;
+        this.resourcetype = resourceType;
+    }
+    @Override
+    public String toString() {
+        StringBuffer buf = new StringBuffer();
+        buf.append(resourceID);
+        return super.toString();
+    }
+	/**
+	 * @return the resourceID
+	 */
+	public QName getResourceID() {
+		return resourceID;
+	}
+	/**
+	 * @param resourceID the resourceID to set
+	 */
+	public void setResourceID(QName resourceID) {
+		this.resourceID = resourceID;
+	}
+	/**
+	 * @return the resourcename
+	 */
+	public String getResourcename() {
+		return resourcename;
+	}
+	/**
+	 * @param resourcename the resourcename to set
+	 */
+	public void setResourcename(String resourcename) {
+		this.resourcename = resourcename;
+	}
+	/**
+	 * @return the owner
+	 */
+	public String getOwner() {
+		return owner;
+	}
+	/**
+	 * @param owner the owner to set
+	 */
+	public void setOwner(String owner) {
+		this.owner = owner;
+	}
+	/**
+	 * @return the resourcetype
+	 */
+	public String getResourcetype() {
+		return resourcetype;
+	}
+	/**
+	 * @param resourcetype the resourcetype to set
+	 */
+	public void setResourcetype(String resourcetype) {
+		this.resourcetype = resourcetype;
+	}
+	/**
+	 * @return the resourcedesc
+	 */
+	public String getResourcedesc() {
+		return resourcedesc;
+	}
+	/**
+	 * @param resourcedesc the resourcedesc to set
+	 */
+	public void setResourcedesc(String resourcedesc) {
+		this.resourcedesc = resourcedesc;
+	}
+	/**
+	 * @return the created
+	 */
+	public Calendar getCreated() {
+		return created;
+	}
+	/**
+	 * @param created the created to set
+	 */
+	public void setCreated(Calendar created) {
+		this.created = created;
+	}
+	/**
+	 * @return the allowedAction
+	 */
+	public String getAllowedAction() {
+		return allowedAction;
+	}
+	/**
+	 * @param allowedAction the allowedAction to set
+	 */
+	public void setAllowedAction(String allowedAction) {
+		this.allowedAction = allowedAction;
+	}
+	/**
+	 * @return the name
+	 */
+	public QName getName() {
+		return name;
+	}
+	/**
+	 * @param name the name to set
+	 */
+	public void setName(QName name) {
+		this.name = name;
+	}
+}
+

Added: incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/doc/DocParser.java
URL: http://svn.apache.org/viewvc/incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/doc/DocParser.java?rev=1139850&view=auto
==============================================================================
--- incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/doc/DocParser.java (added)
+++ incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/doc/DocParser.java Sun Jun 26 17:50:29 2011
@@ -0,0 +1,124 @@
+/*
+* 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.xregistry.doc;
+
+import java.io.IOException;
+import java.io.StringReader;
+import java.util.Hashtable;
+
+import javax.xml.namespace.QName;
+
+import org.apache.airavata.xregistry.XregistryException;
+import org.apache.xmlbeans.XmlException;
+
+import edu.indiana.extreme.gfac.schemas.SchemaValidator;
+import edu.indiana.extreme.gfac.wsdl.WSDLConstants;
+import edu.indiana.extreme.gfac.wsdl.WSDLGenerator;
+import edu.indiana.extreme.namespaces.x2004.x01.gFac.ApplicationDescriptionDocument;
+import edu.indiana.extreme.namespaces.x2004.x01.gFac.ApplicationDescriptionType;
+import edu.indiana.extreme.namespaces.x2004.x01.gFac.HostDescriptionDocument;
+import edu.indiana.extreme.namespaces.x2004.x01.gFac.HostDescriptionType;
+import edu.indiana.extreme.namespaces.x2004.x01.gFac.MethodType;
+import edu.indiana.extreme.namespaces.x2004.x01.gFac.ServiceMapDocument;
+import edu.indiana.extreme.namespaces.x2004.x01.gFac.ServiceMapType;
+import edu.indiana.extreme.namespaces.x2004.x01.gFac.ApplicationDescriptionType.ApplicationName;
+import edu.indiana.extreme.namespaces.x2004.x01.gFac.ServiceType.ServiceName;
+
+public class DocParser {
+
+    public static String parseHostDesc(String hostDescAsStr) throws XregistryException {
+        try {
+            HostDescriptionType hostDesc = HostDescriptionDocument.Factory.parse(
+                    new StringReader(hostDescAsStr)).getHostDescription();
+            hostDesc.validate();
+            return hostDesc.getHostName();
+        } catch (XmlException e) {
+            throw new XregistryException(e);
+        } catch (IOException e) {
+            throw new XregistryException(e);
+        }
+    }
+
+    public static ServiceMapType parseServiceDesc(String serviceDescAsStr)
+            throws XregistryException {
+        try {
+            ServiceMapType serviceDesc = ServiceMapDocument.Factory.parse(
+                    new StringReader(serviceDescAsStr)).getServiceMap();
+            serviceDesc.validate();
+            return serviceDesc;
+        } catch (XmlException e) {
+            throw new XregistryException(e);
+        } catch (IOException e) {
+            throw new XregistryException(e);
+        }
+    }
+
+    public static QName getServiceName(ServiceName serviceName) {
+        return new QName(serviceName.getTargetNamespace(), serviceName.getStringValue());
+    }
+
+    public static ApplicationDescriptionType parseAppeDesc(String appDescAsStr) throws XregistryException {
+        try {
+            ApplicationDescriptionType appDesc = ApplicationDescriptionDocument.Factory.parse(
+                    new StringReader(appDescAsStr)).getApplicationDescription();
+            appDesc.validate();
+            return appDesc;
+        } catch (XmlException e) {
+            throw new XregistryException(e);
+        } catch (IOException e) {
+            throw new XregistryException(e);
+        }
+    }
+
+    public static QName getAppName(ApplicationName appName) {
+        return new QName(appName.getTargetNamespace(), appName.getStringValue());
+    }
+
+    public static MethodType findOperationWithApplication(ServiceMapType serviceMap) {
+        MethodType[] methods = serviceMap.getPortTypeArray()[0].getMethodArray();
+        for (int i = 0; i < methods.length; i++) {
+            if (methods[i].getApplication() != null) {
+                return methods[i];
+            }
+        }
+        return null;
+    }
+    
+    public static String createWsdl(String serviceMapAsStr,boolean isAbstract) throws XregistryException{
+        try {
+            ServiceMapType serviceMap = ServiceMapDocument.Factory.parse(serviceMapAsStr).getServiceMap();
+            SchemaValidator validator = new SchemaValidator(serviceMap);
+            validator.validate();
+            QName serviceQname = new QName(serviceMap.getService().getServiceName()
+                    .getTargetNamespace(), serviceMap.getService().getServiceName()
+                    .getStringValue());
+            WSDLGenerator wsdlGenerator = new WSDLGenerator();
+            Hashtable serviceTable = wsdlGenerator.generateWSDL(null, serviceQname, null,
+                    serviceMap, isAbstract);
+            if(isAbstract){
+                return (String) serviceTable.get(WSDLConstants.AWSDL);
+            }else{
+                return (String) serviceTable.get(WSDLConstants.WSDL);
+            }
+        } catch (XmlException e) {
+            throw new XregistryException(e);
+        } catch (Exception e) {
+            throw new XregistryException(e);
+        }
+    }
+
+}

Added: incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/doc/DocumentRegistry.java
URL: http://svn.apache.org/viewvc/incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/doc/DocumentRegistry.java?rev=1139850&view=auto
==============================================================================
--- incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/doc/DocumentRegistry.java (added)
+++ incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/doc/DocumentRegistry.java Sun Jun 26 17:50:29 2011
@@ -0,0 +1,82 @@
+/*
+* 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.xregistry.doc;
+
+import java.util.List;
+
+import javax.xml.namespace.QName;
+
+import org.apache.airavata.xregistry.XregistryException;
+
+
+public interface DocumentRegistry {
+
+    public String registerHostDesc(String user, String hostDescAsStr) throws XregistryException;
+
+    public String registerServiceDesc(String user, String serviceDescAsStr, String awsdlAsStr)
+            throws XregistryException;
+
+    public String registerAppDesc(String user, String appDescAsStr) throws XregistryException;
+
+    public void removeServiceDesc(String serviceName) throws XregistryException;
+
+    public void removeAppDesc(String appName, String hostName) throws XregistryException;
+
+    public void removeHostDesc(String hostName) throws XregistryException;
+
+    public String getServiceDesc(String serviceName) throws XregistryException;
+
+    public String getAppDesc(String appName, String hostName) throws XregistryException;
+
+    public String getHostDesc(String hostName) throws XregistryException;
+
+    public String registerConcreteWsdl(String user, String wsdlAsStr, int lifetimeAsSeconds)
+            throws XregistryException;
+
+    public String getConcreateWsdl(String wsdlQName) throws XregistryException;
+
+    public void removeConcreteWsdl(String wsdlQName) throws XregistryException;
+
+    public String getAbstractWsdl(String wsdlQName) throws XregistryException;
+
+    public List<DocData> findServiceInstance(String user,String serviceName) throws XregistryException;
+
+    public List<DocData> findServiceDesc(String user,String serviceName) throws XregistryException;
+
+    public List<AppData> findAppDesc(String user,String query) throws XregistryException;
+
+    public List<DocData> findHosts(String user,String hostName) throws XregistryException;
+
+    public String[] app2Hosts(String appName) throws XregistryException;
+    
+    public void registerDocument(String user,QName resourceID,String document)throws XregistryException;
+    
+    public void removeDocument(String user,QName resourceID)throws XregistryException;
+    
+    public List<DocData> findDocument(String user,String query)throws XregistryException;
+    
+    public String getDocument(String user,QName docName) throws XregistryException;
+    
+    public void registerOGCEResource(String user,QName resourceID,String resourceName, String resourceType, String resourceDesc, String resourceDocuemnt, String resoureParentTypedID)throws XregistryException;
+    
+    public void removeOGCEResource(String user,QName resourceID,String resourceType)throws XregistryException;
+    
+    public List<DocData> findOGCEResource(String user,String query,String resourceName,String resourceType,String resoureParentTypedID)throws XregistryException;
+    
+    public String getOGCEResource(String user,QName resourceID, String resourceType, String resoureParentTypedID) throws XregistryException;
+
+}



Mime
View raw message