/*
ESUP-portail is a french academic project developed under the GPL (General Public License) augmented according to the following :
A binary or source file developped by ESUP-portail can be used or compiled with products under Apache license.
The official english text of the GPL can be found here : http://www.gnu.org/licenses/gpl.html .
A non official french translation can be found here : http://www.linux-France.org/article/these/gpl.html .
The different kinds of licenses governing the products developed by the Apache foundation can be found here : http://www.apache.org/licenses .
It follows that you can as well as use download contents as well modify and redistribute them provided you respect the GPL terms.
Downloading and using such contents do not provide any guaranty.
Be sure that you have well understood the terms of the license before using the contents it covers.
The ESUP-portail distribution includes the following distributions :
    * UPortal :
      software developed by JA-SIG (Java Architecture - Special Interest Group)
      You can find the license page here : http://mis105.udel.edu/ja-sig/uportal/license.html
    * CAS :
      SSO solution developed by Yale University
      You can find the project page here : http://www.yale.edu/tp/auth
    * Cocoon :
      XML framework distributed by the Apache foundation under Apache license;
      Please find the full text here : http://cocoon.apache.org/2.1/license.html
    * Mod_dav:
      A DAV module for Apache web server
      You can find the project page here : http://www.webdav.org/mod_dav
    * IMP :
      webmail from Horde application framework
      You can find the project page here : http://www.horde.org
    * …. To be completed
*/
package org.esupportail.portal.channels.CStockage.channelAction.classic.sharing;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.Vector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ojb.broker.util.GUID;
import org.esupportail.portal.channels.CStockage.config.Server;
import org.esupportail.portal.channels.CStockage.config.Space;
import org.esupportail.portal.channels.CStockage.exception.AclAccessException;
import org.esupportail.portal.channels.CStockage.exception.AclReadException;
import org.esupportail.portal.channels.CStockage.exception.AclWriteException;
import org.esupportail.portal.channels.CStockage.exception.DataBaseException;
import org.esupportail.portal.channels.CStockage.exception.NotSupportedAclException;
import org.esupportail.portal.channels.CStockage.exception.PropertiesException;
import org.esupportail.portal.channels.CStockage.exception.ServerException;
import org.esupportail.portal.channels.CStockage.provider.access.ServerAccess;
import org.esupportail.portal.channels.CStockage.spacesPersonalization.DataBaseAccess;
import org.esupportail.portal.channels.CStockage.spacesPersonalization.ServerTool;
import org.esupportail.portal.channels.CStockage.spacesPersonalization.target.GroupForPersonalization;
import org.esupportail.portal.channels.CStockage.spacesPersonalization.target.UserForPersonalization;
import org.esupportail.portal.utils.webdav.acl.EsupPermission;
import org.esupportail.portal.utils.webdav.acl.EsupPermissions;

/**
 * Id: SharingTool.java,v 1.0 13 janv. 2005
 * Copyright (c) 2005 Esup Portail (www.esup-portail.org)
 * Classes: SharingTool
 * Original Author: Yohan Colmant
 * This class is a tool used to manage the sharing actions
 */
public class SharingTool {

	/**
	 * Logger object
	 */
	protected static final Log log = LogFactory.getLog(SharingTool.class);
	
	
	/**
	 * The object used to access the database
	 */
	private DataBaseAccess dbAccess;
	
	
	/**
	 * If the server into the database is administrated
	 */
	public static final String ADMINISTRATED_SERVER = "administrated_server";

	
	/**
	 * Constructor
	 * @throws PropertiesException
	 */
	public SharingTool() throws PropertiesException {
		dbAccess = new DataBaseAccess();		
	}
	

	

	
	
	
	
	/******************
	 *    SHARING 
	 *****************/
	
	
	

	/**
	 * Return the server name with the url of the server and the path
	 * @param serverUrl the url of the server
	 * @param path the path on the server
	 * @return the server name with the url of the server and the path
	 */
	private static String getServerName(String serverUrl, String path) {
		return serverUrl+path;
	}
	
	
	
	

