KickJava   Java API By Example, From Geeks To Geeks.

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


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 package org.jahia.services.usermanager;
14
15 import org.jahia.data.JahiaDBDOMObject;
16 import org.jahia.data.JahiaDOMObject;
17 import org.jahia.exceptions.JahiaException;
18 import org.jahia.registries.ServicesRegistry;
19 import org.jahia.services.cache.Cache;
20 import org.jahia.services.cache.CacheFactory;
21 import org.jahia.utils.JahiaTools;
22
23 import java.sql.Connection JavaDoc;
24 import java.sql.ResultSet JavaDoc;
25 import java.sql.SQLException JavaDoc;
26 import java.sql.Statement JavaDoc;
27 import java.util.*;
28 import java.sql.PreparedStatement JavaDoc;
29
30
31 /**
32  * DB implementation of the Manage users memberhip Service in a multi site context
33  *
34  * @author Khue Ng
35  */

36 public class JahiaSiteUserManagerDBService extends JahiaSiteUserManagerService {
37     private static org.apache.log4j.Logger logger =
38             org.apache.log4j.Logger.getLogger(JahiaSiteUserManagerDBService.class);
39
40     private static final String JavaDoc KEY_SEPARATOR = "###";
41
42     private static JahiaSiteUserManagerDBService mInstance;
43
44     public static final String JavaDoc SITE_USERS_CACHE = "SiteUsersCache";
45     private Cache siteUserCache;
46
47
48     /**
49      * Inner class
50      */

51     private class SiteUserBean {
52
53         protected String JavaDoc username;
54         protected int siteID = -1;
55         protected String JavaDoc userID;
56
57         protected SiteUserBean(String JavaDoc username,
58                                int siteID,
59                                String JavaDoc userID
60                                ) {
61
62             this.username = username;
63             this.siteID = siteID;
64             this.userID = userID;
65
66         }
67     }
68
69
70     /**
71      * Default constructor.
72      *
73      * @throws JahiaException Raise a JahiaException when during initialization
74      * one of the needed services could not be instanciated.
75      */

76     protected JahiaSiteUserManagerDBService() throws JahiaException {
77         siteUserCache = CacheFactory.createCache(SITE_USERS_CACHE);
78     }
79
80
81     /**
82      * Create an new instance of the Site User Manager Service if the instance do not
83      * exist, or return the existing instance.
84      *
85      * @return Return the instance of the Site User Manager Service.
86      */

87     public static synchronized JahiaSiteUserManagerDBService getInstance() {
88         if (mInstance == null) {
89             try {
90                 mInstance = new JahiaSiteUserManagerDBService();
91             } catch (JahiaException ex) {
92                 logger.error(
93                         "Could not create an instance of the JahiaSiteUserManagerDBService class");
94
95             }
96         }
97         return mInstance;
98     }
99
100
101     /**
102      * Create a new membership for a user on a gived site
103      *
104      * @param int siteID, the site identifier
105      * @param JahiaUser user, the user to add as member
106      */

107     public synchronized boolean addMember(int siteID, JahiaUser user) throws JahiaException {
108
109         if (user == null) {
110             return false;
111         }
112
113         try {
114
115             // add new membership to database
116
StringBuffer JavaDoc query = new StringBuffer JavaDoc("insert into jahia_sites_users values('");
117             query.append(JahiaTools.quote(user.getUsername()));
118             query.append("',");
119             query.append(siteID);
120             query.append(",'");
121             query.append(JahiaTools.quote(user.getName()));
122             query.append("')");
123
124             executeQueryNoResultSet(query.toString());
125
126             siteUserCache.put(buildCacheKey(siteID, user.getUsername()), user);
127
128         } catch (JahiaException je) {
129             String JavaDoc errorMsg = "Error in dbAddMember(int siteID, JahiaUser user) : " + je.getMessage();
130             logger.error(errorMsg + " -> BAILING OUT");
131             throw new JahiaException("Cannot add member in the database",
132                     errorMsg, JahiaException.DATABASE_ERROR, JahiaException.CRITICAL_SEVERITY);
133         }
134
135         return true;
136     }
137
138
139     /**
140      * Remove a user's membership from a site, doesn't delete the user
141      *
142      * @param int siteID, the site identifier
143      * @param JahiaUser user reference on the user to be removed from the site.
144      */

145     public synchronized boolean removeMember(int siteID, JahiaUser user)
146             throws JahiaException {
147
148         if (user == null) {
149             return false;
150         }
151
152         try {
153
154             // remove a member of a site from database
155
StringBuffer JavaDoc query = new StringBuffer JavaDoc(
156                     "delete from jahia_sites_users where username_sites_users='");
157             query.append(JahiaTools.quote(user.getUsername()));
158             query.append("' and siteid_sites_users=");
159             query.append(siteID);
160
161             executeQueryNoResultSet(query.toString());
162
163             siteUserCache.remove(buildCacheKey(siteID, user.getUsername()));
164
165         } catch (JahiaException je) {
166             String JavaDoc errorMsg = "Error in dbRemoveMember(int siteID, JahiaUser user) : " + je.getMessage();
167             logger.error(errorMsg + " -> BAILING OUT");
168             throw new JahiaException("Cannot add member in the database",
169                     errorMsg, JahiaException.DATABASE_ERROR, JahiaException.CRITICAL_SEVERITY);
170         }
171
172         return true;
173     }
174
175
176     /**
177      * Remove a user's membership from all sites, doesn't delete the user
178      *
179      * @param JahiaUser user, the user to be removed from the site.
180      */

181     public synchronized boolean removeMember(JahiaUser user) throws JahiaException {
182
183         if (user == null) {
184             return false;
185         }
186
187         try {
188
189             StringBuffer JavaDoc query = new StringBuffer JavaDoc(
190                     "delete from jahia_sites_users where userid_sites_users='");
191             query.append(JahiaTools.quote(user.getUserKey()));
192             query.append("'");
193
194             executeQueryNoResultSet(query.toString());
195
196             removeUserFromAllSites(user);
197
198         } catch (JahiaException je) {
199             String JavaDoc errorMsg = "Error in dbRemoveMember(JahiaUser user) : " + je.getMessage();
200             logger.error(errorMsg + " -> BAILING OUT");
201             throw new JahiaException("Cannot add member in the database",
202                     errorMsg, JahiaException.DATABASE_ERROR, JahiaException.CRITICAL_SEVERITY);
203         }
204
205         return true;
206     }
207
208
209     /**
210      * Remove all users of a site ( only the membership, not the user )
211      *
212      * @param int siteID, the identifier of the site.
213      */

214     public synchronized boolean removeMembers(int siteID) throws JahiaException {
215
216         if (siteID == 0) {
217             return false;
218         }
219
220         try {
221
222             StringBuffer JavaDoc query = new StringBuffer JavaDoc(
223                     "delete from jahia_sites_users where siteid_sites_users=");
224             query.append(siteID);
225
226             executeQueryNoResultSet(query.toString());
227
228             removeUsersFromSite(siteID);
229
230         } catch (JahiaException je) {
231             String JavaDoc errorMsg = "Error in dbRemoveMember(JahiaUser user) : " + je.getMessage();
232             logger.error(errorMsg + " -> BAILING OUT");
233             throw new JahiaException("Cannot add member in the database",
234                     errorMsg, JahiaException.DATABASE_ERROR, JahiaException.CRITICAL_SEVERITY);
235         }
236
237         return true;
238     }
239
240
241     /**
242      * This method returns the list of all the usernames of members of a site.
243      *
244      * @param int siteID, the site identifier
245      * @return Return an Hashtable of username/usrid couples members of this site.
246      */

247     public Hashtable getMembersMap(int siteID) throws JahiaException {
248
249         Hashtable members = new Hashtable();
250         Connection JavaDoc dbConn = null;
251         Statement JavaDoc statement = null;
252
253         try {
254
255             SiteUserBean suBean = null;
256             dbConn = org.jahia.services.database.ConnectionDispenser.getConnection();
257             statement = dbConn.createStatement();
258             if (statement != null) {
259
260                 StringBuffer JavaDoc query = new StringBuffer JavaDoc(
261                         "select * from jahia_sites_users where siteid_sites_users=");
262                 query.append(siteID);
263                 ResultSet JavaDoc rs = statement.executeQuery(query.toString());
264                 if (rs != null) {
265                     while (rs.next()) {
266                         suBean = getSiteUserBeanFromResultSet(rs);
267                         if (suBean != null) {
268                             members.put(suBean.username, suBean.userID);
269                         }
270                     }
271                 }
272             }
273
274         } catch (SQLException JavaDoc se) {
275             String JavaDoc errorMsg = "Error in dbGetSites : " + se.getMessage();
276             logger.error(errorMsg + " -> BAILING OUT");
277             throw new JahiaException("Cannot load sites from the database",
278                     errorMsg, JahiaException.DATABASE_ERROR, JahiaException.CRITICAL_SEVERITY);
279
280         } catch (JahiaException je) {
281             String JavaDoc errorMsg = "Error in dbRemoveMember(JahiaUser user) : " + je.getMessage();
282             logger.error(errorMsg + " -> BAILING OUT");
283             throw new JahiaException("Cannot add member in the database",
284                     errorMsg, JahiaException.DATABASE_ERROR, JahiaException.CRITICAL_SEVERITY);
285
286         } finally {
287             closeStatement(statement);
288         }
289
290         return members;
291     }
292
293
294     /**
295      * This method returns the list of all members of this site.
296      *
297      * @param int siteID, the site identifier
298      * @return Vector of members of this site.
299      */

300     public Vector getMembers(int siteID) throws JahiaException {
301
302         Hashtable hash = new Hashtable();
303         Vector members = new Vector();
304
305         try {
306
307             hash = getMembersMap(siteID);
308             if (hash != null) {
309                 Enumeration enumeration = hash.elements();
310                 String JavaDoc usrKey = null;
311                 JahiaUser user = null;
312                 while (enumeration.hasMoreElements()) {
313                     usrKey = (String JavaDoc) enumeration.nextElement();
314                     user = ServicesRegistry.getInstance()
315                             .getJahiaUserManagerService()
316                             .lookupUser(usrKey);
317                     if (user != null) {
318                         members.add(user);
319                     }
320                 }
321             }
322
323         } catch (JahiaException je) {
324             String JavaDoc errorMsg = "Error in dbRemoveMember(JahiaUser user) : " + je.getMessage();
325             logger.error(errorMsg + " -> BAILING OUT");
326             throw new JahiaException("Cannot get member from the database",
327                     errorMsg, JahiaException.DATABASE_ERROR, JahiaException.CRITICAL_SEVERITY);
328         }
329
330         return members;
331     }
332
333
334     /**
335      * Check if a user has or not access on a site.
336      *
337      * @param int siteID, the site identifier
338      * @param String username, the site identifier
339      * @return Return the user if not null.
340      */

341     public JahiaUser getMember(int siteID, String JavaDoc username) throws JahiaException {
342
343         JahiaUser user = null;
344         Connection JavaDoc dbConn = null;
345         PreparedStatement JavaDoc statement = null;
346
347         user = (JahiaUser) siteUserCache.get(buildCacheKey(siteID, username));
348         if (user != null) {
349             return user;
350         }
351
352         try {
353
354             SiteUserBean suBean = null;
355             dbConn = org.jahia.services.database.ConnectionDispenser.getConnection();
356             StringBuffer JavaDoc query = new StringBuffer JavaDoc(
357                     "select * from jahia_sites_users where siteid_sites_users=?");
358             query.append(" and username_sites_users=?");
359             statement = dbConn.prepareStatement(query.toString());
360             if (statement != null) {
361
362                 statement.setInt(1, siteID);
363                 statement.setString(2, username);
364                 ResultSet JavaDoc rs = statement.executeQuery();
365                 if (rs != null) {
366                     while (rs.next()) {
367                         suBean = getSiteUserBeanFromResultSet(rs);
368                         if (suBean != null) {
369                             user =
370                                     ServicesRegistry.getInstance().getJahiaUserManagerService()
371                                     .lookupUser(suBean.userID);
372                             if (user != null) {
373                                 siteUserCache.put(buildCacheKey(siteID, username), user);
374                             }
375                         }
376                     }
377
378                     if (user == null) {
379                         // user could come from an external service such as LDAP, so we will look him up directly.
380
if (!"".equals(username)) {
381                             user = ServicesRegistry.getInstance().
382                                    getJahiaUserManagerService().lookupUser(
383                                 siteID,
384                                 username);
385                         }
386                         if (user != null) {
387                             siteUserCache.put(buildCacheKey(siteID, username), user);
388                         }
389                     }
390                 }
391             }
392
393         } catch (SQLException JavaDoc se) {
394             String JavaDoc errorMsg = "Error in isMember : " + se.getMessage();
395             logger.error(errorMsg + " -> BAILING OUT");
396             throw new JahiaException("Cannot load sites from the database",
397                     errorMsg, JahiaException.DATABASE_ERROR, JahiaException.CRITICAL_SEVERITY);
398
399         } catch (JahiaException je) {
400             String JavaDoc errorMsg = "Error in isMember(siteid, username) : " + je.getMessage();
401             logger.error(errorMsg + " -> BAILING OUT");
402             throw new JahiaException("Cannot get data from the database",
403                     errorMsg, JahiaException.DATABASE_ERROR, JahiaException.CRITICAL_SEVERITY);
404
405         } finally {
406             closeStatement(statement);
407         }
408
409         return user;
410     }
411
412
413     /**
414      * Build a SiteUserBean from a resultset
415      *
416      * @return JahiaSite the site bean
417      */

418     protected SiteUserBean getSiteUserBeanFromResultSet(ResultSet JavaDoc rs) throws JahiaException {
419
420         SiteUserBean suBean = null;
421
422         if (rs != null) {
423             String JavaDoc username = null;
424             int siteID = -1;
425             String JavaDoc userID = null;
426
427             try {
428                 username = rs.getString("username_sites_users");
429                 siteID = rs.getInt("siteid_sites_users");
430                 userID = rs.getString("userid_sites_users");
431
432             } catch (SQLException JavaDoc se) {
433                 String JavaDoc errorMsg = "Error in getSiteUserBeanFromResultSet(rs) : " + se.getMessage();
434                 logger.error(errorMsg + " -> BAILING OUT");
435                 throw new JahiaException("Cannot read data from resultset",
436                         errorMsg, JahiaException.DATABASE_ERROR,
437                         JahiaException.CRITICAL_SEVERITY);
438             }
439             suBean = new SiteUserBean(username, siteID, userID);
440         }
441         return suBean;
442     }
443
444
445     /**
446      * return a DOM document of all users membership of a site
447      *
448      * @param int the site id
449      * @return JahiaDOMObject a DOM representation of this object
450      */

451     public JahiaDOMObject getUserMembershipsAsDOM(int siteID)
452             throws JahiaException {
453
454         Connection JavaDoc dbConn = null;
455         Statement JavaDoc statement = null;
456
457         JahiaDBDOMObject dom = null;
458
459         try {
460             String JavaDoc sqlQuery = "SELECT * FROM jahia_sites_users where siteid_sites_users=" + siteID;
461
462             dbConn = org.jahia.services.database.ConnectionDispenser.getConnection();
463             statement = dbConn.createStatement();
464             if (statement != null) {
465                 ResultSet JavaDoc rs = statement.executeQuery(sqlQuery);
466                 if (rs != null) {
467                     dom = new JahiaDBDOMObject();
468                     dom.addTable("jahia_sites_users", rs);
469                     return dom;
470                 }
471             }
472         } catch (SQLException JavaDoc se) {
473             String JavaDoc errorMsg = "Error in getUserMembershipsAsDOM(int siteID) : " + se.getMessage();
474             logger.error(errorMsg);
475             throw new JahiaException("Cannot load data from the database",
476                     errorMsg, JahiaException.DATABASE_ERROR,
477                     JahiaException.CRITICAL_SEVERITY);
478
479         } finally {
480             closeStatement(statement);
481         }
482
483         return dom;
484     }
485
486
487     /**
488      * return a DOM document of external users ( from other site except server admin )
489      * that have membership access on this site
490      *
491      * @param int the site id
492      * @return JahiaDOMObject a DOM representation of this object
493      */

494     public JahiaDOMObject getAuthExternalUsersAsDOM(int siteID)
495             throws JahiaException {
496
497         Connection JavaDoc dbConn = null;
498         Statement JavaDoc statement = null;
499
500         JahiaDBDOMObject dom = null;
501
502         try {
503             String JavaDoc sqlQuery = "SELECT * FROM jahia_users"
504                     + " WHERE siteid_jahia_users <>0 AND siteid_jahia_users <>" + siteID
505                     + " AND name_jahia_users IN "
506                     + "(SELECT username_sites_users from jahia_sites_users where siteid_sites_users="
507                     + siteID + ") AND key_jahia_users IN "
508                     + "(SELECT userid_sites_users from jahia_sites_users where siteid_sites_users="
509                     + siteID + ")";
510
511             dbConn = org.jahia.services.database.ConnectionDispenser.getConnection();
512             statement = dbConn.createStatement();
513             if (statement != null) {
514                 ResultSet JavaDoc rs = statement.executeQuery(sqlQuery);
515                 if (rs != null) {
516                     dom = new JahiaDBDOMObject();
517                     dom.addTable("jahia_users", rs);
518                     return dom;
519                 }
520             }
521         } catch (SQLException JavaDoc se) {
522             String JavaDoc errorMsg = "Error in getAuthExternalUsersAsDOM(int siteID) : " + se.getMessage();
523             logger.error(errorMsg);
524             throw new JahiaException("Cannot load data from the database",
525                     errorMsg, JahiaException.DATABASE_ERROR,
526                     JahiaException.CRITICAL_SEVERITY);
527
528         } finally {
529             closeStatement(statement);
530         }
531
532         return dom;
533     }
534
535     public void refreshUser(int id, String JavaDoc username) {
536         siteUserCache.remove(buildCacheKey(id, username));
537     }
538
539
540     private void executeQueryNoResultSet(String JavaDoc queryStr) throws JahiaException {
541
542         Connection JavaDoc dbConn = null;
543         Statement JavaDoc statement = null;
544
545         try {
546             dbConn = org.jahia.services.database.ConnectionDispenser.getConnection();
547             statement = dbConn.createStatement();
548             if (statement != null) {
549                 statement.executeUpdate(queryStr);
550             }
551         } catch (SQLException JavaDoc se) {
552             String JavaDoc errorMsg = "Error in executeQueryNoResultSet(String queryStr) : " + se.getMessage();
553             logger.error(errorMsg + " -> BAILING OUT");
554             throw new JahiaException("Cannot execute query" + queryStr,
555                     errorMsg, JahiaException.DATABASE_ERROR, JahiaException.CRITICAL_SEVERITY);
556
557         } finally {
558             closeStatement(statement);
559         }
560
561     }
562
563     private void closeStatement(Statement JavaDoc statement) {
564         // Close the opened statement
565
try {
566             if (statement != null) {
567                 statement.close();
568             }
569         } catch (SQLException JavaDoc sqlEx) {
570             logger.warn("Cannot close a statement", sqlEx);
571         }
572     }
573
574     private String JavaDoc buildCacheKey(int siteID, String JavaDoc username) {
575         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
576         result.append(siteID);
577         result.append(KEY_SEPARATOR);
578         result.append(username);
579         return result.toString();
580     }
581
582     private void removeUserFromAllSites(JahiaUser user) {
583         ArrayList keysToRemove = new ArrayList();
584         Object JavaDoc[] siteUserKeys = siteUserCache.keys();
585         for (int i = 0; i < siteUserKeys.length; i++) {
586             String JavaDoc curKey = (String JavaDoc) siteUserKeys[i];
587             JahiaUser curUser = (JahiaUser) siteUserCache.get(curKey);
588             if (curUser.getUserKey().equals(user.getUserKey())) {
589                 keysToRemove.add(curKey);
590             }
591         }
592         Iterator keyIter = keysToRemove.iterator();
593         while (keyIter.hasNext()) {
594             String JavaDoc curKey = (String JavaDoc) keyIter.next();
595             siteUserCache.remove(curKey);
596         }
597     }
598
599     private void removeUsersFromSite(int siteID) {
600         ArrayList keysToRemove = new ArrayList();
601         Object JavaDoc[] siteUserKeys = siteUserCache.keys();
602         for (int i = 0; i < siteUserKeys.length; i++) {
603             String JavaDoc curKey = (String JavaDoc) siteUserKeys[i];
604             if (curKey.startsWith(Integer.toString(siteID) + KEY_SEPARATOR)) {
605                 keysToRemove.add(curKey);
606             }
607         }
608         Iterator keyIter = keysToRemove.iterator();
609         while (keyIter.hasNext()) {
610             String JavaDoc curKey = (String JavaDoc) keyIter.next();
611             siteUserCache.remove(curKey);
612         }
613     }
614
615 }
616
Popular Tags