FileDocCategorySizeDatePackage
ApplicationListener.javaAPI DocApache Struts 2.0.9 Apps7594Mon Jul 23 13:43:12 BST 2007mailreader2

ApplicationListener

public final class ApplicationListener extends Object implements ServletContextListener

ServletContextListener that initializes and finalizes the persistent storage of User and Subscription information for the Struts Demonstration Application, using an in-memory database backed by an XML file.

IMPLEMENTATION WARNING - If this web application is run from a WAR file, or in another environment where reading and writing of the web application resource is impossible, the initial contents will be copied to a file in the web application temporary directory provided by the container. This is for demonstration purposes only - you should NOT assume that files written here will survive a restart of your servlet container.

This class was borrowed from the Shale Mailreader. Changes were:

  • Path to database.xml (under classes here).
  • Class to store protocol list (an array here).

DEVELOPMENT NOTE - Another approach would be to instantiate the database via Spring.

Fields Summary
public static final String
DATABASE_KEY

Appication scope attribute key under which the in-memory version of our database is stored.

public static final String
PROTOCOLS_KEY

Application scope attribute key under which the valid selection items for the protocol property is stored.

private ServletContext
context

The ServletContext for this web application.

private org.apache.struts.apps.mailreader.dao.impl.memory.MemoryUserDatabase
database
The {@link MemoryUserDatabase} object we construct and make available.
private Log
log

Logging output for this plug in instance.

private String
pathname

The web application resource path of our persistent database storage file.

Constructors Summary
Methods Summary
private java.lang.StringcalculatePath()

Calculate and return an absolute pathname to the XML file to contain our persistent storage information.

throws
Exception if an input/output error occurs


        // Can we access the database via file I/O?
        String path = context.getRealPath(pathname);
        if (path != null) {
            return (path);
        }

        // Does a copy of this file already exist in our temporary directory
        File dir = (File)
                context.getAttribute("javax.servlet.context.tempdir");
        File file = new File(dir, "struts-example-database.xml");
        if (file.exists()) {
            return (file.getAbsolutePath());
        }

        // Copy the static resource to a temporary file and return its path
        InputStream is =
                context.getResourceAsStream(pathname);
        BufferedInputStream bis = new BufferedInputStream(is, 1024);
        FileOutputStream os =
                new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(os, 1024);
        byte buffer[] = new byte[1024];
        while (true) {
            int n = bis.read(buffer);
            if (n <= 0) {
                break;
            }
            bos.write(buffer, 0, n);
        }
        bos.close();
        bis.close();
        return (file.getAbsolutePath());

    
public voidcontextDestroyed(javax.servlet.ServletContextEvent event)

Gracefully shut down this database, releasing any resources that were allocated at initialization.

param
event ServletContextEvent to process


        log.info("Finalizing memory database plug in");

        if (database != null) {
            try {
                database.close();
            } catch (Exception e) {
                log.error("Closing memory database", e);
            }
        }

        context.removeAttribute(DATABASE_KEY);
        context.removeAttribute(PROTOCOLS_KEY);
        database = null;
        context = null;

    
public voidcontextInitialized(javax.servlet.ServletContextEvent event)

Initialize and load our initial database from persistent storage.

param
event The context initialization event


        log.info("Initializing memory database plug in from '" +
                pathname + "'");

        // Remember our associated ServletContext
        this.context = event.getServletContext();

        // Construct a new database and make it available
        database = new MemoryUserDatabase();
        try {
            String path = calculatePath();
            if (log.isDebugEnabled()) {
                log.debug(" Loading database from '" + path + "'");
            }
            database.setPathname(path);
            database.open();
        } catch (Exception e) {
            log.error("Opening memory database", e);
            throw new IllegalStateException("Cannot load database from '" +
                    pathname + "': " + e);
        }
        context.setAttribute(DATABASE_KEY, database);

    
public java.lang.StringgetPathname()

Return the application resource path to the database.

return
application resource path path to the database


                         
       
        return (this.pathname);
    
public voidsetPathname(java.lang.String pathname)

Set the application resource path to the database.

param
pathname to the database

        this.pathname = pathname;