	/**
	 * Get the users for whose the resource is shared
	 * @param serverUrl the url of the server
	 * @param path the path of the resource
	 * @return an object array composed by one Space and 2 hashtables. The first hashtable contains users, the second contains groups
	 * @throws DataBaseException
	 * @throws PropertiesException
	 * @throws ServerException
	 * @throws AclReadException
	 * @throws AclAccessException
	 * @throws AclWriteException
	 * @throws NotSupportedAclException
	 */
	/*public Object[] getTargetsOfAvailableSpace(Space currentSpace, String serverUrl, String path) throws DataBaseException, PropertiesException, ServerException {

		Space sharedSpace = null;
		Hashtable users = new Hashtable();
		Hashtable groups = new Hashtable();
		
		// do the request
		Vector result = dbAccess.getTargetsOfAvailableSpace(getServerName(serverUrl, path));
		
		// get the server object
		if (result!=null && result.size()!=0) {
			
			String[] line = (String[])result.elementAt(0);
			String serverId = line[0];
			String serverXml = line[1];
			
			ServerTool spaceTool = new ServerTool(serverXml);
			ArrayList spaces = spaceTool.getSpaces();
			
			sharedSpace = (Space)spaces.get(0);
			sharedSpace.getServer().setId(serverId);
		
		
			// for each user and group
			for (int i=0; result!=null && i<result.size(); i++) {
				line = (String[])result.elementAt(i);
				
				String availableSpaceTargetId = line[2];
				String targetKey = line[3];
				String targetIsUser = line[4];
				String read = line[5];
				String write = line[6];
				String share = line[7];
				
				// if the target is a user
				if (targetIsUser.equals("T")) {
					UserForPersonalization user = new UserForPersonalization(targetKey);
					user.setIdOfSharing(availableSpaceTargetId);
					user.setReading(read);
					user.setWriting(write);
					user.setSharing(share);
					users.put(user.getKey(), user);
				}
				
				// the target is a group
				else {
					GroupForPersonalization group = new GroupForPersonalization(targetKey, null);
					group.setIdOfSharing(availableSpaceTargetId);
					group.setReading(read);
					group.setWriting(write);
					group.setSharing(share);
					groups.put(group.getKey(), group);
				}
			}
		}
		else {
			Server ser = (Server)currentSpace.getServer().clone();
			Space spa = (Space)currentSpace.clone();
			
			ArrayList list = new ArrayList(1);
			list.add(spa);
			ser.setSpaces(list);
			ser.setId(null);
			
			spa.setServer(ser);
			
			sharedSpace = spa;
			sharedSpace.setLabel(null);
			sharedSpace.setKey(null);
		}
		
		// return the result
		Object[] res = new Object[3];
		res[0] = sharedSpace;
		res[1] = users;
		res[2] = groups;
		return res;
	}*/
	public Object[] getTargetsOfAvailableSpace(Space currentSpace, String serverUrl, String path) throws DataBaseException, PropertiesException, ServerException, AclReadException, AclAccessException, AclWriteException, NotSupportedAclException {

		if (currentSpace.managesAcl()) {
			return getTargetsOfAvailableSpaceFromAcl(currentSpace, serverUrl, path);
		}
		else {
			return getTargetsOfAvailableSpaceFromDatabase(currentSpace, serverUrl, path);
		}
		
	}
	
	
	/**
	 * Get the users for whose the resource is shared from the database
	 * @param serverUrl the url of the server
	 * @param path the path of the resource
	 * @return an object array composed by one Space and 2 hashtables. The first hashtable contains users, the second contains groups
	 * @throws DataBaseException
	 * @throws PropertiesException
	 * @throws ServerException
	 */
	private Object[] getTargetsOfAvailableSpaceFromDatabase(Space currentSpace, String serverUrl, String path) throws DataBaseException, PropertiesException, ServerException {

		Space sharedSpace = null;
		Hashtable users = new Hashtable();
		Hashtable groups = new Hashtable();
		
		// do the request
		Vector result = dbAccess.getTargetsOfAvailableSpace(getServerName(serverUrl, path));
		
		// get the server object
		if (result!=null && result.size()!=0) {
			
			String[] line = (String[])result.elementAt(0);
			String serverId = line[0];
			String serverXml = line[1];
			
			ServerTool spaceTool = new ServerTool(serverXml);
			ArrayList spaces = spaceTool.getSpaces();
			
			sharedSpace = (Space)spaces.get(0);
			sharedSpace.getServer().setId(serverId);
		
		
			// for each user and group
			for (int i=0; result!=null && i<result.size(); i++) {
				line = (String[])result.elementAt(i);
				
				String availableSpaceTargetId = line[2];
				String targetKey = line[3];
				String targetIsUser = line[4];
				String read = line[5];
				String write = line[6];
				String share = line[7];
				
				// if the target is a user
				if (targetIsUser.equals("T")) {
					UserForPersonalization user = new UserForPersonalization(targetKey);
					user.setIdOfSharing(availableSpaceTargetId);
					user.setReading(read);
					user.setWriting(write);
					user.setSharing(share);
					users.put(user.getKey(), user);
				}
				
				// the target is a group
				else {
					GroupForPersonalization group = new GroupForPersonalization(targetKey, null);
					group.setIdOfSharing(availableSpaceTargetId);
					group.setReading(read);
					group.setWriting(write);
					group.setSharing(share);
					groups.put(group.getKey(), group);
				}
			}
		}
		else {
			Server ser = (Server)currentSpace.getServer().clone();
			Space spa = (Space)currentSpace.clone();
			
			ArrayList list = new ArrayList(1);
			list.add(spa);
			ser.setSpaces(list);
			ser.setId(null);
			
			spa.setServer(ser);
			
			sharedSpace = spa;
			sharedSpace.setLabel(null);
			sharedSpace.setKey(null);
		}
		
		// return the result
		Object[] res = new Object[3];
		res[0] = sharedSpace;
		res[1] = users;
		res[2] = groups;
		return res;
	}
	
	
	
