KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > services > usermanager > JahiaDBUser


1 //
2
// ____.
3
// __/\ ______| |__/\. _______
4
// __ .____| | \ | +----+ \
5
// _______| /--| | | - \ _ | : - \_________
6
// \\______: :---| : : | : | \________>
7
// |__\---\_____________:______: :____|____:_____\
8
// /_____|
9
//
10
// . . . i n j a h i a w e t r u s t . . .
11
//
12
//
13
// NK 12.04.2001 - Changed to support Multi Site
14

15 package org.jahia.services.usermanager;
16
17 import org.jahia.exceptions.JahiaException;
18 import org.jahia.exceptions.database.JahiaDatabaseConnectionException;
19 import org.jahia.exceptions.database.JahiaDatabaseException;
20 import org.jahia.registries.ServicesRegistry;
21
22 import java.security.Principal JavaDoc;
23 import java.util.Enumeration JavaDoc;
24 import java.util.Properties JavaDoc;
25 import java.util.StringTokenizer JavaDoc;
26 import java.util.Vector JavaDoc;
27 import java.io.Serializable JavaDoc;
28 import java.util.Iterator JavaDoc;
29
30
31 /**
32  * A JahiaUser represents a physical person who is defined by a username and
33  * a password for authentification purpose. Every other property of a JahiaUser
34  * is stored in it's properties list, which hold key-value string pairs.
35  * For example email, firstname, lastname, ... information should be stored in
36  * this properties list.
37  *
38  * @author Fulco Houkes
39  * @version 1.1
40  */

