KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > Yasna > forum > database > DbUser


1 /**
2  * Copyright (C) 2001 Yasna.com. All rights reserved.
3  *
4  * ===================================================================
5  * The Apache Software License, Version 1.1
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  * notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  * notice, this list of conditions and the following disclaimer in
16  * the documentation and/or other materials provided with the
17  * distribution.
18  *
19  * 3. The end-user documentation included with the redistribution,
20  * if any, must include the following acknowledgment:
21  * "This product includes software developed by
22  * Yasna.com (http://www.yasna.com)."
23  * Alternately, this acknowledgment may appear in the software itself,
24  * if and wherever such third-party acknowledgments normally appear.
25  *
26  * 4. The names "Yazd" and "Yasna.com" must not be used to
27  * endorse or promote products derived from this software without
28  * prior written permission. For written permission, please
29  * contact yazd@yasna.com.
30  *
31  * 5. Products derived from this software may not be called "Yazd",
32  * nor may "Yazd" appear in their name, without prior written
33  * permission of Yasna.com.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED. IN NO EVENT SHALL YASNA.COM OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of Yasna.com. For more information
51  * on Yasna.com, please see <http://www.yasna.com>.
52  */

53
54 /**
55  * Copyright (C) 2000 CoolServlets.com. All rights reserved.
56  *
57  * ===================================================================
58  * The Apache Software License, Version 1.1
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  * notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  * notice, this list of conditions and the following disclaimer in
69  * the documentation and/or other materials provided with the
70  * distribution.
71  *
72  * 3. The end-user documentation included with the redistribution,
73  * if any, must include the following acknowledgment:
74  * "This product includes software developed by
75  * CoolServlets.com (http://www.coolservlets.com)."
76  * Alternately, this acknowledgment may appear in the software itself,
77  * if and wherever such third-party acknowledgments normally appear.
78  *
79  * 4. The names "Jive" and "CoolServlets.com" must not be used to
80  * endorse or promote products derived from this software without
81  * prior written permission. For written permission, please
82  * contact webmaster@coolservlets.com.
83  *
84  * 5. Products derived from this software may not be called "Jive",
85  * nor may "Jive" appear in their name, without prior written
86  * permission of CoolServlets.com.
87  *
88  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
89  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
90  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
91  * DISCLAIMED. IN NO EVENT SHALL COOLSERVLETS.COM OR
92  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
93  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
94  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
95  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
96  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
97  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
98  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
99  * SUCH DAMAGE.
100  * ====================================================================
101  *
102  * This software consists of voluntary contributions made by many
103  * individuals on behalf of CoolServlets.com. For more information
104  * on CoolServlets.com, please see <http://www.coolservlets.com>.
105  */

106
107 package com.Yasna.forum.database;
108
109 import com.Yasna.forum.*;
110 import com.Yasna.forum.locale.YazdLocale;
111 import com.Yasna.util.*;
112
113 import java.util.*;
114 import java.text.*;
115 import java.sql.*;
116 import java.security.*;
117
118 /**
119  * Database implementation of the User interface. Additionally, it filters all
120  * HTML tags from fields before returning them for security purposes.<p>
121  *
122  * Use of the Yazd user system is optional. There a number of different ways
123  * to create your own user system or to integrate into an existing user
124  * system:<ul>
125  * <li> Edit the source of this class and modify the database queries to match
126  * your user system.
127  * <li> Implement a set of custom classes and tell the ForumFactory to load
128  * them. In this case, it is still recommended to use the Yazd user API
129  * since that will mean much less reimplementation work in the other
130  * classes.</ul>
131  *
132  * If you can follow the Yazd API for your own user data, but need access
133  * within Yazd to extended user properties, such as addresses or other
134  * personal data, and easy solution is to adapt the user properties facility
135  * to load and access this data.
136  */