	/**
	 * Get the users for whose the resource is shared from the acl
	 * @param serverUrl the url of the server
	 * @param path the path of the resource
	 * @return an object array composed by one Space and 2 hashtables. The first hashtable contains users, the second contains groups
	 * @throws DataBaseException
	 * @throws PropertiesException
	 * @throws ServerException
	 * @throws AclReadException
	 * @throws AclAccessException
	 * @throws AclWriteException
	 * @throws NotSupportedAclException
	 */
	private Object[] getTargetsOfAvailableSpaceFromAcl(Space currentSpace, String serverUrl, String path) throws DataBaseException, PropertiesException, ServerException, AclReadException, AclAccessException, AclWriteException, NotSupportedAclException {

		Space sharedSpace = null;
		Hashtable users = new Hashtable();
		Hashtable groups = new Hashtable();
		
		// the acl attributes
		String aclUserPrefix = currentSpace.getAclUserPrefix();
		String aclGroupPrefix = currentSpace.getAclGroupPrefix();
		String aclUportalGroup = currentSpace.getAclUportalGroup();
		
		// get the acl
		EsupPermissions permissions = currentSpace.getServerAccessObject().getPermissions(path);
		
		// get the permissions not inherited and on users and groups
		Iterator iter = permissions.iterator();
		while (iter.hasNext()) {
			EsupPermission perm = (EsupPermission)iter.next();
			
			// if grant and not inherited
			if (perm.isGrantPermission() && !perm.isInherited()) {
				
				// if user
				if (perm.isPrincipalUser()) {
					String principal = perm.getPrincipal();
					
					String key = principal.substring(aclUserPrefix.length());
					//System.out.println("user: "+key+" "+perm.getPermissionType());
					
					Object o = users.get(key);
					UserForPersonalization user = null;
					if (o!=null) {
						user = (UserForPersonalization)o;
					}
					else {
						user = new UserForPersonalization(key);
						users.put(key, user);
					}
					
					if (perm.getPermissionType().equals(EsupPermission.READ)) {
						user.setReading(true);
					}
					else {
						if (perm.getPermissionType().equals(EsupPermission.WRITE)) {
							user.setWriting(true);
						}
						else {
							if (perm.getPermissionType().equals(EsupPermission.WRITE_ACL)) {
								user.setSharing(true);
							}
							else {
								if (perm.getPermissionType().equals(EsupPermission.ALL)) {
									user.setReading(true);
									user.setWriting(true);
									user.setSharing(true);
									user.setModifiable(false);
								}
							}
						}
					}
					
				}
				
				// if group
				else if (perm.isPrincipalGroup()) {
					String principal = perm.getPrincipal();
					
					if (principal.startsWith(aclGroupPrefix+aclUportalGroup)) {
						String hierarchy = principal.substring((aclGroupPrefix+aclUportalGroup).length());
						
						StringTokenizer strToken = new StringTokenizer(hierarchy, "/");
						String key = "";
						while (strToken.hasMoreTokens()) {
							key = strToken.nextToken();
						}
						//System.out.println("group: "+key+" "+perm.getPermissionType());
						
						Object o = groups.get(key);
						GroupForPersonalization group = null;
						if (o!=null) {
							group = (GroupForPersonalization)o;
						}
						else {
							group = new GroupForPersonalization(hierarchy);
							groups.put(key, group);
						}
						
						if (perm.getPermissionType().equals(EsupPermission.READ)) {
							group.setReading(true);
						}
						else {
							if (perm.getPermissionType().equals(EsupPermission.WRITE)) {
								group.setWriting(true);
							}
							else {
								if (perm.getPermissionType().equals(EsupPermission.WRITE_ACL)) {
									group.setSharing(true);
								}
								else {
									if (perm.getPermissionType().equals(EsupPermission.ALL)) {
										group.setReading(true);
										group.setWriting(true);
										group.setSharing(true);
										group.setModifiable(false);
									}
								}
							}
						}
					}
				}
			}
		}
		//System.out.println("\n\n");
		
		
		
		// do the request to know the ids in the database
		Vector result = dbAccess.getTargetsOfAvailableSpace(getServerName(serverUrl, path));
		
		// get the server object
		if (result!=null && result.size()!=0) {
			
			String[] line = (String[])result.elementAt(0);
			String serverId = line[0];
			String serverXml = line[1];
			
			ServerTool spaceTool = new ServerTool(serverXml);
			ArrayList spaces = spaceTool.getSpaces();
			
			sharedSpace = (Space)spaces.get(0);
			sharedSpace.getServer().setId(serverId);
		}
		else {
			Server ser = (Server)currentSpace.getServer().clone();
			Space spa = (Space)currentSpace.clone();
			
			ArrayList list = new ArrayList(1);
			list.add(spa);
			ser.setSpaces(list);
			ser.setId(null);
			
			spa.setServer(ser);
			
			sharedSpace = spa;
			sharedSpace.setLabel(null);
			sharedSpace.setKey(null);
		}
		
		// return the result
		Object[] res = new Object[3];
		res[0] = sharedSpace;
		res[1] = users;
		res[2] = groups;
		return res;
	}
	
	
	
	
	
	
	
	
	