41 public class JahiaDBUser implements JahiaUser, Serializable JavaDoc {
42     private static org.apache.log4j.Logger logger =
43             org.apache.log4j.Logger.getLogger (JahiaDBUser.class);
44     /** User unique identification number in the database. */
45     private int mID;
46
47     /** User unique identification name */
48     private String JavaDoc mUsername;
49
50     /** User password */
51     private String JavaDoc mPassword;
52
53     /** Each user has an unique String identifier * */
54     private String JavaDoc mUserKey;
55
56     /** Site id , the owner of this user */
57     private int mSiteID = -1;
58
59
60     /** User home page property * */
61     private static final String JavaDoc mHOMEPAGE_PROP = "user_homepage";
62
63     // language property constants
64
private static final String JavaDoc mLANGUAGES_ORDER_PROP = "language_codes";
65     private static final String JavaDoc mLANGUAGES_ORDER_PROP_SEPARATOR = ",";
66     private static final String JavaDoc mLANGUAGES_MIX_PROP = "langage_mix";
67     private static final String JavaDoc mLANGUAGES_ONLYUSER_PROP = "language_onlyuser";
68
69     /** User additional parameters. */
70     private UserProperties mProperties = new UserProperties ();
71
72
73     //--------------------------------------------------------------------------
74
// FH 29 Mar. 2001
75
// Initial implementation
76
//
77
/**
78      * Create a new JahiaDBUser class instance. The passed in password must
79      * already be encrypted, no ecryption will be done. If the passed in
80      * properties is null, then the user will have no additional parameter than
81      * it's id, name and password.
82      *
83      * @param id User unique identification number.
84      * @param name User identification name.
85      * @param password User password.
86      * @param int siteID
87      * The site id
88      * @param properties User properties.
89      */

90     protected JahiaDBUser (int id, String JavaDoc name, String JavaDoc password, String JavaDoc userKey, int siteID,
91                            UserProperties properties) {
92         mID = id;
93         mUsername = name;
94         mPassword = password;
95         mUserKey = userKey;
96         mSiteID = siteID;
97
98         if (properties != null) {
99             mProperties = properties;
100         }
101     }
102
103
104     //--------------------------------------------------------------------------
105
// FH 29 Mar. 2001
106
// Initial implementation
107
//
108
public boolean equals (Object JavaDoc another) {
109         if (another instanceof Principal JavaDoc) {
110             if (another != null) {
111                 return (getName ().equals (((Principal JavaDoc) another).getName ()));
112             }
113         }
114         return false;
115     }
116
117
118     //--------------------------------------------------------------------------
119
// FH 29 Mar. 2001
120
// Initial implementation
121
//
122
/**
123      * Retrieve the user's unique database identification number.
124      *
125      * @return The user unique identification number.
126      */

127     public int getID () {
128         return mID;
129     }
130
131
132     //--------------------------------------------------------------------------
133
// FH 29 Mar. 2001
134
// Initial implementation
135
//
136
public String JavaDoc getName () {
137         return getUserKey ();
138     }
139
140     //--------------------------------------------------------------------------
141
// FH 29 Mar. 2001
142
// Initial implementation
143
//
144
public String JavaDoc getUsername () {
145         return mUsername;
146     }
147
148     //--------------------------------------------------------------------------
149
// NK 12 Avr. 2001
150
// Initial implementation
151
//
152
public String JavaDoc getUserKey () {
153         return mUserKey;
154     }
155
156     //--------------------------------------------------------------------------
157
// NK 12 Avr. 2001
158
// Initial implementation
159
//
160
public int getSiteID () {
161         return mSiteID;
162     }
163
164     public void setSiteID (int siteID) {
165         mSiteID = siteID;
166     }
167
168     //-------------------------------------------------------------------------
169
/**
170      * Returns the user's home page id.
171      * -1 : undefined
172      *
173      * @return int The user homepage id.
174      */

175     public int getHomepageID () {
176
177         if (mProperties != null) {
178
179             try {
180                 String JavaDoc value = mProperties.getProperty (mHOMEPAGE_PROP);
181                 if (value == null)
182                     return -1;
183                 return Integer.parseInt (value);
184             } catch (Throwable JavaDoc t) {
185                 t.printStackTrace ();
186             }
187         }
188         return -1;
189     }
190
191     //-------------------------------------------------------------------------
192
/**
193      * Set the home page id.
194      *
195      * @param int The user homepage id.
196      *
197      * @return false on error
198      */

199     public boolean setHomepageID (int id) {
200
201         /*
202         if ( !removeProperty(mHOMEPAGE_PROP) )
203             return false;
204         */

205         return setProperty (mHOMEPAGE_PROP, String.valueOf (id));
206     }
207
208     //--------------------------------------------------------------------------
209
// FH 29 Mar. 2001
210
// Initial implementation
211
//
212
/**
213      * @deprecated use getUserProperties() instead
214      * @return Properties the properties returned here should NEVER be modified,
215      * only modifications through setProperty() are supported and serialized.
216      */

217     public Properties JavaDoc getProperties () {
218         if (mProperties != null) {
219             return mProperties.getProperties();
220         } else {
221             return null;
222         }
223     }
224
225     /**
226      * The properties here should not be modified, as the modifications will
227      * not be serialized. Use the setProperty() method to modify a user's
228      * properties.
229      * @return UserProperties
230      */

231     public UserProperties getUserProperties() {
232         return mProperties;
233     }
234
235     //--------------------------------------------------------------------------
236
// FH 29 Mar. 2001
237
// Initial implementation
238
//
239
public String JavaDoc getProperty (String JavaDoc key) {
240
241         if ((mProperties != null) && (key != null)) {
242             return mProperties.getProperty (key);
243         }
244         return null;
245     }
246
247     public UserProperty getUserProperty(String JavaDoc key) {
248         if ((mProperties != null) && (key != null)) {
249             return mProperties.getUserProperty (key);
250         }
251         return null;
252     }
253
254     //--------------------------------------------------------------------------
255
// FH 29 Mar. 2001
256
// Initial implementation
257
//
258
/**
259      * Return a unique hashcode identifiying the user.
260      *
261      * @return Return a valid hashcode integer of the user, On failure, -1 is
262      * returned.
263      */

264     public int hashCode () {
265         return ("user" + mID).hashCode ();
266     }
267
268
269     //--------------------------------------------------------------------------
270
// FH 29 Mar. 2001
271
// Initial implementation
272
//
273
/**
274      * Remove the specified property from the properties list.
275      *
276      * @param key Property's name.
277      *
278      * @return Return true on success or false on any failure.
279      */

280     public synchronized boolean removeProperty (String JavaDoc key) {
281         boolean result = false;
282
283         if (mProperties == null) {
284             return result;
285         }
286
287         if ((key != null) && (key.length () > 0) && (!mProperties.isReadOnly(key))) {
288             JahiaUserDBUtils utils = JahiaUserDBUtils.getInstance ();
289             if (utils != null) {
290                 try {
291                     result = utils.removeProperty (key, mID, getProviderName (), getUserKey ());
292                 }
293                         // general database exeception
294
catch (JahiaDatabaseException ex) {
295                     // false will be returned automaticaly
296
}
297
298                         // database connection failure
299
catch (JahiaDatabaseConnectionException ex) {
300                     // false will be returned automaticaly
301
}
302
303                         // catch all the Jahia exceptions
304
catch (JahiaException ex) {
305                     // false will be returned automaticaly
306
}
307             }
308         }
309
310         if (result) {
311             mProperties.removeUserProperty (key);
312         }
313
314         return result;
315     }
316
317     public synchronized boolean isPasswordReadOnly() {
318         return false;
319     }
320
321     //---------------------------------------------------------------------------
322
// FH 29 Mar. 2001
323
// Initial implementation
324
//
325
/**
326      * Change the user's password.
327      *
328      * @param newPassword New user's password
329      *
330      * @return Return true id the old password is the same as the current one and
331      * the new password is valid. Return false on any failure.
332      */

333     public synchronized boolean setPassword (String JavaDoc password) {
334         boolean result = false;
335
336         // try to avoid a NullPointerException
337
if (password != null) {
338             // password should not be empty.
339
if (password.length () > 0) {
340                 // Encrypt the new password
341
String JavaDoc tmp = JahiaUserManagerService.
342                         encryptPassword (password);
343                 JahiaUserDBUtils utils = JahiaUserDBUtils.getInstance ();
344                 if (utils != null) {
345                     try {
346                         result = utils.setPassword (password, mID);
347                         if (result) {
348                             mPassword = tmp;
349                             ServicesRegistry.getInstance().getJahiaUserManagerService().updateCache(this);
350                         }
351                     }
352                             // general database exeception
353
catch (JahiaDatabaseException ex) {
354                         // false will be returned automaticaly
355
}
356
357                             // database connection failure
358
catch (JahiaDatabaseConnectionException ex) {
359                         // false will be returned automaticaly
360
}
361
362                             // catch all the Jahia exceptions
363
catch (JahiaException ex) {
364                         // false will be returned automaticaly
365
}
366                 }
367             }
368         }
369         return result;
370     }
371
372     public String JavaDoc getPassword() {
373         return mPassword;
374     }
375
376     //--------------------------------------------------------------------------
377
// FH 29 Mar. 2001
378
// Initial implementation
379
//
380
/**
381      * Add (or update if not already in the property list) a property key-value
382      * pair in the user's properties list.
383      *
384      * @param key Property's name.
385      * @param value Property's value.
386      *
387      * @return Return true on success or false on any failure.
388      */

389     public synchronized boolean setProperty (String JavaDoc key, String JavaDoc value) {
390         boolean result = false;
391
392         if (mProperties == null) {
393             return result;
394         }
395
396         if ((key != null) && (value != null) && (!mProperties.isReadOnly(key))) {
397
398             JahiaUserDBUtils utils = JahiaUserDBUtils.getInstance ();
399             if (utils != null) {
400                 try {
401                     if (getProperty (key) == null) {
402                         result =
403                                 utils.addProperty (key, value, mID, getProviderName (),
404                                         getUserKey ());
405                     } else {
406                         result =
407                                 utils.updateProperty (key, value, mID, getProviderName (),
408                                         getUserKey ());
409                     }
410                 }
411                         // general database exeception
412
catch (JahiaDatabaseException ex) {
413                     // false will be returned automaticaly
414
}
415
416                         // database connection failure
417
catch (JahiaDatabaseConnectionException ex) {
418                     // false will be returned automaticaly
419
}
420
421                         // catch all the Jahia exceptions
422
catch (JahiaException ex) {
423                     // false will be returned automaticaly
424
}
425             }
426
427             if (result) {
428                 try {
429                     mProperties.setProperty(key, value);
430                 } catch (UserPropertyReadOnlyException uproe) {
431                     logger.warn("Cannot set read-only property " + key);
432                 }
433                 ServicesRegistry.getInstance().getJahiaUserManagerService().updateCache(this);
434             }
435         }
436         return result;
437     }
438
439
440     //--------------------------------------------------------------------------
441
// FH 29 Mar. 2001
442
// Initial implementation
443
//
444
public boolean verifyPassword (String JavaDoc password) {
445
446         if (password != null) {
447             String JavaDoc test = JahiaUserManagerService.encryptPassword (password);
448             return mPassword.equals (test);
449         }
450         return false;
451     }
452
453
454     //--------------------------------------------------------------------------
455
// FH 29 Mar. 2001
456
// Initial implementation
457
//
458
/**
459      * Return a string representation of the user and it's internal state.
460      *
461      * @return A string representation of this user.
462      */

463     public String JavaDoc toString () {
464         StringBuffer JavaDoc output = new StringBuffer JavaDoc ("Detail of user [" + mUsername + "]\n");
465         output.append (" - ID [" + Integer.toString (mID) + "]");
466         output.append (" - password [" + mPassword + "]\n");
467
468         if (mProperties != null) {
469             output.append(" - properties :");
470
471             Iterator JavaDoc nameIter = mProperties.propertyNameIterator();
472             String JavaDoc name;
473             if (nameIter.hasNext()) {
474                 output.append("\n");
475                 while (nameIter.hasNext()) {
476                     name = (String JavaDoc) nameIter.next();
477                     output.append(
478                         " " + name + " -> [" +
479                         (String JavaDoc) mProperties.getProperty(name) + "]\n");
480                 }
481             } else {
482                 output.append(" -no properties-\n");
483             }
484         }
485         return output.toString ();
486     }
487
488
489     //--------------------------------------------------------------------------
490
// NK 06 Avr. 2001
491
/**
492      * Test if the user is an admin member
493      *
494      * @return Return true if the user is an admin member
495      * false on any error.
496      */

497     public boolean isAdminMember (int siteID) {
498
499         return isMemberOfGroup (siteID, JahiaGroupManagerService.ADMINISTRATORS_GROUPNAME);
500     }
501
502     /**
503      * Test if the user is the root user
504      *
505      * @return Return true if the user is the root user
506      * false on any error.
507      */

508     public boolean isRoot () {
509         /** @todo FIXME in this implementation the super user is necessarily
510          * always in the jahia database implementation
511          */

512         if (getID () == JahiaUserManagerDBProvider.ROOT_USER_ID) {
513             return true;
514         } else {
515             return false;
516         }
517     }
518
519
520     //-------------------------------------------------------------------------
521
public boolean isMemberOfGroup (int siteID, String JavaDoc name) {
522         // Get the services registry
523
ServicesRegistry servicesRegistry = ServicesRegistry.getInstance ();
524         if (servicesRegistry != null) {
525
526             // get the group management service
527
JahiaGroupManagerService groupService =
528                     servicesRegistry.getJahiaGroupManagerService ();
529
530             // lookup the requested group
531
JahiaGroup group = groupService.lookupGroup (siteID, name);
532             if (group != null) {
533                 return group.isMember (this);
534             }
535         }
536         return false;
537     }
538
539     /**
540      * Retrieve a vector of language codes stored for this user. The order
541      * of these codes is important. The first language is the first choice, and
542      * as the list goes down so does the importance of the languages.
543      *
544      * @return a Vector containing String objects that contain language codes,
545      * the vector may be empty if this property was never set for the user.
546      */

547     public Vector JavaDoc getLanguageCodes () {
548         String JavaDoc encodedLanguagesCodes = getProperty (mLANGUAGES_ORDER_PROP);
549         Vector JavaDoc result = new Vector JavaDoc ();
550         if (encodedLanguagesCodes != null) {
551             StringTokenizer JavaDoc strTokens = new StringTokenizer JavaDoc (encodedLanguagesCodes,
552                     mLANGUAGES_ORDER_PROP_SEPARATOR);
553             while (strTokens.hasMoreTokens ()) {
554                 String JavaDoc curLanguageCode = strTokens.nextToken ();
555                 result.add (curLanguageCode);
556             }
557         }
558         return result;
559     }
560
561     /**
562      * Sets the language codes for a user. This Vector contains String object
563      * that contain language codes. The order of this list is defined so as that
564      * the most important language is first.
565      *
566      * @param userLanguages a Vector of String object containing the language
567      * codes. The order is from the most important language first to the least
568      * important one last.
569      */

570     public void setLanguageCodes (Vector JavaDoc userLanguages) {
571         StringBuffer JavaDoc encodedLanguageCodes = new StringBuffer JavaDoc ();
572         Enumeration JavaDoc userLanguagesEnum = userLanguages.elements ();
573         while (userLanguagesEnum.hasMoreElements ()) {
574             String JavaDoc curLanguage = (String JavaDoc) userLanguagesEnum.nextElement ();
575             if (curLanguage.indexOf (mLANGUAGES_ORDER_PROP_SEPARATOR) != 0) {
576                 // we found the separator character inside the string.
577
logger.debug ("Invalid " + mLANGUAGES_ORDER_PROP_SEPARATOR +
578                         " character in language code : " + curLanguage +
579                         ". Not storing this language code.");
580             } else {
581                 encodedLanguageCodes.append (curLanguage);
582                 encodedLanguageCodes.append (mLANGUAGES_ORDER_PROP_SEPARATOR);
583             }
584         }
585         String JavaDoc encodedLanguageCodeStr = encodedLanguageCodes.toString ();
586         // we must now remove the extra separator at the end of the encoded list
587
encodedLanguageCodeStr =
588                 encodedLanguageCodeStr.substring (0, encodedLanguageCodeStr.length () - 1);
589         setProperty (mLANGUAGES_ORDER_PROP, encodedLanguageCodeStr);
590     }
591
592     /**
593      * Returns true if this user has activated the language mixing function
594      * of Jahia. This means that the content that will be displayed on his
595      * page will content multiple languages based on language preference list.
596      *
597      * @return true if the property is active.
598      */

599     public boolean isMixLanguagesActive () {
600         String JavaDoc mixActiveStr = getProperty (mLANGUAGES_MIX_PROP);
601         if (mixActiveStr != null) {
602             Boolean JavaDoc mixActiveBool = Boolean.valueOf (mixActiveStr);
603             return mixActiveBool.booleanValue ();
604         } else {
605             logger.debug (mLANGUAGES_MIX_PROP +
606                     " property not found for user " +
607                     this.getUsername () +
608                     ". Defaulting to false.");
609             return false;
610         }
611     }
612
613     /**
614      * Sets the user property that indicates whether the user wants to see
615      * mixed language content in the pages he is browsing or not.
616      *
617      * @param mixLanguagesActive a boolean set to true to allow language mixing
618      */

619     public void setMixLanguagesActive (boolean mixLanguagesActive) {
620         setProperty (mLANGUAGES_MIX_PROP,
621                 new Boolean JavaDoc (mixLanguagesActive).toString ());
622     }
623
624     /**
625      * Returns true if the user has setup this property indicating that he
626      * doesn't want to default to any other languages than the ones he has
627      * setup in his users settings. This will shortcut defaulting to the
628      * browser and site settings.
629      *
630      * @return true if the user only wants to see the languages he has configured
631      * and never the ones configured in his browser or in the site settings.
632      */

633     public boolean isUserLanguagesOnlyActive () {
634         String JavaDoc userLanguagesOnlyStr = getProperty (mLANGUAGES_ONLYUSER_PROP);
635         if (userLanguagesOnlyStr != null) {
636             Boolean JavaDoc userLanguagesOnlyBool = Boolean.valueOf (userLanguagesOnlyStr);
637             return userLanguagesOnlyBool.booleanValue ();
638         } else {
639             logger.debug (mLANGUAGES_ONLYUSER_PROP +
640                     " property not found for user " +
641                     this.getUsername () +
642                     ". Defaulting to false.");
643             return false;
644         }
645
646     }
647
648     /**
649      * Sets the value indicating whether a user wants to fallback to browser
650      * or site setting languages. If set to true this means we are NOT falling
651      * back to the above mentioned settings.
652      *
653      * @param userLanguagesOnlyActive true means we are not falling back to
654      * browser or site settings.
655      */

656     public void setUserLanguagesOnlyActive (boolean userLanguagesOnlyActive) {
657         setProperty (mLANGUAGES_ONLYUSER_PROP,
658                 new Boolean JavaDoc (userLanguagesOnlyActive).toString ());
659
660     }
661
662     /**
663      * Get the name of the provider of this user.
664      *
665      * @return String representation of the name of the provider of this user
666      */

667     public String JavaDoc getProviderName () {
668         return JahiaUserManagerDBProvider.PROVIDER_NAME;
669     }
670
671
672 }
673
Popular Tags