137 public class DbUser implements User, Cacheable {
138
139     /** DATABASE QUERIES **/
140     private static final String JavaDoc LOAD_PROPERTIES =
141             "SELECT name, propValue FROM yazdUserProp WHERE userID=?";
142     private static final String JavaDoc LOAD_LASTPOST =
143             "select max(creationDate) as lastpost from yazdMessage where userID=?";
144     private static final String JavaDoc DELETE_PROPERTIES =
145             "DELETE FROM yazdUserProp WHERE userID=?";
146     private static final String JavaDoc INSERT_PROPERTY =
147             "INSERT INTO yazdUserProp(userID,name,propValue) VALUES(?,?,?)";
148     private static final String JavaDoc LOAD_USER_BY_USERNAME =
149             "SELECT * FROM "+SystemProperty.getProperty("User.Table")+" WHERE "+SystemProperty.getProperty("User.Column.Username")+"=?";
150     private static final String JavaDoc LOAD_USER_BY_ID =
151             "SELECT * FROM "+SystemProperty.getProperty("User.Table")+" WHERE "+SystemProperty.getProperty("User.Column.UserID")+"=?";
152     private static final String JavaDoc INSERT_USER =
153             "INSERT INTO "+SystemProperty.getProperty("User.Table")+"("+SystemProperty.getProperty("User.Column.UserID")+
154                     ","+SystemProperty.getProperty("User.Column.Username")+
155                     ","+SystemProperty.getProperty("User.Column.PasswordHash")+",email)" +
156                     "VALUES(?,?,?,?)";
157     private static final String JavaDoc SAVE_USER =
158             "UPDATE "+SystemProperty.getProperty("User.Table")+" SET "+SystemProperty.getProperty("User.Column.PasswordHash")+
159                     "=?, "+SystemProperty.getProperty("User.Column.Email")+"=?, "+SystemProperty.getProperty("User.Column.Name")+"=? " +
160                     " WHERE "+SystemProperty.getProperty("User.Column.UserID")+"=?";
161     private static final String JavaDoc DELETE_PERMISSIONS =
162             "DELETE FROM yazdUserPerm WHERE userID=?";
163     private static final String JavaDoc INSERT_PERMISSION =
164             "INSERT INTO yazdUserPerm(userID,forumID,permission) VALUES(?,?,?)";
165     private static final String JavaDoc INSERT_AUTO_GROUP= "insert into yazdGroupUser(groupID,userID,administrator) select groupID,?,0 from yazdGroup where automember=1";
166
167     /**
168      * user id of -2 means no user id has been set yet. -1 is reserved for
169      * "anonymous user" and 0 is reserved for "all users".
170      */

171     private int id = -2;
172     private String JavaDoc username;
173     private String JavaDoc passwordHash;
174     private String JavaDoc name = "";
175     private String JavaDoc email;
176     private boolean nameVisible = true;
177     private boolean emailVisible = true;
178     private boolean threadSubscribe = false;
179     private long lastlogin;
180     private long regdate;
181     private long lastpost=-1;
182     private Properties properties;
183     private Object JavaDoc propertyLock = new Object JavaDoc();
184
185     /**
186      * Create a new DbUser with all required fields.
187      *
188      * @param username the username for the user.
189      * @param password a password for the user.
190      * @param email the email address for the user.
191      */

192     protected DbUser(String JavaDoc username, String JavaDoc password, String JavaDoc email) throws UserAlreadyExistsException {
193         this.id = DbSequenceManager.nextID("User");
194         this.username = username;
195         //Compute hash of password.
196
this.passwordHash = StringUtils.hash(password);
197         this.email = email;
198         properties = new Properties();
199         insertIntoDb();
200         insertAutoGroupMembership();
201         setProperty("namevisible",Boolean.toString(nameVisible));
202         setProperty("emailvisible",Boolean.toString(emailVisible));
203         setProperty("lastlogin",Long.toString(Calendar.getInstance().getTimeInMillis()));
204         setProperty("regdate",Long.toString(Calendar.getInstance().getTimeInMillis()));
205         setProperty("ranking","3");
206         if(!Boolean.valueOf(PropertyManager.getProperty("User.DisableActivation")).booleanValue()){
207             String JavaDoc code = StringUtils.randomString(7);
208             setProperty("notactive",code);
209             if (this.email!=null && !"".equals(email)){
210                 // ok ready to send mail to user
211
String JavaDoc emailBody = PropertyManager.getProperty("yazdActivate.MailBody") +
212                         " \n\r"+PropertyManager.getProperty("yazdUrl")+
213                         "activate.jsp?user="+this.id+"&code="+code;
214                 MailSender.send(PropertyManager.getProperty("yazdMailSMTPServer"),
215                         PropertyManager.getProperty("yazdMailFrom"),
216                         this.email,
217                         PropertyManager.getProperty("yazdActivate.MailSubject"),
218                         emailBody);
219             }
220         }
221
222     }
223
224     /**
225      * Load a DbUser object specified by userID.
226      *
227      * @param userID the userID of the user to load.
228      */

229     protected DbUser(int userID) throws UserNotFoundException {
230         this.id = userID;
231         loadFromDb();
232         loadProperties();
233         loadLastPost();
234         //This is done to be backward compatible with Yazd 1.0
235
nameVisible = Boolean.valueOf(getProperty("namevisible")).booleanValue();
236         emailVisible = Boolean.valueOf(getProperty("emailvisible")).booleanValue();
237         threadSubscribe = Boolean.valueOf(getProperty("threadSubscribe")).booleanValue();
238         try {
239             lastlogin = Long.parseLong(getProperty("lastlogin"));
240         } catch(Exception JavaDoc e){
241             lastlogin=0;
242         }
243         try {
244             regdate = Long.parseLong(getProperty("regdate"));
245         } catch (Exception JavaDoc e){
246             regdate = 0;
247         }
248         if(getProperty("ranking")==null){
249             setProperty("ranking","3");
250         }
251     }
252
253     /**
254      * Load a DbUser object specified by username.
255      *
256      * @param username the username of the user to load.
257      */

258     protected DbUser(String JavaDoc username) throws UserNotFoundException {
259         this.username = username;
260         loadFromDb();
261         loadProperties();
262         loadLastPost();
263         //This is done to be backward compatible with Yazd 1.0
264
nameVisible = Boolean.valueOf(getProperty("namevisible")).booleanValue();
265         emailVisible = Boolean.valueOf(getProperty("emailvisible")).booleanValue();
266         threadSubscribe = Boolean.valueOf(getProperty("threadSubscribe")).booleanValue();
267         try {
268             lastlogin = Long.parseLong(getProperty("lastlogin"));
269         } catch(Exception JavaDoc e){
270             lastlogin=0;
271         }
272         try {
273             regdate = Long.parseLong(getProperty("regdate"));
274         } catch (Exception JavaDoc e){
275             regdate = 0;
276         }
277         if(getProperty("ranking")==null){
278             setProperty("ranking","3");
279         }
280
281     }
282
283     //FROM THE USER INTERFACE//
284
protected void activateUser(){
285         properties.remove("notactive");
286         saveProperties();
287     }
288     public int getID() {
289         return id;
290     }
291
292     public boolean isAnonymous() {
293         return (id==-1);
294     }
295
296     public String JavaDoc getUsername() {
297         return StringUtils.escapeHTMLTags(username);
298     }
299
300     public String JavaDoc getName() {
301         return StringUtils.escapeHTMLTags(name);
302     }
303
304     public void setName(String JavaDoc name) throws UnauthorizedException {
305         this.name = name;
306         saveToDb();
307     }
308
309     public boolean isNameVisible() {
310         return nameVisible;
311     }
312
313     public void setNameVisible(boolean visible) throws UnauthorizedException {
314         this.nameVisible = visible;
315         saveToDb();
316     }
317
318     public boolean getThreadSubscribe() {
319         return threadSubscribe;
320     }
321
322     public Calendar getLastLogin(){
323         Calendar cal =Calendar.getInstance();
324         cal.setTimeInMillis(lastlogin);
325         return cal;
326     }
327     public Calendar getLastPost(){
328         // This date might be cached and therefore incorrect.
329
if (lastpost <0){
330             // this means that the user hasn't posted a message yet and we are returning a null value.
331
return null;
332         } else {
333             Calendar cal =Calendar.getInstance();
334             cal.setTimeInMillis(lastpost);
335             return cal;
336         }
337     }
338     public Locale getUserLocale(){
339         String JavaDoc locale = this.getProperty("locale");
340         if(locale==null){
341             //if there is no user locale then return the default locale
342
return YazdLocale.getDefaultYazdLocale();
343         }
344         String JavaDoc lang=null,country=null,variant=null;
345         int pos = 0;
346         int delPos = 0;
347         if ((delPos = locale.indexOf(",", pos)) != -1) {
348             lang = locale.substring(pos, delPos);
349             pos = delPos + 1; // next character after the delimiter
350
}else if (pos <= locale.length()) {
351             lang = locale.substring(pos);
352             pos = locale.length() + 1;
353         }
354         if ((delPos = locale.indexOf(",", pos)) != -1) {
355             country = locale.substring(pos, delPos);
356             pos = delPos + 1; // next character after the delimiter
357
} else if (pos <= locale.length()) {
358             country = locale.substring(pos);
359             pos = locale.length() + 1;
360         }
361         if (pos <= locale.length()) {
362             // add rest of String
363
variant=locale.substring(pos);
364
365         }
366         if (variant!=null){
367             return new Locale(lang,country,variant);
368         }else if (country != null){
369             //this is the one that should return most values.
370
return new Locale(lang,country);
371         }else{
372             return new Locale(lang);
373         }
374
375     }
376     public TimeZone getUserTimeZone(){
377         String JavaDoc timezone = this.getProperty("timezone");
378         if(timezone==null){
379             //if there is no user locale then return the default locale
380
return TimeZone.getDefault();
381         }
382         return TimeZone.getTimeZone(timezone);
383     }
384     public void setUserTimeZone(String JavaDoc timezoneid) throws UnauthorizedException{
385         this.setProperty("timezone",timezoneid);
386     }
387     public void setUserLocale(Locale locale) throws UnauthorizedException{
388         this.setProperty("Locale",locale.getLanguage()+("".equals(locale.getCountry())?"":","+locale.getCountry())+("".equals(locale.getVariant())?"":","+locale.getVariant()));
389     }
390
391     public void setThreadSubscribe(boolean emailReply) throws UnauthorizedException {
392         this.threadSubscribe = emailReply;
393         setProperty("threadSubscribe",Boolean.toString(emailReply));
394     }
395
396     public void setPassword(String JavaDoc password) throws UnauthorizedException {
397         //Compute hash of password.
398
this.passwordHash = StringUtils.hash(password);
399         saveToDb();
400     }
401
402     public String JavaDoc getPasswordHash() throws UnauthorizedException {
403         return passwordHash;
404     }
405
406     public void setPasswordHash(String JavaDoc passwordHash) {
407         this.passwordHash = passwordHash;
408         saveToDb();
409     }
410
411     public String JavaDoc getEmail() {
412         return StringUtils.escapeHTMLTags(email);
413     }
414
415     public void setEmail(String JavaDoc email) throws UnauthorizedException {
416         this.email = email;
417         saveToDb();
418     }
419
420     public boolean isEmailVisible() {
421         return emailVisible;
422     }
423
424     public void setEmailVisible(boolean visible) throws UnauthorizedException {
425         this.emailVisible = visible;
426         setProperty("emailvisible",Boolean.toString(visible));
427     }
428
429     public String JavaDoc getProperty(String JavaDoc name) {
430         return StringUtils.escapeHTMLTags((String JavaDoc)properties.get(name));
431     }
432
433     public Enumeration propertyNames() {
434         return properties.propertyNames();
435     }
436
437     public void setProperty(String JavaDoc name, String JavaDoc value) {
438         properties.put(name, value);
439         saveProperties();
440     }
441
442     public ForumPermissions getPermissions(Authorization authorization) {
443         if (authorization.getUserID() == id || id==-1 || id==0) {
444             return new ForumPermissions(false,false,false,true,false,false,false,false);
445         }
446         else {
447             return ForumPermissions.none();
448         }
449     }
450
451     public boolean hasPermission(int type) {
452         return true;
453     }
454
455     //FROM THE CACHEABLE INTERFACE//
456

457     public int getSize() {
458         //Approximate the size of the object in bytes by calculating the size
459
//of each field.
460
int size = 0;
461         size += CacheSizes.sizeOfObject(); //overhead of object
462
size += CacheSizes.sizeOfInt(); //id
463
size += CacheSizes.sizeOfString(username); //username
464
size += CacheSizes.sizeOfString(passwordHash); //password
465
size += CacheSizes.sizeOfString(name); //name
466
size += CacheSizes.sizeOfString(email); //email
467
size += CacheSizes.sizeOfBoolean(); //nameVisible
468
size += CacheSizes.sizeOfBoolean(); //emailVisible
469
size += CacheSizes.sizeOfObject(); //property lock
470
size += CacheSizes.sizeOfProperties(properties);//properties object
471
size += CacheSizes.sizeOfLong(); //last login
472
size += CacheSizes.sizeOfLong(); //last post
473

474         return size;
475     }
476
477     //OTHER METHODS
478

479     /**
480      * Returns a String representation of the User object using the username.
481      *
482      * @return a String representation of the User object.
483      */

484     public String JavaDoc toString() {
485         return username;
486     }
487
488     public int hashCode() {
489         return id;
490     }
491
492     public boolean equals(Object JavaDoc object) {
493         if (this == object) {
494             return true;
495         }
496         if (object != null && object instanceof DbUser) {
497             return id == ((DbUser)object).getID();
498         }
499         else {
500             return false;
501         }
502     }
503
504     /**
505      * Loads user properties from the database.
506      */

507     private void loadProperties() {
508         //If "anonymous" or "all users", do nothing.
509
if (id == -1 || id == 0) {
510             properties = new Properties();
511             return;
512         }
513         //Acquire a lock so that no other property loading or saving can be
514
//performed at the same time.
515
synchronized(propertyLock) {
516             Properties newProps = new Properties();
517             Connection con = null;
518             PreparedStatement pstmt = null;
519             try {
520                 con = DbConnectionManager.getConnection();
521                 pstmt = con.prepareStatement(LOAD_PROPERTIES);
522                 pstmt.setInt(1, id);
523                 ResultSet rs = pstmt.executeQuery();
524                 while(rs.next()) {
525                     String JavaDoc name = rs.getString("name");
526                     String JavaDoc value = rs.getString("propValue");
527                     newProps.put(name, value);
528                 }
529             }
530             catch( SQLException sqle ) {
531                 System.err.println("Error in DbUser:loadProperties():" + sqle);
532                 sqle.printStackTrace();
533             }
534             finally {
535                 try { pstmt.close(); }
536                 catch (Exception JavaDoc e) { e.printStackTrace(); }
537                 try { con.close(); }
538                 catch (Exception JavaDoc e) { e.printStackTrace(); }
539             }
540             this.properties = newProps;
541         }
542     }
543
544     /**
545      * Loads user properties from the database.
546      */

547     private void loadLastPost() {
548         if (id == -1 || id == 0) {
549             return;
550         }
551         Connection con = null;
552         PreparedStatement pstmt = null;
553         try {
554             con = DbConnectionManager.getConnection();
555             pstmt = con.prepareStatement(LOAD_LASTPOST);
556             pstmt.setInt(1, id);
557             ResultSet rs = pstmt.executeQuery();
558             if(rs.next()) {
559                 lastpost = Long.parseLong(rs.getString("lastpost"));
560             }
561         }
562         catch( SQLException sqle ) {
563             System.err.println("Error in DbUser:loadProperties():" + sqle);
564             sqle.printStackTrace();
565         }catch(NumberFormatException JavaDoc e){
566             lastpost=-1;
567         }finally {
568             try { pstmt.close(); }
569             catch (Exception JavaDoc e) { e.printStackTrace(); }
570             try { con.close(); }
571             catch (Exception JavaDoc e) { e.printStackTrace(); }
572         }
573
574     }
575
576     /**
577      * Saves user properties to the database.
578      */

579     private void saveProperties() {
580         //If "anonymous" or "all users", do nothing.
581
if (id == -1 || id == 0) {
582             return;
583         }
584         //Acquire a lock so that no other property loading or saving can be
585
//performed at the same time.
586
synchronized(propertyLock) {
587             Connection con = null;
588             PreparedStatement pstmt = null;
589             try {
590                 con = DbConnectionManager.getConnection();
591                 //Delete all old values.
592
pstmt = con.prepareStatement(DELETE_PROPERTIES);
593                 pstmt.setInt(1, id);
594                 pstmt.execute();
595                 pstmt.close();
596                 //Now insert new values.
597
pstmt = con.prepareStatement(INSERT_PROPERTY);
598                 Enumeration enume = properties.keys();
599                 while (enume.hasMoreElements()) {
600                     String JavaDoc name = (String JavaDoc)enume.nextElement();
601                     String JavaDoc value = (String JavaDoc)properties.get(name);
602                     pstmt.setInt(1, id);
603                     pstmt.setString(2, name);
604                     pstmt.setString(3, value);
605                     pstmt.executeUpdate();
606                 }
607             }
608             catch( SQLException sqle ) {
609                 System.err.println(sqle);
610             }
611             finally {
612                 try { pstmt.close(); }
613                 catch (Exception JavaDoc e) { e.printStackTrace(); }
614                 try { con.close(); }
615                 catch (Exception JavaDoc e) { e.printStackTrace(); }
616             }
617         }
618     }
619
620     /**
621      * Load the user data from the database.
622      */

623     private void loadFromDb() throws UserNotFoundException {
624         //If the user is anonymous or "all users", do nothing.
625
if (id == -1 || id == 0) {
626             return;
627         }
628         // Otherwise, select user data from User table and fill in relevant fields.
629
String JavaDoc query;
630         //We may want to do a username lookup.
631
if (username != null) {
632             query = LOAD_USER_BY_USERNAME;
633         }
634         //Otherwise, a lookup by id
635
else {
636             query = LOAD_USER_BY_ID;
637         }
638         Connection con = null;
639         PreparedStatement pstmt = null;
640         try {
641             con = DbConnectionManager.getConnection();
642             pstmt = con.prepareStatement(query);
643             if (username != null) {
644                 pstmt.setString(1, username);
645             }
646             else {
647                 pstmt.setInt(1, id);
648             }
649
650             ResultSet rs = pstmt.executeQuery();
651             if (!rs.next()) {
652                 throw new UserNotFoundException(
653                         "Failed to read user " + id + " from database."
654                 );
655             }
656             this.id = rs.getInt(SystemProperty.getProperty("User.Column.UserID"));
657             this.username = rs.getString(SystemProperty.getProperty("User.Column.Username"));
658             this.passwordHash = rs.getString(SystemProperty.getProperty("User.Column.PasswordHash"));
659             this.name = rs.getString(SystemProperty.getProperty("User.Column.Name"));
660             this.email = rs.getString(SystemProperty.getProperty("User.Column.Email"));
661         }
662         catch( SQLException sqle ) {
663             throw new UserNotFoundException(
664                     "Failed to read user " + id + " from database.", sqle
665             );
666         }
667         finally {
668             try { pstmt.close(); }
669             catch (Exception JavaDoc e) { e.printStackTrace(); }
670             try { con.close(); }
671             catch (Exception JavaDoc e) { e.printStackTrace(); }
672         }
673     }
674
675     /**
676      * Inserts a new user record into the database.
677      */

678     private void insertIntoDb() throws UserAlreadyExistsException{
679         Connection con = null;
680         PreparedStatement pstmt = null;
681         try {
682             con = DbConnectionManager.getConnection();
683             pstmt = con.prepareStatement(INSERT_USER);
684             pstmt.setInt(1, id);
685             pstmt.setString(2, username);
686             pstmt.setString(3, passwordHash);
687             pstmt.setString(4, email);
688             pstmt.executeUpdate();
689         }
690         catch( SQLException sqle ) {
691             System.err.println("Error in DbUser:insertIntoDb()-" + sqle);
692             sqle.printStackTrace();
693         throw new UserAlreadyExistsException();
694         }
695         finally {
696             try { pstmt.close(); }
697             catch (Exception JavaDoc e) { e.printStackTrace(); }
698             try { con.close(); }
699             catch (Exception JavaDoc e) { e.printStackTrace(); }
700         }
701     }
702
703     private void insertAutoGroupMembership(){
704         Connection con = null;
705         PreparedStatement pstmt = null;
706         try {
707             con = DbConnectionManager.getConnection();
708             pstmt = con.prepareStatement(INSERT_AUTO_GROUP);
709             pstmt.setInt(1, id);
710             pstmt.executeUpdate();
711         }
712         catch( SQLException sqle ) {
713             System.err.println("Error in DbUser:insertAutoGroupMembership()-" + sqle);
714             sqle.printStackTrace();
715         }
716         finally {
717             try { pstmt.close(); }
718             catch (Exception JavaDoc e) { e.printStackTrace(); }
719             try { con.close(); }
720             catch (Exception JavaDoc e) { e.printStackTrace(); }
721         }
722
723     }
724     /**
725      * Save the user data to the database.
726      */

727     private void saveToDb() {
728         if ( id == -1 || id == 0 ) {
729             //"anonymous" or "all users", do nothing
730
return;
731         }
732         Connection con = null;
733         PreparedStatement pstmt = null;
734         try {
735             con = DbConnectionManager.getConnection();
736             pstmt = con.prepareStatement(SAVE_USER);
737             pstmt.setString(1, passwordHash);
738             pstmt.setString(2, email);
739             pstmt.setString(3, name);
740             pstmt.setInt(4, id);
741             pstmt.executeUpdate();
742         }
743         catch( SQLException sqle ) {
744             System.err.println( "SQLException in DbUser.java:saveToDb(): " + sqle );
745             sqle.printStackTrace();
746         }
747         finally {
748             try { pstmt.close(); }
749             catch (Exception JavaDoc e) { e.printStackTrace(); }
750             try { con.close(); }
751             catch (Exception JavaDoc e) { e.printStackTrace(); }
752         }
753     }
754 }
755
Popular Tags