	/**
	 * Add sharing properties for the users and groups into the database
	 * @param currentSpace the current space we are using
	 * @param sharedSpace the space we are sharing
	 * @param serverUrl the url of the server
	 * @param fromKey the key of the people who shares
	 * @param path the resource path
	 * @param users the target users
	 * @param groups the target groups
	 * @throws DataBaseException
	 * @throws AclAccessException
	 * @throws AclWriteException
	 * @throws AclReadException
	 * @throws NotSupportedAclException
	 * @throws PropertiesException
	 */
	public void addStorageAvailableSpace(Space currentSpace, Space sharedSpace, String serverUrl, String fromKey, String path, Vector users, Vector groups) throws DataBaseException, AclAccessException, AclWriteException, AclReadException, NotSupportedAclException, PropertiesException {
	
		////////////////////////
		// add into the database
		
		// the server id
		String serverId = sharedSpace.getServer().getId();
		
		// if serverId == null, we generate a new id
		if (serverId == null) {
			serverId = new GUID().toString();
			sharedSpace.getServer().setId(serverId);
		}
		
		// for each space, we generate a key
		ArrayList spaces = sharedSpace.getServer().getSpaces();
		for (int i=0; i<spaces.size(); i++) {
			Space s = (Space)spaces.get(i);
			if (s.getKey() == null)
				s.setKey(new GUID().toString());
		}

		// the xml server
		String xmlServer = sharedSpace.getXml();

		// we add the server sharing to the database
		dbAccess.addStorageAvailableSpace(serverId, getServerName(serverUrl, path), xmlServer, fromKey);
		
		// the users
		for (int i=0; i<users.size(); i++) {
			
			UserForPersonalization user = (UserForPersonalization)users.elementAt(i);
			
			// if we don't have this, we add into database
			dbAccess.addStorageAvailableSpaceTarget(user.getKey(), true, user.isReading(), user.isWriting(), user.isSharing(), serverId, sharedSpace.getKey(), false);			
		
		
			/////////////////////
			// set the ACL rights
			if (currentSpace.managesAcl()) {		
				ServerAccess access = currentSpace.getServerAccessObject();
				String principal = currentSpace.getAclUserPrefix()+user.getKey();
				if (user.isReading() && user.isWriting() && user.isSharing()) {
					access.grant(path, principal, EsupPermission.READ);
					access.grant(path, principal, EsupPermission.WRITE);
					// TODO
					access.grant(path, principal, EsupPermission.READ_ACL);
					access.grant(path, principal, EsupPermission.WRITE_ACL);
				}
				else {
					if (user.isWriting() && user.isReading()) {
						access.grant(path, principal, EsupPermission.READ);
						access.grant(path, principal, EsupPermission.WRITE);
					}
					else {
						if (user.isReading()) {
							access.grant(path, principal, EsupPermission.READ);
						}
					}
				}
			}
		}
		

		// the groups
		for (int i=0; i<groups.size(); i++) {
			
			GroupForPersonalization group = (GroupForPersonalization)groups.elementAt(i);
			
			// if we don't have this, we add into database
			dbAccess.addStorageAvailableSpaceTarget(group.getKey(), false, group.isReading(), group.isWriting(), group.isSharing(), serverId, sharedSpace.getKey(), false);			
		
			/////////////////////
			// set the ACL rights
			if (currentSpace.managesAcl()) {
				Vector groupHierarchyKey = group.getGroupHierarchy();
				if (groupHierarchyKey!=null) {
					String principal = currentSpace.getAclGroupPrefix();
					if (currentSpace.getAclUportalGroup()!=null && !currentSpace.getAclUportalGroup().trim().equals("")) {
						principal = principal+currentSpace.getAclUportalGroup()+"/";
					}
					for (int j=0; j<groupHierarchyKey.size(); j++) {
						principal = principal + groupHierarchyKey.elementAt(j);
						if (j!=groupHierarchyKey.size()-1)
							principal = principal + "/";
					}
					
					ServerAccess access = currentSpace.getServerAccessObject();
					if (group.isReading() && group.isWriting() && group.isSharing()) {
						access.grant(path, principal, EsupPermission.READ);
						access.grant(path, principal, EsupPermission.WRITE);
						// 	TODO
						access.grant(path, principal, EsupPermission.READ_ACL);
						access.grant(path, principal, EsupPermission.WRITE_ACL);
					}
					else {
						if (group.isWriting() && group.isReading()) {
							access.grant(path, principal, EsupPermission.READ);
							access.grant(path, principal, EsupPermission.WRITE);
						}
						else {
							if (group.isReading()) {
								access.grant(path, principal, EsupPermission.READ);
							}
						}
					}
				}
			}
		}
	}
	


	
	
	
	

