package com.dbxml.db.core.security;

/*
 * dbXML - Native XML Database
 * Copyright (C) 1999-2004  The dbXML Group, L.L.C.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * $Id: AccessUtils.java,v 1.3 2004/02/12 00:17:57 bradford Exp $
 */

import com.dbxml.db.common.adapters.XMLSerializableAdapter;
import com.dbxml.db.common.xpath.XPathQueryResolver;
import com.dbxml.db.core.Collection;
import com.dbxml.db.core.DBException;
import com.dbxml.db.core.Database;
import com.dbxml.db.core.SystemCollection;
import com.dbxml.db.core.adapter.Adapter;
import com.dbxml.db.core.data.Key;
import com.dbxml.db.core.query.ResultSet;
import com.dbxml.db.core.transaction.Transaction;
import com.dbxml.util.SoftHashMap;
import com.dbxml.xml.dtsm.DTSMException;
import com.dbxml.xml.dtsm.DTSMHelper;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

/**
 * AccessUtils manages Users, Roles, and Access control lists for dbXML.
 * This class is provided as a convenience engine for SecurityManager
 * implementations, though some SecurityManagers may choose to utilize
 * other methods of managing permissions.
 */

public final class AccessUtils {
   private static final String[] EmptyStrings = new String[0];

   private Map userCache = Collections.synchronizedMap(new SoftHashMap());
   private Map roleCache = Collections.synchronizedMap(new SoftHashMap());
   private Map accessCache = Collections.synchronizedMap(new SoftHashMap());

   private Database database;
   private XMLSerializableAdapter userCol;
   private XMLSerializableAdapter roleCol;
   private XMLSerializableAdapter accessCol;

   public AccessUtils(Database database) {
      this.database = database;
   }

   private void checkAccess(Adapter col, int permissions) throws SecurityException {
      database.getSecurityManager().access(col.getCanonicalName(), permissions);
   }

   public String[] listUsers() throws DBException {
      Transaction tx = new Transaction();
      try {
			XMLSerializableAdapter col = getUsersCollection();
			Key[] keys = col.listKeys(tx);
			String[] result = new String[keys.length];
			for ( int i = 0; i < keys.length; i++ )
				result[i] = keys[i].toString();
         return result;
      }
      catch ( DBException e ) {
         tx.cancel();
         throw e;
      }
		finally {
			if ( tx.getStatus() == Transaction.ACTIVE )
				tx.commit();
		}
   }

   public User readUser(String userID) throws InvalidUserException {
      Transaction tx = new Transaction();
      try {
			XMLSerializableAdapter col = getUsersCollection();
         User user = (User)userCache.get(userID);
			if ( user != null ) {
				// Perform access check for cached items
				checkAccess(col, Access.READ);
			}
			else {
            user = (User)col.getObject(tx, userID);
				if ( user != null )
            	userCache.put(userID, user);
				else
		         throw new InvalidUserException("User '"+userID+"' doesn't exist");
         }
         return user;
      }
      catch ( DBException e ) {
         try {
            tx.cancel();
         }
         catch ( DBException ex ) {
            ex.printStackTrace(System.err);
         }
         throw new InvalidUserException("Unknown User '"+userID+"'", e);
      }
		finally {
			if ( tx.getStatus() == Transaction.ACTIVE ) {
				try {
					tx.commit();
				}
				catch ( DBException e ) {
					e.printStackTrace(System.err);
				}
			}
		}
   }

   public void storeUser(User user) throws DBException {
      Transaction tx = new Transaction();
      try {
         XMLSerializableAdapter col = getUsersCollection();
         String userID = user.getId();
         col.setObject(tx, userID, user);
         userCache.put(userID, user);
      }
      catch ( DBException e ) {
         tx.cancel();
         throw e;
      }
		finally {
			if ( tx.getStatus() == Transaction.ACTIVE )
				tx.commit();
		}
   }

