KickJava   Java API By Example, From Geeks To Geeks.

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


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.util.*;
110 import com.Yasna.forum.*;
111 import com.Yasna.forum.util.ClientIP;
112 import com.Yasna.forum.Tasks.EmailWatchManager;
113 import com.Yasna.forum.Tasks.SessionManager;
114 import com.Yasna.forum.Tasks.CleanAccounts;
115
116 import java.sql.*;
117 import java.util.*;
118 import java.io.*;
119
120 /**
121  * Database implementation of the ForumFactory interface.
122  */

123 public class DbForumFactory extends ForumFactory {
124
125     /** DATABASE QUERIES **/
126     private static final String JavaDoc FORUM_COUNT = "SELECT count(*) FROM yazdForum";
127     private static final String JavaDoc DELETE_FORUM = "DELETE FROM yazdForum WHERE forumID=?";
128     private static final String JavaDoc DELETE_CATEGORY = "DELETE FROM yazdCategory WHERE categoryID=?";
129     private static final String JavaDoc DELETE_FORUM_USER_PERMS =
130         "DELETE FROM yazdUserPerm WHERE forumID=?";
131     private static final String JavaDoc DELETE_FORUM_GROUP_PERMS =
132         "DELETE FROM yazdGroupPerm WHERE forumID=?";
133     private static final String JavaDoc DELETE_FORUM_PROPERTIES =
134         "DELETE FROM yazdForumProp WHERE forumID=?";
135     private static final String JavaDoc GET_USER_PERMS =
136          "SELECT DISTINCT permission FROM yazdUserPerm WHERE forumID=? " +
137          "AND userID=?";
138     private static final String JavaDoc USERS_WITH_PERM =
139         "SELECT DISTINCT userID FROM yazdUserPerm WHERE forumID=? AND permission=?";
140     private static final String JavaDoc GET_GROUP_PERMS =
141         "SELECT DISTINCT permission from yazdGroupPerm WHERE forumID=? " +
142         "AND groupID=?";
143     private static final String JavaDoc GROUPS_WITH_PERM =
144         "SELECT DISTINCT groupID FROM yazdGroupPerm WHERE forumID=? AND permission=?";
145     private static final String JavaDoc ALL_MESSAGES =
146         "SELECT messageID FROM yazdMessage";
147     private static final String JavaDoc DELETE_MESSAGE =
148         "DELETE FROM yazdMessage WHERE messageID=?";
149     private static final String JavaDoc INSERT_BLACK_LIST="insert into yazdBlackList(ip,blockcount) values (?,?)";
150     private static final String JavaDoc DELETE_BLACK_LIST="delete from yazdBlackList where ip=?";
151     private static final String JavaDoc SELECT_BLACK_LIST="select blockcount from yazdBlackList where ip=?";
152     private static final String JavaDoc SELECT_ARTICLE_MAP="select threadID from yazdArticleMap where pageKey=? and forumID=?";
153     private static final String JavaDoc SESSION_LIST = "select sessionID,IP,userID from yazdSessions";
154     private static final String JavaDoc YESTERDAY_SESSION_COUNT = "select usercount from yazdUserStats where day_dt=?";
155
156     protected DbCacheManager cacheManager;
157     protected EmailWatchManager watchManager;
158     protected SessionManager sessionManager;
159
160     /**
161      * The profile manager provides access to users and groups.
162      */

163     private ProfileManager profileManager;
164
165     /**
166      * The search indexer periodically runs to index forum content
167      */

168     private DbSearchIndexer searchIndexer;
169
170     /**
171      * Creates a new DbForumFactory.
172      */

173     public DbForumFactory() {
174         watchManager = new EmailWatchManager(this);
175         cacheManager = new DbCacheManager();
176
177         profileManager = new DbProfileManager(this);
178         searchIndexer = new DbSearchIndexer(this);
179         sessionManager = new SessionManager();
180         if(Boolean.valueOf(SystemProperty.getProperty("RemoveNotActiveAccounts")).booleanValue()){
181             new CleanAccounts();
182         }
183     }
184
185     //FROM THE FORUMFACTORY INTERFACE//
186

187     public Forum createForum(String JavaDoc name, String JavaDoc description,
188                              boolean moderated, int forumGroupID,boolean article)
189             throws UnauthorizedException, ForumAlreadyExistsException
190     {
191         Forum newForum = null;
192         try {
193             Forum existingForum = getForum(name);
194
195             //The forum already exists since now exception, so:
196
throw new ForumAlreadyExistsException();
197         }
198         catch (ForumNotFoundException fnfe) {
199             //The forum doesn't already exist so we can create a new one
200
newForum = new DbForum(name, description, moderated, forumGroupID, this,article);
201         }
202         return newForum;
203     }
204
205     public void deleteForum(Forum forum) throws UnauthorizedException {
206         //First, remove forum from memory.
207
cacheManager.remove(DbCacheManager.FORUM_CACHE, new Integer JavaDoc(forum.getID()));
208         cacheManager.remove(DbCacheManager.USER_PERMS_CACHE, new Integer JavaDoc(forum.getID()));
209         cacheManager.remove(DbCacheManager.FORUM_ID_CACHE, forum.getName());
210
211         //Delete all messages and threads in the forum.
212
Iterator threads = forum.threads();
213         while (threads.hasNext()) {
214             ForumThread thread = (ForumThread)threads.next();
215             forum.deleteThread(thread);
216         }
217
218         //Now, delete all filters associated with the forum. We delete in
219
//reverse order since filter indexes will change if we don't delete
220
//the last filter entry.
221
int filterCount = forum.getForumMessageFilters().length;
222         for (int i=filterCount-1; i>=0; i--) {
223             forum.removeForumMessageFilter(i);
224         }
225
226         //Finally, delete the forum itself and all permissions and properties
227
//associated with it.
228
Connection con = null;
229         PreparedStatement pstmt = null;
230         try {
231             con = DbConnectionManager.getConnection();
232             pstmt = con.prepareStatement(DELETE_FORUM);
233             pstmt.setInt(1,forum.getID());
234             pstmt.execute();
235             pstmt.close();
236             //User perms
237
pstmt = con.prepareStatement(DELETE_FORUM_USER_PERMS);
238             pstmt.setInt(1,forum.getID());
239             pstmt.execute();
240             pstmt.close();
241             //Group perms
242
pstmt = con.prepareStatement(DELETE_FORUM_GROUP_PERMS);
243             pstmt.setInt(1,forum.getID());
244             pstmt.execute();
245             pstmt.close();
246             //Properties
247
pstmt = con.prepareStatement(DELETE_FORUM_PROPERTIES);
248             pstmt.setInt(1,forum.getID());
249             pstmt.execute();
250         }
251         catch( Exception JavaDoc sqle ) {
252             System.err.println("Error in DbForumFactory:deleteForum()-" + sqle);
253         }
254         finally {
255             try { pstmt.close(); }
256             catch (Exception JavaDoc e) { e.printStackTrace(); }
257             try { con.close(); }
258             catch (Exception JavaDoc e) { e.printStackTrace(); }
259         }
260     }
261
262     public void deleteCategory(Category category) throws UnauthorizedException {
263         //First, remove forum from memory.
264
cacheManager.remove(DbCacheManager.CATEGORY_CACHE, new Integer JavaDoc(category.getID()));
265         cacheManager.remove(DbCacheManager.CATEGORY_ID_CACHE, category.getName());
266
267         //Delete all forumgroups and forums in the cayegory.
268
Iterator categories = category.forumGroups();
269         while (categories.hasNext()) {
270             ForumGroup forumGroup = (ForumGroup)categories.next();
271             category.deleteForumGroup(forumGroup);
272         }
273
274
275         //Finally, delete the category itself
276
Connection con = null;
277         PreparedStatement pstmt = null;
278         try {
279             con = DbConnectionManager.getConnection();
280             pstmt = con.prepareStatement(DELETE_CATEGORY);
281             pstmt.setInt(1,category.getID());
282             pstmt.execute();
283             pstmt.close();
284         }
285         catch( Exception JavaDoc sqle ) {
286             System.err.println("Error in DbForumFactory:deleteCategory()-" + sqle);
287         }
288         finally {
289             try { pstmt.close(); }
290             catch (Exception JavaDoc e) { e.printStackTrace(); }
291             try { con.close(); }
292             catch (Exception JavaDoc e) { e.printStackTrace(); }
293         }
294     }
295
296     public Iterator forumsModeration(){ //this has to be revisited again
297
return null;
298     }
299     public Forum getForum(int forumID)
300             throws ForumNotFoundException, UnauthorizedException
301     {
302         //If cache is not enabled, do a new lookup of object
303
if (!cacheManager.isCacheEnabled()) {
304             return new DbForum(forumID, this);
305         }
306         //Cache is enabled.
307
Integer JavaDoc forumIDInteger = new Integer JavaDoc(forumID);
308         DbForum forum = (DbForum)cacheManager.get(DbCacheManager.FORUM_CACHE, forumIDInteger);
309         if(forum == null) {
310             forum = new DbForum(forumID, this);
311             cacheManager.add(DbCacheManager.FORUM_CACHE, forumIDInteger, forum);
312         }
313         return forum;
314     }
315
316     public Forum getForum(String JavaDoc name)
317             throws ForumNotFoundException, UnauthorizedException
318     {
319         //If cache is not enabled, do a new lookup of object
320
if (!cacheManager.isCacheEnabled()) {
321             Forum forum = new DbForum(name, this);
322             return forum;
323         }
324         //Cache is enabled.
325
CacheableInteger forumIDInteger = (CacheableInteger)cacheManager.get(
326                 DbCacheManager.FORUM_ID_CACHE,
327                 name
328         );
329         //if id wan't found in cache, load it up and put it there.
330
if (forumIDInteger == null) {
331             Forum forum = new DbForum(name, this);
332             forumIDInteger = new CacheableInteger(new Integer JavaDoc(forum.getID()));
333             cacheManager.add(DbCacheManager.FORUM_ID_CACHE, name, forumIDInteger);
334         }
335         return getForum(forumIDInteger.getInteger().intValue());
336     }
337
338     public int getForumCount() {
339         int forumCount = 0;
340         Connection con = null;
341         PreparedStatement pstmt = null;
342         try {
343             con = DbConnectionManager.getConnection();
344             pstmt = con.prepareStatement(FORUM_COUNT);
345             ResultSet rs = pstmt.executeQuery();
346             rs.next();
347             forumCount = rs.getInt(1);
348         }
349         catch( SQLException sqle ) {
350             System.err.println("DbForumFactory:getForumCount() failed: " + sqle);
351         }
352         finally {
353             try { pstmt.close(); }
354             catch (Exception JavaDoc e) { e.printStackTrace(); }
355             try { con.close(); }
356             catch (Exception JavaDoc e) { e.printStackTrace(); }
357         }
358         return forumCount;
359     }
360
361     public Iterator forums() {
362         return new DbForumFactoryIterator(this);
363     }
364     public Iterator forumsWithArticlesForums(){
365         return new DbForumFactoryIterator(this);
366     }
367     public Category getCategory(int categoryID)
368             throws CategoryNotFoundException, UnauthorizedException
369     {
370         //If cache is not enabled, do a new lookup of object
371
if (!cacheManager.isCacheEnabled()) {
372             return new DbCategory(categoryID, this);
373         }
374         //Cache is enabled.
375
Integer JavaDoc categoryIDInteger = new Integer JavaDoc(categoryID);
376         DbCategory category = (DbCategory)cacheManager.get(DbCacheManager.CATEGORY_CACHE, categoryIDInteger);
377         if(category == null) {
378             category = new DbCategory(categoryID, this);
379             cacheManager.add(DbCacheManager.CATEGORY_CACHE, categoryIDInteger, category);
380         }
381         return category;
382     }
383
384     public Category getCategory(String JavaDoc name)
385             throws CategoryNotFoundException, UnauthorizedException
386     {
387         //If cache is not enabled, do a new lookup of object
388
if (!cacheManager.isCacheEnabled()) {
389             Category category = new DbCategory(name, this);
390             return category;
391         }
392         //Cache is enabled.
393
CacheableInteger categoryIDInteger = (CacheableInteger)cacheManager.get(
394                 DbCacheManager.CATEGORY_ID_CACHE,
395                 name
396         );
397         //if id wan't found in cache, load it up and put it there.
398
if (categoryIDInteger == null) {
399             Category category = new DbCategory(name, this);
400             categoryIDInteger = new CacheableInteger(new Integer JavaDoc(category.getID()));
401             cacheManager.add(DbCacheManager.CATEGORY_ID_CACHE, name, categoryIDInteger);
402         }
403         return getCategory(categoryIDInteger.getInteger().intValue());
404     }
405
406     public Iterator categories() {
407         return new DbCategoryIterator(this);
408     }
409
410     public Category createCategory(String JavaDoc name, String JavaDoc description)
411             throws UnauthorizedException, CategoryAlreadyExistsException
412     {
413         Category newCategory = null;
414         try {
415             Category existingCategory = getCategory(name);
416
417             //The forum already exists since now exception, so:
418
throw new CategoryAlreadyExistsException();
419         }
420         catch (CategoryNotFoundException fnfe) {
421             //The forum doesn't already exist so we can create a new one
422
newCategory = new DbCategory(name, description, this);
423         }
424         return newCategory;
425     }
426
427     public ProfileManager getProfileManager() {
428         return profileManager;
429     }
430
431     public SearchIndexer getSearchIndexer() {
432         return searchIndexer;
433     }
434
435     public int[] usersWithPermission(int permissionType)
436             throws UnauthorizedException
437     {
438         int [] users = new int[0];
439         Connection con = null;
440         PreparedStatement pstmt = null;
441         try {
442             con = DbConnectionManager.getConnection();
443             pstmt = con.prepareStatement(USERS_WITH_PERM);
444             pstmt.setInt(1,-1);
445             pstmt.setInt(2,permissionType);
446             ResultSet rs = pstmt.executeQuery();
447             ArrayList userList = new ArrayList();
448             while (rs.next()) {
449                 userList.add(new Integer JavaDoc(rs.getInt("userID")));
450             }
451             users = new int[userList.size()];
452             for (int i=0; i<users.length; i++) {
453                 users[i] = ((Integer JavaDoc)userList.get(i)).intValue();
454             }
455         }
456         catch( SQLException sqle ) {
457             sqle.printStackTrace();
458         }
459         finally {
460             try { pstmt.close(); }
461             catch (Exception JavaDoc e) { e.printStackTrace(); }
462             try { con.close(); }
463             catch (Exception JavaDoc e) { e.printStackTrace(); }
464         }
465         return users;
466     }
467
468     public int[] groupsWithPermission(int permissionType)
469             throws UnauthorizedException
470     {
471         int [] groups = new int[0];
472         Connection con = null;
473         PreparedStatement pstmt = null;
474         try {
475             con = DbConnectionManager.getConnection();
476             pstmt = con.prepareStatement(GROUPS_WITH_PERM);
477             pstmt.setInt(1,-1);
478             pstmt.setInt(2,permissionType);
479             ResultSet rs = pstmt.executeQuery();
480             ArrayList groupList = new ArrayList();
481             while (rs.next()) {
482                 groupList.add(new Integer JavaDoc(rs.getInt("groupID")));
483             }
484             groups = new int[groupList.size()];
485             for (int i=0; i<groups.length; i++) {
486                 groups[i] = ((Integer JavaDoc)groupList.get(i)).intValue();
487             }
488         }
489         catch( SQLException sqle ) {
490             System.err.println("Error in DbForum.groupsWithPermission:" + sqle);
491             sqle.printStackTrace();
492         }
493         finally {
494             try { pstmt.close(); }
495             catch (Exception JavaDoc e) { e.printStackTrace(); }
496             try { con.close(); }
497             catch (Exception JavaDoc e) { e.printStackTrace(); }
498         }
499         return groups;
500     }
501
502     public ForumPermissions getPermissions(Authorization authorization) {
503         int userID = authorization.getUserID();
504
505         //Get the user perm cache for this forum
506
Cache userPermCache = (Cache)getCacheManager().get(
507             DbCacheManager.USER_PERMS_CACHE,
508             new Integer JavaDoc(-1)
509         );
510
511         //Simple case: if cache is turned on and the user is already cached,
512
//we can simply return the cached permissions.
513
if (userPermCache != null) {
514             ForumPermissions permissions =
515                     (ForumPermissions)userPermCache.get(new Integer JavaDoc(userID));
516             if (permissions != null) {
517                 return permissions;
518             }
519         }
520
521         //Not so simple case: cache is not turned on or the user permissions
522
//have not been cached yet.
523
boolean isAnonymous = (userID == -1);
524         boolean isUser = !isAnonymous;
525
526         ForumPermissions finalPermissions = ForumPermissions.none();
527     // check each forum for a specific permission
528
/*Iterator allForums = this.forums();
529     Forum forum;
530     ForumPermissions forumUserPermissions;
531     while (allForums.hasNext()){
532         forum = (Forum)allForums.next();
533         forumUserPermissions = getUserPermissions(userID,forum.getID());
534                 finalPermissions = new ForumPermissions(finalPermissions, forumUserPermissions);
535     } */

536
537
538         //Step 1 - Get permissions for the User. This includes anonymous
539
//perms, "special user" perms, and the specific perms for the user.
540
if (isUser) {
541             ForumPermissions userPermissions = getUserPermissions(userID, -1);
542             //Combine permissions
543
finalPermissions = new ForumPermissions(finalPermissions, userPermissions);
544         }
545         //Add in anonymous perms.
546
ForumPermissions anonyPermissions = null;
547         if (userPermCache != null) {
548             anonyPermissions = (ForumPermissions)userPermCache.get(new Integer JavaDoc(-1));
549         }
550         //Otherwise, do our own lookup.
551
if (anonyPermissions == null) {
552             anonyPermissions = getUserPermissions(-1, -1);
553             //Add to cache so it will be there next time.
554
if (userPermCache != null) {
555                 userPermCache.add(new Integer JavaDoc(-1), anonyPermissions);
556             }
557         }
558         //Combine permissions
559
finalPermissions = new ForumPermissions(finalPermissions, anonyPermissions);
560
561         //If they are a valid user, figure out "any user" permissions.
562
if (isUser) {
563             ForumPermissions specialUserPermissions = null;
564             //Check for cache
565
if (userPermCache != null) {
566                 specialUserPermissions = (ForumPermissions)userPermCache.get(new Integer JavaDoc(0));
567             }
568             //Otherwise, do our own lookup.
569
if (specialUserPermissions == null) {
570                 specialUserPermissions = getUserPermissions(0, -1);
571                 //Add to cache so it will be there next time.
572
if (userPermCache != null) {
573                     userPermCache.add(new Integer JavaDoc(0), specialUserPermissions);
574                 }
575             }
576             //Combine permissions
577
finalPermissions = new ForumPermissions(finalPermissions, specialUserPermissions);
578         }
579
580         //Step 2 -- get Permissions for all groups the user is in.
581
int [] groups = ((DbProfileManager)getProfileManager()).getUserGroups(userID);
582         for (int i=0; i<groups.length; i++) {
583             ForumPermissions groupPermissions = getGroupPermissions(groups[i], -1);
584             finalPermissions = new ForumPermissions(finalPermissions, groupPermissions);
585         }
586
587         //Finally, add user to cache so it will be there next time.
588
if (isUser && userPermCache != null) {
589             userPermCache.add(new Integer JavaDoc(userID), finalPermissions);
590         }
591
592         return finalPermissions;
593     }
594
595     public boolean hasPermission(int type) {
596         return true;
597     }
598
599     //OTHER METHODS//
600

601     /**
602      * Returns the cache manager object.
603      */

604     public DbCacheManager getCacheManager() {
605         return cacheManager;
606     }
607     /**
608      * returns the watch manager. This is only used by this package.
609      * @return watchmanager
610      */

611     public EmailWatchManager getWatchManager(){
612         return watchManager;
613     }
614     public SessionManager getSessionManager(){
615         return sessionManager;
616     }
617
618     /**
619      * Cleans the Yazd database of "junk". This is currently defined as: <ul>
620      * <li> Messages with no subject or body.
621      * <li> Messages that do not belong to a thread.</ul>
622      *
623      * Please be aware that this method will <b>permanently</b> delete forum
624      * content. You may want to perform a database backup before calling this
625      * method.<p>
626      *
627      * This method requires two database connections and may take a long time
628      * to execute, as it must iterate through ever message record in the
629      * database.
630      */

631     public void cleanDatabase() {
632         //Iterate through all forums, threads to delete unwanted messages.
633
Iterator forums = forums();
634         while (forums.hasNext()) {
635             Forum forum = (Forum)forums.next();
636             Iterator threads = forum.threads();
637             while (threads.hasNext()) {
638                 try {
639                     ForumThread thread = (ForumThread)threads.next();
640                     Iterator messages = thread.messages();
641                     while (messages.hasNext()) {
642                         try {
643                             ForumMessage message = (ForumMessage)messages.next();
644                             //System.err.println("Evaluating message " + message.getID() + " for deletion");
645
if (/*message.getSubject() == null ||*/ message.getBody() == null) {
646                                 //System.err.println("Deleting message...");
647
thread.deleteMessage(message);
648                             }
649                         }
650                         catch (Exception JavaDoc me) {
651                             me.printStackTrace();
652                         }
653                     }
654                 }
655                 catch (Exception JavaDoc te) {
656                     te.printStackTrace();
657                 }
658             }
659         }
660
661 /*
662         //Select all message ID's directly from the message table.
663         Connection con = null;
664         PreparedStatement pstmt = null;
665         try {
666             con = DbConnectionManager.getConnection();
667             pstmt = con.prepareStatement(ALL_MESSAGES);
668             ResultSet rs = pstmt.executeQuery();
669             while(rs.next()) {
670                 try {
671                     int messageID = rs.getInt(1);
672                     //Convert to object
673                     ForumMessage message = new DbForumMessage(messageID, this);
674                     ForumThread thread = message.getForumThread();
675                     if (thread == null) {
676                         //manually delete this message from the database. It won't
677                         //appear in any search indexes or in any threads, so this
678                         //shouldn't have any side effects.
679                         Connection con2 = null;
680                         PreparedStatement pstmt2 = null;
681                         try {
682                             con2 = DbConnectionManager.getConnection();
683                             pstmt2 = con.prepareStatement(DELETE_MESSAGE);
684                             pstmt2.setInt(1, messageID);
685                             pstmt2.execute();
686                         }
687                         catch( SQLException sqle ) {
688                             sqle.printStackTrace();
689                         }
690                         finally {
691                             try { pstmt2.close(); }
692                             catch (Exception e) { e.printStackTrace(); }
693                             try { con2.close(); }
694                             catch (Exception e) { e.printStackTrace(); }
695                         }
696                     }
697                 }
698                 catch (ForumMessageNotFoundException fmnfe) {
699                     fmnfe.printStackTrace();
700                 }
701             }
702         }
703         catch( SQLException sqle ) {
704             sqle.printStackTrace();
705         }
706         finally {
707             try { pstmt.close(); }
708             catch (Exception e) { e.printStackTrace(); }
709             try { con.close(); }
710             catch (Exception e) { e.printStackTrace(); }
711         }
712 */

713     }
714
715     /**
716      * Returns a thread specified by its id. Will return null
717      * if the thread is not in the forum. If cache is turned
718      * on, it will use it.
719      */

720     public DbForumThread getThread(int threadID, DbForum forum) throws
721             ForumThreadNotFoundException
722     {
723         //If cache is not enabled, do a new lookup of object
724
if (!cacheManager.isCacheEnabled()) {
725             return new DbForumThread(threadID, forum, this);
726         }
727         //Cache is enabled.
728
Integer JavaDoc threadIDInteger = new Integer JavaDoc(threadID);
729         DbForumThread thread = (DbForumThread)cacheManager.get(
730                 DbCacheManager.THREAD_CACHE,
731                 threadIDInteger
732         );
733         if(thread == null) {
734             thread = new DbForumThread(threadID, forum, this);
735             //System.err.println("Aflatoon adding to cache");
736
cacheManager.add(DbCacheManager.THREAD_CACHE, threadIDInteger, thread);
737         }
738         return thread;
739     }
740
741     /**
742      * Returns a forumgroup specified by its id. Will return null
743      * if the forumgroup is not in the category. If cache is turned
744      * on, it will use it.
745      */

746     public DbForumGroup getForumGroup(int forumGroupID, DbCategory category) throws
747             ForumGroupNotFoundException
748     {
749         //If cache is not enabled, do a new lookup of object
750
if (!cacheManager.isCacheEnabled()) {
751             return new DbForumGroup(forumGroupID, category, this);
752         }
753         //Cache is enabled.
754
Integer JavaDoc forumGroupIDInteger = new Integer JavaDoc(forumGroupID);
755         DbForumGroup forumGroup = (DbForumGroup)cacheManager.get(
756                 DbCacheManager.FORUM_GROUP_CACHE,
757                 forumGroupIDInteger
758         );
759         if(forumGroup == null) {
760             forumGroup = new DbForumGroup(forumGroupID, category, this);
761             cacheManager.add(DbCacheManager.FORUM_GROUP_CACHE, forumGroupIDInteger, forumGroup);
762         }
763         return forumGroup;
764     }
765
766     /**
767      * Returns a message from the thread based on its id. If cache is turned
768      * on, it will use it.
769      *
770      * @param messageID the ID of the message to get from the thread.
771      */

772     protected DbForumMessage getMessage(int messageID)
773             throws ForumMessageNotFoundException
774     {
775         //If cache is not enabled, do a new lookup of object
776
if (!cacheManager.isCacheEnabled()) {
777             return new DbForumMessage(messageID, this);
778         }
779         //Cache is enabled.
780
Integer JavaDoc messageIDInteger = new Integer JavaDoc(messageID);
781         DbForumMessage message = (DbForumMessage)cacheManager.get(
782                 DbCacheManager.MESSAGE_CACHE,
783                 messageIDInteger
784         );
785         if(message == null) {
786             //Load the message
787
message = new DbForumMessage(messageID, this);
788             //Add it to cache.
789
cacheManager.add(DbCacheManager.MESSAGE_CACHE, messageIDInteger, message);
790         }
791         return message;
792     }
793
794     /**
795      * Logs events in the system. Very beginnings here....
796      */

797     protected void log(String JavaDoc message, Exception JavaDoc e) {
798         System.err.println("Log event : " + message);
799         e.printStackTrace();
800     }
801
802     /**
803      * Returns the permissions that a particular user has for the forum.
804      */

805     protected ForumPermissions getUserPermissions(int userID, int forumID) {
806         Connection con = null;
807         PreparedStatement pstmt = null;
808         //Initialize a permissions array with no permissions.
809
boolean [] permissions = new boolean[8];
810         for (int i=0; i<permissions.length; i++) {
811             permissions[i] = false;
812         }
813         try {
814             con = DbConnectionManager.getConnection();
815             pstmt = con.prepareStatement(GET_USER_PERMS);
816             pstmt.setInt(1, forumID);
817             pstmt.setInt(2, userID);
818             ResultSet rs = pstmt.executeQuery();
819             while(rs.next()) {
820                 int newPerm = rs.getInt("permission");
821                 permissions[newPerm] = true;
822             }
823         }
824         catch( SQLException sqle ) {
825             System.err.println("Error in DbForum.java:" + sqle);
826             sqle.printStackTrace();
827         }
828         finally {
829             try { pstmt.close(); }
830             catch (Exception JavaDoc e) { e.printStackTrace(); }
831             try { con.close(); }
832             catch (Exception JavaDoc e) { e.printStackTrace(); }
833         }
834         return new ForumPermissions(permissions);
835     }
836
837     /**
838      * Returns the permissions that a particular group has for the forum.
839      */

840     protected ForumPermissions getGroupPermissions(int groupID, int forumID) {
841         Connection con = null;
842         PreparedStatement pstmt = null;
843         //Initialize a permissions array with no permissions.
844
boolean [] permissions = new boolean[8];
845         for (int i=0; i<permissions.length; i++) {
846             permissions[i] = false;
847         }
848         try {
849             con = DbConnectionManager.getConnection();
850             pstmt = con.prepareStatement(GET_GROUP_PERMS);
851             pstmt.setInt(1, forumID);
852             pstmt.setInt(2, groupID);
853             ResultSet rs = pstmt.executeQuery();
854             while(rs.next()) {
855                 int newPerm = rs.getInt("permission");
856                 permissions[newPerm] = true;
857             }
858         }
859         catch( SQLException sqle ) {
860             sqle.printStackTrace();
861         }
862         finally {
863             try { pstmt.close(); }
864             catch (Exception JavaDoc e) { e.printStackTrace(); }
865             try { con.close(); }
866             catch (Exception JavaDoc e) { e.printStackTrace(); }
867         }
868         return new ForumPermissions(permissions);
869     }
870     public Query createQuery(){
871         return new DbQuery(this);
872     }
873     public void BlackListIP(ClientIP cip,boolean add) throws UnauthorizedException{
874         Connection con = null;
875         PreparedStatement pstmt = null;
876         try {
877             con = DbConnectionManager.getConnection();
878             if(add){
879                 pstmt = con.prepareStatement(INSERT_BLACK_LIST);
880                 pstmt.setString(1,cip.getRemoteIP());
881                 pstmt.setInt(2,0);
882             }else{
883                 pstmt = con.prepareStatement(DELETE_BLACK_LIST);
884                 pstmt.setString(1,cip.getRemoteIP());
885             }
886             pstmt.executeUpdate();
887         }
888         catch( SQLException sqle ) {
889             sqle.printStackTrace();
890         }
891         finally {
892             try { pstmt.close(); }
893             catch (Exception JavaDoc e) { e.printStackTrace(); }
894             try { con.close(); }
895             catch (Exception JavaDoc e) { e.printStackTrace(); }
896         }
897
898     }
899     public boolean isBlackListed(ClientIP cip){
900         boolean bl=false;
901
902         Connection con = null;
903         PreparedStatement pstmt = null;
904         try {
905             con = DbConnectionManager.getConnection();
906             pstmt = con.prepareStatement(SELECT_BLACK_LIST);
907             pstmt.setString(1,cip.getRemoteIP());
908             ResultSet rs = pstmt.executeQuery();
909             if(rs.next()){
910                 bl = true;
911             }
912         }
913         catch( SQLException sqle ) {
914             sqle.printStackTrace();
915         }
916         finally {
917             try { pstmt.close(); }
918             catch (Exception JavaDoc e) { e.printStackTrace(); }
919             try { con.close(); }
920             catch (Exception JavaDoc e) { e.printStackTrace(); }
921         }
922
923         return bl;
924
925     }
926     public ForumThread getArticleThread(String JavaDoc pageKey,Forum forum) throws ForumThreadNotFoundException,UnauthorizedException{
927         Connection con = null;
928         PreparedStatement pstmt = null;
929         ForumThread thread=null;
930         try {
931             con = DbConnectionManager.getConnection();
932             pstmt = con.prepareStatement(SELECT_ARTICLE_MAP);
933             pstmt.setString(1,pageKey);
934             pstmt.setInt(2,forum.getID());
935             ResultSet rs = pstmt.executeQuery();
936             if(rs.next()){
937                 thread=this.getThread(rs.getInt("threadID"),(DbForum)this.getForum(forum.getID()));
938             } else{
939                 throw new ForumThreadNotFoundException();
940             }
941         }catch( SQLException sqle ) {
942             sqle.printStackTrace();
943         }
944         catch(ForumNotFoundException e){
945
946         }
947         finally {
948             try { pstmt.close(); }
949             catch (Exception JavaDoc e) { e.printStackTrace(); }
950             try { con.close(); }
951             catch (Exception JavaDoc e) { e.printStackTrace(); }
952         }
953         return thread;
954
955     }
956     public ThreadType getThreadType(int typeid){
957         //If cache is not enabled, do a new lookup of object
958
if (!cacheManager.isCacheEnabled()) {
959             return new DbThreadType(typeid);
960         }
961         //Cache is enabled.
962
Integer JavaDoc typeIDInteger = new Integer JavaDoc(typeid);
963         DbThreadType type = (DbThreadType)cacheManager.get(
964                 DbCacheManager.THREAD_TYPE_ID_CACHE,
965                 typeIDInteger
966         );
967         if(type == null) {
968             //Load the message
969
type = new DbThreadType(typeid);
970             //Add it to cache.
971
cacheManager.add(DbCacheManager.THREAD_TYPE_ID_CACHE, typeIDInteger, type);
972         }
973         return type;
974
975     }
976     public Iterator getThreadTypeIterator(){
977         return new DbThreadTypeIterator(this);
978     }
979     public Iterator getSessionList(){
980         Connection con = null;
981         PreparedStatement pstmt = null;
982         ArrayList sessions=new ArrayList();
983         try {
984             con = DbConnectionManager.getConnection();
985             pstmt = con.prepareStatement(SESSION_LIST);
986             ResultSet rs = pstmt.executeQuery();
987             while(rs.next()){
988                 sessions.add(
989                         new SessionVO(rs.getString("sessionID"),rs.getString("IP"),rs.getInt("userID"))
990                 );
991             }
992         }catch( SQLException sqle ) {
993             sqle.printStackTrace();
994         }
995         finally {
996             try { pstmt.close(); }
997             catch (Exception JavaDoc e) { e.printStackTrace(); }
998             try { con.close(); }
999             catch (Exception JavaDoc e) { e.printStackTrace(); }
1000        }
1001        return sessions.iterator();
1002
1003    }
1004    public int getYesterdayUserCount(){
1005        Connection con = null;
1006        PreparedStatement pstmt = null;
1007        int usercount=0;
1008        Calendar now = Calendar.getInstance();
1009        int now_in_minutes = (int)(now.getTimeInMillis()*1.0/(1000.0 * 60.0));
1010        int now_today = (int)(now_in_minutes * 1.0/(60.0 * 24.0));
1011        try {
1012            con = DbConnectionManager.getConnection();
1013            pstmt = con.prepareStatement(YESTERDAY_SESSION_COUNT);
1014            pstmt.setInt(1,now_today-1);
1015            ResultSet rs = pstmt.executeQuery();
1016            if(rs.next()){
1017                usercount = rs.getInt("usercount");
1018            }
1019        }catch( SQLException sqle ) {
1020            sqle.printStackTrace();
1021        }
1022        finally {
1023            try { pstmt.close(); }
1024            catch (Exception JavaDoc e) { e.printStackTrace(); }
1025            try { con.close(); }
1026            catch (Exception JavaDoc e) { e.printStackTrace(); }
1027        }
1028        return usercount;
1029
1030    }
1031
1032}
1033
Popular Tags