	/**
	 * Delete sharing properties for users into the database
	 * @param currentSpace the current space
	 * @param users we want to delete preferences
	 * @param serverId the id of the server
	 * @throws DataBaseException
	 * @throws AclAccessException
	 * @throws AclWriteException
	 * @throws AclReadException
	 * @throws NotSupportedAclException
	 * @throws PropertiesException
	 */
	public void delStorageAvailableSpaceForUsers(Space currentSpace, Vector users, String serverId) throws DataBaseException, AclAccessException, AclWriteException, AclReadException, NotSupportedAclException, PropertiesException {
		
		// for each user
		for(int i=0; i<users.size(); i++) {
		
			UserForPersonalization user = (UserForPersonalization)users.elementAt(i);
			
			// delete from the database
			String id = user.getIdOfSharing();
			dbAccess.delStorageUsersPreferences(id);
			dbAccess.delStorageAvailableSpaceTarget(id);		
		
			// remove the ACL
			if (currentSpace.managesAcl()) {
				String principal = currentSpace.getAclUserPrefix()+user.getKey();
				currentSpace.getServerAccessObject().revoke(currentSpace.getCurrentPath(), principal, EsupPermission.READ);
				currentSpace.getServerAccessObject().revoke(currentSpace.getCurrentPath(), principal, EsupPermission.WRITE);
				//TODO 
				currentSpace.getServerAccessObject().revoke(currentSpace.getCurrentPath(), principal, EsupPermission.READ_ACL);
				currentSpace.getServerAccessObject().revoke(currentSpace.getCurrentPath(), principal, EsupPermission.WRITE_ACL);
			}
		}
		
		// check if we have to delete from the available spaces table
		Vector v = dbAccess.getTargetsOfAvailableSpace(getServerName(currentSpace.getUrl(), currentSpace.getCurrentPath()));
		if (v==null || v.size() == 0) {
			dbAccess.delStorageAvailableSpace(serverId);
		}
		
		
	}
	
	
	
	


