FileDocCategorySizeDatePackage
MemoryUserDatabase.javaAPI DocApache Tomcat 6.0.1422647Fri Jul 20 04:20:36 BST 2007org.apache.catalina.users

MemoryUserDatabase

public class MemoryUserDatabase extends Object implements org.apache.catalina.UserDatabase

Concrete implementation of {@link UserDatabase} that loads all defined users, groups, and roles into an in-memory data structure, and uses a specified XML file for its persistent storage.

author
Craig R. McClanahan
version
$Revision: 467222 $ $Date: 2006-10-24 05:17:11 +0200 (mar., 24 oct. 2006) $
since
4.1

Fields Summary
private static org.apache.juli.logging.Log
log
protected HashMap
groups
The set of {@link Group}s defined in this database, keyed by group name.
protected String
id
The unique global identifier of this user database.
protected String
pathname
The relative (to catalina.base) or absolute pathname to the XML file in which we will save our persistent information.
protected String
pathnameOld
The relative or absolute pathname to the file in which our old information is stored while renaming is in progress.
protected String
pathnameNew
The relative or absolute pathname ot the file in which we write our new information prior to renaming.
protected boolean
readonly
A flag, indicating if the user database is read only.
protected HashMap
roles
The set of {@link Role}s defined in this database, keyed by role name.
private static org.apache.catalina.util.StringManager
sm
The string manager for this package.
protected HashMap
users
The set of {@link User}s defined in this database, keyed by user name.
Constructors Summary
public MemoryUserDatabase()
Create a new instance with default values.


    // ----------------------------------------------------------- Constructors


                
      

        super();

    
public MemoryUserDatabase(String id)
Create a new instance with the specified values.

param
id Unique global identifier of this user database


        super();
        this.id = id;

    
Methods Summary
public voidclose()
Finalize access to this user database.

exception
Exception if any exception is thrown during closing


        save();

        synchronized (groups) {
            synchronized (users) {
                users.clear();
                groups.clear();
            }
        }

    
public org.apache.catalina.GroupcreateGroup(java.lang.String groupname, java.lang.String description)
Create and return a new {@link Group} defined in this user database.

param
groupname The group name of the new group (must be unique)
param
description The description of this group


        MemoryGroup group = new MemoryGroup(this, groupname, description);
        synchronized (groups) {
            groups.put(group.getGroupname(), group);
        }
        return (group);

    
public org.apache.catalina.RolecreateRole(java.lang.String rolename, java.lang.String description)
Create and return a new {@link Role} defined in this user database.

param
rolename The role name of the new group (must be unique)
param
description The description of this group


        MemoryRole role = new MemoryRole(this, rolename, description);
        synchronized (roles) {
            roles.put(role.getRolename(), role);
        }
        return (role);

    
public org.apache.catalina.UsercreateUser(java.lang.String username, java.lang.String password, java.lang.String fullName)
Create and return a new {@link User} defined in this user database.

param
username The logon username of the new user (must be unique)
param
password The logon password of the new user
param
fullName The full name of the new user


        MemoryUser user = new MemoryUser(this, username, password, fullName);
        synchronized (users) {
            users.put(user.getUsername(), user);
        }
        return (user);

    
public org.apache.catalina.GroupfindGroup(java.lang.String groupname)
Return the {@link Group} with the specified group name, if any; otherwise return null.

param
groupname Name of the group to return


        synchronized (groups) {
            return ((Group) groups.get(groupname));
        }

    
public org.apache.catalina.RolefindRole(java.lang.String rolename)
Return the {@link Role} with the specified role name, if any; otherwise return null.

param
rolename Name of the role to return


        synchronized (roles) {
            return ((Role) roles.get(rolename));
        }

    
public org.apache.catalina.UserfindUser(java.lang.String username)
Return the {@link User} with the specified user name, if any; otherwise return null.

param
username Name of the user to return


        synchronized (users) {
            return ((User) users.get(username));
        }

    
public java.util.IteratorgetGroups()
Return the set of {@link Group}s defined in this user database.



    // ------------------------------------------------------------- Properties


                    
       

        synchronized (groups) {
            return (groups.values().iterator());
        }

    
public java.lang.StringgetId()
Return the unique global identifier of this user database.


        return (this.id);

    
public java.lang.StringgetPathname()
Return the relative or absolute pathname to the persistent storage file.


        return (this.pathname);

    
public booleangetReadonly()
Returning the readonly status of the user database


        return (this.readonly);

    
public java.util.IteratorgetRoles()
Return the set of {@link Role}s defined in this user database.


        synchronized (roles) {
            return (roles.values().iterator());
        }

    
org.apache.catalina.util.StringManagergetStringManager()
Return the StringManager for use in looking up messages.


        return (sm);

    
public java.util.IteratorgetUsers()
Return the set of {@link User}s defined in this user database.


        synchronized (users) {
            return (users.values().iterator());
        }

    
public booleanisWriteable()
Check for permissions to save this user database to persistent storage location


        File file = new File(pathname);
        if (!file.isAbsolute()) {
            file = new File(System.getProperty("catalina.base"),
                            pathname);
        }
        File dir = file.getParentFile();
        return dir.exists() && dir.isDirectory() && dir.canWrite();

    
public voidopen()
Initialize access to this user database.

