KickJava   Java API By Example, From Geeks To Geeks.

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


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 package com.Yasna.forum.database;
55
56 import com.Yasna.forum.*;
57 import com.Yasna.util.Cacheable;
58 import com.Yasna.util.CacheSizes;
59
60 import java.util.Iterator JavaDoc;
61 import java.util.ArrayList JavaDoc;
62 import java.sql.*;
63
64 /**
65  * Database implementation of the Group interface.
66  *
67  * @see Group
68  */

69 public class DbGroup implements Group, Cacheable {
70
71     /** DATABASE QUERIES **/
72     private static final String JavaDoc ADD_ADMIN =
73         "INSERT INTO yazdGroupUser(groupID,userID,administrator) VALUES(?,?,1)";
74     private static final String JavaDoc REMOVE_ADMIN =
75         "DELETE FROM yazdGroupUser WHERE groupID=? AND userID=? AND administrator=1";
76     private static final String JavaDoc ADD_USER =
77         "INSERT INTO yazdGroupUser(groupID,userID,administrator) VALUES(?,?,0)";
78     private static final String JavaDoc REMOVE_USER =
79         "DELETE FROM yazdGroupUser WHERE groupID=? AND userID=? AND administrator=0";
80     private static final String JavaDoc ADMIN_TEST =
81         "SELECT userID FROM yazdGroupUser WHERE groupID=? AND userID=? AND " +
82         "administrator=1";
83     private static final String JavaDoc MEMBER_TEST =
84         "SELECT userID FROM yazdGroupUser WHERE groupID=? AND userID=?";
85     private static final String JavaDoc ADMIN_COUNT =
86         "SELECT count(*) FROM yazdGroupUser WHERE groupID=? " +
87         "AND administrator=1";
88     private static final String JavaDoc MEMBER_COUNT =
89         "SELECT DISTINCT count(userID) FROM yazdGroupUser " +
90         "WHERE groupID=?";
91     private static final String JavaDoc LOAD_ADMINS =
92         "SELECT userID FROM yazdGroupUser WHERE administrator=1 AND groupID=?";
93     private static final String JavaDoc LOAD_USERS =
94         "SELECT userID FROM yazdGroupUser WHERE groupID=?";
95     private static final String JavaDoc LOAD_GROUP_BY_ID =
96         "SELECT * FROM yazdGroup WHERE groupID=?";
97     private static final String JavaDoc LOAD_GROUP_BY_NAME =
98         "SELECT * FROM yazdGroup WHERE name=?";
99     private static final String JavaDoc INSERT_GROUP =
100         "INSERT INTO yazdGroup(name,description,groupID,automember) VALUES(?,?,?,0)";
101     private static final String JavaDoc SAVE_GROUP =
102         "UPDATE yazdGroup SET name=?, description=?,automember=? WHERE groupID=?";
103
104     private int id;
105     private String JavaDoc name = null;
106     private String JavaDoc description = "";
107     private boolean automembership = false;
108
109     private ProfileManager profileManager;
110     private DbForumFactory factory;
111
112     /**
113      * Creates a new group.
114      *
115      * @param the name of the group.
116      * @param profileManager a ProfileManager that can be used to perform user
117      * and group operations.
118      */

119     protected DbGroup(String JavaDoc name, DbForumFactory factory) {
120         this.name = name;
121         this.factory = factory;
122         this.profileManager = factory.getProfileManager();
123         this.id = DbSequenceManager.nextID("Group");
124         insertIntoDb();
125     }
126
127     /**
128      * Loads a group from the database based on its id.
129      *
130      * @param id the id of the group to load.
131      * @param profileManager a ProfileManager that can be used to perform user
132      * and group operations.
133      */

134     protected DbGroup(int id, DbForumFactory factory)
135             throws GroupNotFoundException
136     {
137         this.id = id;
138         this.factory = factory;
139         this.profileManager = factory.getProfileManager();
140         loadFromDb();
141     }
142
143     /**
144      * Loads a group from the database based on its name. The implementation
145      * of this method is rather hackish since it includes a fake parameter just
146      * so that it can have a different method signature than the first
147      * constructor. Even so, this methodology makes this class behave more like
148      * our other classes, so we're gleefully leaving it this way. :)
149      *
150      * @param name the name of the group to load.
151      * @param fake a fake paramater that can always be null.
152      * @param profileManager a ProfileManager that can be used to perform user
153      * and group operations.
154      */

155     protected DbGroup(String JavaDoc name, Object JavaDoc fake, DbForumFactory factory)
156             throws GroupNotFoundException
157     {
158         this.name = name;
159         this.factory = factory;
160         this.profileManager = factory.getProfileManager();
161         loadFromDb();
162     }
163
164     //FROM THE USER INTERFACE//
165

166     public int getID() {
167         return id;
168     }
169
170     public String JavaDoc getName() {
171         return name;
172     }
173      public boolean getAutoGroupMembership(){
174          return automembership;
175      }
176     public void setAutoGroupMembership(boolean param) throws UnauthorizedException{
177         this.automembership=param;
178         saveToDb();
179     }
180     public void setName(String JavaDoc name) throws UnauthorizedException {
181         this.name = name;
182         saveToDb();
183     }
184
185     public String JavaDoc getDescription() {
186         return description;
187     }
188
189     public void setDescription(String JavaDoc description)
190             throws UnauthorizedException
191     {
192         this.description = description;
193         saveToDb();
194     }
195
196     public void addAdministrator(User user) throws UnauthorizedException {
197         Connection con = null;
198         PreparedStatement pstmt = null;
199         try {
200             con = DbConnectionManager.getConnection();
201             pstmt = con.prepareStatement(ADD_ADMIN);
202             pstmt.setInt(1, id);
203             pstmt.setInt(2, user.getID());
204             pstmt.execute();
205         }
206         catch( SQLException sqle ) {
207             sqle.printStackTrace();
208         }
209         finally {
210             try { pstmt.close(); }
211             catch (Exception JavaDoc e) { e.printStackTrace(); }
212             try { con.close(); }
213             catch (Exception JavaDoc e) { e.printStackTrace(); }
214         }
215
216         //Now, remove the user from the USER_PERM_CACHE since being in the
217
//group could affect their permissions.
218
DbCacheManager cacheManager = factory.getCacheManager();
219         cacheManager.removeUserPerm(new Integer JavaDoc(user.getID()));
220     }
221
222     public void removeAdministrator(User user) throws UnauthorizedException {
223         Connection con = null;
224         PreparedStatement pstmt = null;
225         try {
226             con = DbConnectionManager.getConnection();
227             pstmt = con.prepareStatement(REMOVE_ADMIN);
228             pstmt.setInt(1, id);
229             pstmt.setInt(2, user.getID());
230             pstmt.execute();
231         }
232         catch( SQLException sqle ) {
233             sqle.printStackTrace();
234         }
235         finally {
236             try { pstmt.close(); }
237             catch (Exception JavaDoc e) { e.printStackTrace(); }
238             try { con.close(); }
239             catch (Exception JavaDoc e) { e.printStackTrace(); }
240         }
241
242         //Now, remove the user from the USER_PERM_CACHE since being in the
243
//group could affect their permissions.
244
DbCacheManager cacheManager = factory.getCacheManager();
245         cacheManager.removeUserPerm(new Integer JavaDoc(user.getID()));
246     }
247
248     public void addMember(User user) throws UnauthorizedException {
249         Connection con = null;
250         PreparedStatement pstmt = null;
251         try {
252             con = DbConnectionManager.getConnection();
253             pstmt = con.prepareStatement(ADD_USER);
254             pstmt.setInt(1, id);
255             pstmt.setInt(2, user.getID());
256             pstmt.execute();
257         }
258         catch( SQLException sqle ) {
259             sqle.printStackTrace();
260         }
261         finally {
262             try { pstmt.close(); }
263             catch (Exception JavaDoc e) { e.printStackTrace(); }
264             try { con.close(); }
265             catch (Exception JavaDoc e) { e.printStackTrace(); }
266         }
267
268         //Now, remove the user from the USER_PERM_CACHE since being in the
269
//group could affect their permissions.
270
DbCacheManager cacheManager = factory.getCacheManager();
271         cacheManager.removeUserPerm(new Integer JavaDoc(user.getID()));
272     }
273
274     public void removeMember(User user) throws UnauthorizedException {
275         Connection con = null;
276         PreparedStatement pstmt = null;
277         try {
278             con = DbConnectionManager.getConnection();
279             pstmt = con.prepareStatement(REMOVE_USER);
280             pstmt.setInt(1, id);
281             pstmt.setInt(2, user.getID());
282             pstmt.execute();
283         }
284         catch( SQLException sqle ) {
285             sqle.printStackTrace();
286         }
287         finally {
288             try { pstmt.close(); }
289             catch (Exception JavaDoc e) { e.printStackTrace(); }
290             try { con.close(); }
291             catch (Exception JavaDoc e) { e.printStackTrace(); }
292         }
293
294         //Now, remove the user from the USER_PERM_CACHE since being in the
295
//group could affect their permissions.
296
DbCacheManager cacheManager = factory.getCacheManager();
297         cacheManager.removeUserPerm(new Integer JavaDoc(user.getID()));
298     }
299
300     public boolean isAdministrator(User user) {
301         boolean answer = false;
302         Connection con = null;
303         PreparedStatement pstmt = null;
304         try {
305             con = DbConnectionManager.getConnection();
306             pstmt = con.prepareStatement(ADMIN_TEST);
307             pstmt.setInt(1, id);
308             pstmt.setInt(2, user.getID());
309             ResultSet rs = pstmt.executeQuery();
310             if (rs.next()) {
311                 answer = true;
312             }
313         }
314         catch( SQLException sqle ) {
315             sqle.printStackTrace();
316         }
317         finally {
318             try { pstmt.close(); }
319             catch (Exception JavaDoc e) { e.printStackTrace(); }
320             try { con.close(); }
321             catch (Exception JavaDoc e) { e.printStackTrace(); }
322         }
323         return answer;
324     }
325
326     public boolean isMember(User user) {
327         boolean answer = false;
328         Connection con = null;
329         PreparedStatement pstmt = null;
330         try {
331             con = DbConnectionManager.getConnection();
332             pstmt = con.prepareStatement(MEMBER_TEST);
333             pstmt.setInt(1, id);
334             pstmt.setInt(2, user.getID());
335             ResultSet rs = pstmt.executeQuery();
336             if (rs.next()) {
337                 answer = true;
338             }
339         }
340         catch( SQLException sqle ) {
341             sqle.printStackTrace();
342         }
343         finally {
344             try { pstmt.close(); }
345             catch (Exception JavaDoc e) { e.printStackTrace(); }
346             try { con.close(); }
347             catch (Exception JavaDoc e) { e.printStackTrace(); }
348         }
349         return answer;
350     }
351
352     public int getAdministratorCount() {
353         int count = 0;
354         boolean answer = false;
355         Connection con = null;
356         PreparedStatement pstmt = null;
357         try {
358             con = DbConnectionManager.getConnection();
359             pstmt = con.prepareStatement(ADMIN_COUNT);
360             pstmt.setInt(1, id);
361             ResultSet rs = pstmt.executeQuery();
362             if (rs.next()) {
363                 count = rs.getInt(1);
364             }
365         }
366         catch( SQLException sqle ) {
367             sqle.printStackTrace();
368         }
369         finally {
370             try { pstmt.close(); }
371             catch (Exception JavaDoc e) { e.printStackTrace(); }
372             try { con.close(); }
373             catch (Exception JavaDoc e) { e.printStackTrace(); }
374         }
375         return count;
376     }
377
378     public int getMemberCount() {
379         int count = 0;
380         boolean answer = false;
381         Connection con = null;
382         PreparedStatement pstmt = null;
383         try {
384             con = DbConnectionManager.getConnection();
385             pstmt = con.prepareStatement(MEMBER_COUNT);
386             pstmt.setInt(1, id);
387             ResultSet rs = pstmt.executeQuery();
388             if (rs.next()) {
389                 count = rs.getInt(1);
390             }
391         }
392         catch( SQLException sqle ) {
393             sqle.printStackTrace();
394         }
395         finally {
396             try { pstmt.close(); }
397             catch (Exception JavaDoc e) { e.printStackTrace(); }
398             try { con.close(); }
399             catch (Exception JavaDoc e) { e.printStackTrace(); }
400         }
401         return count;
402     }
403
404     public Iterator JavaDoc members() {
405         ArrayList JavaDoc admins = new ArrayList JavaDoc();
406         //Load list of group admins from db.
407
Connection con = null;
408         PreparedStatement pstmt = null;
409
410         try {
411             con = DbConnectionManager.getConnection();
412             pstmt = con.prepareStatement(LOAD_USERS);
413             pstmt.setInt(1, id);
414             ResultSet rs = pstmt.executeQuery();
415             User user = null;
416             while (rs.next()) {
417                 try {
418                     user = profileManager.getUser(rs.getInt("userID"));
419                 }
420                 catch (UserNotFoundException unfe) {
421                     unfe.printStackTrace(System.out);
422                 }
423                 admins.add(user);
424             }
425         }
426         catch( SQLException sqle ) {
427             System.err.println( "SQLException in DbGroup.java:" +
428             "users():reading group data " + sqle );
429             sqle.printStackTrace();
430         }
431         finally {
432             try { pstmt.close(); }
433             catch (Exception JavaDoc e) { e.printStackTrace(); }
434             try { con.close(); }
435             catch (Exception JavaDoc e) { e.printStackTrace(); }
436         }
437         return admins.iterator();
438     }
439
440     public Iterator JavaDoc administrators() {
441         ArrayList JavaDoc admins = new ArrayList JavaDoc();
442         //Load list of group admins from db.
443
Connection con = null;
444         PreparedStatement pstmt = null;
445
446         try {
447             con = DbConnectionManager.getConnection();
448             pstmt = con.prepareStatement(LOAD_ADMINS);
449             pstmt.setInt(1, id);
450             ResultSet rs = pstmt.executeQuery();
451             User user = null;
452             while (rs.next()) {
453                 try {
454                     user = profileManager.getUser(rs.getInt("userID"));
455                 }
456                 catch (UserNotFoundException unfe) {
457                     unfe.printStackTrace(System.out);
458                 }
459                 admins.add(user);
460             }
461         }
462         catch( SQLException sqle ) {
463             System.err.println( "SQLException in DbGroup.java:" +
464             "administrators():reading group data " + sqle );
465             sqle.printStackTrace();
466         }
467         finally {
468             try { pstmt.close(); }
469             catch (Exception JavaDoc e) { e.printStackTrace(); }
470             try { con.close(); }
471             catch (Exception JavaDoc e) { e.printStackTrace(); }
472         }
473         return admins.iterator();
474     }
475
476     public ForumPermissions getPermissions(Authorization authorization) {
477         int userID = authorization.getUserID();
478         try {
479             User user = profileManager.getUser(userID);
480             if (isAdministrator(user)) {
481                 return new ForumPermissions(false, false, false, false,
482                         true, false, false, false);
483             }
484         }
485         catch (Exception JavaDoc e) { }
486
487         return ForumPermissions.none();
488     }
489
490     public boolean hasPermission(int type) {
491         return true;
492     }
493
494     //FROM THE CACHEABLE INTERFACE//
495

496     public int getSize() {
497         //Approximate the size of the object in bytes by calculating the size
498
//of each field.
499
int size = 0;
500         size += CacheSizes.sizeOfObject(); //overhead of object
501
size += CacheSizes.sizeOfInt(); //id
502
size += CacheSizes.sizeOfString(name); //name
503
size += CacheSizes.sizeOfString(description); //description
504
size += CacheSizes.sizeOfObject(); //profile manager ref.
505
size += CacheSizes.sizeOfObject(); //forum factory ref.
506

507         return size;
508     }
509
510     //OTHER METHODS
511

512     /**
513      * Returns a String representation of the Group object using the group name.
514      *
515      * @return a String representation of the Group object.
516      */

517     public String JavaDoc toString() {
518         return name;
519     }
520
521     public int hashCode() {
522         return id;
523     }
524
525     public boolean equals(Object JavaDoc object) {
526         if (this == object) {
527             return true;
528         }
529         if (object != null && object instanceof DbGroup) {
530             return id == ((DbGroup)object).getID();
531         }
532         else {
533             return false;
534         }
535     }
536
537     /**
538      * Load the group data from the database.
539      */

540     private synchronized void loadFromDb() throws GroupNotFoundException {
541         String JavaDoc query;
542         if (name == null) {
543             query = LOAD_GROUP_BY_ID;
544         }
545         else {
546             query = LOAD_GROUP_BY_NAME;
547         }
548         Connection con = null;
549         PreparedStatement pstmt = null;
550         try {
551             con = DbConnectionManager.getConnection();
552             pstmt = con.prepareStatement(query);
553             if (name == null) {
554                 pstmt.setInt(1, id);
555             }
556             else {
557                 pstmt.setString(1, name);
558             }
559             ResultSet rs = pstmt.executeQuery();
560             if (!rs.next()) {
561                 throw new GroupNotFoundException();
562             }
563             this.id = rs.getInt("groupID");
564             this.name = rs.getString("name");
565             this.description = rs.getString("description");
566             this.automembership = (rs.getInt("automember")==1)?true:false;
567         }
568         catch( SQLException sqle ) {
569             System.err.println( "SQLException in DbGroup.java:" +
570             "loadFromDb():reading group data " + sqle );
571             throw new GroupNotFoundException();
572         }
573         finally {
574             try { pstmt.close(); }
575             catch (Exception JavaDoc e) { e.printStackTrace(); }
576             try { con.close(); }
577             catch (Exception JavaDoc e) { e.printStackTrace(); }
578         }
579     }
580
581     /**
582      * Inserts a new record into the database.
583      */

584     private void insertIntoDb() {
585         StringBuffer JavaDoc insert = new StringBuffer JavaDoc();
586         Connection con = null;
587         PreparedStatement pstmt = null;
588         try {
589             con = DbConnectionManager.getConnection();
590             pstmt = con.prepareStatement(INSERT_GROUP);
591             pstmt.setString(1, name);
592             pstmt.setString(2, description);
593             pstmt.setInt(3, id);
594             pstmt.executeUpdate();
595         }
596         catch( SQLException sqle ) {
597             System.err.println("Error in DbGroup:insertIntoDb()-" + sqle);
598             sqle.printStackTrace();
599         }
600         finally {
601             try { pstmt.close(); }
602             catch (Exception JavaDoc e) { e.printStackTrace(); }
603             try { con.close(); }
604             catch (Exception JavaDoc e) { e.printStackTrace(); }
605         }
606     }
607
608     /**
609      * Saves group data to the db.
610      */

611     private synchronized void saveToDb() {
612         Connection con = null;
613         PreparedStatement pstmt = null;
614         try {
615             con = DbConnectionManager.getConnection();
616             pstmt = con.prepareStatement(SAVE_GROUP);
617             pstmt.setString(1, name);
618             pstmt.setString(2, description);
619             pstmt.setInt(3,(automembership?1:0));
620             pstmt.setInt(4, id);
621             pstmt.executeUpdate();
622         }
623         catch( SQLException sqle ) {
624             System.err.println( "SQLException in DbGroup.java:saveToDb(): " + sqle );
625             sqle.printStackTrace();
626         }
627         finally {
628             try { pstmt.close(); }
629             catch (Exception JavaDoc e) { e.printStackTrace(); }
630             try { con.close(); }
631             catch (Exception JavaDoc e) { e.printStackTrace(); }
632         }
633     }
634 }
635
636
Popular Tags