	/**
	 * Delete sharing properties for groups into the database
	 * @param currentSpace the current space
	 * @param groups the groups we want to delete sharing
	 * @param serverId the id of the server
	 * @throws DataBaseException
	 * @throws AclAccessException
	 * @throws AclWriteException
	 * @throws AclReadException
	 * @throws NotSupportedAclException
	 * @throws PropertiesException
	 */
	public void delStorageAvailableSpaceForGroups(Space currentSpace, Vector groups, String serverId) throws DataBaseException, AclAccessException, AclWriteException, AclReadException, NotSupportedAclException, PropertiesException {

		// for each group
		for(int i=0; i<groups.size(); i++) {
		
			GroupForPersonalization group = (GroupForPersonalization)groups.elementAt(i);
		
			// delete from the database
			String id = group.getIdOfSharing();		
			dbAccess.delStorageUsersPreferences(id);
			dbAccess.delStorageAvailableSpaceTarget(id);
		
			// remove the ACL
			if (currentSpace.managesAcl()) {
				Vector groupHierarchyKey = group.getGroupHierarchy();
				if (groupHierarchyKey!=null) {
					String principal = currentSpace.getAclGroupPrefix();
					if (currentSpace.getAclUportalGroup()!=null && !currentSpace.getAclUportalGroup().trim().equals("")) {
						principal = principal+currentSpace.getAclUportalGroup()+"/";
					}
					for (int j=0; j<groupHierarchyKey.size(); j++) {
						principal = principal + groupHierarchyKey.elementAt(j);
						if (j!=groupHierarchyKey.size()-1)
							principal = principal + "/";
					}
					
					currentSpace.getServerAccessObject().revoke(currentSpace.getCurrentPath(), principal, EsupPermission.READ);
					currentSpace.getServerAccessObject().revoke(currentSpace.getCurrentPath(), principal, EsupPermission.WRITE);
					//TODO
					currentSpace.getServerAccessObject().revoke(currentSpace.getCurrentPath(), principal, EsupPermission.READ_ACL);
					currentSpace.getServerAccessObject().revoke(currentSpace.getCurrentPath(), principal, EsupPermission.WRITE_ACL);
				}
			}
		}

		// check if we have to delete from the available spaces table
		Vector v = dbAccess.getTargetsOfAvailableSpace(getServerName(currentSpace.getUrl(), currentSpace.getCurrentPath()));
		if (v==null || v.size() == 0) {
			dbAccess.delStorageAvailableSpace(serverId);
		}
		
		
	}
	
	
	
