KickJava   Java API By Example, From Geeks To Geeks.

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


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
14 package org.jahia.services.usermanager;
15
16 import java.sql.Connection JavaDoc;
17 import java.sql.PreparedStatement JavaDoc;
18 import java.sql.ResultSet JavaDoc;
19 import java.sql.SQLException JavaDoc;
20 import java.sql.Statement JavaDoc;
21 import java.util.Enumeration JavaDoc;
22 import java.util.HashSet JavaDoc;
23 import java.util.Iterator JavaDoc;
24 import java.util.Properties JavaDoc;
25 import java.util.Set JavaDoc;
26 import java.util.Vector JavaDoc;
27
28 import org.jahia.data.JahiaDBDOMObject;
29 import org.jahia.data.JahiaDOMObject;
30 import org.jahia.exceptions.JahiaException;
31 import org.jahia.exceptions.JahiaInitializationException;
32 import org.jahia.exceptions.database.JahiaDatabaseException;
33 import org.jahia.registries.ServicesRegistry;
34 import org.jahia.services.acl.JahiaACLManagerService;
35 import org.jahia.services.database.JahiaIncrementorsDBService;
36 import org.jahia.settings.SettingsBean;
37 import org.jahia.services.cache.Cache;
38 import org.jahia.services.cache.CacheFactory;
39
40
41 /**
42  * @author Fulco Houkes
43  * @version 2.0
44  */

