KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > killingar > forum > internal > managers > ForumManager


1 /* Copyright 2000-2005 Anders Hovmöller
2  *
3  * The person or persons who have associated their work with
4  * this document (the "D<gedicator") hereby dedicate the entire
5  * copyright in the work of authorship identified below (the
6  * "Work") to the public domain.
7  *
8  * Dedicator makes this dedication for the benefit of the
9  * public at large and to the detriment of Dedicator's heirs
10  * and successors. Dedicator intends this dedication to be an
11  * overt act of relinquishment in perpetuity of all present
12  * and future rights under copyright law, whether vested or
13  * contingent, in the Work. Dedicator understands that such
14  * relinquishment of all rights includes the relinquishment of
15  * all rights to enforce (by lawsuit or otherwise) those
16  * copyrights in the Work.
17  *
18  * Dedicator recognizes that, once placed in the public
19  * domain, the Work may be freely reproduced, distributed,
20  * transmitted, used, modified, built upon, or otherwise
21  * exploited by anyone for any purpose, commercial or non-
22  * commercial, and in any way, including by methods that have
23  * not yet been invented or conceived.
24  */

25
26 /**
27  * Main manager for the forum.
28  */

29 package net.killingar.forum.internal.managers;
30
31 import net.killingar.StringUtils;
32 import net.killingar.forum.internal.*;
33 import net.killingar.forum.internal.caches.GroupMembershipsCache;
34 import net.killingar.forum.internal.caches.GroupsCache;
35 import net.killingar.forum.internal.caches.UserItem;
36 import net.killingar.forum.internal.caches.UsersCache;
37
38 import java.sql.*;
39 import java.util.*;
40
41 public final class ForumManager extends AbstractManager implements java.io.Serializable JavaDoc
42 {
43     public static final long NOT_LOGGED_IN = -1;
44     private long mUserID = NOT_LOGGED_IN;
45     private transient Map managers;
46     private TimeManager times;
47     private static transient UsersCache usersCache = new UsersCache();
48     private static transient GroupsCache groupsCache = new GroupsCache();
49     private static transient GroupMembershipsCache groupMembershipsCache = new GroupMembershipsCache(usersCache, groupsCache);
50
51     // cached data
52
//private static Map accessLevels = new HashMap();
53

54     // general methods
55
public ForumManager() throws SQLException, ClassNotFoundException JavaDoc, InstantiationException JavaDoc, IllegalAccessException JavaDoc
56   {
57         managers = new HashMap();
58         initialize();
59         manager = this;
60         times = (TimeManager)getManager(TimeManager.class.getName());
61   }
62
63     private void readObject(java.io.ObjectInputStream JavaDoc in) throws java.io.IOException JavaDoc, ClassNotFoundException JavaDoc
64     {
65         in.defaultReadObject();
66         managers = new HashMap();
67     }
68
69     /**
70      * Initialize this class.
71      * Set up database connectivity and initialize all registered managers.
72      */

73     public void initialize() throws ClassNotFoundException JavaDoc, SQLException
74     {
75         Set s = managers.entrySet();
76         AbstractManager a = null;
77         for (Iterator i = s.iterator(); i.hasNext(); a = (AbstractManager)i.next());
78         {
79             if (a != null)
80                 a.initialize(this);
81         }
82     }
83
84     /**
85      * Send action to managers.
86      */

87     public void sendAction(String JavaDoc action)
88     {
89         Set s = managers.entrySet();
90         AbstractManager a = null;
91         for (Iterator i = s.iterator(); i.hasNext(); a = (AbstractManager)((Map.Entry)i.next()).getValue());
92         {
93             if (a != null)
94                 a.actionPerformed(action);
95         }
96     }
97
98     /**
99      * Get a manager. If none exists with the given class name, one will be created.
100      */

101     public AbstractManager getManager(String JavaDoc className) throws ClassNotFoundException JavaDoc, InstantiationException JavaDoc, IllegalAccessException JavaDoc
102     {
103         synchronized (managers)
104         {
105             AbstractManager a = (AbstractManager)managers.get(className);
106             if (a == null)
107             {
108                 a = (AbstractManager)Class.forName(className).newInstance();
109                 a.initialize(this);
110                 managers.put(className, a);
111             }
112
113             return a;
114         }
115     }
116
117     public AreaHotlistManager getAreaHotlistManager() throws ClassNotFoundException JavaDoc, InstantiationException JavaDoc, IllegalAccessException JavaDoc
118     {
119         return (AreaHotlistManager)getManager(AreaHotlistManager.class.getName());
120     }
121
122     /**
123      * Login a user.
124      * Sends: "logout", "login", "login failed"
125      */

126     public boolean login(String JavaDoc username, String JavaDoc password) throws SQLException, ClassNotFoundException JavaDoc
127     {
128         return login(username, password, null);
129     }
130   public boolean login(String JavaDoc username, String JavaDoc password, String JavaDoc source) throws SQLException, ClassNotFoundException JavaDoc
131   {
132         logout();
133
134     if (username == null || password == null)
135     {
136       // error
137
return false;
138     }
139
140         username = username.trim();
141
142         Connection c = null;
143         PreparedStatement statement = null;
144         ResultSet result = null;
145
146         try
147         {
148             try
149             {
150                 c = getNewConnection();
151                 statement = c.prepareStatement("select ID from Users where Name = ? AND Password = ?");
152                 statement.setString(1, username);
153                 statement.setString(2, StringUtils.passwordEncode(password));
154
155                 // check userid/password
156
result = statement.executeQuery();
157                 if (result.next())
158                 {
159                     mUserID = result.getLong(1);
160                     sendAction("login");
161
162                     System.out.println("SKForum: login succeeded: "+getUserID()+" "+username);
163
164                     if (source != null)
165                     {
166                         statement.close();
167                         result.close();
168                         c.close();
169                         c = getNewConnection();
170                         statement = c.prepareStatement("insert into Log (UpdateTime, Message) values(NOW(), ?)");
171                         statement.setString(1, "login succeeded: "+getUserID()+" "+username+" "+source);
172                         statement.executeUpdate();
173                     }
174
175                     return true; // user authenticated
176
}
177                 else
178                 {
179                     // migration support
180
statement.close();
181                     result.close();
182                     c.close();
183                     c = getNewConnection();
184                     statement = c.prepareStatement("select ID from Users where Name = ? AND Password = PASSWORD(?)");
185                     statement.setString(1, username);
186                     statement.setString(2, password);
187                     result = statement.executeQuery();
188                     if (result.next())
189                     {
190                         mUserID = result.getLong(1);
191                         sendAction("login");
192
193                         statement = c.prepareStatement("update Users set Password = ? where ID = ?");
194                         statement.setString(1, StringUtils.passwordEncode(password));
195                         statement.setLong(2, mUserID);
196                         statement.executeUpdate();
197
198                         System.out.println("SKForum: login success, migration done");
199                         return true; // user authenticated
200
}
201                 }
202             }
203             catch (SQLException e)
204             {
205                 e.printStackTrace();
206                 System.out.println("SKForum: run installer");
207
208                 // this is the first login ever
209

210                 // run installer
211
try
212                 {
213                     net.killingar.forum.Install.createTables();
214                 }
215                 catch (SQLException ex)
216                 {
217                     System.out.println("SKForum: Installation failed");
218                     ex.printStackTrace();
219                     throw ex;
220                 }
221             }
222             finally { closeAll(c, statement, result); c = null; statement = null; result = null; }
223
224             c = getNewConnection();
225             statement = c.prepareStatement("select count(*) from Users");
226             result = statement.executeQuery();
227
228             if (!result.next() || result.getLong(1) != 0)
229             {
230                 mUserID = NOT_LOGGED_IN;
231                 sendAction("login failed");
232                 System.out.println("SKForum: login failed: "+username);
233
234                 if (source != null)
235                 {
236                     statement.close();
237                     result.close();
238                     c.close();
239                     c = getNewConnection();
240                     statement = c.prepareStatement("insert into Log (UpdateTime, Message) values(NOW(), ?)");
241                     statement.setString(1, "login failed: "+username+" "+source);
242                     statement.executeUpdate();
243                 }
244                 return false; // error
245
}
246             else
247             {
248                 // create the user we've been given, create admin group and add him to it
249
statement = c.prepareStatement("insert into Users (Name, Password, LastChanged, LastChangedUser) values(?, ?, NOW(), ?)");
250                 statement.setString(1, username);
251                 statement.setString(2, StringUtils.passwordEncode(password));
252                 statement.setLong(3, manager.getUserID());
253                 statement.executeUpdate();
254
255                 result = statement.getGeneratedKeys();
256                 result.next();
257                 mUserID = result.getLong(1);
258
259                 statement = c.prepareStatement("insert into Groups (User, Name, Access, Type, LastChanged, LastChangedUser) values(? , 'administrators', 9223372036854775807, 'admin', NOW(), ?)");
260                 statement.setLong(1, manager.getUserID());
261                 statement.setLong(2, manager.getUserID());
262                 statement.executeUpdate();
263                 result = statement.getGeneratedKeys();
264                 result.next();
265                 long adminGroupID = result.getLong(1);
266
267                 statement = c.prepareStatement("insert into GroupMemberships (Parent, User, LastChanged, LastChangedUser) values(?, ?, NOW(), 0)");
268                 statement.setLong(1, adminGroupID);
269                 statement.setLong(2, manager.getUserID());
270                 statement.executeUpdate();
271
272                 sendAction("login");
273
274                 System.out.println("SKForum: Installation succeeded");
275                 return true;
276             }
277         }
278         finally { closeAll(c, statement, result); }
279     }
280
281     /**
282      * Logout.
283      * Sends: "logout"
284      */

285     public void logout()
286     {
287         mUserID = NOT_LOGGED_IN;
288         sendAction("logout");
289         managers.clear();
290     }
291
292     /**
293      * Returns true if the user is logged in.
294      */

295     public boolean isLoggedIn()
296     {
297         return mUserID != NOT_LOGGED_IN;
298     }
299
300     /**
301      * Get the user id of the currently logged in user.
302      */

303     public long getUserID()
304     {
305         return mUserID;
306     }
307
308     // user methods
309
/**
310      * Returns the key to set the password of the specified user.
311      * This method is only to be used by password forget features that send email and similar.
312      */

313     public String JavaDoc getNewPasswordKey(String JavaDoc inUsername) throws SQLException
314     {
315         Connection c = null;
316         PreparedStatement statement = null;
317         ResultSet result = null;
318
319         try
320         {
321             c = getNewConnection();
322             statement = c.prepareStatement("select NewPasswordKey from Users where Name = ?");
323             statement.setString(1, inUsername);
324
325             result = statement.executeQuery();
326       result.next();
327             String JavaDoc r = result.getString(1);
328
329             if (r == null)
330             {
331                 r = Integer.toHexString((int)(Math.random()*Integer.MAX_VALUE));
332                 statement = c.prepareStatement("update Users set LastChanged = NOW(), LastChangedUser = NULL, NewPasswordKey = ? where Name = ?");
333                 statement.setString(1, r);
334                 statement.setString(2, inUsername);
335                 statement.executeUpdate();
336             }
337
338             return r;
339         }
340         finally { closeAll(c, statement, result); }
341     }
342
343     public String JavaDoc getSecretEmail(String JavaDoc inUsername) throws SQLException
344     {
345         Connection c = null;
346         PreparedStatement statement = null;
347         ResultSet result = null;
348
349         try
350         {
351             c = getNewConnection();
352             statement = c.prepareStatement("select SecretEmail, Email, PublicEmail from Users where Name = ?");
353             statement.setString(1, inUsername);
354
355             result = statement.executeQuery();
356       result.next();
357             String JavaDoc r = result.getString(1);
358
359             if (r == null)
360                 r = result.getString(2);
361
362             if (r == null)
363                 r = result.getString(3);
364
365             return r;
366         }
367         finally { closeAll(c, statement, result); }
368     }
369
370     public void setNewPassword(String JavaDoc inUsername, String JavaDoc inNewPassword, String JavaDoc inKey) throws SQLException, AccessDeniedException
371     {
372         Connection c = null;
373         PreparedStatement statement = null;
374         ResultSet result = null;
375
376         try
377         {
378             c = getNewConnection();
379             statement = c.prepareStatement("select NewPasswordKey from Users where Name = ?");
380             statement.setString(1, inUsername);
381
382             result = statement.executeQuery();
383       result.next();
384             String JavaDoc key = result.getString(1);
385
386             if (!inKey.equals(key))
387                 throw new AccessDeniedException("incorrect key specified");
388
389             statement = c.prepareStatement("update Users set LastChanged = NOW(), LastChangedUser = ?, Password = ?, NewPasswordKey = null where Name = ?");
390             statement.setLong(1, manager.getUserID());
391             statement.setString(2, StringUtils.passwordEncode(inNewPassword));
392             statement.setString(3, inUsername);
393
394       statement.executeUpdate();
395         }
396         finally { closeAll(c, statement, result); }
397     }
398
399     /**
400      * Change a users details.
401      * Sends: "change user"
402      */

403   public void changeUser(User user, String JavaDoc newpassword) throws SQLException, AccessDeniedException
404     {
405         if (user.ID != mUserID)
406             checkMyAccess(AccessLevel.changeUser);
407
408         checkMyAccess(AccessLevel.userDetails);
409
410         Connection c = null;
411         PreparedStatement statement = null;
412         ResultSet result = null;
413
414         try
415         {
416             c = getNewConnection();
417
418             // change username
419
User oldData = getUser(user.ID);
420             if (!oldData.name.equals(user.name))
421             {
422                 statement = c.prepareStatement("select ID from Users where Name = ? AND ID != ?");
423                 statement.setString(1, user.name);
424                 statement.setLong(2, user.ID);
425                 result = statement.executeQuery();
426                 if (result.next())
427                     throw new AccessDeniedException("username taken");
428
429         statement = c.prepareStatement("update Users set LastChanged = NOW(), LastChangedUser = ?, Name = ? where ID = ?");
430                 statement.setLong(1, manager.getUserID());
431                 statement.setString(2, user.name);
432                 statement.setLong(3, user.ID);
433                 statement.executeUpdate();
434             }
435
436             // change password
437
if (newpassword != null && newpassword.length() > 0)
438             {
439         statement = c.prepareStatement("update Users set LastChanged = NOW(), LastChangedUser = ?, Password = ? where ID = ?");
440                 statement.setLong(1, manager.getUserID());
441                 statement.setString(2, StringUtils.passwordEncode(newpassword));
442                 statement.setLong(3, user.ID);
443                 statement.executeUpdate();
444             }
445
446             // change details
447
statement = c.prepareStatement("update Users set LastChanged = NOW(), LastChangedUser = ?, Icq = ?, Email = ?, PublicEmail = ?, SecretEmail = ?, Telephone = ?, Mobilephone = ?, Address = ?, Other = ?, Birthdate = ?, RealName = ? where ID = ?");
448             statement.setLong(1, manager.getUserID());
449             statement.setString(2, user.icq);
450             statement.setString(3, user.restrictedEmail);
451             statement.setString(4, user.publicEmail);
452             statement.setString(5, user.secretEmail);
453             statement.setString(6, user.telephone);
454             statement.setString(7, user.mobilephone);
455             statement.setString(8, user.address);
456             statement.setString(9, user.other);
457             statement.setDate(10, user.birthdate);
458             statement.setString(11, user.realName);
459             statement.setLong(12, user.ID);
460
461             statement.executeUpdate();
462
463             // update cache
464
//usersCache.add(user);
465
usersCache.add(new UserItem(
466                 new User(
467                     user.ID,
468                     user.name,
469                     user.publicEmail),
470
471                 user));
472
473             sendAction("change user");
474         }
475         finally { closeAll(c, statement, result); }
476   }
477
478     /**
479      * Add a user.
480      * Sends: "add user"
481      */

482   public long addUser(User user, String JavaDoc password) throws SQLException, AccessDeniedException
483   {
484         if (getUserID() != NOT_LOGGED_IN)
485             checkMyAccess(AccessLevel.addUser);
486
487         Connection c = null;
488         PreparedStatement statement = null;
489         ResultSet result = null;
490
491         try
492         {
493             c = getNewConnection();
494             statement = c.prepareStatement(
495                 "insert into Users ("+
496                     // public data
497
"Name, "+
498                     "PublicEmail, "+
499                     // secret data
500
"Password, "+
501                     "SecretEmail, "+
502                     // restricted data
503
"Email, "+
504                     "Icq, "+
505                     "Telephone, "+
506                     "Mobilephone, "+
507                     "Address, "+
508                     "Other, "+
509                     "RealName, "+
510                     "Birthdate, "+
511                     "LastChanged, "+
512                     "LastChangedUser) "+
513                 "values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?)");
514
515             statement.setString(1, user.name);
516             statement.setString(2, user.publicEmail);
517             // secret data
518
statement.setString(3, StringUtils.passwordEncode(password));
519             statement.setString(4, user.secretEmail);
520             // restricted data
521
statement.setString(5, user.restrictedEmail);
522             statement.setString(6, user.icq);
523             statement.setString(7, user.telephone);
524             statement.setString(8, user.mobilephone);
525             statement.setString(9, user.address);
526             statement.setString(10, user.other);
527             statement.setString(11, user.realName);
528             statement.setDate(12, user.birthdate);
529             statement.setLong(13, manager.getUserID());
530
531             statement.executeUpdate();
532             result = statement.getGeneratedKeys();
533             result.next();
534             user.ID = result.getLong(1);
535
536             // update cache
537
getUser(user.ID);
538
539             sendAction("add user");
540
541             if (getUserID() == NOT_LOGGED_IN) // self-creation of account, set defaults
542
{
543                 Properties p = net.killingar.Utils.getProperties();
544
545                 long groups[] = Utils.getLongsFromString(p.getProperty(getClass().getName()+".addUserExternal.memberOf"));
546                 long hotlistAreasActive[] = Utils.getLongsFromString(p.getProperty(getClass().getName()+".addUserExternal.hotlist.active.areas"));
547                 long hotlistAreasPassive[] = Utils.getLongsFromString(p.getProperty(getClass().getName()+".addUserExternal.hotlist.passive.areas"));
548                 long hotlistAreaGroupsActive[] = Utils.getLongsFromString(p.getProperty(getClass().getName()+".addUserExternal.hotlist.active.areaGroups"));
549                 long hotlistAreaGroupsPassive[] = Utils.getLongsFromString(p.getProperty(getClass().getName()+".addUserExternal.hotlist.passive.areaGroups"));
550
551                 for (int i = 0; i != groups.length; i++) statement.executeUpdate("insert into GroupMemberships (Parent, User, LastChanged, LastChangedUser) values("+groups[i]+", "+user.getId()+", NOW(), "+manager.getUserID()+")");
552                 for (int i = 0; i != hotlistAreasActive.length; i++) statement.executeUpdate("insert into AreaHotlist (User, Area, AreaGroup, System) values ("+user.getId()+", "+hotlistAreasActive[i]+", null, "+AreaHotlistManager.systemActive+")");
553                 for (int i = 0; i != hotlistAreasPassive.length; i++) statement.executeUpdate("insert into AreaHotlist (User, Area, AreaGroup, System) values ("+user.getId()+", "+hotlistAreasPassive[i]+", null, "+AreaHotlistManager.systemPassive+")");
554                 for (int i = 0; i != hotlistAreaGroupsActive.length; i++) statement.executeUpdate("insert into AreaHotlist (User, Area, AreaGroup, System) values ("+user.getId()+", null, "+hotlistAreaGroupsActive[i]+", "+AreaHotlistManager.systemActive+")");
555                 for (int i = 0; i != hotlistAreaGroupsPassive.length; i++) statement.executeUpdate("insert into AreaHotlist (User, Area, AreaGroup, System) values ("+user.getId()+", null, "+hotlistAreaGroupsPassive[i]+", "+AreaHotlistManager.systemPassive+")");
556             }
557
558             return user.ID;
559         }
560         finally { closeAll(c, statement, result); }
561   }
562
563     /**
564      * Get a list of users that match the search string.
565      */

566     public User[] searchUsers(String JavaDoc search) throws SQLException
567     {
568         Connection c = null;
569         PreparedStatement statement = null;
570         ResultSet result = null;
571
572         try
573         {
574             c = getNewConnection();
575             statement = c.prepareStatement(
576                 "select "+
577                                 " ID, Name, PublicEmail, Email, Icq, Telephone, Mobilephone, Address, Other, RealName, Birthdate "+
578                                 "from "+
579                                 " Users "+
580                                 "where "+
581                 " match (Name, Email, Icq, Telephone, Mobilephone, Address, Other, Realname, Publicemail) against (?)");
582             statement.setString(1, search);
583
584             result = statement.executeQuery();
585             List v = new ArrayList();
586             while (result.next())
587             {
588                 long userID = result.getLong(1);
589                 if (sharesRestrictedGroup(mUserID, userID) || hasAccess(mUserID, AccessLevel.viewUser))
590                 {
591                     v.add(new User(
592                         userID,
593                         result.getString(2),
594                         result.getString(3),
595                         result.getString(4),
596                         null,
597                         result.getString(5),
598                         result.getString(6),
599                         result.getString(7),
600                         result.getString(8),
601                         result.getString(9),
602                         result.getString(10),
603                         result.getDate (11)));
604                 }
605
606                 else
607                 {
608                     v.add(new User(
609                         userID,
610                         result.getString(2),
611                         result.getString(3),
612                         null,
613                         null,
614                         null,
615                         null,
616                         null,
617                         null,
618                         null,
619                         null,
620                         null));
621                 }
622             }
623
624             User r[] = new User[v.size()];
625             v.toArray(r);
626             return r;
627         }
628         finally { closeAll(c, statement, result); }
629     }
630
631     /**
632      * Get a list of all users.
633      */

634     public User[] getUsers() throws SQLException
635     {
636         // FIXME: use the cache system
637

638         Connection c = null;
639         PreparedStatement statement = null;
640         ResultSet result = null;
641
642         try
643         {
644             c = getNewConnection();
645             statement = c.prepareStatement(
646                  "select "+
647                                 " ID, Name, PublicEmail, Email, SecretEmail, Icq, Telephone, Mobilephone, Address, Other, RealName, Birthdate "+
648                                 "from "+
649                 " Users order by Name");
650
651             result = statement.executeQuery();
652             List v = new ArrayList();
653             while (result.next())
654             {
655                 long userID = result.getLong(1);
656                 if (!sharesRestrictedGroup(mUserID, userID) && !hasAccess(mUserID, AccessLevel.viewUser))
657                 {
658                     v.add(new User(
659                         userID,
660                         result.getString(2),
661                         null,
662                         null,
663                         null,
664                         null,
665                         null,
666                         null,
667                         null,
668                         null,
669                         null,
670                         null));
671                 }
672
673                 else
674                 {
675                     v.add(new User(
676                         userID,
677                         result.getString(2),
678                         result.getString(3),
679                         result.getString(4),
680                         (userID == mUserID)?result.getString(5):null,
681                         result.getString(6),
682                         result.getString(7),
683                         result.getString(8),
684                         result.getString(9),
685                         result.getString(10),
686                         result.getString(11),
687                         result.getDate (12)));
688                 }
689
690             }
691
692             User r[] = new User[v.size()];
693             v.toArray(r);
694             return r;
695         }
696         finally { closeAll(c, statement, result); }
697     }
698
699     /**
700      * Get the info of a user.
701      */

702     public User getUser(long userID) throws SQLException
703     {
704         return usersCache.getUser(this, userID);
705     }
706
707     /**
708      * Get the info of a user given the user name.
709      */

710     public User getUser(String JavaDoc username) throws SQLException
711     {
712         return usersCache.getUser(this, username);
713     }
714
715     /**
716      * Get the number of days since a user read the forum.
717      */

718     public long daysSinceUserRead(long userID) throws SQLException
719     {
720         return (System.currentTimeMillis()-times.getUserTime(userID, TimeManager.systemWelcome).getTime())/(1000*60*60*24);
721     }
722
723     // group methods
724
/**
725      * Get a list of groups.
726      */

727     public Group[] getGroups() throws SQLException
728     {
729         // FIXME: use the cache system
730

731         Connection c = null;
732         PreparedStatement statement = null;
733         ResultSet result = null;
734
735         try
736         {
737             c = getNewConnection();
738             statement = c.prepareStatement("select ID, User, Access, Name, Type from Groups order by Name");
739
740             result = statement.executeQuery();
741             List v = new ArrayList();
742             while (result.next())
743             {
744                 v.add(new Group(
745                     result.getLong(1),
746                     result.getLong(2),
747                     result.getLong(3),
748                     result.getString(4),
749                     result.getString(5)));
750             }
751
752             Group r[] = new Group[v.size()];
753             v.toArray(r);
754             return r;
755         }
756         finally { closeAll(c, statement, result); }
757     }
758
759     /**
760      * Get a list of groups containing the specified user.
761      */

762     public Group[] getGroupsOfUser(long userID) throws SQLException
763     {
764         return groupMembershipsCache.getGroupsOfUser(userID);
765     }
766
767     /**
768      * Get a list of users in a group. If groupID == -1, returns a list of users that belong to no group.
769      */

770     public User[] getUsersInGroup(long groupID) throws SQLException
771     {
772         return groupMembershipsCache.getUsersInGroup(this, groupID);
773     }
774
775     /**
776      * Check if the user is a member of the specified group.
777      */

778     public boolean isUserInGroup(long userID, long groupID) throws SQLException
779     {
780         return groupMembershipsCache.isUserInGroup(userID, groupID);
781     }
782
783     /**
784      * Get a list of groups created by a specific user.
785      */

786     /*public Group[] getGroupsCreatedByUser(long userID) throws SQLException
787     {
788         Connection c = null;
789         PreparedStatement statement = null;
790         ResultSet result = null;
791
792         try
793         {
794             c = getNewConnection();
795             statement = c.prepareStatement();
796
797             result = statement.executeQuery("select ID, User, Access, Name Type, from Groups where User = "+userID);
798             List v = new ArrayList();
799             while (result.next())
800             {
801                 v.add(new Group(
802                     result.getLong(1),
803                     result.getLong(2),
804                     result.getLong(3),
805                     result.getString(4),
806                     result.getString(5)));
807             }
808
809             Group r[] = new Group[v.size()];
810             v.toArray(r);
811             return r;
812         }
813         finally { closeAll(c, statement, result); }
814     }*/

815
816     /**
817      * Get group data.
818      */

819     public Group getGroup(long groupID) throws SQLException
820     {
821         return groupsCache.getGroup(groupID);
822     }
823
824     /**
825      * Add a group.
826      * Sends: "add group"
827      */

828     public void addGroup(Group group) throws SQLException, AccessDeniedException
829     {
830         checkMyAccess(group.access);
831
832         Connection c = null;
833         PreparedStatement statement = null;
834         ResultSet result = null;
835
836         try
837         {
838             c = getNewConnection();
839             statement = c.prepareStatement("insert into Groups (User, Name, Access, Type, LastChanged, LastChangedUser) values(?, ?, ?, ?, NOW(), ?)");
840             statement.setLong(1, manager.getUserID());
841             statement.setString(2, group.name);
842             statement.setLong(3, group.access);
843             statement.setString(4, group.type);
844             statement.setLong(5, manager.getUserID());
845
846             statement.executeUpdate();
847             result = statement.getGeneratedKeys();
848             sendAction("add group");
849         }
850         finally { closeAll(c, statement, result); }
851     }
852
853     /**
854      * Remove a group.
855      * Sends: "remove group"
856      */

857     public void removeGroup(long groupID) throws SQLException, AccessDeniedException
858     {
859         if (getGroup(groupID).ownerID != mUserID)
860             checkMyAccess(AccessLevel.removeGroup);
861
862         Connection c = null;
863         Statement statement = null;
864         ResultSet result = null;
865
866         try
867         {
868             c = getNewConnection();
869             statement = c.createStatement();
870
871             statement.executeUpdate("delete from Groups where ID = "+groupID);
872             statement.executeUpdate("delete from GroupMemberships where Parent = "+groupID);
873             sendAction("remove group");
874         }
875         finally { closeAll(c, statement, result); }
876     }
877
878     /**
879      * Change a group.
880      * Sends: "change group"
881      */

882     public void changeGroup(Group group) throws SQLException, AccessDeniedException
883     {
884         if (getGroup(group.ID).ownerID != mUserID)
885             checkMyAccess(AccessLevel.changeGroup);
886
887         checkMyAccess(group.access);
888
889         Connection c = null;
890         PreparedStatement statement = null;
891         ResultSet result = null;
892
893         try
894         {
895             c = getNewConnection();
896             statement = c.prepareStatement("update Groups set LastChanged = NOW(), LastChangedUser = ?, User = ?, Name = ?, Access = ?, Type = ? where ID = ?");
897             statement.setLong(1, manager.getUserID());
898             statement.setLong(2, group.ownerID);
899             statement.setString(3, group.name);
900             statement.setLong(4, group.access);
901             statement.setString(5, group.type);
902             statement.setLong(6, group.ID);
903
904             statement.executeUpdate();
905             sendAction("change group");
906         }
907         finally { closeAll(c, statement, result); }
908     }
909
910     /**
911      * Add a user to a group.
912      * Sends: "add user to group"
913      */

914     public void addUserToGroup(long userID, long groupID) throws SQLException, AccessDeniedException
915     {
916         if (!hasInvite(userID, groupID))
917         {
918             if (getGroup(groupID).ownerID == mUserID)
919             {
920                 if (!sharesRestrictedGroup(userID, mUserID) && !hasAccess(mUserID, AccessLevel.viewUser))
921                     throw new AccessDeniedException("illegal attempt to add a user to a group");
922             }
923             else
924                 checkMyAccess(AccessLevel.changeGroup);
925         }
926
927     if (!isUserInGroup(userID, groupID))
928         {
929             Connection c = null;
930             Statement statement = null;
931             ResultSet result = null;
932
933             try
934             {
935                 c = getNewConnection();
936                 statement = c.createStatement();
937
938                 statement.executeUpdate("delete from GroupMemberships where Parent = "+groupID+" AND User = "+userID);
939                 statement.executeUpdate("delete from GroupInvites where Parent = "+groupID+" AND User = "+userID);
940
941                 statement.executeUpdate("insert into GroupMemberships (Parent, User, LastChanged, LastChangedUser) values("+groupID+", "+userID+", NOW(), "+manager.getUserID()+")");
942
943                 groupMembershipsCache.update(true);
944
945                 sendAction("add user to group");
946             }
947             finally { closeAll(c, statement, result); }
948         }
949     }
950
951     /**
952      * Get invites for a user.
953      */

954     public ArrayList getInvites(long userID) throws SQLException, AccessDeniedException
955     {
956         Connection c = null;
957         Statement statement = null;
958         ResultSet result = null;
959
960         try
961         {
962             c = getNewConnection();
963             statement = c.createStatement();
964
965             ArrayList l = new ArrayList();
966
967             result = statement.executeQuery("select * from Groups, GroupInvites where Parent = Groups.ID and GroupInvites.User = "+userID);
968             while (result.next())
969                 l.add(GroupsCache.getGroupFromRow(result));
970
971             return l;
972         }
973         finally { closeAll(c, statement, result); }
974     }
975     public ArrayList getInvites() throws SQLException, AccessDeniedException
976     {
977         return getInvites(getUserID());
978     }
979
980     /**
981      * Has the user an invite for the group?
982      */

983     public boolean hasInvite(long userID, long groupID) throws SQLException, AccessDeniedException
984     {
985         Connection c = null;
986         Statement statement = null;
987         ResultSet result = null;
988
989         try
990         {
991             c = getNewConnection();
992             statement = c.createStatement();
993
994             result = statement.executeQuery("select count(*) from GroupInvites where User = "+userID+" and Parent = "+groupID);
995             result.next();
996             return result.getInt(1) != 0;
997         }
998         finally { closeAll(c, statement, result); }
999     }
1000
1001    /**
1002     * Add invite.
1003     */

1004    public void addInvite(long userID, long groupID) throws SQLException, AccessDeniedException
1005    {
1006        if (getGroup(groupID).ownerID != mUserID)
1007            checkMyAccess(AccessLevel.changeGroup);
1008
1009        Connection c = null;
1010        Statement statement = null;
1011        ResultSet result = null;
1012
1013        try
1014        {
1015            c = getNewConnection();
1016            statement = c.createStatement();
1017
1018            statement.executeUpdate("insert into GroupInvites (User, Parent, LastChangedUser) values("+userID+", "+groupID+", "+manager.getUserID()+")");
1019        }
1020        finally { closeAll(c, statement, result); }
1021    }
1022
1023    /**
1024     * Deny invite.
1025     */

1026    public void denyInvite(long groupID) throws SQLException, AccessDeniedException
1027    {
1028        Connection c = null;
1029        Statement statement = null;
1030        ResultSet result = null;
1031
1032        try
1033        {
1034            c = getNewConnection();
1035            statement = c.createStatement();
1036
1037            statement.executeUpdate("delete from GroupInvites where User = "+getUserID()+" and Parent = "+groupID);
1038        }
1039        finally { closeAll(c, statement, result); }
1040    }
1041
1042    /**
1043     * Remove a user from a group.
1044     * Sends: "remove user from group"
1045     */

1046    public void removeUserFromGroup(long userID, long groupID) throws SQLException, AccessDeniedException
1047    {
1048        if (getGroup(groupID).ownerID != mUserID)
1049            checkMyAccess(AccessLevel.changeGroup);
1050
1051        Connection c = null;
1052        Statement statement = null;
1053        ResultSet result = null;
1054
1055        try
1056        {
1057            c = getNewConnection();
1058            statement = c.createStatement();
1059
1060            //statement.executeUpdate("delete from GroupMemberships where Parent = "+groupID+" AND User = "+userID);
1061
statement.executeUpdate("update GroupMemberships set LastChanged = NOW(), LastChangedUser = "+manager.getUserID()+", Deleted = 1 where Parent = "+groupID+" AND User = "+userID);
1062
1063      groupMembershipsCache.update(true);
1064
1065            sendAction("remove user from group");
1066        }
1067        finally { closeAll(c, statement, result); }
1068    }
1069
1070    // access functions
1071
/**
1072     * Get the access rights of a user.
1073     */

1074    public long getUserAccess(long userID) throws SQLException
1075    {
1076        return groupMembershipsCache.getUserAccess(userID);
1077    }
1078
1079    /**
1080     * Returns true if the user has all the rights specified by accessLevels.
1081     */

1082    public boolean hasAccess(long userID, long accessLevels) throws SQLException
1083    {
1084        return (getUserAccess(userID) & accessLevels) == accessLevels;
1085    }
1086
1087    public boolean hasAccess(long accessLevels) throws SQLException
1088    {
1089        return (getUserAccess(getUserID()) & accessLevels) == accessLevels;
1090    }
1091
1092    /**
1093     * Returns true if the two users have some restricted group in common.
1094     */

1095    public boolean sharesRestrictedGroup(long userID1, long userID2) throws SQLException
1096    {
1097        return groupMembershipsCache.sharesGroup(userID1, userID2, "restricted");
1098    }
1099
1100    /**
1101     * Returns true if the two users have some admin group in common.
1102     */

1103    public boolean sharesAdminGroup(long userID1, long userID2) throws SQLException
1104    {
1105        return groupMembershipsCache.sharesGroup(userID1, userID2, "admin");
1106    }
1107
1108    /**
1109     * Returns true if the two users have any group in common.
1110     */

1111    public boolean sharesGroup(long userID1, long userID2) throws SQLException
1112    {
1113        return groupMembershipsCache.sharesGroup(userID1, userID2);
1114    }
1115
1116
1117    public String JavaDoc getGroupsString() throws SQLException { return getGroupsString(getUserID(), "Parent", ""); }
1118    public String JavaDoc getGroupsString(String JavaDoc key) throws SQLException { return getGroupsString(getUserID(), key, ""); }
1119    public String JavaDoc getGroupsString(String JavaDoc key, String JavaDoc prefixIfNonEmpty) throws SQLException { return getGroupsString(getUserID(), key, prefixIfNonEmpty); }
1120    public String JavaDoc getGroupsString(long userID, String JavaDoc key, String JavaDoc prefixIfNonEmpty) throws SQLException
1121    {
1122        String JavaDoc groupsString = "";
1123
1124        Group groups[] = getGroupsOfUser(userID);
1125        if (groups.length > 0)
1126        {
1127            StringBuffer JavaDoc s = new StringBuffer JavaDoc(prefixIfNonEmpty);
1128            s.append(" (");
1129            for (int i = 0; i < groups.length; i++)
1130            {
1131                if (i != 0)
1132                    s.append(" OR ");
1133
1134                s.append(key);
1135                s.append("=");
1136                s.append(groups[i].getId());
1137            }
1138
1139            s.append(") ");
1140            groupsString = s.toString();
1141        }
1142
1143        return groupsString;
1144    }
1145
1146    /**
1147     * Returns the list of users that has any common group with the specified user.
1148     */

1149    public User[] getCommonGroupUsers(long userID) throws SQLException
1150    {
1151        return groupMembershipsCache.getCommonGroupUsers(this, userID);
1152    }
1153
1154    /**
1155     * Check the access level of the current user, throw an exception if he has too little access.
1156     */

1157    public void checkMyAccess(long accessLevels) throws SQLException, AccessDeniedException
1158    {
1159        if (!hasAccess(getUserID(), accessLevels))
1160            throw new AccessDeniedException("access denied ("+AccessLevel.toString(accessLevels)+") for user "+mUserID);
1161    }
1162}
Popular Tags