	/**
	 * Update the "reading" and "writing" attributes for a specifical sharing for a user
	 * @param currentSpace the current space
	 * @param users the target users
	 * @throws DataBaseException
	 * @throws AclAccessException
	 * @throws AclWriteException
	 * @throws AclReadException
	 * @throws NotSupportedAclException
	 * @throws PropertiesException
	 */
	public void updateReadAndWriteAndShareSpaceUsers(Space currentSpace, Vector users)throws DataBaseException, AclAccessException, AclWriteException, AclReadException, NotSupportedAclException, PropertiesException {


		// for each group
		for (int i=0; i<users.size(); i++) {
		
			UserForPersonalization user = (UserForPersonalization)users.elementAt(i);
			
			// update the database		
			dbAccess.updateReadAndWriteAndShareSpace(user.isReading(), user.isWriting(), user.isSharing(), user.isObliged(), user.getIdOfSharing());
			
			// update the ACL
			if (currentSpace.managesAcl()) {
				String path = currentSpace.getCurrentPath();
				
				String principal = currentSpace.getAclUserPrefix()+user.getKey();
				ServerAccess access = currentSpace.getServerAccessObject();
				access.revoke(currentSpace.getCurrentPath(), principal, EsupPermission.READ);
				access.revoke(currentSpace.getCurrentPath(), principal, EsupPermission.WRITE);
				access.revoke(currentSpace.getCurrentPath(), principal, EsupPermission.READ_ACL);
				access.revoke(currentSpace.getCurrentPath(), principal, EsupPermission.WRITE_ACL);
				if (user.isReading() && user.isWriting() && user.isSharing()) {
					access.grant(path, principal, EsupPermission.READ);
					access.grant(path, principal, EsupPermission.WRITE);
					// TODO
					access.grant(path, principal, EsupPermission.READ_ACL);
					access.grant(path, principal, EsupPermission.WRITE_ACL);
				}
				else {
					if (user.isWriting() && user.isReading()) {
						access.grant(path, principal, EsupPermission.READ);
						access.grant(path, principal, EsupPermission.WRITE);
					}
					else {
						if (user.isReading()) {
							access.grant(path, principal, EsupPermission.READ);
						}
					}
				}
			}
		}
	}

	
	/**
	 * Update the "reading" and "writing" attributes for a specifical sharing for a group
	 * @param currentSpace the current space
	 * @param groups the target groups
	 * @throws DataBaseException
	 * @throws AclAccessException
	 * @throws AclWriteException
	 * @throws AclReadException
	 * @throws NotSupportedAclException
	 * @throws PropertiesException
	 */
	public void updateReadAndWriteAndShareSpaceGroups(Space currentSpace, Vector groups)throws DataBaseException, AclAccessException, AclWriteException, AclReadException, NotSupportedAclException, PropertiesException {

		// for each group
		for (int i=0; i<groups.size(); i++) {
		
			GroupForPersonalization group = (GroupForPersonalization)groups.elementAt(i);
			
			// update the database
			dbAccess.updateReadAndWriteAndShareSpace(group.isReading(), group.isWriting(), group.isSharing(), group.isObliged(), group.getIdOfSharing());

			// update the ACL
			if (currentSpace.managesAcl()) {
				String path = currentSpace.getCurrentPath();
				
				Vector groupHierarchyKey = group.getGroupHierarchy();				
				if (groupHierarchyKey!=null) {
					String principal = currentSpace.getAclGroupPrefix();
					if (currentSpace.getAclUportalGroup()!=null && !currentSpace.getAclUportalGroup().trim().equals("")) {
						principal = principal+currentSpace.getAclUportalGroup()+"/";
					}
					for (int j=0; j<groupHierarchyKey.size(); j++) {
						principal = principal + groupHierarchyKey.elementAt(j);
						if (j!=groupHierarchyKey.size()-1)
							principal = principal + "/";
					}
					
					ServerAccess access = currentSpace.getServerAccessObject();
					access.revoke(currentSpace.getCurrentPath(), principal, EsupPermission.READ);
					access.revoke(currentSpace.getCurrentPath(), principal, EsupPermission.WRITE);
					access.revoke(currentSpace.getCurrentPath(), principal, EsupPermission.READ_ACL);
					access.revoke(currentSpace.getCurrentPath(), principal, EsupPermission.WRITE_ACL);
					if (group.isReading() && group.isWriting() && group.isSharing()) {
						access.grant(path, principal, EsupPermission.READ);
						access.grant(path, principal, EsupPermission.WRITE);
						// 	TODO
						access.grant(path, principal, EsupPermission.READ_ACL);
						access.grant(path, principal, EsupPermission.WRITE_ACL);
					}
					else {
						if (group.isWriting() && group.isReading()) {
							access.grant(path, principal, EsupPermission.READ);
							access.grant(path, principal, EsupPermission.WRITE);
						}
						else {
							if (group.isReading()) {
								access.grant(path, principal, EsupPermission.READ);
							}
						}
					}
				}
			}
		}
		
	}
	
	
	

