KickJava   Java API By Example, From Geeks To Geeks.

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


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 java.util.*;
110 import java.sql.*;
111 import com.Yasna.forum.*;
112 import com.Yasna.util.*;
113
114 /**
115  * Database implementation of the ProfileManager interface.
116  */

117 public class DbProfileManager implements ProfileManager {
118
119     /** DATABASE QUERIES **/
120     private static final String JavaDoc USER_GROUPS =
121         "SELECT groupID from yazdGroupUser WHERE userID=?";
122     private static final String JavaDoc USER_MESSAGE_COUNT =
123         "SELECT count(*) FROM yazdMessage,yazdForum,yazdThread WHERE " +
124         "yazdMessage.userID=? AND yazdForum.forumID=? AND " +
125         "yazdThread.forumID=yazdForum.forumID AND " +
126         "yazdMessage.threadID=yazdThread.threadID";
127     private static final String JavaDoc USER_COUNT = "SELECT count(*) FROM "+SystemProperty.getProperty("User.Table");
128     private static final String JavaDoc ALL_USER_MESSAGES =
129         "SELECT messageID FROM yazdMessage WHERE userID=?";
130     private static final String JavaDoc DELETE_USER_MESSAGES =
131         "UPDATE yazdMessage set userID=-1 WHERE userID=?";
132     private static final String JavaDoc DELETE_USER_PERMS =
133         "DELETE FROM yazdUserPerm WHERE userID=?";
134     private static final String JavaDoc DELETE_USER_GROUPS =
135         "DELETE FROM yazdGroupUser WHERE userID=?";
136     private static final String JavaDoc DELETE_USER_PROPS =
137         "DELETE FROM yazdUserProp WHERE userID=?";
138     private static final String JavaDoc DELETE_USER =
139         "DELETE FROM "+SystemProperty.getProperty("User.Table")+" WHERE "+SystemProperty.getProperty("User.Column.UserID")+"=?";
140     private static final String JavaDoc GROUP_COUNT = "SELECT count(*) FROM yazdGroup";
141     private static final String JavaDoc DELETE_GROUP_USERS =
142         "DELETE FROM yazdGroupUser WHERE groupID=?";
143     private static final String JavaDoc DELETE_GROUP =
144         "DELETE FROM yazdGroup WHERE groupID=?";
145
146     private User anonymousUser = null;
147     private User specialUser = null;
148     private DbForumFactory factory;
149
150
151     /**
152      * Creates a new ProfileManager.
153      */

154     public DbProfileManager(DbForumFactory factory) {
155         this.factory = factory;
156         try {
157             anonymousUser = getUser(-1);
158             specialUser = getUser(0);
159         }
160         catch (UserNotFoundException unfe) { }
161     }
162
163     //FROM THE PROFILEMANAGER INTERFACE//
164

165     public User createUser(String JavaDoc username, String JavaDoc password, String JavaDoc email)
166             throws UserAlreadyExistsException
167     {
168         User newUser = null;
169         try {
170             User existingUser = getUser(username);
171
172             //The user already exists since now exception, so:
173
throw new UserAlreadyExistsException();
174         }
175         catch (UserNotFoundException unfe) {
176             //The user doesn't already exist so we can create a new user
177
newUser = new DbUser(username, password, email);
178         }
179         return newUser;
180     }
181     public boolean activateUser(int userID, String JavaDoc Code){
182         DbUser user;
183         boolean success=false;
184         try{
185         DbCacheManager cacheManager = factory.getCacheManager();
186         //If cache is not enabled, do a new lookup of object
187
if (!cacheManager.isCacheEnabled()) {
188             user= new DbUser(userID);
189         }
190         //Cache is enabled.
191
Integer JavaDoc userIDInteger = new Integer JavaDoc(userID);
192         user = (DbUser)cacheManager.get(
193                 DbCacheManager.USER_CACHE,
194                 userIDInteger
195         );
196         if(user == null) {
197             user = new DbUser(userID);
198             cacheManager.add(DbCacheManager.USER_CACHE, userIDInteger, user);
199         }
200         }catch(Exception JavaDoc e){
201             return success;
202         }
203         if (user.getProperty("notactive")!=null && user.getProperty("notactive").equals(Code)){
204             user.activateUser();
205             return true;
206         } else{
207             return false;
208         }
209
210     }
211     public User getUser(int userID) throws UserNotFoundException {
212         DbCacheManager cacheManager = factory.getCacheManager();
213         //If cache is not enabled, do a new lookup of object
214
if (!cacheManager.isCacheEnabled()) {
215             return new DbUser(userID);
216         }
217         //Cache is enabled.
218
Integer JavaDoc userIDInteger = new Integer JavaDoc(userID);
219         DbUser user = (DbUser)cacheManager.get(
220                 DbCacheManager.USER_CACHE,
221                 userIDInteger
222         );
223         if(user == null) {
224             user = new DbUser(userID);
225             cacheManager.add(DbCacheManager.USER_CACHE, userIDInteger, user);
226         }
227         return user;
228     }
229
230     public User getUser(String JavaDoc username) throws UserNotFoundException {
231         DbCacheManager cacheManager = factory.getCacheManager();
232         //If cache is not enabled, do a new lookup of object
233
if (!cacheManager.isCacheEnabled()) {
234             User user = new DbUser(username);
235             return getUser(user.getID());
236         }
237         //Cache is enabled.
238
CacheableInteger userIDInteger = (CacheableInteger)cacheManager.get(
239                 DbCacheManager.USER_ID_CACHE,
240                 username
241         );
242         //if id wan't found in cache, load it up and put it there.
243
if (userIDInteger == null) {
244             User user = new DbUser(username);
245             userIDInteger = new CacheableInteger(new Integer JavaDoc(user.getID()));
246             cacheManager.add(DbCacheManager.USER_ID_CACHE, username, userIDInteger);
247         }
248         return getUser(userIDInteger.getInteger().intValue());
249     }
250
251     public User getAnonymousUser() {
252         return anonymousUser;
253     }
254
255     public User getSpecialUser() {
256         return specialUser;
257     }
258
259     public void deleteUser(User user) throws UnauthorizedException {
260         int userID = user.getID();
261         int [] messages;
262         //Get array of all user's messages in the system so that
263
//we can expire them from cache.
264
ArrayList tempMessages = new ArrayList();
265         Connection con = null;
266         PreparedStatement pstmt = null;
267         try {
268             con = DbConnectionManager.getConnection();
269             pstmt = con.prepareStatement(ALL_USER_MESSAGES);
270             pstmt.setInt(1, user.getID());
271             ResultSet rs = pstmt.executeQuery();
272             while (rs.next()) {
273                 tempMessages.add(new Integer JavaDoc(rs.getInt("messageID")));
274             }
275         }
276         catch( SQLException sqle ) {
277             System.err.println("Error in DbProfileManager:deleteUser()-" + sqle);
278             sqle.printStackTrace();
279         }
280         finally {
281             try { pstmt.close(); }
282             catch (Exception JavaDoc e) { e.printStackTrace(); }
283             try { con.close(); }
284             catch (Exception JavaDoc e) { e.printStackTrace(); }
285         }
286         //Now copy into an array.
287
messages = new int[tempMessages.size()];
288         for (int i=0; i<messages.length; i++) {
289             messages[i] = ((Integer JavaDoc)tempMessages.get(i)).intValue();
290         }
291
292         con = null;
293         pstmt = null;
294         try {
295             con = DbConnectionManager.getConnection();
296             //mark all message by user as anonymous
297
pstmt = con.prepareStatement(DELETE_USER_MESSAGES);
298             pstmt.setInt(1,userID);
299             pstmt.execute();
300             pstmt.close();
301             //remove all permissions given to user
302
pstmt = con.prepareStatement(DELETE_USER_PERMS);
303             pstmt.setInt(1,userID);
304             pstmt.execute();
305             pstmt.close();
306             //remove user from all groups
307
pstmt = con.prepareStatement(DELETE_USER_GROUPS);
308             pstmt.setInt(1,userID);
309             pstmt.execute();
310             pstmt.close();
311             //delete all of the users's extended properties
312
pstmt = con.prepareStatement(DELETE_USER_PROPS);
313             pstmt.setInt(1,userID);
314             pstmt.execute();
315             pstmt.close();
316             //delete the actual user entry
317
pstmt = con.prepareStatement(DELETE_USER);
318             pstmt.setInt(1,userID);
319             pstmt.execute();
320         }
321         catch( SQLException sqle ) {
322             sqle.printStackTrace();
323         }
324         finally {
325             try { pstmt.close(); }
326             catch (Exception JavaDoc e) { e.printStackTrace(); }
327             try { con.close(); }
328             catch (Exception JavaDoc e) { e.printStackTrace(); }
329         }
330
331         //Finally, expire all relevant caches
332
//all of users's messages
333
DbCacheManager cacheManager = factory.getCacheManager();
334         for (int i=0; i<messages.length; i++) {
335             cacheManager.remove(
336                     DbCacheManager.MESSAGE_CACHE,
337                     new Integer JavaDoc(messages[i])
338             );
339         }
340         //user cache
341
cacheManager.remove(DbCacheManager.USER_ID_CACHE, user.getUsername());
342         cacheManager.remove(DbCacheManager.USER_CACHE, new Integer JavaDoc(userID));
343     }
344
345     public Group createGroup(String JavaDoc name) throws UnauthorizedException,
346             GroupAlreadyExistsException
347     {
348         Group newGroup = null;
349         try {
350             Group existingGroup = getGroup(name);
351
352             //The group already exists since now exception, so:
353
throw new GroupAlreadyExistsException();
354         }
355         catch (GroupNotFoundException unfe) {
356             //The group doesn't already exist so we can create a new group
357
newGroup = new DbGroup(name, factory);
358         }
359         return newGroup;
360     }
361
362     public Group getGroup(int groupID) throws GroupNotFoundException {
363         DbCacheManager cacheManager = factory.getCacheManager();
364         //If cache is not enabled, do a new lookup of object
365
if (!cacheManager.isCacheEnabled()) {
366             return new DbGroup(groupID, factory);
367         }
368         //Cache is enabled.
369
Integer JavaDoc groupIDInteger = new Integer JavaDoc(groupID);
370         DbGroup group = (DbGroup)cacheManager.get(
371                 DbCacheManager.GROUP_CACHE,
372                 groupIDInteger
373         );
374         if(group == null) {
375             group = new DbGroup(groupID, factory);
376             cacheManager.add(DbCacheManager.GROUP_CACHE, groupIDInteger, group);
377         }
378         return group;
379     }
380
381     public Group getGroup(String JavaDoc name) throws GroupNotFoundException {
382         DbCacheManager cacheManager = factory.getCacheManager();
383         //If cache is not enabled, do a new lookup of object
384
if (!cacheManager.isCacheEnabled()) {
385             Group group = new DbGroup(name, null, factory);
386             return getGroup(group.getID());
387         }
388         //Cache is enabled.
389
CacheableInteger groupIDInteger = (CacheableInteger)cacheManager.get(
390                 DbCacheManager.GROUP_ID_CACHE,
391                 name
392         );
393         //if id wan't found in cache, load it up and put it there.
394
if (groupIDInteger == null) {
395             Group group = new DbGroup(name, null, factory);
396             groupIDInteger = new CacheableInteger(new Integer JavaDoc(group.getID()));
397             cacheManager.add(DbCacheManager.GROUP_ID_CACHE, name, groupIDInteger);
398         }
399         return getGroup(groupIDInteger.getInteger().intValue());
400     }
401
402     public void deleteGroup(Group group) throws UnauthorizedException {
403         int groupID = group.getID();
404         int [] members = new int[group.getMemberCount()];
405         Iterator iter = group.members();
406         for (int i=0; i<members.length; i++) {
407             User user = (User)iter.next();
408             members[i] = user.getID();
409         }
410
411         Connection con = null;
412         PreparedStatement pstmt = null;
413         try {
414             con = DbConnectionManager.getConnection();
415             //mark all message by user as anonymous
416
pstmt = con.prepareStatement(DELETE_GROUP_USERS);
417             pstmt.setInt(1,groupID);
418             pstmt.execute();
419             pstmt.close();
420             //remove all permissions given to user
421
pstmt = con.prepareStatement(DELETE_GROUP);
422             pstmt.setInt(1,groupID);
423             pstmt.execute();
424             pstmt.close();
425         }
426         catch( SQLException sqle ) {
427             sqle.printStackTrace();
428         }
429         finally {
430             try { pstmt.close(); }
431             catch (Exception JavaDoc e) { e.printStackTrace(); }
432             try { con.close(); }
433             catch (Exception JavaDoc e) { e.printStackTrace(); }
434         }
435
436         //Finally, expire all relevant caches
437
DbCacheManager cacheManager = factory.getCacheManager();
438         cacheManager.remove(DbCacheManager.GROUP_ID_CACHE, group.getName());
439         cacheManager.remove(DbCacheManager.GROUP_CACHE, new Integer JavaDoc(groupID));
440         //Removing a group can change the permissions of all the users in that
441
//group. Therefore, remove each user from the user perms cache.
442
for (int i=0; i<members.length; i++) {
443             cacheManager.removeUserPerm(new Integer JavaDoc(members[i]));
444         }
445     }
446
447     public int getUserCount() {
448         int count = 0;
449         Connection con = null;
450         PreparedStatement pstmt = null;
451         try {
452             con = DbConnectionManager.getConnection();
453             pstmt = con.prepareStatement(USER_COUNT);
454             ResultSet rs = pstmt.executeQuery();
455             if (rs.next()) {
456                 count = rs.getInt(1);
457             }
458         }
459         catch( SQLException sqle ) {
460             sqle.printStackTrace();
461         }
462         finally {
463             try { pstmt.close(); }
464             catch (Exception JavaDoc e) { e.printStackTrace(); }
465             try { con.close(); }
466             catch (Exception JavaDoc e) { e.printStackTrace(); }
467         }
468         return count;
469     }
470
471     public int getGroupCount() {
472         int count = 0;
473         Connection con = null;
474         PreparedStatement pstmt = null;
475         try {
476             con = DbConnectionManager.getConnection();
477             pstmt = con.prepareStatement(GROUP_COUNT);
478             ResultSet rs = pstmt.executeQuery();
479             if (rs.next()) {
480                 count = rs.getInt(1);
481             }
482         }
483         catch( SQLException sqle ) {
484             sqle.printStackTrace();
485         }
486         finally {
487             try { pstmt.close(); }
488             catch (Exception JavaDoc e) { e.printStackTrace(); }
489             try { con.close(); }
490             catch (Exception JavaDoc e) { e.printStackTrace(); }
491         }
492         return count;
493     }
494
495     public Iterator users() {
496         return new DbUserIterator(this);
497     }
498
499     public Iterator users(int startIndex, int numResults) {
500         return new DbUserIterator(this, startIndex, numResults);
501     }
502
503     public Iterator groups() {
504         return new DbGroupIterator(this);
505     }
506
507     public Iterator groups(int startIndex, int numResults) {
508         return new DbGroupIterator(this, startIndex, numResults);
509     }
510
511     public int userMessageCount(User user, Forum forum) {
512         int count = 0;
513         Connection con = null;
514         PreparedStatement pstmt = null;
515         try {
516             con = DbConnectionManager.getConnection();
517             pstmt = con.prepareStatement(USER_MESSAGE_COUNT);
518             pstmt.setInt(1, user.getID());
519             pstmt.setInt(2, forum.getID());
520             ResultSet rs = pstmt.executeQuery();
521             if (rs.next()) {
522                 count = rs.getInt(1);
523             }
524         }
525         catch( SQLException sqle ) {
526             sqle.printStackTrace();
527         }
528         finally {
529             try { pstmt.close(); }
530             catch (Exception JavaDoc e) { e.printStackTrace(); }
531             try { con.close(); }
532             catch (Exception JavaDoc e) { e.printStackTrace(); }
533         }
534         return count;
535     }
536
537     public Iterator userMessages(User user, Forum forum,int start,int numRes) {
538         return new DbUserMessagesIterator(factory, user, forum,start,numRes);
539     }
540
541     /**
542      * Returns an array of all the groups that the user belongs to.
543      */

544     protected int[] getUserGroups(int userID) {
545         Connection con = null;
546         PreparedStatement pstmt = null;
547         int [] groups = new int[0];
548         try {
549             con = DbConnectionManager.getConnection();
550             pstmt = con.prepareStatement(USER_GROUPS);
551             pstmt.setInt(1,userID);
552             ResultSet rs = pstmt.executeQuery();
553             ArrayList groupList = new ArrayList();
554             while (rs.next()) {
555                 groupList.add(new Integer JavaDoc(rs.getInt("groupID")));
556             }
557             groups = new int[groupList.size()];
558             for (int i=0; i<groups.length; i++) {
559                 groups[i] = ((Integer JavaDoc)groupList.get(i)).intValue();
560             }
561         }
562         catch( SQLException sqle ) {
563             sqle.printStackTrace();
564         }
565         finally {
566             try { pstmt.close(); }
567             catch (Exception JavaDoc e) { e.printStackTrace(); }
568             try { con.close(); }
569             catch (Exception JavaDoc e) { e.printStackTrace(); }
570         }
571         return groups;
572     }
573 }
574
Popular Tags