KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > nemesis > forum > impl > DbUser


1 /*
2  * NEMESIS-FORUM.
3  * Copyright (C) 2002 David Laurent(lithium2@free.fr). All rights reserved.
4  *
5  * Copyright (c) 2000 The Apache Software Foundation. All rights reserved.
6  *
7  * Copyright (C) 2001 Yasna.com. All rights reserved.
8  *
9  * Copyright (C) 2000 CoolServlets.com. All rights reserved.
10  *
11  * NEMESIS-FORUM. is free software; you can redistribute it and/or
12  * modify it under the terms of the Apache Software License, Version 1.1,
13  * or (at your option) any later version.
14  *
15  * NEMESIS-FORUM core framework, NEMESIS-FORUM backoffice, NEMESIS-FORUM frontoffice
16  * application are parts of NEMESIS-FORUM and are distributed under
17  * same terms of licence.
18  *
19  *
20  * NEMESIS-FORUM includes software developed by the Apache Software Foundation (http://www.apache.org/)
21  * and software developed by CoolServlets.com (http://www.coolservlets.com).
22  * and software developed by Yasna.com (http://www.yasna.com).
23  *
24  */

25 package org.nemesis.forum.impl;
26
27 import java.sql.Connection JavaDoc;
28 import java.sql.PreparedStatement JavaDoc;
29 import java.sql.ResultSet JavaDoc;
30 import java.sql.SQLException JavaDoc;
31 import java.util.Enumeration JavaDoc;
32 import java.util.Properties JavaDoc;
33
34 import org.apache.commons.logging.Log;
35 import org.apache.commons.logging.LogFactory;
36 import org.nemesis.forum.Authorization;
37 import org.nemesis.forum.ForumPermissions;
38 import org.nemesis.forum.Group;
39 import org.nemesis.forum.User;
40 import org.nemesis.forum.exception.UnauthorizedException;
41 import org.nemesis.forum.exception.UserNotFoundException;
42 import org.nemesis.forum.util.StringUtils;
43 import org.nemesis.forum.util.cache.CacheSizes;
44 import org.nemesis.forum.util.cache.Cacheable;
45 import org.nemesis.forum.util.jdbc.DbConnectionManager;
46 /**
47  * Database implementation of the User interface. Additionally, it filters all
48  * HTML tags from fields before returning them for security purposes.<p>
49  *
50  * Use of the user system is optional. There a number of different ways
51  * to create your own user system or to integrate into an existing user
52  * system:<ul>
53  * <li> Edit the source of this class and modify the database queries to match
54  * your user system.
55  * <li> Implement a set of custom classes and tell the ForumFactory to load
56  * them. In this case, it is still recommended to use the user API
57  * since that will mean much less reimplementation work in the other
58  * classes.</ul>
59  *
60  * If you can follow the API for your own user data, but need access
61  * within to extended user properties, such as addresses or other
62  * personal data, and easy solution is to adapt the user properties facility
63  * to load and access this data.
64  */

