KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > struts > webapp > example > memory > MemoryDatabasePlugIn


1 /*
2  * $Id: MemoryDatabasePlugIn.java 54929 2004-10-16 16:38:42Z germuska $
3  *
4  * Copyright 2000-2004 Apache Software Foundation
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */

18 package org.apache.struts.webapp.example.memory;
19
20
21 import java.io.BufferedInputStream JavaDoc;
22 import java.io.BufferedOutputStream JavaDoc;
23 import java.io.File JavaDoc;
24 import java.io.FileOutputStream JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import javax.servlet.ServletException JavaDoc;
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.logging.LogFactory;
29 import org.apache.struts.action.ActionServlet;
30 import org.apache.struts.action.PlugIn;
31 import org.apache.struts.config.ModuleConfig;
32 import org.apache.struts.webapp.example.Constants;
33
34 /**
35  * <p><strong>MemoryDatabasePlugIn</strong> initializes and finalizes the
36  * persistent storage of User and Subscription information for the Struts
37  * Demonstration Application, using an in-memory database backed by an
38  * XML file.</p>
39  *
40  * <p><strong>IMPLEMENTATION WARNING</strong> - If this web application is run
41  * from a WAR file, or in another environment where reading and writing of the
42  * web application resource is impossible, the initial contents will be copied
43  * to a file in the web application temporary directory provided by the
44  * container. This is for demonstration purposes only - you should
45  * <strong>NOT</strong> assume that files written here will survive a restart
46  * of your servlet container.</p>
47  *
48  * @version $Rev: 54929 $ $Date: 2004-10-16 17:38:42 +0100 (Sat, 16 Oct 2004) $
49  */

50
51 public final class MemoryDatabasePlugIn implements PlugIn {
52
53
54     // ----------------------------------------------------- Instance Variables
55

56
57     /**
58      * The {@link MemoryUserDatabase} object we construct and make available.
59      */

60     private MemoryUserDatabase database = null;
61
62
63     /**
64      * Logging output for this plug in instance.
65      */

66     private Log log = LogFactory.getLog(this.getClass());
67
68
69     /**
70      * The {@link ActionServlet} owning this application.
71      */

72     private ActionServlet servlet = null;
73
74
75     // ------------------------------------------------------------- Properties
76

77
78     /**
79      * The web application resource path of our persistent database
80      * storage file.
81      */

82     private String JavaDoc pathname = "/WEB-INF/database.xml";
83
84     public String JavaDoc getPathname() {
85         return (this.pathname);
86     }
87
88     public void setPathname(String JavaDoc pathname) {
89         this.pathname = pathname;
90     }
91
92
93     // --------------------------------------------------------- PlugIn Methods
94

95
96     /**
97      * Gracefully shut down this database, releasing any resources
98      * that were allocated at initialization.
99      */

100     public void destroy() {
101
102         log.info("Finalizing memory database plug in");
103
104         if (database != null) {
105             try {
106                 database.close();
107             } catch (Exception JavaDoc e) {
108                 log.error("Closing memory database", e);
109             }
110         }
111
112     servlet.getServletContext().removeAttribute(Constants.DATABASE_KEY);
113         database = null;
114         servlet = null;
115         database = null;
116     }
117
118
119     /**
120      * Initialize and load our initial database from persistent storage.
121      *
122      * @param servlet The ActionServlet for this web application
123      * @param config The ApplicationConfig for our owning module
124      *
125      * @exception ServletException if we cannot configure ourselves correctly
126      */

127     public void init(ActionServlet servlet, ModuleConfig config)
128         throws ServletException JavaDoc {
129
130         log.info("Initializing memory database plug in from '" +
131                  pathname + "'");
132
133         // Remember our associated configuration and servlet
134
this.servlet = servlet;
135
136         // Construct a new database and make it available
137
database = new MemoryUserDatabase();
138         try {
139             String JavaDoc path = calculatePath();
140             if (log.isDebugEnabled()) {
141                 log.debug(" Loading database from '" + path + "'");
142             }
143             database.setPathname(path);
144             database.open();
145         } catch (Exception JavaDoc e) {
146             log.error("Opening memory database", e);
147             throw new ServletException JavaDoc("Cannot load database from '" +
148                                        pathname + "'", e);
149         }
150
151         // Make the initialized database available
152
servlet.getServletContext().setAttribute(Constants.DATABASE_KEY,
153                                                  database);
154
155     }
156
157
158     // --------------------------------------------------------- Public Methods
159

160
161     // ------------------------------------------------------ Protected Methods
162

163
164     // -------------------------------------------------------- Private Methods
165

166
167     /**
168      * Calculate and return an absolute pathname to the XML file to contain
169      * our persistent storage information.
170      *
171      * @exception Exception if an input/output error occurs
172      */

173     private String JavaDoc calculatePath() throws Exception JavaDoc {
174
175         // Can we access the database via file I/O?
176
String JavaDoc path = servlet.getServletContext().getRealPath(pathname);
177         if (path != null) {
178             return (path);
179         }
180
181         // Does a copy of this file already exist in our temporary directory
182
File JavaDoc dir = (File JavaDoc)
183             servlet.getServletContext().getAttribute
184             ("javax.servlet.context.tempdir");
185         File JavaDoc file = new File JavaDoc(dir, "struts-example-database.xml");
186         if (file.exists()) {
187             return (file.getAbsolutePath());
188         }
189
190         // Copy the static resource to a temporary file and return its path
191
InputStream JavaDoc is =
192             servlet.getServletContext().getResourceAsStream(pathname);
193         BufferedInputStream JavaDoc bis = new BufferedInputStream JavaDoc(is, 1024);
194         FileOutputStream JavaDoc os =
195             new FileOutputStream JavaDoc(file);
196         BufferedOutputStream JavaDoc bos = new BufferedOutputStream JavaDoc(os, 1024);
197         byte buffer[] = new byte[1024];
198         while (true) {
199             int n = bis.read(buffer);
200             if (n <= 0) {
201                 break;
202             }
203             bos.write(buffer, 0, n);
204         }
205         bos.close();
206         bis.close();
207         return (file.getAbsolutePath());
208
209     }
210
211
212 }
213
Popular Tags