exception
Exception if any exception is thrown during opening


        synchronized (groups) {
            synchronized (users) {

                // Erase any previous groups and users
                users.clear();
                groups.clear();
                roles.clear();

                // Construct a reader for the XML input file (if it exists)
                File file = new File(pathname);
                if (!file.isAbsolute()) {
                    file = new File(System.getProperty("catalina.base"),
                                    pathname);
                }
                if (!file.exists()) {
                    return;
                }
                FileInputStream fis = new FileInputStream(file);

                // Construct a digester to read the XML input file
                Digester digester = new Digester();
                digester.addFactoryCreate
                    ("tomcat-users/group",
                     new MemoryGroupCreationFactory(this));
                digester.addFactoryCreate
                    ("tomcat-users/role",
                     new MemoryRoleCreationFactory(this));
                digester.addFactoryCreate
                    ("tomcat-users/user",
                     new MemoryUserCreationFactory(this));

                // Parse the XML input file to load this database
                try {
                    digester.parse(fis);
                    fis.close();
                } catch (Exception e) {
                    try {
                        fis.close();
                    } catch (Throwable t) {
                        ;
                    }
                    throw e;
                }

            }
        }

    
public voidremoveGroup(org.apache.catalina.Group group)
Remove the specified {@link Group} from this user database.

param
group The group to be removed


        synchronized (groups) {
            Iterator users = getUsers();
            while (users.hasNext()) {
                User user = (User) users.next();
                user.removeGroup(group);
            }
            groups.remove(group.getGroupname());
        }

    
public voidremoveRole(org.apache.catalina.Role role)
Remove the specified {@link Role} from this user database.

param
role The role to be removed


        synchronized (roles) {
            Iterator groups = getGroups();
            while (groups.hasNext()) {
                Group group = (Group) groups.next();
                group.removeRole(role);
            }
            Iterator users = getUsers();
            while (users.hasNext()) {
                User user = (User) users.next();
                user.removeRole(role);
            }
            roles.remove(role.getRolename());
        }

    
public voidremoveUser(org.apache.catalina.User user)
Remove the specified {@link User} from this user database.

param
user The user to be removed


        synchronized (users) {
            users.remove(user.getUsername());
        }

    
public voidsave()
Save any updated information to the persistent storage location for this user database.

exception
Exception if any exception is thrown during saving


        if (getReadonly()) {
            return;
        }

        if (!isWriteable()) {
            log.warn(sm.getString("memoryUserDatabase.notPersistable"));
            return;
        }

        // Write out contents to a temporary file
        File fileNew = new File(pathnameNew);
        if (!fileNew.isAbsolute()) {
            fileNew =
                new File(System.getProperty("catalina.base"), pathnameNew);
        }
        PrintWriter writer = null;
        try {

            // Configure our PrintWriter
            FileOutputStream fos = new FileOutputStream(fileNew);
            OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF8");
            writer = new PrintWriter(osw);

            // Print the file prolog
            writer.println("<?xml version='1.0' encoding='utf-8'?>");
            writer.println("<tomcat-users>");

            // Print entries for each defined role, group, and user
            Iterator values = null;
            values = getRoles();
            while (values.hasNext()) {
                writer.print("  ");
                writer.println(values.next());
            }
            values = getGroups();
            while (values.hasNext()) {
                writer.print("  ");
                writer.println(values.next());
            }
            values = getUsers();
            while (values.hasNext()) {
                writer.print("  ");
                writer.println(values.next());
            }

            // Print the file epilog
            writer.println("</tomcat-users>");

            // Check for errors that occurred while printing
            if (writer.checkError()) {
                writer.close();
                fileNew.delete();
                throw new IOException
                    (sm.getString("memoryUserDatabase.writeException",
                                  fileNew.getAbsolutePath()));
            }
            writer.close();
        } catch (IOException e) {
            if (writer != null) {
                writer.close();
            }
            fileNew.delete();
            throw e;
        }

        // Perform the required renames to permanently save this file
        File fileOld = new File(pathnameOld);
        if (!fileOld.isAbsolute()) {
            fileOld =
                new File(System.getProperty("catalina.base"), pathnameOld);
        }
        fileOld.delete();
        File fileOrig = new File(pathname);
        if (!fileOrig.isAbsolute()) {
            fileOrig =
                new File(System.getProperty("catalina.base"), pathname);
        }
        if (fileOrig.exists()) {
            fileOld.delete();
            if (!fileOrig.renameTo(fileOld)) {
                throw new IOException
                    (sm.getString("memoryUserDatabase.renameOld",
                                  fileOld.getAbsolutePath()));
            }
        }
        if (!fileNew.renameTo(fileOrig)) {
            if (fileOld.exists()) {
                fileOld.renameTo(fileOrig);
            }
            throw new IOException
                (sm.getString("memoryUserDatabase.renameNew",
                              fileOrig.getAbsolutePath()));
        }
        fileOld.delete();

    
public voidsetPathname(java.lang.String pathname)
Set the relative or absolute pathname to the persistent storage file.

param
pathname The new pathname


        this.pathname = pathname;
        this.pathnameOld = pathname + ".old";
        this.pathnameNew = pathname + ".new";

    
public voidsetReadonly(boolean readonly)
Setting the readonly status of the user database

param
pathname The new pathname


        this.readonly = readonly;

    
public java.lang.StringtoString()
Return a String representation of this UserDatabase.


        StringBuffer sb = new StringBuffer("MemoryUserDatabase[id=");
        sb.append(this.id);
        sb.append(",pathname=");
        sb.append(pathname);
        sb.append(",groupCount=");
        sb.append(this.groups.size());
        sb.append(",roleCount=");
        sb.append(this.roles.size());
        sb.append(",userCount=");
        sb.append(this.users.size());
        sb.append("]");
        return (sb.toString());