KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * $Id: MemoryUserDatabase.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.File JavaDoc;
23 import java.io.FileInputStream JavaDoc;
24 import java.io.FileOutputStream JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.OutputStreamWriter JavaDoc;
27 import java.io.PrintWriter JavaDoc;
28 import java.util.HashMap JavaDoc;
29 import org.apache.commons.digester.Digester;
30 import org.apache.commons.digester.ObjectCreationFactory;
31 import org.apache.commons.logging.Log;
32 import org.apache.commons.logging.LogFactory;
33 import org.apache.struts.webapp.example.Subscription;
34 import org.apache.struts.webapp.example.User;
35 import org.apache.struts.webapp.example.UserDatabase;
36 import org.apache.struts.webapp.example.ExpiredPasswordException;
37 import org.xml.sax.Attributes JavaDoc;
38
39
40 /**
41  * <p>Concrete implementation of {@link UserDatabase} for an in-memory
42  * database backed by an XML data file.</p>
43  *
44  * @version $Rev: 54929 $ $Date: 2004-10-16 17:38:42 +0100 (Sat, 16 Oct 2004) $
45  * @since Struts 1.1
46  */

47
48 public class MemoryUserDatabase implements UserDatabase {
49
50
51     // ----------------------------------------------------------- Constructors
52

53
54     // ----------------------------------------------------- Instance Variables
55

56
57     /**
58      * Logging output for this user database instance.
59      */

60     private Log log = LogFactory.getLog(this.getClass());
61
62
63     /**
64      * The {@link User}s associated with this UserDatabase, keyed by username.
65      */

66     private HashMap JavaDoc users = new HashMap JavaDoc();
67
68
69     // ------------------------------------------------------------- Properties
70

71
72     /**
73      * Absolute pathname to the persistent file we use for loading and storing
74      * persistent data.
75      */

76     private String JavaDoc pathname = null;
77
78     private String JavaDoc pathnameOld = null;
79
80     private String JavaDoc pathnameNew = null;
81
82     public String JavaDoc getPathname() {
83         return (this.pathname);
84     }
85
86     public void setPathname(String JavaDoc pathname) {
87         this.pathname = pathname;
88         pathnameOld = pathname + ".old";
89         pathnameNew = pathname + ".new";
90     }
91
92
93     // --------------------------------------------------------- Public Methods
94

95
96     // See interface for Javadoc
97
public void close() throws Exception JavaDoc {
98
99         save();
100
101     }
102
103
104     // See interface for Javadoc
105
public User createUser(String JavaDoc username) {
106
107         synchronized (users) {
108             if (users.get(username) != null) {
109                 throw new IllegalArgumentException JavaDoc("Duplicate user '" +
110                                                    username + "'");
111             }
112             if (log.isTraceEnabled()) {
113                 log.trace("Creating user '" + username + "'");
114             }
115             MemoryUser user = new MemoryUser(this, username);
116             synchronized (users) {
117                 users.put(username, user);
118             }
119             return (user);
120         }
121
122     }
123
124
125     // See interface for Javadoc
126
public User findUser(String JavaDoc username) throws ExpiredPasswordException {
127
128         synchronized (users) {
129             return ((User) users.get(username));
130         }
131
132     }
133
134
135     // See interface for Javadoc
136
public User[] findUsers() {
137
138         synchronized (users) {
139             User results[] = new User[users.size()];
140             return ((User[]) users.values().toArray(results));
141         }
142
143     }
144
145
146     // See interface for Javadoc
147
public void open() throws Exception JavaDoc {
148
149         FileInputStream JavaDoc fis = null;
150         BufferedInputStream JavaDoc bis = null;
151
152         try {
153
154             // Acquire an input stream to our database file
155
if (log.isDebugEnabled()) {
156                 log.debug("Loading database from '" + pathname + "'");
157             }
158             fis = new FileInputStream JavaDoc(pathname);
159             bis = new BufferedInputStream JavaDoc(fis);
160
161             // Construct a digester to use for parsing
162
Digester digester = new Digester();
163             digester.push(this);
164             digester.setValidating(false);
165             digester.addFactoryCreate
166                 ("database/user",
167                  new MemoryUserCreationFactory(this));
168             digester.addFactoryCreate
169                 ("database/user/subscription",
170                  new MemorySubscriptionCreationFactory());
171
172             // Parse the input stream to initialize our database
173
digester.parse(bis);
174             bis.close();
175             bis = null;
176             fis = null;
177
178         } catch (Exception JavaDoc e) {
179
180             log.error("Loading database from '" + pathname + "':", e);
181             throw e;
182
183         } finally {
184
185             if (bis != null) {
186                 try {
187                     bis.close();
188                 } catch (Throwable JavaDoc t) {
189                     ;
190                 }
191                 bis = null;
192                 fis = null;
193             }
194
195         }
196
197     }
198
199
200     // See interface for Javadoc
201
public void removeUser(User user) {
202
203         if (!(this == user.getDatabase())) {
204             throw new IllegalArgumentException JavaDoc
205                 ("User not associated with this database");
206         }
207         if (log.isTraceEnabled()) {
208             log.trace("Removing user '" + user.getUsername() + "'");
209         }
210         synchronized (users) {
211             users.remove(user.getUsername());
212         }
213
214     }
215
216
217     // See interface for Javadoc
218
public void save() throws Exception JavaDoc {
219
220         if (log.isDebugEnabled()) {
221             log.debug("Saving database to '" + pathname + "'");
222         }
223         File JavaDoc fileNew = new File JavaDoc(pathnameNew);
224         PrintWriter JavaDoc writer = null;
225
226         try {
227
228             // Configure our PrintWriter
229
FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(fileNew);
230             OutputStreamWriter JavaDoc osw = new OutputStreamWriter JavaDoc(fos);
231             writer = new PrintWriter JavaDoc(osw);
232
233             // Print the file prolog
234
writer.println("<?xml version='1.0'?>");
235             writer.println("<database>");
236
237             // Print entries for each defined user and associated subscriptions
238
User users[] = findUsers();
239             for (int i = 0; i < users.length; i++) {
240                 writer.print(" ");
241                 writer.println(users[i]);
242                 Subscription subscriptions[] =
243                     users[i].getSubscriptions();
244                 for (int j = 0; j < subscriptions.length; j++) {
245                     writer.print(" ");
246                     writer.println(subscriptions[j]);
247                     writer.print(" ");
248                     writer.println("</subscription>");
249                 }
250                 writer.print(" ");
251                 writer.println("</user>");
252             }
253
254             // Print the file epilog
255
writer.println("</database>");
256
257             // Check for errors that occurred while printing
258
if (writer.checkError()) {
259                 writer.close();
260                 fileNew.delete();
261                 throw new IOException JavaDoc
262                     ("Saving database to '" + pathname + "'");
263             }
264             writer.close();
265             writer = null;
266
267         } catch (IOException JavaDoc e) {
268
269             if (writer != null) {
270                 writer.close();
271             }
272             fileNew.delete();
273             throw e;
274
275         }
276
277
278         // Perform the required renames to permanently save this file
279
File JavaDoc fileOrig = new File JavaDoc(pathname);
280         File JavaDoc fileOld = new File JavaDoc(pathnameOld);
281         if (fileOrig.exists()) {
282             fileOld.delete();
283             if (!fileOrig.renameTo(fileOld)) {
284                 throw new IOException JavaDoc
285                     ("Renaming '" + pathname + "' to '" + pathnameOld + "'");
286             }
287         }
288         if (!fileNew.renameTo(fileOrig)) {
289             if (fileOld.exists()) {
290                 fileOld.renameTo(fileOrig);
291             }
292             throw new IOException JavaDoc
293                 ("Renaming '" + pathnameNew + "' to '" + pathname + "'");
294         }
295         fileOld.delete();
296
297     }
298
299
300 }
301
302
303 /**
304  * Digester object creation factory for subscription instances.
305  */