   public void removeUser(User user) throws DBException {
      Transaction tx = new Transaction();
      try {
         XMLSerializableAdapter col = getUsersCollection();
			String userID = user.getId();

         col.remove(tx, userID);
         userCache.remove(userID);
      }
      catch ( DBException e ) {
         tx.cancel();
         throw e;
      }
		finally {
			if ( tx.getStatus() == Transaction.ACTIVE )
				tx.commit();
		}
   }

   public String[] listRoles() throws DBException {
      Transaction tx = new Transaction();
      try {
         XMLSerializableAdapter col = getRolesCollection();
			Key[] keys = col.listKeys(tx);
			String[] result = new String[keys.length];
			for ( int i = 0; i < keys.length; i++ )
				result[i] = keys[i].toString();
         return result;
      }
      catch ( DBException e ) {
         tx.cancel();
         throw e;
      }
		finally {
			if ( tx.getStatus() == Transaction.ACTIVE )
				tx.commit();
		}
   }

   public String[] listUsersForRole(String roleID) throws DBException {
      Transaction tx = new Transaction();
      try {
         XMLSerializableAdapter col = getUsersCollection();
         String queryString = "/user[role[.='"+roleID+"']]/@id";
         ResultSet rs = col.queryCollection(tx, XPathQueryResolver.STYLE_XPATH, queryString, null);
         Set roles = new TreeSet();
         while ( rs.next() ) {
            try {
               String userID = DTSMHelper.tableToText(rs.getResult());
               roles.add(userID);
            }
            catch ( DTSMException e ) {
               // Should never happen
            }
         }
			return (String[])roles.toArray(EmptyStrings);
      }
      catch ( DBException e ) {
         tx.cancel();
         throw e;
      }
		finally {
			if ( tx.getStatus() == Transaction.ACTIVE )
				tx.commit();
		}
   }

   public Role readRole(String roleID) throws InvalidRoleException {
      Transaction tx = new Transaction();
      try {
			XMLSerializableAdapter col = getRolesCollection();
         Role role = (Role)roleCache.get(roleID);
			if ( role != null ) {
				// Perform access check for cached items
				checkAccess(col, Access.READ);
			}
			else {
            role = (Role)col.getObject(tx, roleID);
				if ( role != null )
            	roleCache.put(roleID, role);
				else
		         throw new InvalidUserException("Role '"+roleID+"' doesn't exist");
         }
         return role;
      }
      catch ( DBException e ) {
         try {
            tx.cancel();
         }
         catch ( DBException ex ) {
            ex.printStackTrace(System.err);
         }
         throw new InvalidRoleException("Unknown Role '"+roleID+"'", e);
      }
		finally {
			if ( tx.getStatus() == Transaction.ACTIVE ) {
				try {
					tx.commit();
				}
				catch ( DBException e ) {
					e.printStackTrace(System.err);
				}
			}
		}
   }

   public void storeRole(Role role) throws DBException {
      Transaction tx = new Transaction();
      try {
         XMLSerializableAdapter col = getRolesCollection();
         String roleID = role.getId();
         col.setObject(tx, roleID, role);
         roleCache.put(roleID, role);
      }
      catch ( DBException e ) {
         tx.cancel();
         throw e;
      }
		finally {
			if ( tx.getStatus() == Transaction.ACTIVE )
				tx.commit();
		}
   }

   public void removeRole(Role role) throws DBException {
      Transaction tx = new Transaction();
      try {
			String roleID = role.getId();

         XMLSerializableAdapter col = getRolesCollection();
         col.remove(tx, roleID);
         roleCache.remove(roleID);

         col = getUsersCollection();
         String queryString = "/user[role[.='"+roleID+"']]/@id";
         ResultSet rs = col.queryCollection(tx, XPathQueryResolver.STYLE_XPATH, queryString, null);
         while ( rs.next() ) {
            try {
               String userID = DTSMHelper.tableToText(rs.getResult());
               User user = readUser(userID);
               user.removeRole(role);
               storeUser(user);
            }
            catch ( DTSMException e ) {
               // Should never happen
            }
         }

         col = getAccessCollection();
         queryString = "/access[role[.='"+roleID+"']]/path/text()";
         rs = col.queryCollection(tx, XPathQueryResolver.STYLE_XPATH, queryString, null);
         while ( rs.next() ) {
            try {
               String path = DTSMHelper.tableToText(rs.getResult());
               Access access = readAccess(path);
               access.removePermissions(role);
               storeAccess(access);
            }
            catch ( DTSMException e ) {
            }
         }
      }
      catch ( DBException e ) {
         tx.cancel();
         throw e;
      }
		finally {
			if ( tx.getStatus() == Transaction.ACTIVE )
				tx.commit();
		}
   }

