airavata-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ramin...@apache.org
Subject svn commit: r1139850 [4/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/doc/DocumentRegistryImpl.java
URL: http://svn.apache.org/viewvc/incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/doc/DocumentRegistryImpl.java?rev=1139850&view=auto
==============================================================================
--- incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/doc/DocumentRegistryImpl.java (added)
+++ incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/doc/DocumentRegistryImpl.java Sun Jun 26 17:50:29 2011
@@ -0,0 +1,788 @@
+/*
+* 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.StringReader;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+
+import javax.wsdl.Definition;
+import javax.wsdl.Port;
+import javax.wsdl.Service;
+import javax.wsdl.WSDLException;
+import javax.wsdl.factory.WSDLFactory;
+import javax.wsdl.xml.WSDLReader;
+import javax.xml.namespace.QName;
+
+import org.apache.airavata.xregistry.SQLConstants;
+import org.apache.airavata.xregistry.XregistryConstants;
+import org.apache.airavata.xregistry.XregistryConstants.DocType;
+import org.apache.airavata.xregistry.XregistryConstants.SqlParmType;
+import org.apache.airavata.xregistry.XregistryException;
+import org.apache.airavata.xregistry.auth.UserAuthorizer;
+import org.apache.airavata.xregistry.context.GlobalContext;
+import org.apache.airavata.xregistry.context.SqlParam;
+import org.apache.airavata.xregistry.utils.Utils;
+import org.xml.sax.InputSource;
+
+import xsul.MLogger;
+import edu.indiana.extreme.namespaces.x2004.x01.gFac.ApplicationDescriptionType;
+import edu.indiana.extreme.namespaces.x2004.x01.gFac.ServiceMapType;
+
+public class DocumentRegistryImpl implements SQLConstants, DocumentRegistry {
+    protected static MLogger log = MLogger.getLogger(XregistryConstants.LOGGER_NAME);
+
+    private final GlobalContext globalContext;
+
+    public DocumentRegistryImpl(final GlobalContext globalContext) {
+        super();
+        this.globalContext = globalContext;
+    }
+
+    public String registerResource(String user, String resourceID, String sql, SqlParam[] sqlParams)
+            throws XregistryException {
+        try {
+            Connection connection = globalContext.createConnection();
+            connection.setAutoCommit(false);
+            PreparedStatement statement = null;
+            try {
+                statement = connection.prepareStatement(ADD_RESOURCE_SQL);
+                // String hostName = DocParser.parseHostDesc(hostDescAsStr);
+                // String resourceID = ResourceUtils.getResourceID(hostName,
+                // ResourceUtils.HOST_DESC_TYPE);
+                statement.setString(1, resourceID);
+                statement.setString(2, user);
+                statement.executeUpdate();
+
+                statement = connection.prepareStatement(sql);
+                for (int i = 0; i < sqlParams.length; i++) {
+                    SqlParam param = sqlParams[i];
+                    switch (param.getType()) {
+                    case Int:
+                        statement.setInt(i + 1, Integer.parseInt(param.getValue()));
+                        break;
+                    case String:
+                        statement.setString(i + 1, param.getValue());
+                        break;
+                    case Long:
+                        statement.setLong(i + 1, Long.parseLong(param.getValue()));
+                        break;
+                    default:
+                        throw new XregistryException("Unknown SQL param type " + param.getType());
+                    }
+                }
+                statement.executeUpdate();
+                log.info("Execuate SQL " + statement);
+                connection.commit();
+                return resourceID;
+            } catch (Throwable e) {
+                connection.rollback();
+                throw new XregistryException(e);
+            } finally {
+            	 try {
+      				statement.close();
+      				connection.setAutoCommit(true);
+                     globalContext.closeConnection(connection);
+      			} catch (SQLException e) {
+      				 throw new XregistryException(e);
+      			}
+            }
+        } catch (SQLException e) {
+            throw new XregistryException(e);
+        }
+    }
+
+    public String getResource(String sql, String[] docKeys, String returnedRow)
+            throws XregistryException {
+        Connection connection = globalContext.createConnection();
+        PreparedStatement statement = null;
+        ResultSet results = null;
+        try {
+            statement = connection.prepareStatement(sql);
+            for (int i = 0; i < docKeys.length; i++) {
+                statement.setString(i + 1, docKeys[i]);
+            }
+            log.info("Execuate SQL " + statement);
+            results = statement.executeQuery();
+            String docToReturn = null;
+            if (results.next()) {
+                docToReturn = results.getString(returnedRow);
+            }
+            return docToReturn;
+        } catch (SQLException e) {
+            throw new XregistryException(e);
+        } finally {
+        	 try {
+        	     results.close();
+        		 statement.close();
+   				connection.setAutoCommit(true);
+                globalContext.closeConnection(connection);
+   			} catch (SQLException e) {
+   				 throw new XregistryException(e);
+   			}
+        }
+    }
+
+	public String getWithTypeResource(String sql, String[] docKeys,
+			String returnedRow) throws XregistryException {
+		Connection connection = globalContext.createConnection();
+		PreparedStatement statement = null;
+		ResultSet results = null;
+		try {
+			statement = connection.prepareStatement(sql);
+			for (int i = 0; i < docKeys.length; i++) {
+				if(i == 0){
+					statement.setString(i+1 , "%" + docKeys[i] + "%" );
+				}else{
+				statement.setString(i+1, docKeys[i]);
+				}
+			}
+			log.info("Execuate SQL " + statement);
+			results = statement.executeQuery();
+			String docToReturn = null;
+			if (results.next()) {
+				docToReturn = results.getString(returnedRow);
+			}
+			return docToReturn;
+		} catch (SQLException e) {
+			throw new XregistryException(e);
+		} finally {
+			try {
+				results.close();
+				statement.close();
+				connection.setAutoCommit(true);
+				globalContext.closeConnection(connection);
+			} catch (SQLException e) {
+				throw new XregistryException(e);
+			}
+		}
+	}
+	public String getResource(String sql, String[] docKeys, String[] returnedRows)
+			throws XregistryException {
+		Connection connection = globalContext.createConnection();
+		PreparedStatement statement = null;
+		ResultSet results = null;
+		
+		try {
+			statement = connection.prepareStatement(sql);
+			for (int i = 0; i < docKeys.length; i++) {
+				statement.setString(i + 1, docKeys[i]);
+			}
+			log.info("Execuate SQL " + statement);
+			results = statement.executeQuery();
+			String docToReturn = null;
+			 List<String[]> list = new ArrayList<String[]>();
+	            while (results.next()) {
+	                String[] returnValues = new String[returnedRows.length];
+	                for (int i = 0; i < returnedRows.length; i++) {
+	                    String rawName = returnedRows[i];
+	                    returnValues[i] = results.getString(rawName);
+	                }
+	                list.add(returnValues);
+	            }
+			return docToReturn;
+		} catch (SQLException e) {
+			throw new XregistryException(e);
+		} finally {
+	    	 try {
+        	     results.close();
+        		 statement.close();
+   				connection.setAutoCommit(true);
+                globalContext.closeConnection(connection);
+   			} catch (SQLException e) {
+   				 throw new XregistryException(e);
+   			}
+    
+		}
+	}
+
+    public void removeResource(String resourceID, String sql, String[] keys)
+            throws XregistryException {
+        try {
+            Connection connection = globalContext.createConnection();
+            connection.setAutoCommit(false);
+            PreparedStatement  statement = null;
+            try {
+                //First remove the resource specific data, thenupdate parent table
+                statement = connection.prepareStatement(sql);
+                for (int i = 0; i < keys.length; i++) {
+                    statement.setString(i + 1, keys[i]);
+                }
+                statement.executeUpdate();
+                
+                statement = connection.prepareStatement(DELETE_RESOURCE_SQL);
+                statement.setString(1, resourceID);
+                statement.executeUpdate();
+                log.info("Execuate SQL " + statement);
+                
+                // Add the group to memory model
+                connection.commit();
+            } catch (SQLException e) {
+                connection.rollback();
+                throw new XregistryException(e);
+            } finally {
+            	 try {
+     				statement.close();
+     				connection.setAutoCommit(true);
+                    globalContext.closeConnection(connection);
+     			} catch (SQLException e) {
+     				 throw new XregistryException(e);
+     			}
+            }
+        } catch (SQLException e) {
+            throw new XregistryException(e);
+        }
+
+    }
+
+    public List<String[]> findResource(String sql, String key, String... returnedRows)
+            throws XregistryException {
+        Connection connection = globalContext.createConnection();
+        PreparedStatement statement =null;
+        ResultSet results = null;
+        try {
+            statement = connection.prepareStatement(sql);
+            statement.setString(1, "%" + key + "%");
+            log.info("Execuate SQL " + statement);
+            results = statement.executeQuery();
+
+            List<String[]> list = new ArrayList<String[]>();
+            while (results.next()) {
+                String[] returnValues = new String[returnedRows.length];
+                for (int i = 0; i < returnedRows.length; i++) {
+                    String rawName = returnedRows[i];
+                    returnValues[i] = results.getString(rawName);
+                }
+                list.add(returnValues);
+            }
+            return list;
+        } catch (SQLException e) {
+            throw new XregistryException(e);
+        } finally {
+            try {
+				results.close();
+				statement.close();
+				globalContext.closeConnection(connection);
+			} catch (SQLException e) {
+				 throw new XregistryException(e);
+			}
+        }
+    }
+
+    public List<String[]> findResource(String sql, String[] key,
+			String... returnedRows) throws XregistryException {
+		Connection connection = globalContext.createConnection();
+		PreparedStatement statement = null;
+		ResultSet results = null;
+		try {
+			 statement = connection.prepareStatement(sql);
+			 statement.setString(1, "%" + key[0] + "%");
+			 statement.setString(2, "%" + key[1] + "%");
+			 //FIXME : Fix to have optional type parameter 
+			 if(key.length >= 3){
+			 statement.setString(3, key[2]);
+			 }
+			 if(key.length == 4){
+			 statement.setString(4, key[3]);
+			 }
+			 log.info("Execuate SQL " + statement);
+			results = statement.executeQuery();
+
+			List<String[]> list = new ArrayList<String[]>();
+			while (results.next()) {
+				String[] returnValues = new String[returnedRows.length];
+				for (int i = 0; i < returnedRows.length; i++) {
+					String rawName = returnedRows[i];
+					returnValues[i] = results.getString(rawName);
+				}
+				list.add(returnValues);
+			}
+			return list;
+		} catch (SQLException e) {
+			throw new XregistryException(e);
+		} finally {
+			 try {
+					results.close();
+					statement.close();
+					globalContext.closeConnection(connection);
+				} catch (SQLException e) {
+					 throw new XregistryException(e);
+				}
+		}
+	}
+    /*
+     * (non-Javadoc)
+     * 
+     * @see xregistry.impl.DocumentRegistry#registerHostDesc(java.lang.String,
+     *      java.lang.String)
+     */
+    public String registerHostDesc(String user, String hostDescAsStr) throws XregistryException {
+        String hostName = DocParser.parseHostDesc(hostDescAsStr);
+        String resourceID = ResourceUtils.getResourceID(DocType.HostDesc,hostName);
+        return registerResource(user, resourceID, ADD_HOST_DESC_SQL, new SqlParam[] {
+                new SqlParam(resourceID), new SqlParam(hostName), new SqlParam(hostDescAsStr) });
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see xregistry.impl.DocumentRegistry#registerServiceDesc(java.lang.String,
+     *      java.lang.String, java.lang.String)
+     */
+    public String registerServiceDesc(String user, String serviceDescAsStr, String awsdlAsStr)
+            throws XregistryException {
+        ServiceMapType serviceMapType = DocParser.parseServiceDesc(serviceDescAsStr);
+        String serviceName = DocParser.getServiceName(serviceMapType.getService().getServiceName())
+                .toString();
+        String resourceID = ResourceUtils.getResourceID(DocType.ServiceDesc,serviceName);
+        // INSERT INTO
+        // service_map_table(resourceid,qname,servicemap_str,appname,awsdl_str)
+        // VALUES (?, ?,?,?,?)
+        return registerResource(user, resourceID, ADD_SERVICE_DESC_SQL, new SqlParam[] {
+                new SqlParam(resourceID), new SqlParam(serviceName),
+                new SqlParam(serviceDescAsStr), new SqlParam(awsdlAsStr) });
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see xregistry.impl.DocumentRegistry#registerAppDesc(java.lang.String,
+     *      java.lang.String)
+     */
+    public String registerAppDesc(String user, String appDescAsStr) throws XregistryException {
+        ApplicationDescriptionType appDesc = DocParser.parseAppeDesc(appDescAsStr);
+        String appName = DocParser.getAppName(appDesc.getApplicationName()).toString();
+        String hostName = appDesc.getDeploymentDescription().getHostName();
+        String resourceID = ResourceUtils.getResourceID(DocType.AppDesc, appName,hostName );
+        
+        // INSERT INTO appdesc_table(resourceid,qname,host_name,appdesc_str)
+        // VALUES (?, ?, ?, ?)
+        return registerResource(user, resourceID, ADD_APP_DESC_SQL, new SqlParam[] {
+                new SqlParam(resourceID), new SqlParam(appName), new SqlParam(hostName),
+                new SqlParam(appDescAsStr) });
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see xregistry.impl.DocumentRegistry#removeServiceDesc(java.lang.String)
+     */
+    public void removeServiceDesc(String serviceName) throws XregistryException {
+        // DELETE FROM service_map_table WHERE qname = ?
+        String resourceID = ResourceUtils.getResourceID(DocType.ServiceDesc,serviceName);
+        removeResource(resourceID, DELETE_SERVICE_DESC_SQL, new String[] { serviceName });
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see xregistry.impl.DocumentRegistry#removeAppDesc(java.lang.String,
+     *      java.lang.String)
+     */
+    public void removeAppDesc(String appName, String hostName) throws XregistryException {
+        // DELETE FROM appdesc_table WHERE qname= ? AND host_name = ?
+        String resourceID = ResourceUtils.getResourceID(DocType.AppDesc,appName,hostName);
+        removeResource(resourceID, DELETE_APP_DESC_SQL, new String[] { appName, hostName });
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see xregistry.impl.DocumentRegistry#removeHostDesc(java.lang.String)
+     */
+    public void removeHostDesc(String hostName) throws XregistryException {
+        // DELETE FROM appdesc_table WHERE qname= ? AND host_name = ?
+        String resourceID = ResourceUtils.getResourceID(DocType.HostDesc,hostName);
+        removeResource(resourceID, DELETE_HOST_DESC_SQL, new String[] { hostName });
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see xregistry.impl.DocumentRegistry#getServiceDesc(java.lang.String)
+     */
+    public String getServiceDesc(String serviceName) throws XregistryException {
+        // SELECT servicemap_str,resourceid from service_map_table where qname =
+        // ?
+        return getResource(GET_SERVICE_DESC_SQL, new String[] { serviceName }, SERVICE_DESC_STR);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see xregistry.impl.DocumentRegistry#getAppDesc(java.lang.String,
+     *      java.lang.String)
+     */
+    public String getAppDesc(String appName, String hostName) throws XregistryException {
+        // SELECT appdesc_str from appdesc_table WHERE qname= ? AND host_name =
+        // ?
+        return getResource(GET_APP_DESC_SQL, new String[] { appName, hostName }, APP_DESC_STR);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see xregistry.impl.DocumentRegistry#getHostDesc(java.lang.String)
+     */
+    public String getHostDesc(String hostName) throws XregistryException {
+        // SELECT hostdesc_str,resourceid from hostdesc_table where host_name =
+        // ?
+        return getResource(GET_HOST_DESC_SQL, new String[] { hostName }, HOST_DESC_STR);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see xregistry.impl.DocumentRegistry#registerConcreteWsdl(java.lang.String,
+     *      java.lang.String, int)
+     */
+    public String registerConcreteWsdl(String user, String wsdlAsStr, int lifetimeAsSeconds)
+            throws XregistryException {
+        try {
+            if(lifetimeAsSeconds < 60*15){
+                lifetimeAsSeconds = 60*15;
+            }
+            
+            
+            WSDLReader reader = WSDLFactory.newInstance().newWSDLReader();
+            Definition definition = reader.readWSDL(null, new InputSource(new StringReader(
+                    wsdlAsStr)));
+
+            if (definition.getServices() == null) {
+                throw new XregistryException(
+                        "WSDL must be a concreate WSDL, it must have service defined");
+            }
+            Iterator it = definition.getServices().values().iterator();
+            if (it.hasNext()) {
+                Service service = (Service) it.next();
+                QName wsdlQname = service.getQName();
+                QName portTypeName;
+                Iterator ports = service.getPorts().values().iterator();
+                if (ports.hasNext()) {
+                    Port port = (Port) ports.next();
+                    portTypeName = port.getBinding().getPortType().getQName();
+                } else {
+                    throw new XregistryException(
+                            "WSDL must be a concreate WSDL, it must have port defined");
+                }
+                String resourceID = ResourceUtils
+                        .getResourceID(DocType.CWsdl,wsdlQname.toString());
+                // INSERT INTO
+                // cwsdl_table(resourceid,qname,wsdl_str,time_stamp,life_time,port_type_name)
+                // VALUES (?, ?, ?, ?, ?, ?)
+                //if CWSDL is alredy there, delete it
+                removeResource(resourceID, DELETE_CWSDL_SQL, new String[]{wsdlQname.toString()});
+                //Add CWSDL
+                return registerResource(user, resourceID, ADD_CWSDL_SQL, new SqlParam[] {
+                        new SqlParam(resourceID), new SqlParam(wsdlQname.toString()),
+                        new SqlParam(wsdlAsStr),
+                        new SqlParam(String.valueOf(System.currentTimeMillis()), SqlParmType.Long),
+                        new SqlParam(String.valueOf(lifetimeAsSeconds*1000), SqlParmType.Int),
+                        new SqlParam(portTypeName.toString()) });
+            } else {
+                throw new XregistryException(
+                        "WSDL must be a concreate WSDL, it must have service defined");
+            }
+        } catch (WSDLException e) {
+            throw new XregistryException(e);
+        }
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see xregistry.impl.DocumentRegistry#getConcreateWsdl(java.lang.String)
+     */
+    public String getConcreateWsdl(String wsdlQName) throws XregistryException {
+        // SELECT wsdl_str from cwsdl_table where qname = ?
+        return getResource(GET_CWSDL_SQL, new String[] { wsdlQName + "%", wsdlQName }, CWSDL_STR);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see xregistry.impl.DocumentRegistry#removeConcreteWsdl(java.lang.String)
+     */
+    public void removeConcreteWsdl(String wsdlQName) throws XregistryException {
+        // DELETE FROM cwsdl_table WHERE qname = ?
+        String resourceID = ResourceUtils.getResourceID(DocType.CWsdl,wsdlQName);
+        removeResource(resourceID, DELETE_CWSDL_SQL, new String[] { wsdlQName });
+
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see xregistry.impl.DocumentRegistry#getAbstractWsdl(java.lang.String)
+     */
+    public String getAbstractWsdl(String wsdlQName) throws XregistryException {
+        // SELECT awsdl_str from service_map_table where qname = ?
+        return getResource(GET_AWSDL_SQL, new String[] { wsdlQName }, AWSDL_STR);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see xregistry.impl.DocumentRegistry#findServiceInstance(java.lang.String)
+     */
+    public List<DocData> findServiceInstance(String user,String serviceName) throws XregistryException {
+        List<String[]> results = findResource(FIND_CWSDL_SQL, serviceName, QNAME, OWNER,RESOURCE_ID);
+        List<DocData> returnValues = new ArrayList<DocData>();
+        StringBuffer buf = new StringBuffer();
+        for(String[] result:results){
+                DocData data = new DocData(QName.valueOf(result[0]),result[1]);
+                data.allowedAction = XregistryConstants.Action.Read.toString();
+                data.resourceID = new QName(result[2]);
+                buf.append(data.name).append(" ");
+                returnValues.add(data);
+        }
+        log.info(new StringBuffer().append("Return Cwsdl:").append(user)
+                .append(":").append(serviceName).append("->").append(buf.toString()).toString());
+        return returnValues;
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see xregistry.impl.DocumentRegistry#findServiceDesc(java.lang.String)
+     */
+    public List<DocData> findServiceDesc(String user,String serviceName) throws XregistryException {
+        List<String[]> results = findResource(FIND_SERVICE_DESC_SQL,
+                serviceName, QNAME, OWNER, RESOURCE_ID);
+        List<DocData> returnValues = new ArrayList<DocData>();
+        for(String[] result:results){
+            String resourceID = ResourceUtils.getResourceID(DocType.ServiceDesc,result[0]);
+            String allowedAction = isAccessible(resourceID, result[1], user);
+            if(allowedAction != null){
+                DocData data = new DocData(QName.valueOf(result[0]),result[1]);
+                data.allowedAction = allowedAction;
+                data.resourceID = new QName(result[2]);
+                data.resourcename = result[2];
+                returnValues.add(data);
+            }
+        }
+        return returnValues;        
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see xregistry.impl.DocumentRegistry#findAppDesc(java.lang.String)
+     */
+    public List<AppData> findAppDesc(String user,String query) throws XregistryException {
+        List<String[]> results = findResource(FIND_APP_DESC_SQL,
+                query, QNAME, OWNER,HOST_NAME,RESOURCE_ID);
+        List<AppData> returnValues = new ArrayList<AppData>();
+        for(String[] result:results){
+            String resourceID = ResourceUtils.getResourceID(DocType.AppDesc,result[0], result[2]);
+            String allowedAction = isAccessible(resourceID, result[1], user);
+            if(allowedAction != null){
+                AppData data = new AppData(QName.valueOf(result[0]),result[1],result[2]);
+                data.allowedAction = allowedAction;
+                data.resourceID = new QName(result[3]);
+                data.resourcename = result[3];
+                returnValues.add(data);
+            }
+        }
+        return returnValues;        
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see xregistry.impl.DocumentRegistry#findHosts(java.lang.String)
+     */
+    public List<DocData> findHosts(String user,String hostName) throws XregistryException {
+        // SELECT host_name from hostdesc_table where host_name like ?
+        List<String[]> results = findResource(FIND_HOST_DESC_SQL, hostName, HOST_NAME,OWNER,RESOURCE_ID);
+        List<DocData> returnValues = new ArrayList<DocData>();
+        for(String[] result:results){
+            String resourceID = ResourceUtils.getResourceID(DocType.HostDesc,result[0]);
+            String allowedAction = isAccessible(resourceID, result[1], user);
+            if(allowedAction != null){
+                DocData data = new DocData(QName.valueOf(result[0]),result[1]);
+                data.allowedAction = allowedAction;
+                data.resourceID = new QName(result[2]);
+                data.resourcename = result[2];
+                returnValues.add(data);
+            }
+        }
+        return returnValues;        
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see xregistry.impl.DocumentRegistry#app2Hosts(java.lang.String)
+     */
+    public String[] app2Hosts(String appName) throws XregistryException {
+    	Connection connection = globalContext.createConnection();
+    	 PreparedStatement statement = null;
+    	 ResultSet results = null;
+        try {
+            statement = connection.prepareStatement(GIVEN_APP_FIND_HOSTS_SQL);
+            statement.setString(1, appName);
+            log.info("Execuate SQL " + statement);
+            results = statement.executeQuery();
+            ArrayList<String> list = new ArrayList<String>();
+            while (results.next()) {
+                list.add(results.getString(HOST_NAME));
+            }
+            return Utils.toStrListToArray(list);
+        } catch (SQLException e) {
+            throw new XregistryException(e);
+        } finally {
+        	 try {
+					results.close();
+					statement.close();
+					globalContext.closeConnection(connection);
+				} catch (SQLException e) {
+					 throw new XregistryException(e);
+				}
+        }
+    } 
+    
+    private String isAccessible(String resourceID,String owner,String currentUser){
+        if(Utils.isSameDN(owner, currentUser)){
+            return  XregistryConstants.Action.All.toString();
+        } else{
+            UserAuthorizer userAuthorizer = globalContext.getAuthorizer().getAuthorizerForUser(currentUser);
+            return userAuthorizer.isAuthorized(resourceID);
+        }
+    }
+
+    public void registerDocument(String user, QName resourceID, String document) throws XregistryException {
+        registerResource(user, resourceID.toString(), ADD_DOC_SQL, new SqlParam[] {
+                new SqlParam(resourceID.toString()), new SqlParam(document) });
+    }
+
+    public List<DocData> findDocument(String user, String query) throws XregistryException {
+        List<String[]> results = findResource(FIND_DOC_SQL, query, RESOURCE_ID,OWNER);
+        List<DocData> returnValues = new ArrayList<DocData>();
+        for(String[] result:results){
+            String resourceID = result[0];
+            String owner = result[1];
+            String allowedAction = isAccessible(resourceID, owner, user);
+            if(allowedAction != null){
+                DocData data = new DocData(QName.valueOf(resourceID),owner);
+                data.allowedAction = allowedAction;
+                data.resourceID = new QName(resourceID);
+                data.resourcename = resourceID;
+                returnValues.add(data);
+            }
+        }
+        return returnValues;    
+    }
+
+    public void removeDocument(String user, QName resourceID) throws XregistryException {
+        removeResource(resourceID.toString(), DELETE_DOC_SQL, new String[] { resourceID.toString() });
+    }
+    
+    public String getDocument(String user,QName docName) throws XregistryException{
+        // SELECT wsdl_str from cwsdl_table where qname = ?
+        return getResource(GET_DOC_SQL, new String[] { docName.toString()}, DOC_STR);
+    }
+
+    public void registerOGCEResource(String user, QName resourceID, String resourceName, String resourceType, String resourceDesc, String resoureDocument, String resoureParentTypedID) throws XregistryException {
+    	String resourceIdString = ResourceUtils.getOGCEResourceID(resourceType, new String[]{resourceID.toString()});
+    	registerResource(user, resourceIdString, ADD_OGCE_RESOURCE_SQL, new SqlParam[] {
+                new SqlParam(resourceIdString),  new SqlParam(resourceName), new SqlParam(resourceType), new SqlParam(resourceDesc) ,new SqlParam(resoureDocument), new SqlParam(resoureParentTypedID) });
+    }
+
+	/**
+	 * 
+	 */
+    public String getOGCEResource(String user, QName resourceID,
+			String resourceType, String resoureParentTypedID) throws XregistryException {
+    	if(resourceType==null || resourceType == ""){
+    		return getWithTypeResource(GET_OGCE_RESOURCE_DESC_SQL_WITHOUTTYPE, new String[] { resourceID.getLocalPart()}, OGCE_RESOURCE);
+        }else{
+        	String resourceIdString = ResourceUtils.getOGCEResourceID(resourceType, new String[]{resourceID.toString()});
+        	return getResource(GET_OGCE_RESOURCE_DESC_SQL, new String[] {resourceIdString, resourceType, resoureParentTypedID}, OGCE_RESOURCE);
+    	}
+    }
+    
+    /**
+     * 
+     */
+	public List<DocData> findOGCEResource(String user, String query, String resourceName, String resourceType, String resoureParentTypedID) throws XregistryException {
+        String[] keys = null;
+        List<String[]> results = null;
+    	if(resourceType==null || resourceType == ""){
+    		  keys = new String[]{query,resourceName};
+    		  results = findResource(FIND_OGCE_RESOURCE_DESC_SQL_WITHOUTTYPE, keys, RESOURCE_ID,OWNER,OGCE_RESOURCE_CREATED, OGCE_RESOURCE_DESC,OGCE_RESOURCE_NAME);
+    	}
+    	else{
+    		 keys = new String[]{query,resourceName,resourceType,resoureParentTypedID};   
+    		 results = findResource(FIND_OGCE_RESOURCE_DESC_SQL, keys, RESOURCE_ID,OWNER,OGCE_RESOURCE_CREATED, OGCE_RESOURCE_DESC,OGCE_RESOURCE_NAME);
+    	}
+        List<DocData> returnValues = new ArrayList<DocData>();
+        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
+        for(String[] result:results){
+            String resourceID = result[0];
+            String owner = result[1];
+            String created = result[2];
+            String resouceDesc = result[3];
+            String resouceName = result[4];
+            
+            String allowedAction = isAccessible(resourceID, owner, user);
+            if(allowedAction != null){
+            	
+            	//XRegistry internally added urn:resourceType: to the id, so remove them from id when sending back
+        		if (resourceID.startsWith("urn:")){
+        			String[] resourceIDArray = resourceID.split(":",3);
+        			if (resourceIDArray.length>=3) {
+            			resourceID = resourceIDArray[2];
+        			}
+        		}
+        		//QName.valueOf has to be used instead of new QName to preserve namespace uri
+                DocData data = new DocData(QName.valueOf(resourceID),owner);
+                data.allowedAction = allowedAction;
+                data.resourceID = QName.valueOf(resourceID);
+                data.resourcename = resouceName;
+                Calendar calendar = Calendar.getInstance();
+				Date date = null;
+				try {
+					date = dateFormat.parse(created);
+				} catch (ParseException e) {
+					log.severe(e.getMessage());
+				}
+                calendar.setTime(date);
+                data.created = calendar;
+                data.resourcetype = resourceType;
+                data.resourcedesc = resouceDesc;
+                returnValues.add(data);
+            }
+        }
+        return returnValues;    
+    }
+
+	public void removeOGCEResource(String user, QName resourceID,
+			String resourceType) throws XregistryException {
+		String resource = ResourceUtils.getOGCEResourceID(resourceType, new String[]{resourceID.toString()});
+    	removeResource(resource, DELETE_OGCE_RESOURCE_SQL, new String[] { resource,resourceType });
+	}
+}

Added: incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/doc/ResourceUtils.java
URL: http://svn.apache.org/viewvc/incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/doc/ResourceUtils.java?rev=1139850&view=auto
==============================================================================
--- incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/doc/ResourceUtils.java (added)
+++ incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/doc/ResourceUtils.java Sun Jun 26 17:50:29 2011
@@ -0,0 +1,71 @@
+/*
+* 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 org.apache.airavata.xregistry.XregistryConstants;
+import org.apache.airavata.xregistry.XregistryException;
+import org.apache.airavata.xregistry.XregistryConstants.DocType;
+
+public class ResourceUtils {
+    
+    public static String getResourceID(DocType type,String... names) throws XregistryException{
+        StringBuffer buf = new StringBuffer();
+        buf.append("urn");
+        switch(type){
+            case ServiceDesc:
+                buf.append(":servicedesc");
+                break;
+            case AppDesc:
+                buf.append(":appdesc");
+                break;
+            case HostDesc:
+                buf.append(":hostdesc");
+                break;
+            case CWsdl:
+                buf.append(":cwsdl");
+                break; 
+            default:
+                throw new XregistryException("Unknown resource type, type =" + type);
+        }
+        
+        for(String name:names){
+            buf.append(":");
+            buf.append(name);    
+        }
+        
+        return buf.toString();
+    }
+    
+    public static String getOGCEResourceID(String resourceType, String... names) throws XregistryException{
+        if (resourceType==null || resourceType == "") {
+        	resourceType = XregistryConstants.DEFAULTOGCERESOURCETYPE;
+        }
+        
+        StringBuffer buf = new StringBuffer();
+        buf.append("urn:");
+        buf.append(resourceType);
+        for(String name:names){
+            buf.append(":");
+            buf.append(name);    
+        }
+        
+        return buf.toString();
+    }
+    
+}
+

Added: incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/group/Group.java
URL: http://svn.apache.org/viewvc/incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/group/Group.java?rev=1139850&view=auto
==============================================================================
--- incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/group/Group.java (added)
+++ incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/group/Group.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.group;
+
+import java.util.Collection;
+import java.util.Map;
+import java.util.Vector;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.airavata.xregistry.utils.Utils;
+
+
+/**
+ * Represent a Group, group may have Users and child groups. The symantics of child groups are resolved by 
+ * assuming of foo is in G1 and G1 is in G2, it is same as foo is in G1 (G1,G2 are groups and foo is a user).
+ */
+
+public class Group {
+    private final String name;
+    private Map<String, String> users = new ConcurrentHashMap<String, String>();
+    private Vector<Group> childGroups = new Vector<Group>();
+    private Vector<Group> parentGroups = new Vector<Group>();
+    private Map<String,String> authorizedResources = new ConcurrentHashMap<String, String>();
+    
+    
+    public Group(final String name) {
+        this.name = name;
+    }
+
+    public void addUser(String user){
+        users.put(user, user);
+    }
+    
+    public void addGroup(Group group){
+        childGroups.add(group);
+        group.addParentGroup(this);
+    }
+
+    public void removeGroup(Group group){
+        childGroups.remove(group);
+        group.removeParentGroup(this);
+    }
+    
+    @Override
+    public boolean equals(Object obj) {
+        if(obj instanceof Group){
+            return name.equals(((Group)obj).name);
+        }
+        return false;
+    }
+    
+    @Override
+    public int hashCode() {
+        return name.hashCode();
+    }
+
+    /**
+     * Check does this user authorized to access resources assigned to this group. It is
+     * decided by checking this group has give user cantained at some level. 
+     * @param user
+     * @param traversal
+     * @return
+     */
+    public boolean isAuthorized(String user,Traversal traversal){
+        if(hasUser(user)){
+          return true;
+        }else{
+            for(Group group:childGroups){
+                if(!traversal.hasVisited(group)){
+                    traversal.addVisited(group);
+                    if(group.isAuthorized(user, traversal)){
+                        return true;
+                    }
+                }
+            }
+        }
+        return false;
+    }
+    
+    
+    public boolean hasGroup(String groupName){
+        for(Group group:childGroups){
+            if(group.getName().equals(groupName)){
+                return true;
+            }
+        }
+        return false;
+    }
+    
+    public boolean hasUser(String user){
+        for(String auser:users.values()){
+            if(Utils.isSameDN(auser,user)){
+                return true;
+            }
+        }
+        return false;
+    }
+    
+    public void removeUser(String userID){
+        users.remove(userID);
+    }
+    
+
+    public String getName() {
+        return name;
+    }
+    
+    public void addParentGroup(Group parentGroup){
+        parentGroups.add(parentGroup);
+    }
+    
+    public void removeParentGroup(Group parentGroup){
+        parentGroups.remove(parentGroup);
+    }
+    
+    public Collection<Group> getParentGroups(){
+        return parentGroups;
+    }
+    
+    public void addAuthorizedResource(String resourceID,String action){
+        authorizedResources.put(resourceID,action);
+    }
+    
+    
+    public boolean removeAuthorizedResource(String resourceID){
+        return authorizedResources.remove(resourceID) != null;
+    }
+    
+    
+    public Map<String,String> getAuthorizedResources(){
+        return authorizedResources;
+    }
+}
+

Added: incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/group/GroupManager.java
URL: http://svn.apache.org/viewvc/incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/group/GroupManager.java?rev=1139850&view=auto
==============================================================================
--- incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/group/GroupManager.java (added)
+++ incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/group/GroupManager.java Sun Jun 26 17:50:29 2011
@@ -0,0 +1,63 @@
+/*
+* 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.group;
+
+import java.util.Collection;
+
+import org.apache.airavata.xregistry.XregistryException;
+
+import xregistry.generated.ListSubActorsGivenAGroupResponseDocument.ListSubActorsGivenAGroupResponse.Actor;
+
+public interface GroupManager {
+
+    public boolean isAdminUser(String user);
+
+    public boolean hasUser(String userName);
+
+    public Group getGroup(String name);
+
+    public void createGroup(String newGroup, String description) throws XregistryException;
+
+    public void createUser(String newUser, String description, boolean isAdmin)
+            throws XregistryException;
+
+    public void addGrouptoGroup(String groupName, String grouptoAddedName)
+            throws XregistryException;
+
+    public void addUsertoGroup(String groupName, String usertoAdded) throws XregistryException;
+
+    public void deleteGroup(String groupID) throws XregistryException;
+
+    public void deleteUser(String userID) throws XregistryException;
+
+    public void removeUserFromGroup(String group, String usertoRemoved) throws XregistryException;
+
+    public void removeGroupFromGroup(String group, String grouptoRemoved) throws XregistryException;
+
+    public String[] listUsers() throws XregistryException;
+
+    public String[] listGroups() throws XregistryException;
+
+    public String[] listGroupsGivenAUser(String user) throws XregistryException;
+
+    public Actor[]  listSubActorsGivenAGroup(String group)throws XregistryException;
+    
+    public Collection<Group> getGroups();
+    
+    public User getUser(String user);
+
+}

Added: incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/group/GroupManagerImpl.java
URL: http://svn.apache.org/viewvc/incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/group/GroupManagerImpl.java?rev=1139850&view=auto
==============================================================================
--- incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/group/GroupManagerImpl.java (added)
+++ incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/group/GroupManagerImpl.java Sun Jun 26 17:50:29 2011
@@ -0,0 +1,527 @@
+/*
+* 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.group;
+
+import static org.apache.airavata.xregistry.utils.Utils.canonicalizeDN;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Hashtable;
+import java.util.List;
+
+import org.apache.airavata.xregistry.SQLConstants;
+import org.apache.airavata.xregistry.XregistryConstants;
+import org.apache.airavata.xregistry.XregistryException;
+import org.apache.airavata.xregistry.context.GlobalContext;
+import org.apache.airavata.xregistry.utils.Utils;
+
+import xregistry.generated.ListSubActorsGivenAGroupResponseDocument.ListSubActorsGivenAGroupResponse.Actor;
+import xsul.MLogger;
+
+public class GroupManagerImpl implements SQLConstants, GroupManager{
+    protected static MLogger log = MLogger.getLogger(XregistryConstants.LOGGER_NAME);
+    private final Hashtable<String,Group> groups = new Hashtable<String, Group>();
+    private final GlobalContext context;
+    private boolean cascadingDeletes = true;
+    private Hashtable<String, User> users = new Hashtable<String, User>();
+    private Hashtable<String, String> adminUsers = new Hashtable<String, String>();
+    
+    public GroupManagerImpl(GlobalContext context) throws XregistryException{
+        Connection connection = context.createConnection();
+        this.context = context; 
+        /** 
+         * We create a Memory model of the Group and user tree at startup and it is kept in sync whenever a change happen to the 
+         * Groups. However database can not be shared by two Xregistry instances
+         */
+        try {
+            Statement statement = connection.createStatement();
+            ResultSet results = statement.executeQuery(SQLConstants.GET_ALL_GROUPS_SQL);
+            while(results.next()){
+                String groupId = results.getString(GROUPID);
+                addGroup(new Group(groupId));
+            }
+            results.close();
+            
+            results = statement.executeQuery(SQLConstants.GET_ALL_GROUP2GROUP_SQL);
+            while(results.next()){
+                String masterGroupId = results.getString(GROUPID);
+                String containedGroupID = results.getString(CONTANTED_GROUP_ID);
+                getGroup(masterGroupId).addGroup(getGroup(containedGroupID));
+            }
+            results.close();
+            
+            results = statement.executeQuery(SQLConstants.GET_ALL_USER2GROUP_SQL);
+            while(results.next()){
+                String userID = results.getString(USERID);
+                String groupId = results.getString(GROUPID);
+                Group group = getGroup(groupId);
+                if(group != null){
+                    group.addUser(userID);
+                }else{
+                    log.warning("Group "+ groupId + " find in user to group table, but not found in Group table. Database may be inconsistant");
+                }
+                
+            }
+            results.close();
+            
+            results = statement.executeQuery(SQLConstants.GET_ADMIN_USERS_SQL);
+            while(results.next()){
+                String adminUSer = results.getString(USERID);
+                adminUsers.put(adminUSer, adminUSer);
+            }
+            results.close();
+            
+            String[] userList = listUsers();
+            
+            if(userList != null){
+                for(String user:userList){
+                    users.put(user,new User(user));
+                }
+            }
+
+            results = statement.executeQuery(SQLConstants.GET_CAPABILITIES);
+            while(results.next()){
+                boolean isUser = results.getBoolean(IS_USER);
+                String resourceID = results.getString(RESOURCE_ID);
+                String action = results.getString(ACTION_TYPE);
+                String actorName = results.getString(ALLOWED_ACTOR);
+                if(!isUser){
+                    Group group = getGroup(actorName);
+                    if(group != null){
+                        group.addAuthorizedResource(resourceID,action);
+                    }
+                }else{
+                    User user = getUser(actorName);
+                    if(user != null){
+                        user.addAuthorizedResource(resourceID,action);
+                    }
+                }
+            }
+            results.close();
+
+            //Create a public group if it is not there and add all users to that group
+            Group publicGroup = getGroup(XregistryConstants.PUBLIC_GROUP);
+            if(publicGroup == null){
+                createGroup(XregistryConstants.PUBLIC_GROUP, "Public Group");
+                publicGroup = getGroup(XregistryConstants.PUBLIC_GROUP);
+            }
+            for(String user:users.keySet()){
+                if(!publicGroup.hasUser(user)){
+                    addUsertoGroup(publicGroup.getName(), user);
+                }
+            }
+            
+            String anonymousUser = Utils.canonicalizeDN(XregistryConstants.ANONYMOUS_USER);
+            if(!hasUser(anonymousUser)){
+                createUser(anonymousUser,anonymousUser, false);
+            }
+            if(!publicGroup.hasUser(anonymousUser)){
+                addUsertoGroup(publicGroup.getName(), anonymousUser);
+            }
+
+        } catch (SQLException e) {
+            throw new XregistryException(e);
+        }finally{
+            context.closeConnection(connection);
+        }
+        
+    }
+    
+    /* (non-Javadoc)
+     * @see xregistry.auth.GroupManager#isAdminUser(java.lang.String)
+     */
+    public boolean isAdminUser(String user){
+        return adminUsers.containsKey(user);
+    }
+    
+    
+    
+    /* (non-Javadoc)
+     * @see xregistry.auth.GroupManager#hasUser(java.lang.String)
+     */
+    public boolean hasUser(String userName){
+        return users.containsKey(userName);
+    }
+    
+    /* (non-Javadoc)
+     * @see xregistry.auth.GroupManager#getGroup(java.lang.String)
+     */
+    public Group getGroup(String name){
+        return groups.get(name);
+    }
+    
+    protected void addGroup(Group group){
+        groups.put(group.getName(), group);
+    }
+    
+    
+    /* (non-Javadoc)
+     * @see xregistry.auth.GroupManager#createGroup(java.lang.String, java.lang.String)
+     */
+    public void createGroup(String newGroup, String description) throws XregistryException{ 
+        Connection connection = context.createConnection();
+        try {
+            PreparedStatement statement = connection.prepareStatement(ADD_GROUP_SQL);
+            statement.setString(1,newGroup );
+            statement.setString(2,description );
+            statement.executeUpdate();
+            //Add the group to memory model 
+            addGroup(new Group(newGroup));
+            log.info("Group "+ newGroup + " Created");
+        } catch (SQLException e) {
+            throw new XregistryException(e);
+        }finally{
+            context.closeConnection(connection);
+        }
+    }
+    
+    
+    /* (non-Javadoc)
+     * @see xregistry.auth.GroupManager#createUser(java.lang.String, java.lang.String, boolean)
+     */
+    public void createUser(String newUser, String description,boolean isAdmin) throws XregistryException {
+        Connection connection = context.createConnection();
+        try {
+            PreparedStatement statement = connection.prepareStatement(ADD_USER_SQL);
+            statement.setString(1,Utils.canonicalizeDN(newUser));
+            statement.setString(2,description );
+            statement.setBoolean(3,isAdmin );
+            statement.executeUpdate();
+            log.info("User "+ newUser + " created");
+            users.put(newUser, new User(newUser));
+        } catch (SQLException e) {
+            throw new XregistryException(e);
+        }finally{
+            context.closeConnection(connection);
+        }
+        
+    }
+
+    
+    /* (non-Javadoc)
+     * @see xregistry.auth.GroupManager#addGrouptoGroup(java.lang.String, java.lang.String)
+     */
+    public void addGrouptoGroup(String groupName, String grouptoAddedName) throws XregistryException {
+        Group group = getGroup(groupName);
+        if(group == null){
+            throw new XregistryException("No such Group "+ groupName);
+        }
+        
+        Group grouptoAdd = getGroup(groupName);
+        if(grouptoAdd == null){
+            throw new XregistryException("No such Group "+ groupName);
+        }
+        
+        if(group.hasGroup(grouptoAddedName)){
+            throw new XregistryException("Group"+ grouptoAddedName + " already exisits in group "+ groupName);
+        }
+        Connection connection = context.createConnection();
+        try {
+            PreparedStatement statement = connection.prepareStatement(ADD_GROUP_TO_GROUP_SQL);
+            statement.setString(1, groupName);
+            statement.setString(2,grouptoAddedName );
+            statement.executeUpdate();
+            group.addGroup(grouptoAdd);
+            log.info("Add Group "+ groupName + " to "+ grouptoAddedName);
+        } catch (SQLException e) {
+            throw new XregistryException(e);
+        }finally{
+            context.closeConnection(connection);
+        }
+        
+        
+    }
+  
+    /* (non-Javadoc)
+     * @see xregistry.auth.GroupManager#addUsertoGroup(java.lang.String, java.lang.String)
+     */
+    public void addUsertoGroup(String groupName, String usertoAdded) throws XregistryException {
+        usertoAdded = Utils.canonicalizeDN(usertoAdded);
+        Group group = getGroup(groupName);
+        if(group == null){
+            throw new XregistryException("No such Group "+ groupName);
+        }
+        if(group.hasUser(usertoAdded)){
+            throw new XregistryException("user "+ usertoAdded + " already exisits in group "+ groupName);
+        }
+        Connection connection = context.createConnection();
+        try {
+            PreparedStatement statement = connection.prepareStatement(ADD_USER_TO_GROUP);
+            statement.setString(1,usertoAdded );
+            statement.setString(2,groupName );
+            statement.executeUpdate();
+            group.addUser(usertoAdded);
+            log.info("Add User "+ usertoAdded + " to "+ groupName);
+        } catch (SQLException e) {
+            throw new XregistryException(e);
+        }finally{
+            context.closeConnection(connection);
+        }
+        
+        
+    }
+    
+    /* (non-Javadoc)
+     * @see xregistry.auth.GroupManager#deleteGroup(java.lang.String)
+     */
+    public void deleteGroup(String groupID) throws XregistryException {
+        try {
+            Connection connection = context.createConnection();
+            connection.setAutoCommit(false);
+            try {
+                PreparedStatement statement1 = connection.prepareStatement(DELETE_GROUP_SQL_MAIN);
+                statement1.setString(1,groupID );
+                int updateCount = statement1.executeUpdate();
+                
+                if(updateCount == 0){
+                    throw new XregistryException("Database is not updated, Can not find such Group "+ groupID);
+                }
+                
+                if(cascadingDeletes){
+                    PreparedStatement statement2 = connection.prepareStatement(DELETE_GROUP_SQL_DEPEND);
+                    statement2.setString(1,groupID );
+                    statement2.setString(2,groupID );
+                    statement2.executeUpdate();
+                }
+                
+                connection.commit();
+                groups.remove(groupID);
+                log.info("Delete Group "+ groupID + (cascadingDeletes?" with cascading deletes ":""));
+            } catch (SQLException e) {
+                connection.rollback();
+                throw new XregistryException(e);
+            }finally{
+                context.closeConnection(connection);
+            }
+        } catch (SQLException e) {
+            throw new XregistryException(e);
+        }
+        
+    }
+    
+    /* (non-Javadoc)
+     * @see xregistry.auth.GroupManager#deleteUser(java.lang.String)
+     */
+    public void deleteUser(String userID) throws XregistryException {
+        try {
+            userID = Utils.canonicalizeDN(userID);
+            Connection connection = context.createConnection();
+            connection.setAutoCommit(false);
+            try {
+                PreparedStatement statement1 = connection.prepareStatement(DELETE_USER_SQL_MAIN);
+                statement1.setString(1,userID );
+                statement1.executeUpdate();
+                
+                PreparedStatement statement2 = connection.prepareStatement(DELETE_USER_SQL_DEPEND);
+                statement2.setString(1,userID );
+                statement2.executeUpdate();
+                
+                connection.commit();
+                Collection<Group> groupList = groups.values();
+                for(Group group:groupList){
+                    group.removeUser(userID);
+                }
+                log.info("Delete User "+ userID);
+            } catch (SQLException e) {
+                connection.rollback();
+                throw new XregistryException(e);
+            }finally{
+                context.closeConnection(connection);
+            }
+        } catch (SQLException e) {
+            throw new XregistryException(e);
+        }
+        
+    }
+    
+    /* (non-Javadoc)
+     * @see xregistry.auth.GroupManager#genericUpdate(java.lang.String, java.lang.String[])
+     */
+    public void genericUpdate(String sql,String[] keys) throws XregistryException{
+        Connection connection = context.createConnection();
+        try {
+            PreparedStatement statement1 = connection.prepareStatement(sql);
+            for(int i = 0;i<keys.length;i++){
+                statement1.setString(i+1,keys[i] );
+            }
+            statement1.executeUpdate();
+        } catch (SQLException e) {
+            throw new XregistryException(e);
+        }finally{
+            context.closeConnection(connection);
+        }
+    }
+    
+    
+    /* (non-Javadoc)
+     * @see xregistry.auth.GroupManager#removeUserFromGroup(java.lang.String, java.lang.String)
+     */
+    public void removeUserFromGroup(String groupName, String usertoRemoved) throws XregistryException {
+        //DELETE FROM group_group_table WHERE AND userid = ?  AND groupid = ? 
+        usertoRemoved = canonicalizeDN(usertoRemoved);
+        genericUpdate(REMOVE_USER_FROM_GROUP, new String[]{usertoRemoved,groupName});
+        Group group = getGroup(groupName);
+        if(group == null){
+            throw new XregistryException("No such group "+ groupName);
+        }
+        if(group.hasUser(usertoRemoved)){
+            group.removeUser(usertoRemoved);    
+        }else{
+            throw new XregistryException("No such User "+ usertoRemoved);
+        }
+        
+    }
+    
+    /* (non-Javadoc)
+     * @see xregistry.auth.GroupManager#removeGroupFromGroup(java.lang.String, java.lang.String)
+     */
+    public void removeGroupFromGroup(String groupName,String grouptoRemovedName)throws XregistryException{
+        //DELETE FROM group_group_table WHERE AND contained_groupid = ?  AND groupid = ?
+        Group group = getGroup(groupName);
+        Group groupToRemove = getGroup(groupName);
+        if(group == null){
+            throw new XregistryException("No such group "+ groupName);
+        }
+        if(grouptoRemovedName == null){
+            throw new XregistryException("No such group "+ grouptoRemovedName);
+        }
+        group.removeGroup(groupToRemove);
+        genericUpdate(REMOVE_GROUP_FROM_GROUP, new String[]{grouptoRemovedName,groupName});
+    }
+    
+    
+    
+    /* (non-Javadoc)
+     * @see xregistry.auth.GroupManager#listUsers()
+     */
+    public String[]  listUsers()throws XregistryException{
+        Connection connection = context.createConnection();
+        ArrayList<String> users = new ArrayList<String>();
+        try{
+            Statement statement = connection.createStatement();
+            ResultSet results = statement.executeQuery(SQLConstants.GET_ALL_USERS_SQL);
+            while(results.next()){
+                String userID = results.getString(USERID);
+                users.add(userID);
+            }
+        }catch(SQLException e){
+            throw new XregistryException(e);
+        }finally{
+            context.closeConnection(connection);
+        }
+        return Utils.toStrListToArray(users);
+    }
+    /* (non-Javadoc)
+     * @see xregistry.auth.GroupManager#listGroups()
+     */
+    public String[]  listGroups()throws XregistryException{
+        Connection connection = context.createConnection();
+        ArrayList<String> groups = new ArrayList<String>();
+        try{
+            Statement statement = connection.createStatement();
+            ResultSet results = statement.executeQuery(SQLConstants.GET_ALL_GROUPS_SQL);
+            while(results.next()){
+                String groupId = results.getString(GROUPID);
+                groups.add(groupId);
+            }
+        }catch(SQLException e){
+            throw new XregistryException(e);
+        }finally{
+            context.closeConnection(connection);
+        }
+        return Utils.toStrListToArray(groups);
+    }
+    /* (non-Javadoc)
+     * @see xregistry.auth.GroupManager#listGroupsGivenAUser(java.lang.String)
+     */
+    public String[]  listGroupsGivenAUser(String user)throws XregistryException{
+        user = canonicalizeDN(user);
+        Connection connection = context.createConnection();
+        ArrayList<String> groups = new ArrayList<String>();
+        try {
+            PreparedStatement statement = connection.prepareStatement(GET_GROUPS_GIVEN_USER);
+            statement.setString(1,user );
+            
+            ResultSet results = statement.executeQuery();
+            while(results.next()){
+                String groupId = results.getString(GROUPID);
+                groups.add(groupId);
+            }
+        } catch (SQLException e) {
+            throw new XregistryException(e);
+        }finally{
+            context.closeConnection(connection);
+        }
+        return Utils.toStrListToArray(groups);
+    }
+    /* (non-Javadoc)
+     * @see xregistry.auth.GroupManager#listUsersGivenAGroup(java.lang.String)
+     */
+    public Actor[]  listSubActorsGivenAGroup(String group)throws XregistryException{
+        List<Actor> actorList = new ArrayList<Actor>();
+        Connection connection = context.createConnection();
+        
+        try {
+            PreparedStatement statement = connection.prepareStatement(GET_USERS_GIVEN_GROUP);
+            statement.setString(1,group );
+            
+            ResultSet results = statement.executeQuery();
+            while(results.next()){
+                String groupId = results.getString(USERID);
+                Actor actor = Actor.Factory.newInstance();
+                actor.setActor(groupId);
+                actor.setIsUser(true);
+                actorList.add(actor);
+            }
+            results.close();
+            statement.close();
+            
+            statement = connection.prepareStatement(GET_SUBGROUPS_GIVEN_GROUP);
+            statement.setString(1,group );
+            results = statement.executeQuery();
+            while(results.next()){
+                String groupId = results.getString(CONTANTED_GROUP_ID);
+                Actor actor = Actor.Factory.newInstance();
+                actor.setActor(groupId);
+                actor.setIsUser(false);
+                actorList.add(actor);
+            }
+            
+        } catch (SQLException e) {
+            throw new XregistryException(e);
+        }finally{
+            context.closeConnection(connection);
+        }
+        return actorList.toArray(new Actor[0]);        
+    }
+
+    public Collection<Group> getGroups(){
+        return groups.values();
+    }
+    
+    public User getUser(String user){
+        return users.get(user);
+    }
+    
+    
+}
+

Added: incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/group/Traversal.java
URL: http://svn.apache.org/viewvc/incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/group/Traversal.java?rev=1139850&view=auto
==============================================================================
--- incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/group/Traversal.java (added)
+++ incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/group/Traversal.java Sun Jun 26 17:50:29 2011
@@ -0,0 +1,33 @@
+/*
+* 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.group;
+
+import java.util.HashMap;
+
+public class Traversal {
+    private HashMap<String,Group> visited = new HashMap<String, Group>();
+    
+    public void addVisited(Group group){
+        visited.put(group.getName(), group);
+    }
+    
+    public boolean hasVisited(Group group){
+        return visited.containsKey(group.getName());
+    }
+}
+

Added: incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/group/User.java
URL: http://svn.apache.org/viewvc/incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/group/User.java?rev=1139850&view=auto
==============================================================================
--- incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/group/User.java (added)
+++ incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/group/User.java Sun Jun 26 17:50:29 2011
@@ -0,0 +1,45 @@
+/*
+* 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.group;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class User {
+    private String userName;
+    private Map<String,String> authorizedResources = new HashMap<String, String>();
+    public User(String userName) {
+        this.userName = userName;
+    }
+    public Map<String, String> getAuthorizedResources() {
+        return authorizedResources;
+    }
+    public String getUserName() {
+        return userName;
+    }
+    
+    public void addAuthorizedResource(String resourceID,String action){
+        authorizedResources.put(resourceID, action);
+    }
+    
+    public boolean removeAuthorizedResource(String resourceID){
+        return authorizedResources.remove(resourceID) != null;
+    }
+    
+}
+

Added: incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/impl/XregistryHttpbasedServices.java
URL: http://svn.apache.org/viewvc/incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/impl/XregistryHttpbasedServices.java?rev=1139850&view=auto
==============================================================================
--- incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/impl/XregistryHttpbasedServices.java (added)
+++ incubator/airavata/services/trunk/xregistry/src/main/java/org/apache/airavata/xregistry/impl/XregistryHttpbasedServices.java Sun Jun 26 17:50:29 2011
@@ -0,0 +1,161 @@
+/*
+* 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.impl;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.xml.namespace.QName;
+
+import org.apache.airavata.xregistry.XregistryConstants;
+import org.apache.airavata.xregistry.XregistryException;
+import org.apache.airavata.xregistry.utils.Utils;
+
+import xsul.MLogger;
+import xsul.http_server.HttpMiniServer;
+import xsul.http_server.HttpServerException;
+import xsul.http_server.HttpServerRequest;
+import xsul.http_server.HttpServerResponse;
+import xsul.http_server.ServerSocketFactory;
+import xsul.message_router.MessageContext;
+import xsul.processor.DynamicInfosetProcessorException;
+import xsul.xservo_soap_http.HttpBasedServices;
+
+public class XregistryHttpbasedServices extends HttpBasedServices {
+    protected static MLogger log = MLogger.getLogger(XregistryConstants.LOGGER_NAME);
+    private static Pattern restReqPattern = Pattern.compile(".*xregistry/(.*?)/(.*?)");
+    
+    private XregistryImpl xregistryImpl;
+ 
+    public XregistryHttpbasedServices(HttpMiniServer server, XregistryImpl xregistryPortType)
+            throws DynamicInfosetProcessorException {
+        super(server);
+        this.xregistryImpl = xregistryPortType;
+    }
+
+    public XregistryHttpbasedServices(int tcpPort, XregistryImpl xregistryPortType)
+            throws DynamicInfosetProcessorException {
+        super(tcpPort);
+        this.xregistryImpl = xregistryPortType;
+    }
+
+    public XregistryHttpbasedServices(ServerSocketFactory serverSocketFactory,
+            XregistryImpl xregistryPortType) throws DynamicInfosetProcessorException {
+        super(serverSocketFactory);
+        this.xregistryImpl = xregistryPortType;
+    }
+
+    @Override
+    public void service(HttpServerRequest req, HttpServerResponse res) throws HttpServerException {
+        try {
+            String method = req.getMethod();
+            String path = req.getPath();
+            if (method.equals("GET") && path.startsWith("/xregistry/")) {
+                String[] parameters = parseURL(path);
+                String docType =  parameters[0];
+                String documentName = parameters[1];
+
+                String result = null;
+                OutputStream out = res.getOutputStream();
+                
+                if (docType.equals("servicedesc")) {
+                    result = xregistryImpl.getServiceDesc(findUserDN(), documentName);
+                } else if (docType.equals("appdesc")) {
+                    String[] params = documentName.split("#");
+                    result = xregistryImpl.getAppDesc(findUserDN(), params[0], parameters[1]);
+                } else if (docType.equals("servicedesc")) {
+                } else if (docType.equals("hostdesc")) {
+                    result = xregistryImpl.getHostDesc(findUserDN(), documentName);
+                } else if (docType.equals("cwsdl")) {
+                    result = xregistryImpl.getConcreateWsdl(findUserDN(), documentName);
+                } else if (docType.equals("awsdl")) {
+                    result = xregistryImpl.getAbstractWsdl(findUserDN(), documentName);
+                } else if (docType.equals("doc")) {
+                    result = xregistryImpl.getDocument(findUserDN(), QName.valueOf(documentName));
+                }
+                res.setContentType("text/xml");
+                out.write(result.getBytes());
+            }else{
+                super.service(req, res);
+            }
+        } catch (XregistryException e) {
+            throw new HttpServerException(e.getMessage(), e);
+        } catch (IOException e) {
+            throw new HttpServerException(e.getMessage(), e);
+        }
+    }
+
+    
+    public static String[] parseURL(String requestUrl) throws XregistryException{
+        try {
+            Matcher matcher = restReqPattern.matcher(requestUrl);
+            if(matcher.matches()){
+                return new String[]{matcher.group(1),URLDecoder.decode(matcher.group(2),"UTF-8")};
+            }
+            return null;
+        } catch (UnsupportedEncodingException e) {
+            throw new XregistryException(e);
+        }
+    }
+    
+//    private String[] parsePath(String path) {
+//        ArrayList<String> params = new ArrayList<String>(5);
+//        StringBuffer buffer = new StringBuffer();
+//        boolean skip = false;
+//        for(char c:path.toCharArray()){
+//            switch(c){
+//                case '/':
+//                    if(!skip){
+//                        params.add(buffer.toString());
+//                        buffer.setLength(0);
+//                    }else{
+//                        buffer.append(c);
+//                    }
+//                    break;
+//                case '(': skip = true;buffer.append('{');break; 
+//                case ')': skip = false;buffer.append('}');break;
+//                default:
+//                    buffer.append(c);
+//            }
+//        }
+//        return params.toArray(new String[]{});
+//    }
+
+    private String findUserDN() {
+        // /C=US/O=National Center for Supercomputing Applications/CN=LEAD
+        // Community User
+
+        // return "/C=US/O=National Center for Supercomputing
+        // Applications/CN=Hemapani Srinath Perera";
+        String userDN = null;
+        MessageContext mc = xsul.xhandler_context.ServerContextAccessHandler.getContext();
+        if (mc != null) {
+            userDN = mc.getIncomingUserDn();
+        }
+
+        if (userDN == null) {
+            userDN = XregistryConstants.ANONYMOUS_USER;
+        }
+        userDN = Utils.canonicalizeDN(userDN);
+        log.info("Invoker = " + userDN);
+        return userDN;
+    }
+}



Mime
View raw message