FileDocCategorySizeDatePackage
MemoryUserDatabase.javaAPI DocExample14408Sun Mar 07 19:48:42 GMT 2004org.apache.struts.webapp.example.memory

MemoryUserDatabase

public final class MemoryUserDatabase extends Object implements org.apache.struts.webapp.example.UserDatabase

Concrete implementation of {@link UserDatabase} for an in-memory database backed by an XML data file.

author
Craig R. McClanahan
version
$Revision: 1.3 $ $Date: 2003/01/11 03:08:23 $
since
Struts 1.1

Fields Summary
private Log
log
Logging output for this user database instance.
private HashMap
users
The {@link User}s associated with this UserDatabase, keyed by username.
private String
pathname
Absolute pathname to the persistent file we use for loading and storing persistent data.
private String
pathnameOld
private String
pathnameNew
Constructors Summary
Methods Summary
public voidclose()

Finalize access to the underlying persistence layer.

exception
Exception if a database access error occurs


        save();

    
public org.apache.struts.webapp.example.UsercreateUser(java.lang.String username)

Create and return a new {@link User} defined in this user database.

param
username Username of the new user
exception
IllegalArgumentExceptionif the specified username is not unique


        synchronized (users) {
            if (users.get(username) != null) {
                throw new IllegalArgumentException("Duplicate user '" +
                                                   username + "'");
            }
            if (log.isTraceEnabled()) {
                log.trace("Creating user '" + username + "'");
            }
            MemoryUser user = new MemoryUser(this, username);
            synchronized (users) {
                users.put(username, user);
            }
            return (user);
        }

    
public org.apache.struts.webapp.example.UserfindUser(java.lang.String username)

Return the existing {@link User} with the specified username, if any; otherwise return null.

param
username Username of the user to retrieve


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

    
public org.apache.struts.webapp.example.User[]findUsers()

Return the set of {@link User}s defined in this user database.


        synchronized (users) {
            User results[] = new User[users.size()];
            return ((User[]) users.values().toArray(results));
        }

    
public java.lang.StringgetPathname()


       
        return (this.pathname);
    
public voidopen()

Initiate access to the underlying persistence layer.

exception
Exception if a database access error occurs


        FileInputStream fis = null;
        BufferedInputStream bis = null;

        try {

            // Acquire an input stream to our database file
            if (log.isDebugEnabled()) {
                log.debug("Loading database from '" + pathname + "'");
            }
            fis = new FileInputStream(pathname);
            bis = new BufferedInputStream(fis);

            // Construct a digester to use for parsing
            Digester digester = new Digester();
            digester.push(this);
            digester.setValidating(false);
            digester.addFactoryCreate
                ("database/user",
                 new MemoryUserCreationFactory(this));
            digester.addFactoryCreate
                ("database/user/subscription",
                 new MemorySubscriptionCreationFactory(this));

            // Parse the input stream to initialize our database
            digester.parse(bis);
            bis.close();
            bis = null;
            fis = null;

        } catch (Exception e) {

            log.error("Loading database from '" + pathname + "':", e);
            throw e;

        } finally {

            if (bis != null) {
                try {
                    bis.close();
                } catch (Throwable t) {
                    ;
                }
                bis = null;
                fis = null;
            }

        }

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

param
user User to be removed
exception
IllegalArgumentException if the specified user is not associated with this database


        if (!(this == user.getDatabase())) {
            throw new IllegalArgumentException
                ("User not associated with this database");
        }
        if (log.isTraceEnabled()) {
            log.trace("Removing user '" + user.getUsername() + "'");
        }
        synchronized (users) {
            users.remove(user.getUsername());
        }

    
public voidsave()

Save any pending changes to the underlying persistence layer.

exception
Exception if a database access error occurs


        if (log.isDebugEnabled()) {
            log.debug("Saving database to '" + pathname + "'");
        }
        File fileNew = new File(pathnameNew);
        PrintWriter writer = null;

        try {

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

            // Print the file prolog
            writer.println("<?xml version='1.0'?>");
            writer.println("<database>");

            // Print entries for each defined user and associated subscriptions
            User users[] = findUsers();
            for (int i = 0; i < users.length; i++) {
                writer.print("  ");
                writer.println(users[i]);
                Subscription subscriptions[] =
                    users[i].getSubscriptions();
                for (int j = 0; j < subscriptions.length; j++) {
                    writer.print("    ");
                    writer.println(subscriptions[j]);
                    writer.print("    ");
                    writer.println("</subscription>");
                }
                writer.print("  ");
                writer.println("</user>");
            }

            // Print the file epilog
            writer.println("</database>");

            // Check for errors that occurred while printing
            if (writer.checkError()) {
                writer.close();
                fileNew.delete();
                throw new IOException
                    ("Saving database to '" + pathname + "'");
            }
            writer.close();
            writer = null;

        } catch (IOException e) {

            if (writer != null) {
                writer.close();
            }
            fileNew.delete();
            throw e;

        }


        // Perform the required renames to permanently save this file
        File fileOrig = new File(pathname);
        File fileOld = new File(pathnameOld);
        if (fileOrig.exists()) {
            fileOld.delete();
            if (!fileOrig.renameTo(fileOld)) {
                throw new IOException
                    ("Renaming '" + pathname + "' to '" + pathnameOld + "'");
            }
        }
        if (!fileNew.renameTo(fileOrig)) {
            if (fileOld.exists()) {
                fileOld.renameTo(fileOrig);
            }
            throw new IOException
                ("Renaming '" + pathnameNew + "' to '" + pathname + "'");
        }
        fileOld.delete();

    
public voidsetPathname(java.lang.String pathname)

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