KickJava   Java API By Example, From Geeks To Geeks.

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


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

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

53
54 public final class MemoryDatabasePlugIn implements PlugIn {
55
56
57     // ----------------------------------------------------- Instance Variables
58

59
60     /**
61      * The application configuration for our owning module.
62      */

63     private ModuleConfig config = null;
64
65
66     /**
67      * The {@link MemoryUserDatabase} object we construct and make available.
68      */

69     private MemoryUserDatabase database = null;
70
71
72     /**
73      * Logging output for this plug in instance.
74      */

75     private Log log = LogFactory.getLog(this.getClass());
76
77
78     /**
79      * The {@link ActionServlet} owning this application.
80      */

81     private ActionServlet servlet = null;
82
83
84     // ------------------------------------------------------------- Properties
85

86
87     /**
88      * The web application resource path of our persistent database
89      * storage file.
90      */

91     private String JavaDoc pathname = "/WEB-INF/database.xml";
92
93     public String JavaDoc getPathname() {
94         return (this.pathname);
95     }
96
97     public void setPathname(String JavaDoc pathname) {
98         this.pathname = pathname;
99     }
100
101
102     // --------------------------------------------------------- PlugIn Methods
103

104
105     /**
106      * Gracefully shut down this database, releasing any resources
107      * that were allocated at initialization.
108      */

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

138     public void init(ActionServlet servlet, ModuleConfig config)
139         throws ServletException JavaDoc {
140
141         log.info("Initializing memory database plug in from '" +
142                  pathname + "'");
143
144         // Remember our associated configuration and servlet
145
this.config = config;
146         this.servlet = servlet;
147
148         // Construct a new database and make it available
149
database = new MemoryUserDatabase();
150         try {
151             String JavaDoc path = calculatePath();
152             if (log.isDebugEnabled()) {
153                 log.debug(" Loading database from '" + path + "'");
154             }
155             database.setPathname(path);
156             database.open();
157         } catch (Exception JavaDoc e) {
158             log.error("Opening memory database", e);
159             throw new ServletException JavaDoc("Cannot load database from '" +
160                                        pathname + "'", e);
161         }
162
163         // Make the initialized database available
164
servlet.getServletContext().setAttribute(Constants.DATABASE_KEY,
165                                                  database);
166
167         // Setup and cache other required data
168
setupCache(servlet, config);
169
170     }
171
172
173     // --------------------------------------------------------- Public Methods
174

175
176     // ------------------------------------------------------ Protected Methods
177

178
179     /**
180      * <p>Cache commonly required data as servlet context attributes.</p>
181      *
182      * @param servlet The <code>ActionServlet</code> instance running
183      * this webapp
184      * @param config The <code>ModuleConfig</code> for this application module
185      */

186     protected void setupCache(ActionServlet servlet, ModuleConfig config) {
187
188         // Set up list of server types under "serverTypes"
189
ArrayList JavaDoc serverTypes = new ArrayList JavaDoc();
190         serverTypes.add(new LabelValueBean("IMAP Protocol", "imap"));
191         serverTypes.add(new LabelValueBean("POP3 Protocol", "pop3"));
192         servlet.getServletContext().setAttribute("serverTypes", serverTypes);
193
194     }
195
196
197
198
199     // -------------------------------------------------------- Private Methods
200

201
202     /**
203      * Calculate and return an absolute pathname to the XML file to contain
204      * our persistent storage information.
205      *
206      * @exception Exception if an input/output error occurs
207      */

208     private String JavaDoc calculatePath() throws Exception JavaDoc {
209
210         // Can we access the database via file I/O?
211
String JavaDoc path = servlet.getServletContext().getRealPath(pathname);
212         if (path != null) {
213             return (path);
214         }
215
216         // Does a copy of this file already exist in our temporary directory
217
File JavaDoc dir = (File JavaDoc)
218             servlet.getServletContext().getAttribute
219             ("javax.servlet.context.tempdir");
220         File JavaDoc file = new File JavaDoc(dir, "struts-example-database.xml");
221         if (file.exists()) {
222             return (file.getAbsolutePath());
223         }
224
225         // Copy the static resource to a temporary file and return its path
226
InputStream JavaDoc is =
227             servlet.getServletContext().getResourceAsStream(pathname);
228         BufferedInputStream JavaDoc bis = new BufferedInputStream JavaDoc(is, 1024);
229         FileOutputStream JavaDoc os =
230             new FileOutputStream JavaDoc(file);
231         BufferedOutputStream JavaDoc bos = new BufferedOutputStream JavaDoc(os, 1024);
232         byte buffer[] = new byte[1024];
233         while (true) {
234             int n = bis.read(buffer);
235             if (n <= 0) {
236                 break;
237             }
238             bos.write(buffer, 0, n);
239         }
240         bos.close();
241         bis.close();
242         return (file.getAbsolutePath());
243
244     }
245
246
247 }
248
Popular Tags