45 public class JahiaUserManagerDBProvider extends JahiaUserManagerProvider implements
46         UsersDBInterface {
47
48     private static org.apache.log4j.Logger logger =
49             org.apache.log4j.Logger.getLogger (JahiaUserManagerDBProvider.class);
50
51     private final String JavaDoc MSG_INTERNAL_ERROR = new String JavaDoc ("User Manager internal error");
52
53
54     private static JahiaUserManagerDBProvider mUserManagerDBService;
55
56     // the DB User cache name.
57
public static final String JavaDoc DB_USER_CACHE = "DBUsersCache";
58
59     /** the overall provider User cache name. */
60     public static final String JavaDoc PROVIDERS_USER_CACHE = "ProvidersUsersCache";
61
62     private Cache mUserCache;
63     private Cache mProvidersUserCache;
64
65     //private JahiaGroupManagerDBService mGroupService = null;
66
private JahiaGroupManagerRoutingService mGroupService = null;
67     private JahiaACLManagerService mACLService = null;
68     private JahiaIncrementorsDBService mIncrementorService = null;
69
70     public static final String JavaDoc PROVIDER_NAME = "jahia";
71
72     /** Root user unique identification number */
73     public static final int ROOT_USER_ID = 0;
74
75     /** Guest user unique identification number */
76     public static final int GUEST_USER_ID = 1;
77
78
79     //--------------------------------------------------------------------------
80
/**
81      * Create an new instance of the User Manager Service if the instance do not
82      * exist, or return the existing instance.
83      *
84      * @return Return the instance of the User Manager Service.
85      */

86     public static JahiaUserManagerDBProvider getInstance () {
87         if (mUserManagerDBService == null) {
88             try {
89                 mUserManagerDBService = new JahiaUserManagerDBProvider ();
90             } catch (JahiaException ex) {
91                 logger.error (
92                         "Could not create an instance of the JahiaUserManagerRoutingService class",
93                         ex);
94             }
95         }
96         return mUserManagerDBService;
97     }
98
99     public void init (SettingsBean jSettings)
100             throws JahiaInitializationException {
101     }
102
103
104     //--------------------------------------------------------------------------
105
/**
106      * This is the method that creates a new user in the system, with all the
107      * specified attributes.
108      *
109      * @param name User identification name.
110      * @param password User password
111      * @param attributes User additional parameters. If the user has no additional
112      * attributes, give a NULL pointer to this parameter.
113      */

114     public synchronized JahiaUser createUser (String JavaDoc name, String JavaDoc password,
115                                               String JavaDoc userKey, int siteID,
116                                               Properties JavaDoc properties) {
117         if (!isNameValid (name)) {
118             return null;
119         }
120
121         // try to avoid a NullPointerException
122
if (!isNameValid (password)) {
123             return null;
124         }
125
126
127         // Check first if the user already exists in the database.
128
if (userExists (siteID, name)) {
129             return null;
130         }
131
132         // get the user and guest group
133
JahiaGroup usersGroup = mGroupService.getUsersGroup (siteID);
134         JahiaGroup guestGroup = mGroupService.getGuestGroup (siteID);
135         if ((usersGroup == null) || (guestGroup == null)) {
136             logger.error ("Ccould not get the [users] or/and [guest] group instance.");
137             return null;
138         }
139
140         // Get the next available user ID
141
int userID;
142         try {
143             userID = mIncrementorService.autoIncrement ("jahia_users");
144             logger.debug ("got new user ID = [" + Integer.toString (userID) + "]");
145         } catch (JahiaException ex) {
146             logger.error ("Exception !!! Could not get a new user ID from the incrementor DB",
147                     ex);
148             return null;
149         }
150
151         // Encrypt the password
152
password = encryptPassword (password);
153         if (password == null) {
154             logger.error ("could not encrypt the user password.");
155             return null;
156         }
157
158         // Create the user
159
JahiaDBUser user = null;
160         if (properties != null) {
161             user = new JahiaDBUser(userID, name, password, userKey, siteID,
162                                    new UserProperties(properties, false));
163         } else {
164             user = new JahiaDBUser(userID, name, password, userKey, siteID,
165                                    null);
166         }
167         // add the user into the cache if the user could be added into the database.
168
if (addUserIntoDB (userID, name, password, userKey, siteID, properties)) {
169             mUserCache.put ("k"+user.getName(), user);
170             /* 2004-16-06 : update by EP
171             new cache to populate : cross providers only based upon names... */

172             mProvidersUserCache.put("k"+user.getName(), user);
173             mUserCache.put("n"+user.getSiteID()+"_"+user.getUsername(), user);
174             mProvidersUserCache.put("n"+user.getSiteID()+"_"+user.getUsername(), user);
175
176             logger.debug ("User [" + name + "] was added into the database and in the cache");
177
178             // by default each user is added to the users and guest group
179
usersGroup.addMember (user);
180             guestGroup.addMember (user);
181         } else {
182             logger.error ("Could not add the user [" + name + "] in the database!!");
183             user = null;
184         }
185
186         return user;
187     }
188
189
190     //--------------------------------------------------------------------------
191
/**
192      * This method removes a user from the system. All the user's attributes are
193      * remove, and also all the related objects belonging to the user. On success,
194      * true is returned and the user parameter is not longer valid. Return false
195      * on any failure.
196      *
197      * @param user reference on the user to be deleted.
198      *
199      * @retrun Return true on success, or false on any failure.
200      */

201     public synchronized boolean deleteUser (JahiaUser user) {
202         logger.debug ("Started");
203         // try to avoid a NullPointerException
204
if (user == null) {
205             return false;
206         }
207
208         /*
209         // cannot delete the root and guest user
210         if ((((JahiaDBUser)user).getID() == ROOT_USER_ID) ||
211             (((JahiaDBUser)user).getID() == GUEST_USER_ID)) {
212             return false;
213         }
214         */

215         // cannot delete the root user
216
if (((JahiaDBUser) user).getID () == ROOT_USER_ID) {
217             return false;
218         }
219
220         // this part has to be synchronized in order to avoid a thread to read invalid data.
221
boolean result = false;
222
223         // remove de user from the database.
224
if (deleteUserFromDB (user)) {
225             logger.debug ("User removed from db");
226
227             // remove the user from the cache
228
mUserCache.remove ("k"+user.getName ());
229
230             /* 2004-23-07 : new cache to flush */
231             mProvidersUserCache.remove ("k"+user.getName ());
232             mUserCache.remove ("n"+user.getSiteID()+"_"+user.getUsername ());
233             mProvidersUserCache.remove ("n"+user.getSiteID()+"_"+user.getUsername ());
234
235             logger.debug ("User removed from cache");
236
237             mGroupService.removeUserFromAllGroups (user);
238
239             logger.debug ("User removed from groups");
240
241             mACLService.removeUserFromAllACLs (user);
242
243             logger.debug ("User removed from acls");
244
245             // and now ... KILL THE VICTIM !!!!!!!
246
user = null;
247             result = true;
248         }
249         return result;
250     }
251
252     /**
253      * Performs a login of the specified user.
254      * @param userID the user identifier defined in this service properties
255      * @param userPassword the password of the user
256      *
257      * @return boolean true if the login succeeded, false otherwise
258      */

259     public boolean login (String JavaDoc userID, String JavaDoc userPassword) {
260         if (lookupUserInDB (userID) != null) {
261             return true; // not necessary in this implementation.
262
} else {
263             return false;
264         }
265     }
266
267     /**
268      * ma méthode
269      */

270     public JahiaUser lookupUser (String JavaDoc userKey, String JavaDoc searchAttributeName) {
271         return lookupUser(userKey);
272     }
273
274
275     //--------------------------------------------------------------------------
276
/**
277      * Load all the user data and attributes. On success a reference on the user
278      * is returned, otherwise NULL is returned.
279      *
280      * @param name User's identification name.
281      *
282      * @return Return a reference on a new created jahiaUser object.
283      */

284     public JahiaUser lookupUser (String JavaDoc userKey) {
285
286         /* 2004-16-06 : update by EP
287         new cache to use : cross providers only based upon names... */

288         JahiaUser user = (JahiaUser)mProvidersUserCache.get ("k"+userKey);
289         if (user == null) {
290             // then look into the local cache, use wrappers
291
JahiaUserWrapper juw = (JahiaUserWrapper) mUserCache.get ("k"+userKey);
292             if (juw == null) {
293                 //logger.debug(" user with key=" + userKey + " is not found in cache");
294
user = lookupUserInDB (userKey);
295                 if (user != null) {
296                     /* 2004-16-06 : update by EP
297                     new cache to populate : cross providers only based upon names... */

298                     mProvidersUserCache.put("k"+user.getName(), user);
299
300                     // names for speed
301
mUserCache.put("n"+user.getSiteID()+"_"+user.getUsername(), new JahiaUserWrapper(user));
302                     mProvidersUserCache.put("n"+user.getSiteID()+"_"+user.getUsername(), user);
303                 }
304                 // wrappers
305
mUserCache.put ("k"+userKey, new JahiaUserWrapper(user));
306             }
307         }
308
309         return user;
310     }
311
312     //--------------------------------------------------------------------------
313
/**
314      * Load all the user data and attributes. On success a reference on the user
315      * is returned, otherwise NULL is returned.
316      *
317      * @param name User's identification name.
318      *
319      * @return Return a reference on a new created jahiaUser object.
320      *
321      * @author NK
322      */

323      public JahiaUser lookupUser (int siteID, String JavaDoc name) {
324         // try to avoid a NullPointerException
325
if (!isNameValid (name)) {
326             return null;
327         }
328
329         /* 2004-16-06 : update by EP
330         new cache to use : cross providers only based upon names... */

331         JahiaUser user = (JahiaUser)mProvidersUserCache.get ("n"+siteID+"_"+name);
332
333         // check siteID reference
334
if (user != null && user.getSiteID() != siteID)
335             user = null;
336
337         if (user == null) {
338             // then look into the local cache, use wrappers
339
JahiaUserWrapper juw = (JahiaUserWrapper) mUserCache.get ("n"+siteID+"_"+name);
340             if (juw != null) {
341                 user = juw.getUser();
342                 // check the SiteID reference
343
if (user != null && user.getSiteID() != siteID)
344                     user = null;
345             }
346
347             if (user == null) {
348                 //logger.debug(" user with key=" + userKey + " is not found in cache");
349
user = (JahiaUser) lookupUserInDB (siteID, name);
350                 if (user != null) {
351                     /* 2004-16-06 : update by EP
352                     new cache to populate : cross providers only based upon names... */

353                     mProvidersUserCache.put("k"+user.getUserKey(), user);
354
355                     // names for speed
356
mUserCache.put("k"+user.getUserKey(), new JahiaUserWrapper(user));
357                     mProvidersUserCache.put("n"+user.getSiteID()+"_"+user.getUsername(), user);
358                 }
359                 // wrappers
360
mUserCache.put ("n"+siteID+"_"+name, new JahiaUserWrapper(user));
361             }
362         }
363
364         return user;
365     }
366
367
368     //--------------------------------------------------------------------------
369
/**
370      * This function checks into the system if the name has already been
371      * assigned to another user.
372      *
373      * @param name User login name.
374      *
375      * @return Return true if the specified name has not been assigned yet,
376      * return false on any failure.
377      */

378     public boolean userExists (int siteID, String JavaDoc name) {
379         // try to avoid a NullPointerException
380
if (name == null) {
381             return false;
382         }
383
384         // name should not be empty.
385
if (name.length () == 0) {
386             return false;
387         }
388
389         return (lookupUser (siteID, name) != null);
390     }
391
392
393     //--------------------------------------------------------------------------
394
/**
395      * This method returns the list of all the user names registed into the system.
396      *
397      * @return Return a vector of strings holding the user identification names.
398      */

399     public Vector JavaDoc getUsernameList (int siteID) {
400         Vector JavaDoc result = new Vector JavaDoc ();
401
402         // Get a database connection
403
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
404         if (dbConn == null) {
405             return result;
406         }
407
408
409         // execute the SELECT query
410
Statement JavaDoc statement = null;
411         StringBuffer JavaDoc query = new StringBuffer JavaDoc ();
412
413         try {
414             statement = dbConn.createStatement ();
415             if (statement != null) {
416                 // Construct the database query
417
query.append ("SELECT ");
418                 query.append (FIELD_USER_NAME_USERS);
419                 query.append (" FROM ");
420                 query.append (JAHIA_USERS);
421                 query.append (" WHERE ");
422                 query.append (FIELD_SITE_ID_USERS);
423                 query.append ("=");
424                 query.append (siteID);
425
426                 ResultSet JavaDoc rs = statement.executeQuery (query.toString ());
427                 if (rs != null) {
428                     while (rs.next ()) {
429                         String JavaDoc name = rs.getString (FIELD_USER_NAME_USERS);
430                         if (name != null) {
431                             result.add (name);
432                         }
433                     }
434                 }
435
436                 // result set not needed anymore.
437
rs = null;
438             }
439         } catch (SQLException JavaDoc ex) {
440             logger.error ("Error while retrieving site " + siteID + " username list", ex);
441         } finally {
442             query = null;
443
444             closeStatement (statement);
445         }
446         return result;
447     }
448
449
450     //-------------------------------------------------------------------------
451
/**
452      * This method returns the list of this site's users' keys.
453      *
454      * @return Return a vector of strings holding the user identification key .
455      */

456     public Vector JavaDoc getUserList (int siteID) {
457
458         Vector JavaDoc result = new Vector JavaDoc ();
459
460         // Get a database connection
461
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
462         if (dbConn == null) {
463             return result;
464         }
465
466
467         // execute the SELECT query
468
Statement JavaDoc statement = null;
469         try {
470             statement = dbConn.createStatement ();
471             if (statement != null) {
472                 // Get the basic user data
473
String JavaDoc query = "SELECT key_jahia_users FROM jahia_users WHERE siteid_jahia_users=" + siteID;
474                 ResultSet JavaDoc rs = statement.executeQuery (query);
475                 if (rs != null) {
476                     while (rs.next ()) {
477                         String JavaDoc name = rs.getString ("key_jahia_users");
478                         if (name != null) {
479                             result.add (name);
480                         }
481                     }
482                 }
483             }
484         } catch (SQLException JavaDoc ex) {
485             logger.error ("Error while retrieving userKey list for site " + siteID, ex);
486         } finally {
487
488             closeStatement (statement);
489         }
490         return result;
491     }
492
493
494
495
496     //-------------------------------------------------------------------------
497
/**
498      * This method return all users' keys in the system.
499      *
500      * @return Return a vector of strings holding the user identification key .
501      */

502     public Vector JavaDoc getUserList () {
503
504         Vector JavaDoc result = new Vector JavaDoc ();
505
506         // Get a database connection
507
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
508         if (dbConn == null) {
509             return result;
510         }
511
512
513         // execute the SELECT query
514
Statement JavaDoc statement = null;
515         try {
516             statement = dbConn.createStatement ();
517             if (statement != null) {
518                 // Get the basic user data
519
String JavaDoc query = "SELECT key_jahia_users FROM jahia_users ";
520                 ResultSet JavaDoc rs = statement.executeQuery (query);
521                 if (rs != null) {
522                     while (rs.next ()) {
523                         String JavaDoc name = rs.getString ("key_jahia_users");
524                         if (name != null) {
525                             result.add (name);
526                         }
527                     }
528                 }
529             }
530         } catch (SQLException JavaDoc ex) {
531             logger.error ("Error while retrieving userKey list", ex);
532         } finally {
533
534             closeStatement (statement);
535         }
536         return result;
537     }
538
539     /**
540      * Find users according to a table of name=value properties. If the left
541      * side value is "*" for a property then it will be tested against all the
542      * properties. ie *=test* will match every property that starts with "test"
543      *
544      * @param siteID site identifier
545      * @param searchCriterias a Properties object that contains search criterias
546      * in the format name,value (for example "*"="*" or "username"="*test*") or
547      * null to search without criterias
548      *
549      * @return Set a set of JahiaUser elements that correspond to those
550      * search criterias
551      *
552      * @todo this code could be cleaner if username was a real user property
553      * but as it isn't we have to do a lot of custom handling.
554      */

555     public Set JavaDoc searchUsers (int siteID, Properties JavaDoc searchCriterias) {
556         /** @todo implement siteID into SQL request */
557         Set JavaDoc result = new HashSet JavaDoc ();
558         Set JavaDoc userKeys = new HashSet JavaDoc ();
559
560         try {
561             userKeys = JahiaUserDBUtils.getInstance().searchUsersByProperties(
562                 siteID, searchCriterias);
563         } catch (JahiaDatabaseException jde) {
564             logger.error("Error while trying to search for user by properties, returning empty set of users", jde);
565             userKeys = new HashSet JavaDoc();
566         }
567
568         // now that we have all the keys, let's load all the users.
569
Iterator JavaDoc userKeyEnum = userKeys.iterator ();
570         while (userKeyEnum.hasNext ()) {
571             String JavaDoc curUserKey = (String JavaDoc) userKeyEnum.next ();
572             JahiaUser user = lookupUser (curUserKey);
573             result.add (user);
574         }
575
576         return result;
577     }
578
579
580     //--------------------------------------------------------------------------
581
/**
582      * Default constructor
583      *
584      * @throws JahiaException The user manager need some Jahia services to be
585      * able to run correctly. If one of these services are not instanciated then a
586      * JahiaException exception is thrown.
587      */

588     protected JahiaUserManagerDBProvider () throws JahiaException {
589         /* Modified by EP to use caches correctly
590         mUserCache = new Hashtable ();*/

591         mUserCache = CacheFactory.createCache (DB_USER_CACHE);
592         mProvidersUserCache = CacheFactory.createCache(PROVIDERS_USER_CACHE);
593
594         ServicesRegistry registry = ServicesRegistry.getInstance ();
595         if (registry != null) {
596
597             mIncrementorService = registry.getJahiaIncrementorsDBService ();
598             if (mIncrementorService == null) {
599                 throw new JahiaException (MSG_INTERNAL_ERROR, "User manager could not get the Incrementors DB Service instance.",
600                         JahiaException.SERVICE_ERROR, JahiaException.CRITICAL_SEVERITY);
601             }
602
603
604             //mGroupService = (JahiaGroupManagerDBService)registry.getJahiaGroupManagerService();
605
mGroupService =
606                     (JahiaGroupManagerRoutingService) registry.getJahiaGroupManagerService ();
607             if (mGroupService == null) {
608                 throw new JahiaException (MSG_INTERNAL_ERROR, "User manager could not get the Group Manager Service instance.",
609                         JahiaException.SERVICE_ERROR, JahiaException.CRITICAL_SEVERITY);
610             }
611
612             mACLService = registry.getJahiaACLManagerService ();
613             if (mACLService == null) {
614                 throw new JahiaException (MSG_INTERNAL_ERROR, "User manager could not get the ACL Manager Service instance.",
615                         JahiaException.SERVICE_ERROR, JahiaException.CRITICAL_SEVERITY);
616             }
617         } else {
618             throw new JahiaException (MSG_INTERNAL_ERROR, "User manager could not get the Service Registry instance.",
619                     JahiaException.REGISTRY_ERROR, JahiaException.CRITICAL_SEVERITY);
620         }
621     }
622
623
624     //--------------------------------------------------------------------------
625
// Executes and INSERT, UPDATE or DELETE SQL operation. This method should not
626
// be used with and SELECT operation. This method lock the object on database
627
// write access.
628
private boolean makeQuery (String JavaDoc query) {
629         // Get a database connection
630
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
631         if (dbConn == null) {
632             return false;
633         }
634
635         boolean result = false;
636         Statement JavaDoc statement = null;
637
638         try {
639             statement = dbConn.createStatement ();
640             if (statement != null) {
641                 synchronized (this) {
642                     statement.executeUpdate (query);
643                     result = true;
644                 }
645             }
646         } catch (SQLException JavaDoc sqlEx) {
647             logger.error ("SQL Exception occured for query [" + query + "]", sqlEx);
648         } finally {
649
650             closeStatement (statement);
651         }
652
653         return result;
654     }
655
656
657     //--------------------------------------------------------------------------
658
private boolean addUserIntoDB (int id, String JavaDoc username, String JavaDoc password,
659                                    String JavaDoc userKey, int siteID,
660                                    Properties JavaDoc properties) {
661         // Get a database connection
662
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
663         if (dbConn == null) {
664             return false;
665         }
666
667         boolean result = true;
668         String JavaDoc userIDStr = Integer.toString (id);
669         PreparedStatement JavaDoc statement = null;
670
671         try {
672             String JavaDoc query = "INSERT INTO jahia_users (id_jahia_users, name_jahia_users, password_jahia_users, key_jahia_users, siteid_jahia_users) VALUES (?,?,?,?,?)";
673
674             statement = dbConn.prepareStatement (query);
675
676             statement.setInt(1, id);
677             statement.setString(2, username);
678             statement.setString(3, password);
679             statement.setString(4, userKey);
680             statement.setInt(5, siteID);
681             statement.executeUpdate ();
682
683             // Add the user's attributes
684
if (properties != null) {
685                 Enumeration JavaDoc enumeration = properties.propertyNames ();
686                 String JavaDoc name, value;
687
688                 if (enumeration.hasMoreElements ()) {
689                     while (enumeration.hasMoreElements ()) {
690                         name = (String JavaDoc) enumeration.nextElement ();
691                         value = properties.getProperty (name);
692
693                         try {
694
695                             JahiaUserDBUtils.getInstance ().addProperty (name,
696                                     value, id, PROVIDER_NAME, userKey);
697                         } catch (JahiaException je) {
698                             logger.error ("Error while storing property [" +
699                                     name + "] with value [" + value +
700                                     "] in database", je);
701                         }
702
703                     }
704                 }
705             }
706         } catch (SQLException JavaDoc sqlEx) {
707             logger.error ("Error while adding user " + userKey + " to the database", sqlEx);
708             result = false;
709         } finally {
710
711             closeStatement (statement);
712         }
713         return result;
714     }
715
716
717     //--------------------------------------------------------------------------
718
private JahiaDBUser lookupUserInDB (int siteID, String JavaDoc name) {
719         // Get a database connection
720
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
721         if (dbConn == null) {
722             return null;
723         }
724
725         JahiaDBUser user = null;
726         UserProperties properties = new UserProperties ();
727
728         // execute the SELECT query
729
PreparedStatement JavaDoc statement = null;
730         try {
731             String JavaDoc query = "SELECT id_jahia_users, password_jahia_users, key_jahia_users FROM jahia_users WHERE name_jahia_users=? and siteid_jahia_users=?";
732             statement = dbConn.prepareStatement (query);
733             if (statement != null) {
734                 statement.setString(1, name);
735                 statement.setInt(2, siteID);
736
737                 ResultSet JavaDoc rs = statement.executeQuery ();
738
739                 if (rs != null) {
740                     if (rs.next ()) {
741                         int userID = rs.getInt ("id_jahia_users");
742                         String JavaDoc password = rs.getString ("password_jahia_users");
743                         String JavaDoc userKey = rs.getString ("key_jahia_users");
744
745                         try {
746                             properties = JahiaUserDBUtils.getInstance ().
747                                     getUserProperties (userID,
748                                             PROVIDER_NAME, userKey);
749                         } catch (JahiaException je) {
750                             logger.error (
751                                     "Error while loading user " + name + " properties for site " + siteID,
752                                     je);
753                         }
754
755                         user =
756                                 new JahiaDBUser (userID, name, password, userKey, siteID,
757                                         properties);
758                     }
759                 }
760             }
761         } catch (SQLException JavaDoc ex) {
762             logger.error ("SQL Exception occured : Could not read the user [" + name +
763                     "] from the database for site id [" + siteID + "]", ex);
764         } finally {
765
766             closeStatement (statement);
767         }
768         return user;
769     }
770
771
772     //--------------------------------------------------------------------------
773
private JahiaDBUser lookupUserInDB (String JavaDoc userKey) {
774         // Get a database connection
775
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
776         if (dbConn == null) {
777             return null;
778         }
779
780         JahiaDBUser user = null;
781         UserProperties properties = new UserProperties ();
782
783         // execute the SELECT query
784
PreparedStatement JavaDoc statement = null;
785         try {
786             statement =
787                     dbConn.prepareStatement (
788                             "SELECT id_jahia_users, name_jahia_users, password_jahia_users, siteid_jahia_users FROM jahia_users WHERE key_jahia_users=?");
789
790             if (statement != null) {
791
792                 statement.setString (1, userKey);
793                 ResultSet JavaDoc rs = statement.executeQuery ();
794                 if (rs != null) {
795                     if (rs.next ()) {
796                         int userID = rs.getInt ("id_jahia_users");
797                         String JavaDoc name = rs.getString ("name_jahia_users");
798                         String JavaDoc password = rs.getString ("password_jahia_users");
799                         int siteID = rs.getInt ("siteid_jahia_users");
800
801                         try {
802                             properties =
803                                     JahiaUserDBUtils.getInstance ().getUserProperties (userID,
804                                             PROVIDER_NAME, userKey);
805                         } catch (JahiaException je) {
806                             logger.error (
807                                     "Error while loading user " + userKey + " properties ", je);
808                         }
809
810                         user =
811                                 new JahiaDBUser (userID, name, password, userKey, siteID,
812                                         properties);
813                     }
814                 }
815             }
816         } catch (SQLException JavaDoc ex) {
817             logger.error ("SQL Exception occured : Could not read the user [" +
818                     userKey + "]", ex);
819         } finally {
820
821             closeStatement (statement);
822         }
823
824         return user;
825     }
826
827
828     //--------------------------------------------------------------------------
829
private boolean deleteUserFromDB (JahiaUser user) {
830         // Get a database connection
831
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
832         if (dbConn == null) {
833             return false;
834         }
835
836         boolean result = false;
837         Statement JavaDoc statement = null;
838
839         try {
840             statement = dbConn.createStatement ();
841
842             String JavaDoc tmpStr = "WHERE id_jahia_users=" + Integer.toString (
843                     ((JahiaDBUser) user).getID ());
844             String JavaDoc query;
845
846             statement.executeUpdate ("DELETE FROM jahia_users " + tmpStr);
847             statement.executeUpdate ("DELETE FROM jahia_user_prop " + tmpStr);
848             result = true;
849         } catch (SQLException JavaDoc sqlEx) {
850             logger.error ("Error while deleting user " + user.getUserKey () + " from database",
851                     sqlEx);
852         } finally {
853             try {
854                 if (statement != null) statement.close ();
855             } catch (SQLException JavaDoc sqlEx) {
856                 logger.error ("Error while closing database statement", sqlEx);
857             }
858         }
859
860         return result;
861     }
862
863
864     //-------------------------------------------------------------------------
865
// FH 2 May 2001
866
/**
867      * Return the amount of users in the database.
868      *
869      * @return The amount of users.
870      */

871     public synchronized int getNbUsers ()
872             throws JahiaException {
873         return getNbUsers (-1);
874     }
875
876
877     //-------------------------------------------------------------------------
878
/**
879      * Return the number of user for a gived site
880      *
881      * @return Return the number of users in the system.
882      */

883     public int getNbUsers (int siteID)
884             throws JahiaException {
885
886         int counter = 0;
887
888         Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
889         if (dbConn != null) {
890             StringBuffer JavaDoc query = new StringBuffer JavaDoc ();
891             Statement JavaDoc statement = null;
892
893             try {
894                 if (siteID != -1) {
895                     query.append ("SELECT COUNT(*)");
896                     query.append (" as nbItems FROM ");
897                     query.append (JAHIA_USERS);
898                     query.append (" WHERE siteid_jahia_users=");
899                     query.append (siteID);
900                 } else {
901                     query.append ("SELECT COUNT(");
902                     query.append (FIELD_USER_KEY_USERS);
903                     query.append (") as nbItems FROM ");
904                     query.append (JAHIA_USERS);
905                 }
906
907                 statement = dbConn.createStatement ();
908                 if (statement != null) {
909                     ResultSet JavaDoc rs = statement.executeQuery (query.toString ());
910                     //logger.debug(query.toString());
911
if (rs != null) {
912                         if (rs.next ()) {
913                             counter = rs.getInt ("nbItems");
914                         }
915                     }
916
917                     // Result set not needed anymore.
918
rs = null;
919                 }
920             } catch (SQLException JavaDoc ex) {
921                 throw new JahiaDatabaseException ("Database error.", ex,
922                         JahiaDatabaseException.ERROR_SEVERITY);
923             } finally {
924                 query = null;
925
926                 closeStatement (statement);
927             }
928         }
929         return counter;
930     }
931
932     public void updateCache(JahiaUser jahiaUser) {
933         mUserCache.put("k"+jahiaUser.getName(), new JahiaUserWrapper(jahiaUser));
934         mProvidersUserCache.put("k"+jahiaUser.getName(), jahiaUser);
935         mUserCache.put("n"+jahiaUser.getSiteID()+"_"+jahiaUser.getUsername(), new JahiaUserWrapper(jahiaUser));
936         mProvidersUserCache.put("n"+jahiaUser.getSiteID()+"_"+jahiaUser.getUsername(), jahiaUser);
937     }
938
939
940     //-------------------------------------------------------------------------
941
/**
942      * This method returns the list of this site's users' ids.
943      *
944      * @return Return a vector of strings holding the user ids .
945      */

946     private Vector JavaDoc getUserIds (int siteID) {
947
948         Vector JavaDoc result = new Vector JavaDoc ();
949
950         // Get a database connection
951
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
952         if (dbConn == null) {
953             return result;
954         }
955
956
957         // execute the SELECT query
958
Statement JavaDoc statement = null;
959         try {
960             statement = dbConn.createStatement ();
961             if (statement != null) {
962                 // Get the basic user data
963
String JavaDoc query = "SELECT id_jahia_users FROM jahia_users WHERE siteid_jahia_users=" + siteID;
964                 ResultSet JavaDoc rs = statement.executeQuery (query);
965                 if (rs != null) {
966                     while (rs.next ()) {
967                         int id = rs.getInt ("id_jahia_users");
968                         result.add (new Integer JavaDoc (id));
969                     }
970                 }
971             }
972         } catch (SQLException JavaDoc ex) {
973             logger.error ("Error while retrieving user IDs from database", ex);
974         } finally {
975
976             closeStatement (statement);
977         }
978         return result;
979     }
980
981
982     //--------------------------------------------------------------------------
983
/**
984      * return a DOM document of all users of a site
985      *
986      * @param int the site id
987      *
988      * @return JahiaDOMObject a DOM representation of this object
989      *
990      * @author NK
991      */

992     public JahiaDOMObject getUsersAsDOM (int siteID)
993             throws JahiaException {
994
995         Connection JavaDoc dbConn = null;
996         Statement JavaDoc statement = null;
997
998         String JavaDoc output = null;
999         JahiaDBDOMObject dom = null;
1000
1001        try {
1002            String JavaDoc sqlQuery = "SELECT * FROM jahia_users where siteid_jahia_users=" + siteID;
1003
1004            dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
1005            statement = dbConn.createStatement ();
1006            if (statement != null) {
1007                ResultSet JavaDoc rs = statement.executeQuery (sqlQuery);
1008                if (rs != null) {
1009                    dom = new JahiaDBDOMObject ();
1010                    dom.addTable ("jahia_users", rs);
1011                    return dom;
1012                }
1013            }
1014        } catch (SQLException JavaDoc se) {
1015            String JavaDoc errorMsg = "Error in getUsersAsDOM(int siteID) : " + se.getMessage ();
1016            logger.error (errorMsg, se);
1017            throw new JahiaException ("Cannot load users from the database",
1018                    errorMsg, JahiaException.DATABASE_ERROR,
1019                    JahiaException.CRITICAL_SEVERITY, se);
1020        } finally {
1021
1022            closeStatement (statement);
1023        }
1024
1025        return dom;
1026    }
1027
1028
1029    //--------------------------------------------------------------------------
1030
/**
1031     * return a DOM document of all user props of a site
1032     *
1033     * @param int the site id
1034     *
1035     * @return JahiaDOMObject a DOM representation of this object
1036     *
1037     * @author NK
1038     */

1039    public JahiaDOMObject getUserPropsAsDOM (int siteID)
1040            throws JahiaException {
1041
1042        Connection JavaDoc dbConn = null;
1043        Statement JavaDoc statement = null;
1044
1045        String JavaDoc output = null;
1046        JahiaDBDOMObject dom = null;
1047
1048
1049        try {
1050
1051            String JavaDoc sqlQuery = "SELECT DISTINCT jahia_user_prop.id_jahia_users,jahia_user_prop.name_jahia_user_prop,jahia_user_prop.value_jahia_user_prop FROM jahia_user_prop ,jahia_users WHERE jahia_user_prop.userkey_jahia_user_prop="
1052                    + "jahia_users.key_jahia_users AND jahia_users.siteid_jahia_users=" + siteID;
1053
1054
1055            dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
1056            statement = dbConn.createStatement ();
1057            if (statement != null) {
1058                ResultSet JavaDoc rs = statement.executeQuery (sqlQuery);
1059                if (rs != null) {
1060                    dom = new JahiaDBDOMObject ();
1061                    dom.addTable ("jahia_user_prop", rs);
1062                    return dom;
1063                }
1064            }
1065        } catch (SQLException JavaDoc se) {
1066            String JavaDoc errorMsg = "Error in getUserPropsAsDOM(int siteID) : " + se.getMessage ();
1067            logger.error (errorMsg, se);
1068            throw new JahiaException ("Cannot load users props from the database",
1069                    errorMsg, JahiaException.DATABASE_ERROR,
1070                    JahiaException.CRITICAL_SEVERITY);
1071        } finally {
1072
1073            closeStatement (statement);
1074        }
1075
1076        return dom;
1077    }
1078
1079    //-------------------------------------------------------------------------
1080
private boolean isNameValid (String JavaDoc name) {
1081
1082        if (name == null) {
1083            return false;
1084        }
1085
1086        if (name.length () == 0) {
1087            return false;
1088        }
1089
1090        String JavaDoc authorizedCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789{}";
1091        /* EP : 2004-17-06
1092        char[] chars = authorizedCharacters.toCharArray ();
1093        char[] nameBuffer = name.toCharArray ();*/

1094
1095        boolean badCharFound = false;
1096        for (int i = 0; i < name.length() && !badCharFound; i++) {
1097            badCharFound = authorizedCharacters.indexOf((int)name.charAt(i)) < 0;
1098            if (badCharFound) {
1099                logger.debug ("Bad character found in DB user name [" +
1100                        name +
1101                        "] at position " + i);
1102            }
1103        }
1104    /* end EP mods */
1105    return (!badCharFound);
1106    }
1107
1108    //-------------------------------------------------------------------------
1109
private void closeStatement (Statement JavaDoc statement) {
1110        // Close the opened statement
1111
try {
1112            if (statement != null) {
1113                statement.close ();
1114            }
1115        } catch (SQLException JavaDoc sqlEx) {
1116            // FIXME -Fulco- : Don't know yet what to do with this exception.
1117
// It should be logged somewhere !
1118
}
1119    }
1120
1121
1122}
1123
1124
Popular Tags