   public String[] listPaths() throws DBException {
      Transaction tx = new Transaction();
      try {
         XMLSerializableAdapter col = getAccessCollection();
			Key[] keys = col.listKeys(tx);
			String[] result = new String[keys.length];
			for ( int i = 0; i < keys.length; i++ )
				result[i] = keys[i].toString();
         return result;
      }
      catch ( DBException e ) {
         tx.cancel();
         throw e;
      }
		finally {
			if ( tx.getStatus() == Transaction.ACTIVE )
				tx.commit();
		}
   }

   public Access readAccess(String path) throws InvalidAccessException {
      Transaction tx = new Transaction();
      try {
         XMLSerializableAdapter col = getAccessCollection();
         Access access = (Access)accessCache.get(path);
			if ( access != null ) {
				// Perform access check for cached items
				checkAccess(col, Access.READ);
			}
			else {
            access = (Access)col.getObject(tx, path);
				if ( access == null ) {
					access = new Access();
					access.setPath(path);
				}
            accessCache.put(path, access);
         }
         return access;
      }
      catch ( DBException e ) {
         try {
            tx.cancel();
         }
         catch ( DBException ex ) {
            ex.printStackTrace(System.err);
         }
         throw new InvalidAccessException("Can't retrieve Access list for '"+path+"'", e);
      }
		finally {
			if ( tx.getStatus() == Transaction.ACTIVE ) {
				try {
					tx.commit();
				}
				catch ( DBException e ) {
					e.printStackTrace(System.err);
				}
			}
		}
   }

   public void storeAccess(Access access) throws DBException {
      Transaction tx = new Transaction();
      try {
         XMLSerializableAdapter col = getAccessCollection();
         String path = access.getPath();
         col.setObject(tx, path, access);
         accessCache.put(path, access);
      }
      catch ( DBException e ) {
         tx.cancel();
         throw e;
      }
		finally {
			if ( tx.getStatus() == Transaction.ACTIVE )
				tx.commit();
		}
   }

   public void removeAccess(String path) throws DBException {
      Transaction tx = new Transaction();
      try {
         XMLSerializableAdapter col = getAccessCollection();
         col.remove(tx, path);
         accessCache.remove(path);
      }
      catch ( DBException e ) {
         tx.cancel();
         throw e;
      }
		finally {
			if ( tx.getStatus() == Transaction.ACTIVE )
				tx.commit();
		}
   }

   private XMLSerializableAdapter getUsersCollection() throws DBException {
      if ( userCol == null ) {
         Collection sysCol = database.getSystemCollection();
         Collection col = sysCol.getCollection(SystemCollection.USERS);
         userCol = new XMLSerializableAdapter(col);
      }
      return userCol;
   }

   private XMLSerializableAdapter getRolesCollection() throws DBException {
      if ( roleCol == null ) {
         Collection sysCol = database.getSystemCollection();
         Collection col = sysCol.getCollection(SystemCollection.ROLES);
         roleCol = new XMLSerializableAdapter(col);
      }
      return roleCol;
   }

   private XMLSerializableAdapter getAccessCollection() throws DBException {
      if ( accessCol == null ) {
         Collection sysCol = database.getSystemCollection();
         Collection col = sysCol.getCollection(SystemCollection.ACCESS);
         accessCol = new XMLSerializableAdapter(col);
      }
      return accessCol;
   }
}