306 class MemorySubscriptionCreationFactory implements ObjectCreationFactory {
307
308     private Digester digester = null;
309
310     public Digester getDigester() {
311         return (this.digester);
312     }
313
314     public void setDigester(Digester digester) {
315         this.digester = digester;
316     }
317
318     public Object JavaDoc createObject(Attributes JavaDoc attributes) {
319         String JavaDoc host = attributes.getValue("host");
320         User user = (User) digester.peek();
321         Subscription subscription = user.createSubscription(host);
322         String JavaDoc autoConnect = attributes.getValue("autoConnect");
323         if (autoConnect == null) {
324             autoConnect = "false";
325         }
326         if ("true".equalsIgnoreCase(autoConnect) ||
327             "yes".equalsIgnoreCase(autoConnect)) {
328             subscription.setAutoConnect(true);
329         } else {
330             subscription.setAutoConnect(false);
331         }
332         subscription.setPassword(attributes.getValue("password"));
333         subscription.setType(attributes.getValue("type"));
334         subscription.setUsername(attributes.getValue("username"));
335         return (subscription);
336     }
337
338 }
339
340
341 /**
342  * Digester object creation factory for user instances.
343  */

344 class MemoryUserCreationFactory implements ObjectCreationFactory {
345
346     public MemoryUserCreationFactory(MemoryUserDatabase database) {
347         this.database = database;
348     }
349
350     private MemoryUserDatabase database = null;
351
352     private Digester digester = null;
353
354     public Digester getDigester() {
355         return (this.digester);
356     }
357
358     public void setDigester(Digester digester) {
359         this.digester = digester;
360     }
361
362     public Object JavaDoc createObject(Attributes JavaDoc attributes) {
363         String JavaDoc username = attributes.getValue("username");
364         User user = database.createUser(username);
365         user.setFromAddress(attributes.getValue("fromAddress"));
366         user.setFullName(attributes.getValue("fullName"));
367         user.setPassword(attributes.getValue("password"));
368         user.setReplyToAddress(attributes.getValue("replyToAddress"));
369         return (user);
370     }
371
372 }
373
Popular Tags