65 class DbUser implements User, Cacheable {
66     static protected Log log = LogFactory.getLog(DbUser.class);
67     /** DATABASE QUERIES **/
68     private static final String JavaDoc LOAD_PROPERTIES = "SELECT name, propValue FROM yazdUserProp WHERE userID=?";
69     private static final String JavaDoc DELETE_PROPERTIES = "DELETE FROM yazdUserProp WHERE userID=?";
70     private static final String JavaDoc INSERT_PROPERTY = "INSERT INTO yazdUserProp(userID,name,propValue) VALUES(?,?,?)";
71     private static final String JavaDoc LOAD_USER_BY_USERNAME = "SELECT * FROM yazdUser WHERE username=?";
72     private static final String JavaDoc LOAD_USER_BY_ID = "SELECT * FROM yazdUser WHERE userID=?";
73     private static final String JavaDoc INSERT_USER ="INSERT INTO yazdUser(userID,username,passwordHash,email,emailVisible," + "nameVisible) VALUES(?,?,?,?,?,?)";
74     private static final String JavaDoc SAVE_USER = "UPDATE yazdUser SET passwordHash=?,email=?,emailVisible=?,name=?," + "nameVisible=? WHERE userID=?";
75     private static final String JavaDoc DELETE_PERMISSIONS = "DELETE FROM yazdUserPerm WHERE userID=?";
76     private static final String JavaDoc INSERT_PERMISSION = "INSERT INTO yazdUserPerm(userID,forumID,permission) VALUES(?,?,?)";
77     
78     //********ajout
79
private static final String JavaDoc ADMIN_TEST = "SELECT groupID FROM yazdGroupUser WHERE groupID=? AND userID=? AND " + "administrator=1";
80     private static final String JavaDoc MEMBER_TEST = "SELECT groupID FROM yazdGroupUser WHERE groupID=? AND userID=?";
81     private static final String JavaDoc ADMIN_COUNT = "SELECT count(*) FROM yazdGroupUser WHERE userID=? " + "AND administrator=1";
82     private static final String JavaDoc MEMBER_COUNT = "SELECT DISTINCT count(groupID) FROM yazdGroupUser " + "WHERE userID=?";
83     
84
85     /**
86      * user id of -2 means no user id has been set yet. -1 is reserved for
87      * "anonymous user" and 0 is reserved for "all users".
88      */

89     private int id = -2;
90     private String JavaDoc username;
91     private String JavaDoc passwordHash;
92     private String JavaDoc name = "";
93     private boolean nameVisible = true;
94     private String JavaDoc email;
95     private boolean emailVisible = true;
96     private Properties JavaDoc properties;
97     private Object JavaDoc propertyLock = new Object JavaDoc();
98
99     /**
100      * Create a new DbUser with all required fields.
101      *
102      * @param username the username for the user.
103      * @param password a password for the user.
104      * @param email the email address for the user.
105      */

106     protected DbUser(String JavaDoc username, String JavaDoc password, String JavaDoc email) {
107         this.id = DbSequenceManager.nextID("User");
108         this.username = username;
109         //Compute hash of password.
110
this.passwordHash = StringUtils.hash(password);
111         this.email = email;
112         properties = new Properties JavaDoc();
113         insertIntoDb();
114     }
115
116     /**
117      * Load a DbUser object specified by userID.
118      *
119      * @param userID the userID of the user to load.
120      */

121     protected DbUser(int userID) throws UserNotFoundException {
122         this.id = userID;
123         loadFromDb();
124         loadProperties();
125     }
126
127     /**
128      * Load a DbUser object specified by username.
129      *
130      * @param username the username of the user to load.
131      */

132     protected DbUser(String JavaDoc username) throws UserNotFoundException {
133         this.username = username;
134         loadFromDb();
135         loadProperties();
136     }
137
138     //FROM THE USER INTERFACE//
139

140     public int getID() {
141         return id;
142     }
143
144     public boolean isAnonymous() {
145         return (id == -1);
146     }
147
148     public String JavaDoc getUsername() {
149         return StringUtils.escapeHTMLTags(username);
150     }
151
152     public String JavaDoc getName() {
153         return StringUtils.escapeHTMLTags(name);
154     }
155
156     public void setName(String JavaDoc name) throws UnauthorizedException {
157         this.name = name;
158         saveToDb();
159     }
160
161     public boolean isNameVisible() {
162         return nameVisible;
163     }
164
165     public void setNameVisible(boolean visible) throws UnauthorizedException {
166         this.nameVisible = visible;
167         saveToDb();
168     }
169
170     public void setPassword(String JavaDoc password) throws UnauthorizedException {
171         //Compute hash of password.
172
this.passwordHash = StringUtils.hash(password);
173         saveToDb();
174     }
175
176     public String JavaDoc getPasswordHash() throws UnauthorizedException {
177         return passwordHash;
178     }
179
180     public void setPasswordHash(String JavaDoc passwordHash) {
181         this.passwordHash = passwordHash;
182         saveToDb();
183     }
184
185     public String JavaDoc getEmail() {
186         return StringUtils.escapeHTMLTags(email);
187     }
188
189     public void setEmail(String JavaDoc email) throws UnauthorizedException {
190         this.email = email;
191         saveToDb();
192     }
193
194     public boolean isEmailVisible() {
195         return emailVisible;
196     }
197
198     public void setEmailVisible(boolean visible) throws UnauthorizedException {
199         this.emailVisible = visible;
200         saveToDb();
201     }
202
203     public String JavaDoc getProperty(String JavaDoc name) {
204         return StringUtils.escapeHTMLTags((String JavaDoc) properties.get(name));
205     }
206
207     public Enumeration JavaDoc propertyNames() {
208         return properties.propertyNames();
209     }
210
211     public void setProperty(String JavaDoc name, String JavaDoc value) {
212         properties.put(name, value);
213         saveProperties();
214     }
215
216     public ForumPermissions getPermissions(Authorization authorization) {
217         if (authorization.getUserID() == id || id == -1 || id == 0) {
218             return new ForumPermissions(false, false, false, true, false, false, false, false);
219         } else {
220             return ForumPermissions.none();
221         }
222     }
223
224     public boolean hasPermission(int type) {
225         return true;
226     }
227
228     //FROM THE CACHEABLE INTERFACE//
229

230     public int getSize() {
231         //Approximate the size of the object in bytes by calculating the size
232
//of each field.
233
int size = 0;
234         size += CacheSizes.sizeOfObject(); //overhead of object
235
size += CacheSizes.sizeOfInt(); //id
236
size += CacheSizes.sizeOfString(username); //username
237
size += CacheSizes.sizeOfString(passwordHash); //password
238
size += CacheSizes.sizeOfString(name); //name
239
size += CacheSizes.sizeOfString(email); //email
240
size += CacheSizes.sizeOfBoolean(); //nameVisible
241
size += CacheSizes.sizeOfBoolean(); //emailVisible
242
size += CacheSizes.sizeOfObject(); //property lock
243
size += CacheSizes.sizeOfProperties(properties); //properties object
244

245         return size;
246     }
247     //******AJOUT
248
public boolean isAdministratorInGroup(Group group) {
249             boolean answer = false;
250             Connection JavaDoc con = null;
251             PreparedStatement JavaDoc pstmt = null;
252             try {
253                 con = DbConnectionManager.getConnection();
254                 pstmt = con.prepareStatement(ADMIN_TEST);
255                 pstmt.setInt(1, group.getID());
256                 pstmt.setInt(2, id);
257                 ResultSet JavaDoc rs = pstmt.executeQuery();
258                 if (rs.next()) {
259                     answer = true;
260                 }
261             } catch (SQLException JavaDoc sqle) {
262                 log.error("" , sqle);
263             } finally {
264                 try {
265                     pstmt.close();
266                 } catch (Exception JavaDoc e) {
267                     log.error("" , e);
268                 }
269                 try {
270                     con.close();
271                 } catch (Exception JavaDoc e) {
272                     log.error("" , e);
273                 }
274             }
275             return answer;
276         }
277
278         public boolean isMemberInGroup(Group group) {
279             boolean answer = false;
280             Connection JavaDoc con = null;
281             PreparedStatement JavaDoc pstmt = null;
282             try {
283                 con = DbConnectionManager.getConnection();
284                 pstmt = con.prepareStatement(MEMBER_TEST);
285                 pstmt.setInt(1, group.getID());
286                 pstmt.setInt(2, id);
287                 ResultSet JavaDoc rs = pstmt.executeQuery();
288                 if (rs.next()) {
289                     answer = true;
290                 }
291             } catch (SQLException JavaDoc sqle) {
292                 log.error("" , sqle);
293             } finally {
294                 try {
295                     pstmt.close();
296                 } catch (Exception JavaDoc e) {
297                     log.error("" , e);
298                 }
299                 try {
300                     con.close();
301                 } catch (Exception JavaDoc e) {
302                     log.error("" , e);
303                 }
304             }
305             return answer;
306         }
307
308         public int getGroupAdministratorCount() {
309             int count = 0;
310             boolean answer = false;
311             Connection JavaDoc con = null;
312             PreparedStatement JavaDoc pstmt = null;
313             try {
314                 con = DbConnectionManager.getConnection();
315                 pstmt = con.prepareStatement(ADMIN_COUNT);
316                 pstmt.setInt(1, id);
317                 ResultSet JavaDoc rs = pstmt.executeQuery();
318                 if (rs.next()) {
319                     count = rs.getInt(1);
320                 }
321             } catch (SQLException JavaDoc sqle) {
322                 log.error("" , sqle);
323             } finally {
324                 try {
325                     pstmt.close();
326                 } catch (Exception JavaDoc e) {
327                     log.error("" , e);
328                 }
329                 try {
330                     con.close();
331                 } catch (Exception JavaDoc e) {
332                     log.error("" , e);
333                 }
334             }
335             return count;
336         }
337
338         public int getGroupCount() {
339             int count = 0;
340             boolean answer = false;
341             Connection JavaDoc con = null;
342             PreparedStatement JavaDoc pstmt = null;
343             try {
344                 con = DbConnectionManager.getConnection();
345                 pstmt = con.prepareStatement(MEMBER_COUNT);
346                 pstmt.setInt(1, id);
347                 ResultSet JavaDoc rs = pstmt.executeQuery();
348                 if (rs.next()) {
349                     count = rs.getInt(1);
350                 }
351             } catch (SQLException JavaDoc sqle) {
352                 log.error("" , sqle);
353             } finally {
354                 try {
355                     pstmt.close();
356                 } catch (Exception JavaDoc e) {
357                     log.error("" , e);
358                 }
359                 try {
360                     con.close();
361                 } catch (Exception JavaDoc e) {
362                     log.error("" , e);
363                 }
364             }
365             return count;
366         }
367     
368     
369     //-------
370

371     
372     
373     //OTHER METHODS
374

375     /**
376      * Returns a String representation of the User object using the username.
377      *
378      * @return a String representation of the User object.
379      */

380     public String JavaDoc toString() {
381         return username;
382     }
383
384     public int hashCode() {
385         return id;
386     }
387
388     public boolean equals(Object JavaDoc object) {
389         if (this == object) {
390             return true;
391         }
392         if (object != null && object instanceof DbUser) {
393             return id == ((DbUser) object).getID();
394         } else {
395             return false;
396         }
397     }
398
399     /**
400      * Loads user properties from the database.
401      */

402     private void loadProperties() {
403         //If "anonymous" or "all users", do nothing.
404
if (id == -1 || id == 0) {
405             properties = new Properties JavaDoc();
406             return;
407         }
408         //Acquire a lock so that no other property loading or saving can be
409
//performed at the same time.
410
synchronized (propertyLock) {
411             Properties JavaDoc newProps = new Properties JavaDoc();
412             Connection JavaDoc con = null;
413             PreparedStatement JavaDoc pstmt = null;
414             try {
415                 con = DbConnectionManager.getConnection();
416                 pstmt = con.prepareStatement(LOAD_PROPERTIES);
417                 pstmt.setInt(1, id);
418                 ResultSet JavaDoc rs = pstmt.executeQuery();
419                 while (rs.next()) {
420                     String JavaDoc name = rs.getString("name");
421                     String JavaDoc value = rs.getString("propValue");
422                     newProps.put(name, value);
423                 }
424             } catch (SQLException JavaDoc sqle) {
425                 log.error("Error in DbUser:loadProperties():" ,sqle);
426                 
427             } finally {
428                 try {
429                     pstmt.close();
430                 } catch (Exception JavaDoc e) {
431                     log.error("" , e);
432                 }
433                 try {
434                     con.close();
435                 } catch (Exception JavaDoc e) {
436                     log.error("" , e);
437                 }
438             }
439             this.properties = newProps;
440         }
441     }
442
443     /**
444      * Saves user properties to the database.
445      */

446     private void saveProperties() {
447         //If "anonymous" or "all users", do nothing.
448
if (id == -1 || id == 0) {
449             return;
450         }
451         //Acquire a lock so that no other property loading or saving can be
452
//performed at the same time.
453
synchronized (propertyLock) {
454             Connection JavaDoc con = null;
455             PreparedStatement JavaDoc pstmt = null;
456             try {
457                 con = DbConnectionManager.getConnection();
458                 //Delete all old values.
459
pstmt = con.prepareStatement(DELETE_PROPERTIES);
460                 pstmt.setInt(1, id);
461                 pstmt.execute();
462                 pstmt.close();
463                 //Now insert new values.
464
pstmt = con.prepareStatement(INSERT_PROPERTY);
465                 Enumeration JavaDoc e = properties.keys();
466                 while (e.hasMoreElements()) {
467                     String JavaDoc name = (String JavaDoc) e.nextElement();
468                     String JavaDoc value = (String JavaDoc) properties.get(name);
469                     pstmt.setInt(1, id);
470                     pstmt.setString(2, name);
471                     pstmt.setString(3, value);
472                     pstmt.executeUpdate();
473                 }
474             } catch (SQLException JavaDoc sqle) {
475                 log.error("" , sqle);
476             } finally {
477                 try {
478                     pstmt.close();
479                 } catch (Exception JavaDoc e) {
480                     log.error("" , e);
481                 }
482                 try {
483                     con.close();
484                 } catch (Exception JavaDoc e) {
485                     log.error("" , e);
486                 }
487             }
488         }
489     }
490
491     /**
492      * Load the user data from the database.
493      */

494     private void loadFromDb() throws UserNotFoundException {
495         //If the user is anonymous or "all users", do nothing.
496
if (id == -1 || id == 0) {
497             return;
498         }
499         // Otherwise, select user data from User table and fill in relevant fields.
500
String JavaDoc query;
501         //We may want to do a username lookup.
502
if (username != null) {
503             query = LOAD_USER_BY_USERNAME;
504         }
505         //Otherwise, a lookup by id
506
else {
507             query = LOAD_USER_BY_ID;
508         }
509         Connection JavaDoc con = null;
510         PreparedStatement JavaDoc pstmt = null;
511         try {
512             con = DbConnectionManager.getConnection();
513             pstmt = con.prepareStatement(query);
514             if (username != null) {
515                 pstmt.setString(1, username);
516             } else {
517                 pstmt.setInt(1, id);
518             }
519
520             ResultSet JavaDoc rs = pstmt.executeQuery();
521             if (!rs.next()) {
522                 throw new UserNotFoundException("Failed to read user " + id + " from database.");
523             }
524             this.id = rs.getInt("userID");
525             this.username = rs.getString("username");
526             this.passwordHash = rs.getString("passwordHash");
527             this.name = rs.getString("name");
528             this.nameVisible = (rs.getInt("nameVisible") == 1);
529             this.email = rs.getString("email");
530             this.emailVisible = (rs.getInt("emailVisible") == 1);
531         } catch (SQLException JavaDoc sqle) {
532             throw new UserNotFoundException("Failed to read user " + id + " from database.", sqle);
533         } finally {
534             try {
535                 pstmt.close();
536             } catch (Exception JavaDoc e) {
537                 log.error("" , e);
538             }
539             try {
540                 con.close();
541             } catch (Exception JavaDoc e) {
542                 log.error("" , e);
543             }
544         }
545     }
546
547     /**
548      * Inserts a new user record into the database.
549      */

550     private void insertIntoDb() {
551         Connection JavaDoc con = null;
552         PreparedStatement JavaDoc pstmt = null;
553         try {
554             con = DbConnectionManager.getConnection();
555             pstmt = con.prepareStatement(INSERT_USER);
556             pstmt.setInt(1, id);
557             pstmt.setString(2, username);
558             pstmt.setString(3, passwordHash);
559             pstmt.setString(4, email);
560             pstmt.setInt(5, emailVisible ? 1 : 0);
561             pstmt.setInt(6, nameVisible ? 1 : 0);
562             pstmt.executeUpdate();
563         } catch (SQLException JavaDoc sqle) {
564             log.error("Error in DbUser:insertIntoDb()-" ,sqle);
565             
566         } finally {
567             try {
568                 pstmt.close();
569             } catch (Exception JavaDoc e) {
570                 log.error("" , e);
571             }
572             try {
573                 con.close();
574             } catch (Exception JavaDoc e) {
575                 log.error("" , e);
576             }
577         }
578     }
579
580     /**
581      * Save the user data to the database.
582      */

583     private void saveToDb() {
584         if (id == -1 || id == 0) {
585             //"anonymous" or "all users", do nothing
586
return;
587         }
588         Connection JavaDoc con = null;
589         PreparedStatement JavaDoc pstmt = null;
590         try {
591             con = DbConnectionManager.getConnection();
592             pstmt = con.prepareStatement(SAVE_USER);
593             pstmt.setString(1, passwordHash);
594             pstmt.setString(2, email);
595             pstmt.setInt(3, emailVisible ? 1 : 0);
596             pstmt.setString(4, name);
597             pstmt.setInt(5, nameVisible ? 1 : 0);
598             pstmt.setInt(6, id);
599             pstmt.executeUpdate();
600         } catch (SQLException JavaDoc sqle) {
601             log.error("SQLException in DbUser.java:saveToDb(): " , sqle);
602             
603         } finally {
604             try {
605                 pstmt.close();
606             } catch (Exception JavaDoc e) {
607                 log.error("" , e);
608             }
609             try {
610                 con.close();
611             } catch (Exception JavaDoc e) {
612                 log.error("" , e);
613             }
614         }
615     }
616 }
617
Popular Tags