KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > freecs > core > UserManager


1 /**
2  * Copyright (C) 2003 Manfred Andres
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17  */

18 package freecs.core;
19
20 import freecs.*;
21 import freecs.auth.AuthManager;
22 import freecs.interfaces.*;
23 import freecs.layout.TemplateSet;
24 import freecs.util.EntityDecoder;
25
26 import java.nio.CharBuffer JavaDoc;
27 import java.nio.charset.Charset JavaDoc;
28 import java.util.ArrayList JavaDoc;
29 import java.util.HashMap JavaDoc;
30 import java.util.List JavaDoc;
31 import java.util.Map JavaDoc;
32 import java.util.Vector JavaDoc;
33 import java.util.Enumeration JavaDoc;
34 import java.util.Iterator JavaDoc;
35
36 public class UserManager extends Thread JavaDoc implements IUserStates, IMessageDestination {
37    public static final UserManager mgr = new UserManager();
38    public static int highWaterMark = 0;
39
40    public final byte[] TOUCH_CONTENT;
41
42    public UserStore ustr = new UserStore();
43    private HashMap JavaDoc fshipList;
44    private Vector JavaDoc schedule, onlineVips, notListedAsOnlineVips, guests, moderators, vips, admins, loggingIn;
45    private volatile long lastModified=0;
46
47     public String JavaDoc ustrState() {
48         return ustr.state();
49     }
50
51
52     private UserManager () {
53        try {
54            CharBuffer JavaDoc cb = CharBuffer.wrap ("<!-- ping -->");
55            TOUCH_CONTENT = Charset.forName (Server.srv.DEFAULT_CHARSET).newEncoder ().encode (cb).array();
56         } catch (Exception JavaDoc e) {
57             Server.debug("static UserManager", "touch_content-construction failed", e, Server.MSG_ERROR, Server.LVL_HALT);
58             throw new RuntimeException JavaDoc ("failed to initialize UserManager");
59         }
60         fshipList = new HashMap JavaDoc ();
61         onlineVips = new Vector JavaDoc();
62         notListedAsOnlineVips = new Vector JavaDoc ();
63         vips=new Vector JavaDoc();
64         admins=new Vector JavaDoc();
65         moderators=new Vector JavaDoc();
66         guests=new Vector JavaDoc ();
67         this.setName ("UserManager");
68         schedule = new Vector JavaDoc ();
69         loggingIn = new Vector JavaDoc();
70     }
71    
72     public static void startUserManager() {
73         mgr.setName("UserManager");
74         mgr.setPriority(Thread.MAX_PRIORITY-1);
75         mgr.start();
76     }
77
78     /**
79      * returns the number of active users
80      */

81     public int getActiveUserCount () {
82         return ustr.size();
83     }
84
85    public static final short LOGIN_OK = 0,
86                               LOGIN_MISSING = 1,
87                               LOGIN_COOKIE_MISSING = 2,
88                               LOGIN_GROUP_MISSING = 3,
89                               LOGIN_GROUP_NOSTART = 4,
90                               LOGIN_GROUP_BAN = 5,
91                               LOGIN_GROUP_LOCK = 6,
92                               LOGIN_COOKIE_DUPLICATE = 7,
93                               LOGIN_PRESENT = 8,
94                               LOGIN_RELOAD = 9,
95                               LOGIN_FAILED =10,
96                               TECHNICAL_ERROR =11,
97                               MAX_USERS =12,
98                               LOGIN_BLOCKED =13,
99                               USERNAME_TOO_LONG =14,
100                               USERNAME_INVALID =15,
101                               USERNAME_NOT_ACTIVATED =16,
102                               USEREMAIL_BANED =17,
103                               LOGIN_CANCELED =18;
104    /**
105     * try to login this user. returns integer containing 0 for ok or any other number (treated as error-code)
106     * @return short 0 = ok, erverything else is an errorcode
107     */

108     public short tryLogin (String JavaDoc uname, String JavaDoc pwd, String JavaDoc grp, TemplateSet ts, RequestReader req, User u) {
109         String JavaDoc ltUname = uname == null ? null : uname.toLowerCase().trim();
110         if ((uname != null && loggingIn.contains(ltUname))
111             || (uname == null && pwd == null && grp == null
112                 && req.currentRequest.getCookie() != null && u != null && u.getCookie().equals(req.currentRequest.getCookie()) && u.check(System.currentTimeMillis())))
113             return LOGIN_RELOAD;
114         if (uname == null)
115             return LOGIN_MISSING;
116         if (uname.length() > Server.srv.MAX_USERNAME_LENGTH)
117             return USERNAME_TOO_LONG;
118         if (!AuthManager.instance.isValidName(uname))
119             return USERNAME_INVALID;
120         loggingIn.add(ltUname);
121         short result = execTryLogin (uname, pwd, grp, ts, req);
122         loggingIn.remove(ltUname);
123         return result;
124     }
125     
126     private short execTryLogin (String JavaDoc uname, String JavaDoc pwd, String JavaDoc grp, TemplateSet ts, RequestReader req) {
127         req.currPosition = RequestReader.TRYLOGIN;
128         if (req.currentRequest.getCookie() == null || req.currentRequest.getCookie().length () < 1)
129             return LOGIN_COOKIE_MISSING;
130         if (grp == null || grp.length () < 1)
131             return LOGIN_GROUP_MISSING;
132         req.currPosition = RequestReader.TRYLOGIN_CHECK4PRESENCE;
133         User un, uc;
134         un = (User) ustr.getUserName(uname.toLowerCase ());
135         uc = (User) ustr.getUserCookie(req.currentRequest.getCookie());
136         if (un != null && uc == null)
137             return LOGIN_PRESENT;
138         if (un == null && uc != null)
139             return LOGIN_COOKIE_DUPLICATE;
140         if (un != null && uc != null && un.equals (uc))
141             return LOGIN_RELOAD;
142         if (un != null && uc != null)
143             return LOGIN_FAILED;
144         User nu;
145         req.currPosition = RequestReader.TRYLOGIN_AUTHENTICATE;
146         try {
147             nu = Server.srv.auth.loginUser (uname, pwd, req.currentRequest.getCookie(), req.currentRequest);
148         } catch (NullPointerException JavaDoc npe) {
149             Server.debug (this, "Catched NPE!", npe, Server.MSG_ERROR, Server.LVL_MAJOR);
150             return TECHNICAL_ERROR;
151         } catch (CanceledRequestException cre) {
152             Server.log (this, "Canceled login due to "
153                     + (cre.timedOut ?
154                       "request timeout" : "connection loss to client"),
155                       Server.MSG_AUTH, Server.LVL_VERBOSE);
156             return LOGIN_CANCELED;
157         } catch (Exception JavaDoc e) {
158             Server.debug (this, "tryLogin:", e, Server.MSG_ERROR, Server.LVL_MAJOR);
159             return TECHNICAL_ERROR;
160         }
161         if (nu == null)
162             return LOGIN_FAILED;
163         if (Server.srv.isBanned(nu.getProperty("email"))) {
164             return USEREMAIL_BANED;
165         }
166         req.currPosition = RequestReader.TRYLOGIN_CORRECT_PERMISSION;
167         
168         // check user-rights here. If user-rights equal 0, the rights will
169
// be corrected to the IUserRights.ROLE_USER.
170
if (nu.hasRole(0) || nu.hasRole(Integer.MIN_VALUE))
171             nu.setPermission(IUserStates.ROLE_USER);
172         // if the user has IUserRights.ROLE_USER, the config will be checked
173
// for the user-rights
174
if (nu.hasRole(IUserStates.ROLE_USER)) {
175             String JavaDoc tname = nu.getName().trim().toLowerCase();
176             if (guests.contains (tname)) {
177                 nu.givePermission (IUserStates.IS_GUEST);
178             }else if (admins.contains (tname)) {
179                 nu.setPermission (IUserStates.ROLE_GOD);
180             } else if (moderators.contains (tname)) {
181                 nu.setPermission (IUserStates.IS_MODERATOR);
182             } else if (vips.contains (tname)) {
183                 nu.setPermission (IUserStates.ROLE_VIP);
184             }
185         }
186         if (ustr.size () >= Server.srv.MAX_USERS
187             && !nu.hasDefaultRight(IUserStates.ROLE_VIP))
188                  return MAX_USERS;
189         req.currPosition = RequestReader.TRYLOGIN_SET_GROUP;
190         if (nu.blocked)
191             return LOGIN_BLOCKED;
192         if (!nu.activated)
193             return USERNAME_NOT_ACTIVATED;
194         if (!GroupManager.mgr.isStartingGroup(grp))
195             return LOGIN_GROUP_NOSTART;
196         Group g = GroupManager.mgr.getStartingGroup (grp);
197         if (g != null) {
198             if (!g.hasState(IGroupState.ENTRANCE))
199                 return LOGIN_GROUP_NOSTART;
200             if (g.usrIsBaned(uname))
201                 return LOGIN_GROUP_BAN;
202             if (!g.hasState(IGroupState.OPEN) && !nu.hasRight(IUserStates.MAY_JOIN_LOCKED_GROUP))
203                 return LOGIN_GROUP_LOCK;
204             req.currPosition = RequestReader.TRYLOGIN_SEND_LOGINMSG;
205         } else {
206             if (!GroupManager.mgr.isStartingGroup(grp))
207                 return LOGIN_GROUP_NOSTART;
208             g = GroupManager.mgr.openGroup(grp, (String JavaDoc) GroupManager.mgr.startGroupThemes.get(grp.trim().toLowerCase()), nu);
209             if (g==null)
210                 return LOGIN_GROUP_NOSTART;
211         }
212         MessageParser mprj = new MessageParser();
213         mprj.setSender (nu);
214         mprj.setMessageTemplate ("message.user.join.server");
215         g.sendMessage (mprj);
216         try {
217             this.addUser (nu);
218             g.addLoginUser (nu);
219         } catch (Exception JavaDoc e) {
220             Server.debug(this, "Exception during addUser: ", e, Server.MSG_ERROR, Server.LVL_MAJOR);
221             return TECHNICAL_ERROR;
222         }
223         
224         List JavaDoc fn;
225         switch (nu.notifyFriends()) {
226             case User.FN_ALL:
227                 fn = (List JavaDoc) fshipList.get (nu.getName ().toLowerCase());
228                 break;
229             case User.FN_FRIEND_AGREEMENT:
230                 // check for strong-friend-relationship
231
// if login-user and the friend have marked each other
232
// as friends, a notification will be sent
233
List JavaDoc allFriends = (List JavaDoc) fshipList.get (nu.getName ().toLowerCase());
234                 if (allFriends == null) {
235                     fn=null;
236                     break;
237                 }
238                 fn = new ArrayList JavaDoc();
239                 for (Iterator JavaDoc i = allFriends.iterator(); i.hasNext(); ) {
240                     User fu = (User) i.next();
241                     if (nu.isFriend(fu)) {
242                         fn.add(fu);
243                     }
244                 }
245                 break;
246             default:
247                 fn = null;
248         }
249         sendFriendNotification (nu, g, fn);
250
251         req.currPosition = RequestReader.TRYLOGIN_SET_PERMISSION;
252         nu.setTemplateSet (ts);
253         req.currPosition = RequestReader.TRYLOGIN_SCHEDULE_VIPMSG;
254         Membership defaultMembership = nu.getDefaultMembership();
255         boolean listedAsOnlinevip = true;
256         if (defaultMembership != null)
257             listedAsOnlinevip = defaultMembership.listedAsOnlinevip();
258         if (nu.hasRight(IUserStates.ROLE_VIP) || nu.hasDefaultRight(ROLE_VIP)) {
259             MessageParser mpr = new MessageParser();
260             mpr.setUsercontext(nu) ;
261             mpr.setMessageTemplate ("message.user.vip");
262             nu.scheduleMessage (mpr);
263             if (listedAsOnlinevip) {
264                 onlineVips.add(nu);
265             } else notListedAsOnlineVips.add(nu);
266         }
267         req.currPosition = RequestReader.TRYLOGIN_SCHEDULE_FRIENDMSGS;
268     
269         Vector JavaDoc onlineFriends = new Vector JavaDoc();
270         for (Enumeration JavaDoc e = nu.friends (); e.hasMoreElements (); ) {
271             String JavaDoc fname = (String JavaDoc) e.nextElement ();
272             User cu = getUserByName (fname);
273             if (cu == null)
274                 continue;
275             onlineFriends.add(cu);
276         }
277         if (onlineFriends.size()>0) {
278             MessageParser mpr = new MessageParser();
279             mpr.setMessageTemplate ("message.f.headline");
280             mpr.setParam(String.valueOf(onlineFriends.size()));
281             nu.scheduleMessage (mpr);
282             for (Enumeration JavaDoc e = onlineFriends.elements(); e.hasMoreElements(); ) {
283                 User cu = (User) e.nextElement();
284                 mpr = new MessageParser ();
285                 mpr.setUsercontext (cu);
286                 Group gg = cu.getGroup ();
287                 mpr.setTargetGroup (gg);
288                 mpr.setMessageTemplate ("message.f.isOnline");
289                 nu.scheduleMessage (mpr);
290             }
291         }
292         MessageParser mpr = new MessageParser();
293         mpr.setMessageTemplate ("message.user.join.server.personal");
294         mpr.setSender(nu);
295         nu.scheduleMessage (mpr);
296         return LOGIN_OK;
297     }
298
299    /**
300     * adds a user to the lists
301     * @param u The user to add
302     */

303     public void addUser (User u) throws Exception JavaDoc {
304         ustr.addUser(u);
305         lastModified=System.currentTimeMillis();
306         if (ustr.size() > highWaterMark)
307             highWaterMark = ustr.size();
308     }
309
310    /**
311     * removes a user from the userlists
312     * @param u the user to remove
313     */

314     public void removeUser (User u) {
315         ustr.removeUser(u);
316         lastModified=System.currentTimeMillis();
317         Membership defaultMembership = u.getDefaultMembership();
318         boolean listedAsOnlinevip = true;
319         if (defaultMembership != null)
320             listedAsOnlinevip = defaultMembership.listedAsOnlinevip();
321         if ((u.hasRight(IUserStates.ROLE_VIP) || u.hasDefaultRight(IUserStates.ROLE_VIP)) && listedAsOnlinevip) {
322             onlineVips.removeElement(u);
323         } else if ((u.hasRight(IUserStates.ROLE_VIP) || u.hasDefaultRight(IUserStates.ROLE_VIP)) && !listedAsOnlinevip) {
324                     notListedAsOnlineVips.removeElement(u);
325         }
326     }
327
328    /**
329     * returns the user identifyed by the give cookie-value
330     * @param c the cookie-value
331     * @return User the user identified by this cookie-value
332     */

333    public User getUserByCookie (String JavaDoc c) {
334       return ustr.getUserCookie(c);
335    }
336
337    /**
338     * returns the user identifyed by the give name
339     * @param n the name
340     * @return User the user identified by this name
341     */

342     public User getUserByName (String JavaDoc n) {
343         if (n.indexOf("&") > -1)
344             n = EntityDecoder.htmlToChar (n);
345         return ustr.getUserName(n);
346     }
347
348    /**
349     * schedules this user to be removed
350    public void scheduleToRemove (User u) {
351       if (u.getRemoveWhen() == 0)
352         return;
353       removableUsers.addElement (u);
354    }
355     */

356
357     /**
358      * adds a friendship-relation
359      * @param u The user which has registered fname as friend
360      * @param fname the name of the user which will be registered with u
361      */

362    public void addFriendship (User u, String JavaDoc fname) {
363       Vector JavaDoc f = (Vector JavaDoc) fshipList.get (fname);
364       if (f == null) {
365          f = new Vector JavaDoc ();
366          fshipList.put (fname, f);
367       }
368       f.addElement (u);
369    }
370
371     /**
372      * removes a friendship-relation
373      * @param u The user which wants to unregister fname as friend
374      * @param fname the name of the user which will be unregisterd with u
375      */

376     public synchronized void removeFriendship (User u, String JavaDoc fname) {
377         Vector JavaDoc f = (Vector JavaDoc) fshipList.get (fname);
378         if (f == null)
379             return;
380         f.remove (u);
381         if (f.size()==0)
382             fshipList.remove(f);
383     }
384
385    /**
386     * cleanup the userspace. if a user times out, we have to remove
387     * this user from all lists and also unregister his key
388     * The touching of users connected via proxy-servers will also be done within here
389     * Also the ScheduledActions will be triggered here
390     */

391     public void run () {
392         long lastMessage = 0;
393         while (Server.srv.isRunning ()) try {
394             if (Server.DEBUG || lastMessage + 5000 > System.currentTimeMillis()) {
395                 Server.log (this, "loopstart", Server.MSG_STATE, Server.LVL_VERY_VERBOSE);
396                 lastMessage = System.currentTimeMillis();
397             }
398             long currTime = System.currentTimeMillis ();
399             long lowestValue = currTime + Math.min(Server.srv.USER_REMOVE_SCHEDULE_TIME, Server.srv.TOUCH_USER_DELAY);
400             lowestValue = checkUsers (currTime, lowestValue);
401
402             // checking the ScheduledActions
403
for (Enumeration JavaDoc e = schedule.elements (); e.hasMoreElements (); ) {
404                 ScheduledAction sa = (ScheduledAction) e.nextElement ();
405                 if (!ustr.contains(sa.getUser())) {
406                     schedule.removeElement (sa);
407                 }
408                 long st = sa.getStartTime ();
409                 if (st > currTime) {
410                     if (st < lowestValue) {
411                         lowestValue = st;
412                     }
413                     continue;
414                 }
415                 sa.execute ();
416                 schedule.removeElement (sa);
417             }
418             long sleepTime = lowestValue - System.currentTimeMillis ();
419             if (sleepTime <= 0)
420                 sleepTime = 33;
421             try {
422                 Thread.sleep(sleepTime);
423             } catch (InterruptedException JavaDoc ie) { }
424         } catch (Exception JavaDoc e) {
425             Server.debug (this, "encountered excpetion", e, Server.MSG_ERROR, Server.LVL_MAJOR);
426         }
427     }
428
429
430     private long checkUsers (long currTime, long lowestValue) {
431         long val = Server.srv.USER_REMOVE_SCHEDULE_TIME * 10;
432         User[] uarr = ustr.toArray();
433         for (int i = 0; i < uarr.length; i++) {
434             User cu = uarr[i];
435             if (cu == null)
436                 continue;
437             if (!cu.check(currTime)) {
438                 cu.removeNow();
439                 continue;
440             }
441             long nextCheck = cu.nextCheck();
442             if (nextCheck < lowestValue) {
443                 lowestValue = nextCheck;
444             }
445             cu.checkReferences();
446             cu.touch (currTime);
447         }
448         return lowestValue;
449     }
450     
451    /**
452     * interface MessageDestination
453     */

454     public void sendMessage (IContainer mc) {
455         synchronized (ustr) {
456             for (Iterator JavaDoc i = ustr.iterator (); i.hasNext (); ) {
457                 User cu = (User) i.next ();
458                 cu.sendMessage (mc);
459             }
460         }
461     }
462
463     public Vector JavaDoc onlineVipList () {
464         return onlineVips;
465     }
466     
467     public Enumeration JavaDoc onlineVips () {
468         return onlineVips.elements();
469     }
470     
471     public Enumeration JavaDoc notListedAsOnlineVips () {
472         return notListedAsOnlineVips.elements();
473     }
474
475    public Iterator JavaDoc users () {
476       return ustr.iterator ();
477    }
478
479     public void scheduleAction (short action, long startTime, User usr, User sender) {
480         ScheduledAction sa = new ScheduledAction (action, startTime, usr, sender);
481         if (schedule.contains (sa))
482             return;
483         schedule.addElement (sa);
484     }
485    
486     public int getHighWaterMark () {
487         return highWaterMark;
488     }
489     
490     public void updateVips (Vector JavaDoc nVips) {
491         Vector JavaDoc removed = (Vector JavaDoc) vips.clone();
492         removed.removeAll(nVips);
493         Vector JavaDoc added = (Vector JavaDoc) nVips.clone();
494         added.removeAll(vips);
495         UserManager umgr = UserManager.mgr;
496         for (Enumeration JavaDoc e = added.elements(); e.hasMoreElements(); ) {
497             String JavaDoc uname = (String JavaDoc) e.nextElement();
498             User cu = umgr.getUserByName(uname);
499             if (cu != null)
500                 cu.setPermission(IUserStates.ROLE_VIP);
501             vips.addElement(uname);
502         }
503         for (Enumeration JavaDoc e = removed.elements(); e.hasMoreElements();) {
504             String JavaDoc uname = (String JavaDoc) e.nextElement();
505             User cu = umgr.getUserByName(uname);
506             if (cu != null)
507                 cu.setPermission(IUserStates.ROLE_USER);
508             while (vips.contains(uname))
509                 vips.removeElement(uname);
510         }
511     }
512
513     public void updateAdmins (Vector JavaDoc nAdmins) {
514         Vector JavaDoc removed = (Vector JavaDoc) admins.clone();
515         removed.removeAll(nAdmins);
516         Vector JavaDoc added = (Vector JavaDoc) nAdmins.clone();
517         added.removeAll(admins);
518         UserManager umgr = UserManager.mgr;
519         for (Enumeration JavaDoc e = added.elements(); e.hasMoreElements(); ) {
520             String JavaDoc uname = (String JavaDoc) e.nextElement();
521             User cu = umgr.getUserByName(uname);
522             if (cu != null)
523                 cu.setPermission(IUserStates.ROLE_GOD);
524             admins.addElement(uname);
525         }
526         for (Enumeration JavaDoc e = removed.elements(); e.hasMoreElements();) {
527             String JavaDoc uname = (String JavaDoc) e.nextElement();
528             User cu = umgr.getUserByName(uname);
529             if (cu != null)
530                 cu.setPermission(IUserStates.ROLE_USER);
531             while (admins.contains(uname))
532                 admins.removeElement(uname);
533         }
534     }
535
536     public void updateModerators (Vector JavaDoc nMod) {
537         Vector JavaDoc removed = (Vector JavaDoc) moderators.clone();
538         removed.removeAll(nMod);
539         Vector JavaDoc added = (Vector JavaDoc) nMod.clone();
540         added.removeAll(moderators);
541         UserManager umgr = UserManager.mgr;
542         for (Enumeration JavaDoc e = added.elements(); e.hasMoreElements(); ) {
543             String JavaDoc uname = (String JavaDoc) e.nextElement();
544             User cu = umgr.getUserByName(uname);
545             if (cu != null)
546                 cu.setPermission(IUserStates.ROLE_VIP);
547             moderators.addElement(uname);
548         }
549         for (Enumeration JavaDoc e = removed.elements(); e.hasMoreElements();) {
550             String JavaDoc uname = (String JavaDoc) e.nextElement();
551             User cu = umgr.getUserByName(uname);
552             if (cu != null)
553                 cu.setPermission(IUserStates.ROLE_USER);
554             while (moderators.contains(uname))
555                 moderators.removeElement(uname);
556         }
557     }
558     
559     public void updateGuests (Vector JavaDoc nGuest) {
560         Vector JavaDoc removed = (Vector JavaDoc) guests.clone();
561         removed.removeAll(nGuest);
562         Vector JavaDoc added = (Vector JavaDoc) nGuest.clone();
563         added.removeAll(guests);
564         UserManager umgr = UserManager.mgr;
565         for (Enumeration JavaDoc e = added.elements(); e.hasMoreElements(); ) {
566             String JavaDoc uname = (String JavaDoc) e.nextElement();
567             User cu = umgr.getUserByName(uname);
568             if (cu != null)
569                 cu.givePermission(IUserStates.IS_GUEST);
570             guests.addElement(uname);
571         }
572         for (Enumeration JavaDoc e = removed.elements(); e.hasMoreElements();) {
573             String JavaDoc uname = (String JavaDoc) e.nextElement();
574             User cu = umgr.getUserByName(uname);
575             if (cu != null)
576                 cu.setPermission(IUserStates.ROLE_USER);
577             while (guests.contains(uname))
578                 guests.removeElement(uname);
579         }
580     }
581
582     public void sendFriendNotification (User forUser, Group inGroup, List JavaDoc to) {
583         if (to==null)
584             return;
585         MessageParser mpr = new MessageParser();
586         mpr.setUsercontext (forUser);
587         mpr.setTargetGroup (inGroup);
588         mpr.setMessageTemplate ("message.f.joined");
589         for (Iterator JavaDoc e = to.iterator (); e.hasNext (); ) {
590             User cu = (User) e.next ();
591             if (!forUser.getGroup().equals(cu.getGroup()))
592                 cu.sendMessage (mpr);
593         }
594     }
595     public Enumeration JavaDoc vips () {
596         return vips.elements();
597     }
598     public Enumeration JavaDoc moderators () {
599         return moderators.elements();
600     }
601     public Enumeration JavaDoc guests () {
602         return guests.elements();
603     }
604
605     /**
606      * method to resolve string-right-declarations to int-bitmask-values
607      * @param name the name of the IUserStates-constant
608      * @return the int-value of the IUserStates-constant
609      */

610     public static int resolveState (String JavaDoc name) {
611         String JavaDoc lowerName = name.toLowerCase();
612         if (lowerName.equals("may_open_group")) {
613             return IUserStates.MAY_OPEN_GROUP;
614         } else if (lowerName.equals("may_open_moderated_group")) {
615             return IUserStates.MAY_OPEN_MODERATED_GROUP;
616         } else if (lowerName.equals("may_lock_group")) {
617             return IUserStates.MAY_LOCK_GROUP;
618         } else if (lowerName.equals("may_lock_moderated_group")) {
619             return IUserStates.MAY_LOCK_MODERATED_GROUP;
620         } else if (lowerName.equals("may_lock_starting_group")) {
621             return IUserStates.MAY_LOCK_STARTING_GROUP;
622         } else if (lowerName.equals("may_join_group")) {
623             return IUserStates.MAY_JOIN_GROUP;
624         } else if (lowerName.equals("may_join_locked_group")) {
625             return IUserStates.MAY_JOIN_LOCKED_GROUP;
626         } else if (lowerName.equals("may_set_theme")) {
627             return IUserStates.MAY_SET_THEME;
628         } else if (lowerName.equals("may_change_right")) {
629             return IUserStates.MAY_CHANGE_RIGHT;
630         } else if (lowerName.equals("may_punish")) {
631             return IUserStates.MAY_PUNISH;
632         } else if (lowerName.equals("may_kick")) {
633             return IUserStates.MAY_KICK;
634         } else if (lowerName.equals("may_kick_hard")) {
635             return IUserStates.MAY_KICK_HARD;
636         } else if (lowerName.equals("may_ban")) {
637             return IUserStates.MAY_BAN;
638         } else if (lowerName.equals("protected_from_punish")) {
639             return IUserStates.PROTECTED_FROM_PUNISH;
640         } else if (lowerName.equals("protected_from_kick")) {
641             return IUserStates.PROTECTED_FROM_KICK;
642         } else if (lowerName.equals("protected_from_ban")) {
643             return IUserStates.PROTECTED_FROM_BAN;
644         } else if (lowerName.equals("protected_from_rightchange")) {
645             return IUserStates.PROTECTED_FROM_RIGHTCHANGE;
646         } else if (lowerName.equals("freely_punishable")) {
647             return IUserStates.FREELY_PUNISHABLE;
648         } else if (lowerName.equals("freely_kickable")) {
649             return IUserStates.FREELY_KICKABLE;
650         } else if (lowerName.equals("freely_banable")) {
651             return IUserStates.FREELY_BANABLE;
652         } else if (lowerName.equals("is_moderator")) {
653             return IUserStates.IS_MODERATOR;
654         } else if (lowerName.equals("may_release_serverban")) {
655             return IUserStates.MAY_RELEASE_SERVERBAN;
656         } else if (lowerName.equals("is_guest")) {
657             return IUserStates.IS_GUEST;
658         } else if (lowerName.equals("role_asshole")) {
659             return IUserStates.ROLE_ASSHOLE;
660         } else if (lowerName.equals("role_user")) {
661             return IUserStates.ROLE_USER;
662         } else if (lowerName.equals("role_vip")) {
663             return IUserStates.ROLE_VIP;
664         } else if (lowerName.equals("role_god")) {
665             return IUserStates.ROLE_GOD;
666         } else if (lowerName.equals("guest")) {
667             return IUserStates.IS_GUEST;
668         } else if (lowerName.equals("moderator")) {
669             return IUserStates.IS_MODERATOR;
670         } else if (lowerName.equals("vip")) {
671             return IUserStates.ROLE_VIP;
672         } else if (lowerName.equals("user")) {
673             return IUserStates.ROLE_USER;
674         } else if (lowerName.equals("asshole")) {
675             return IUserStates.ROLE_ASSHOLE;
676         }
677         return 0;
678     }
679     
680     public String JavaDoc toString() {
681         return ("[UserManager]");
682     }
683     
684     public class UserStore {
685         private Map JavaDoc usrName = new HashMap JavaDoc();
686         private Map JavaDoc usrCookie = new HashMap JavaDoc();
687         private User[] uarr = new User[0];
688         
689         private UserStore () { }
690         
691  
692         public synchronized String JavaDoc state() {
693             StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
694             sb.append ("<table border=1><tr><td>");
695             for (Iterator JavaDoc i = usrName.entrySet().iterator(); i.hasNext(); )
696                 sb.append (i.next()).append("<br>");
697             sb.append ("</td><td>");
698             for (Iterator JavaDoc i = usrCookie.entrySet().iterator(); i.hasNext(); )
699                 sb.append (i.next()).append("<br>");
700             sb.append ("</td></tr></table>");
701             return sb.toString();
702         }
703  
704         /**
705          * @return the number of users currently logged in
706          */

707         public synchronized int size() {
708             return usrName.size();
709         }
710
711         public void addUser (User u) throws Exception JavaDoc {
712             String JavaDoc name = u.getName();
713             String JavaDoc cookie = u.getCookie();
714             if (name==null || name.length() < 1
715                 || cookie==null || cookie.length() < 1)
716                     throw new Exception JavaDoc ("Tryed to add invalid user (cookie: " + cookie + " / name: " + name);
717             name = name.trim().toLowerCase();
718             if (usrName.containsKey(name)
719                 || usrCookie.containsKey(cookie))
720                 throw new Exception JavaDoc ("Tryed to add duplicate user: " + name);
721             synchronized (this) {
722                 usrName.put(name, u);
723                 usrCookie.put(cookie, u);
724                 uarr=null;
725             }
726         }
727         
728         public synchronized User[] toArray() {
729             if (uarr==null) {
730                 uarr = (User[]) usrName.values().toArray(new User[0]);
731             }
732             return uarr;
733         }
734         
735         public void removeUser (User u) {
736             String JavaDoc name = u.getName();
737             String JavaDoc cookie = u.getCookie();
738             synchronized (this) {
739                 if (name!=null) {
740                     usrName.remove(name.trim().toLowerCase());
741                     uarr=null;
742                 }
743                 if (cookie!=null)
744                     usrCookie.remove(cookie);
745             }
746         }
747
748         public synchronized User getUserCookie(String JavaDoc cookie) {
749             return (User) usrCookie.get(cookie);
750         }
751
752         public User getUserName(String JavaDoc name) {
753             if (name==null)
754                 return null;
755             String JavaDoc key = name.trim().toLowerCase();
756             synchronized (this) {
757                 return (User) usrName.get(key);
758             }
759         }
760         
761         public synchronized boolean contains (User u) {
762             String JavaDoc cookie = u.getCookie();
763             String JavaDoc name = u.getName();
764             User c, n;
765             synchronized (this) {
766                 c = getUserCookie(cookie);
767                 n = getUserName(name);
768             }
769             return (c!=null && n!=null);
770         }
771         
772         public Iterator JavaDoc iterator() {
773             return new UserStoreIterator(this);
774         }
775         
776         class UserStoreIterator implements Iterator JavaDoc {
777             private Iterator JavaDoc ci;
778             private User cu;
779             private UserStore ustr;
780             UserStoreIterator (UserStore ustr) {
781                 ci = usrName.values().iterator();
782                 this.ustr = ustr;
783             }
784
785             public void remove() {
786                 synchronized (ustr) {
787                     if (cu==null)
788                         throw new IllegalStateException JavaDoc();
789                     usrCookie.remove(cu.getCookie());
790                     ci.remove();
791                     uarr=null;
792                 }
793             }
794
795             public boolean hasNext() {
796                 return ci.hasNext();
797             }
798
799             public Object JavaDoc next() {
800                 cu = (User) ci.next();
801                 return cu;
802             }
803         }
804    }
805
806     /**
807      * @return
808      */

809     public long lastModified() {
810         return lastModified;
811     }
812 }
Popular Tags