	/**
	 * Update the label of the sharing properties into the database for users
	 * @param sharedSpace the space we are sharing
	 * @throws DataBaseException
	 */
	public void updateXmlServerAvailableSpace(Space sharedSpace) throws DataBaseException {

		// update the database
		dbAccess.updateXmlServerAvailableSpace(sharedSpace.getXml(), sharedSpace.getServer().getId());

	}
	
	


	/**
	 * Delete sharing properties for url and path into the database
	 * @param url the url of the space
	 * @param path the path of the space
	 * @throws DataBaseException
	 */
	public void delStorageAvailableSpaceForSpecifiedPath(String url, String path) throws DataBaseException {
 
		// get ids of spaces with the specified url and path
		Vector[] ids = dbAccess.getIdOfSpacesWithServerName(getServerName(url, path));
		Vector id_storage_available_spaces = ids[0];
		Vector id_storage_available_spaces_targets = ids[1];
		
		// for each we delete from preferences database
		for (int i=0; i<id_storage_available_spaces_targets.size(); i++) {
			String id = (String)id_storage_available_spaces_targets.elementAt(i);
			
			// delete from the database			
			dbAccess.delStorageUsersPreferences(id);
			dbAccess.delStorageAvailableSpaceTarget(id);
		}
		
		// for each id, we delete from the 2 tables in database
		for (int i=0; i<id_storage_available_spaces.size(); i++) {
			String id = (String)id_storage_available_spaces.elementAt(i);
			
			// delete from the database			
			dbAccess.delStorageAvailableSpace(id);
		}
			
	}

	

	/**
	 * Update the path of shared spaces
	 * @param url the url of the space
	 * @param oldPath the old path of the space
	 * @param newPath the new path of the space
	 * @return the result of the query
	 * @throws DataBaseException
	 */
	public void updatePathOfSharing(String url, String oldPath, String newPath) throws DataBaseException {

		// get ids and xml with specified url and path
		Vector[] res = dbAccess.getIdAndXmlOfSharing(getServerName(url, oldPath));
		
		// replace into xml the path
		Vector xmls = res[1];
		Vector xmlsReplace = new Vector();
		for (int i=0; i<xmls.size(); i++) {
			String xml = (String)xmls.elementAt(i);
			String xmlReplace = xml.replaceAll("path=\""+oldPath+"\"", "path=\""+newPath+"\"");
			xmlsReplace.add(xmlReplace);
		}
		
		// set new path and xml
		Vector ids = res[0];
		for (int i=0; i<ids.size(); i++) {
			String id = (String)ids.elementAt(i);
			String xml = (String)xmlsReplace.elementAt(i);
			dbAccess.updatePathOfSharing(getServerName(url, newPath), xml, id);
		}
			
	}
	
	
	
	
}
