KickJava   Java API By Example, From Geeks To Geeks.

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


1 package org.jahia.services.usermanager;
2
3 /**
4  * <p>Title: </p>
5  * <p>Description: </p>
6  * <p>Copyright: Copyright (c) 2003</p>
7  * <p>Company: </p>
8  * @author not attributable
9  * @version 1.0
10  */

11
12 import org.jahia.data.JahiaDBDOMObject;
13 import org.jahia.data.JahiaDOMObject;
14 import org.jahia.exceptions.JahiaException;
15 import org.jahia.registries.ServicesRegistry;
16 import org.jahia.services.acl.JahiaACLManagerService;
17 import org.jahia.services.database.JahiaIncrementorsDBService;
18 import org.jahia.services.sites.JahiaSite;
19 import org.jahia.services.sites.JahiaSiteTools;
20 import org.jahia.utils.JahiaTools;
21
22 import java.sql.Connection JavaDoc;
23 import java.sql.ResultSet JavaDoc;
24 import java.sql.SQLException JavaDoc;
25 import java.sql.Statement JavaDoc;
26 import java.util.*;
27 import org.jahia.services.cache.CacheFactory;
28 import org.jahia.services.cache.Cache;
29
30 public class JahiaGroupManagerDBProvider extends JahiaGroupManagerProvider {
31
32     private static org.apache.log4j.Logger logger =
33             org.apache.log4j.Logger.getLogger (JahiaGroupManagerDBProvider.class);
34
35     private final String JavaDoc MSG_INTERNAL_ERROR = new String JavaDoc (
36             "Group Manager internal error");
37
38     public static final String JavaDoc USERS_GROUPNAME = "users";
39     public static final String JavaDoc ADMINISTRATORS_GROUPNAME = "administrators";
40     public static final String JavaDoc GUEST_GROUPNAME = "guest";
41     private static final String JavaDoc GROUPNAME_PROPERTY_NAME = "groupname";
42
43     public static final String JavaDoc PROVIDER_NAME = "jahia";
44
45     // references to needed services.
46
private JahiaIncrementorsDBService mIncrementorService = null;
47
48     private static JahiaGroupManagerDBProvider mGroupManagerDBProvider;
49
50     // the DB Group cache name.
51
public static final String JavaDoc DB_GROUP_CACHE = "DBGroupsCache";
52
53     /** the overall provider Group cache name. */
54     public static final String JavaDoc PROVIDERS_GROUP_CACHE = "ProvidersGroupsCache";
55
56     private Cache mGroupCache;
57     private Cache mProvidersGroupCache;
58
59     /** User Member type designation * */
60     protected static int mUSERTYPE = 1;
61
62     /** Group Member type designation * */
63     protected static int mGROUPTYPE = 2;
64
65     //--------------------------------------------------------------------------
66
/**
67      * Default constructor.
68      *
69      * @throws JahiaException Raise a JahiaException when during initialization
70      * one of the needed services could not be instanciated.
71      */

72     protected JahiaGroupManagerDBProvider ()
73         throws JahiaException {
74
75         mGroupCache = CacheFactory.createCache (DB_GROUP_CACHE);
76         mProvidersGroupCache = CacheFactory.createCache(PROVIDERS_GROUP_CACHE);
77
78         ServicesRegistry registry = ServicesRegistry.getInstance ();
79         if (registry != null) {
80             mIncrementorService = registry.getJahiaIncrementorsDBService ();
81             if (mIncrementorService == null) {
82                 throw new JahiaException (MSG_INTERNAL_ERROR,
83                         "Group manager could not get the Incrementors DB Service instance.",
84                         JahiaException.SERVICE_ERROR,
85                         JahiaException.CRITICAL_SEVERITY);
86             }
87         } else {
88             throw new JahiaException (MSG_INTERNAL_ERROR,
89                     "Group manager could not get the Service Registry instance.",
90                     JahiaException.REGISTRY_ERROR,
91                     JahiaException.CRITICAL_SEVERITY);
92         }
93     }
94
95     //-------------------------------------------------------------------------
96
/**
97      * Create an new instance of the Group Manager Service if the instance do not
98      * exist, or return the existing instance.
99      *
100      * @return Return the instance of the Group Manager Service.
101      */

102     public static JahiaGroupManagerDBProvider getInstance () {
103         if (mGroupManagerDBProvider == null) {
104             try {
105                 mGroupManagerDBProvider = new JahiaGroupManagerDBProvider ();
106             } catch (JahiaException ex) {
107                 logger.error (
108                         "Could not create an instance of the JahiaGroupManagerDBService class",
109                         ex);
110             }
111         }
112         return mGroupManagerDBProvider;
113     }
114
115     //-------------------------------------------------------------------------
116
/**
117      * Create a new group in the system.
118      *
119      * @param int siteID the site owner of this user
120      * @param groupname Group's unique identification name
121      *
122      * @return Retrun a reference on a group object on success, or if the groupname
123      * already exists or another error occured, null is returned.
124      */

125     public synchronized JahiaGroup createGroup (int siteID, String JavaDoc name,
126                                                 Properties properties) {
127         // try to avoid a NullPointerException
128
if (!isNameValid (name)) {
129             return null;
130         }
131
132         // Check if the group already exists
133
if (groupExists (siteID, name)) {
134             return null;
135         }
136
137         // Get the next available group ID
138
int groupID;
139         try {
140             groupID = ServicesRegistry.getInstance ().
141                     getJahiaIncrementorsDBService ().autoIncrement (
142                             "jahia_grps");
143         } catch (JahiaException ex) {
144             return null;
145         } catch (NullPointerException JavaDoc ex) {
146             logger.error ("Could not get the Jahia Incrementor Service !", ex);
147             return null;
148         }
149
150         // Create the group
151
JahiaDBGroup group = null;
152         String JavaDoc groupKey = name + ":" + String.valueOf (siteID);
153         try {
154             group = new JahiaDBGroup (groupID, name, groupKey, siteID, null,
155                     properties);
156         } catch (JahiaException ex) {
157             logger.error ("Could not create group [" + name + "] in createGroup()", ex);
158             return null;
159         }
160
161         // add the grp into the cache if the user could be added into the database.
162
if (addGroupIntoDB (groupID, name, groupKey, siteID, properties)) {
163             mGroupCache.put ("k"+groupKey, new JahiaGroupWrapper(group));
164
165             logger.debug ("Group [" + name +
166                 "] was added into the database and in the cache");
167
168             /* 2004-16-06 : update by EP
169             new cache to populate : cross providers only based upon names...
170             2004-23-07 : use wrappers */

171             mProvidersGroupCache.put("k"+groupKey, group);
172
173             // with name for speed
174
mGroupCache.put ("n"+group.getSiteID()+"_"+group.getGroupname (), new JahiaGroupWrapper(group));
175             mProvidersGroupCache.put("n"+group.getSiteID()+"_"+group.getGroupname (), group);
176         } else {
177             logger.error ("Could not add the group [" + name +
178                     "] in the database!!");
179             group = null;
180         }
181
182         return group;
183     }
184
185     //-------------------------------------------------------------------------
186
/**
187      * Lookup the group information from the underlaying system (DB, LDAP, ... )
188      * Try to lookup the group into the cache, if it's not in the cache, then
189      * load it into the cahce from the database.
190      *
191      * @param int siteID the site id
192      * @param name Group's unique identification name.
193      *
194      * @return Return a reference on a the specified group name. Return null
195      * if the group doesn't exist or when any error occured.
196      */

197     public JahiaGroup lookupGroup (int siteID, String JavaDoc name) {
198         // try to avoid a NullPointerException
199
if (!isNameValid (name)) {
200             return null;
201         }
202
203         /* 2004-16-06 : update by EP
204         new cache to browse : cross providers ... */

205         JahiaGroup group = (JahiaGroup) mProvidersGroupCache.get ("n"+siteID+"_"+name);
206
207         // check the SiteID reference
208
if (group != null && group.getSiteID() != siteID)
209             group = null;
210
211         if (group == null) {
212             // 2004-23-07 : use wrappers
213
JahiaGroupWrapper jgw = (JahiaGroupWrapper) mGroupCache.get ("n"+siteID+"_"+name);
214             if (jgw != null) {
215                 group = jgw.getGroup();
216                 // check the SiteID reference
217
if (group != null && group.getSiteID() != siteID)
218                     group = null;
219             }
220
221             if (group == null) {
222                 group = lookupGroupInDB (siteID, name);
223                 if (group != null) {
224                     /* 2004-16-06 : update by EP
225                     new cache to populate : cross providers ... */

226                     mProvidersGroupCache.put ("k"+group.getName(), group);
227                     // with name for speed
228
mProvidersGroupCache.put ("n"+siteID+"_"+group.getGroupname (), group);
229                     // 2004-23-07 : use wrappers
230
mGroupCache.put("k"+group.getName(), new JahiaGroupWrapper(group));
231                 }
232                 // 2004-23-07 : use wrappers
233
mGroupCache.put("n"+siteID+"_"+name, new JahiaGroupWrapper(group));
234             }
235         }
236
237         return group;
238     }
239
240
241     //-------------------------------------------------------------------------
242
/**
243      * Lookup the group information from the underlaying system (DB, LDAP, ... )
244      * Try to lookup the group into the cache, if it's not in the cache, then
245      * load it into the cahce from the database.
246      *
247      * @param String groupKey Group's unique identification key.
248      *
249      * @return Return a reference on a the specified group name. Return null
250      * if the group doesn't exist or when any error occured.
251      */

252     public JahiaGroup lookupGroup (String JavaDoc groupKey) {
253         /* 2004-16-06 : update by EP
254         new cache to browse : cross providers ... */

255         JahiaGroup group = (JahiaGroup) mProvidersGroupCache.get ("k"+groupKey);
256         if (group == null) {
257             // 2004-23-07 : use wrappers
258
JahiaGroupWrapper jgw = (JahiaGroupWrapper) mGroupCache.get ("k"+groupKey);
259             if (jgw == null) {
260                 //logger.debug(" group with key=" + tmpGroupKey + " is not found in cache");
261
group = lookupGroupInDB (groupKey);
262
263                 if (group != null) {
264                     /* 2004-16-06 : update by EP
265                     new cache to populate : cross providers ... */

266                     mProvidersGroupCache.put ("k"+groupKey, group);
267                     // with name for speed
268
mProvidersGroupCache.put ("n"+group.getSiteID()+"_"+group.getGroupname (), group);
269                     // 2004-23-07 : store wrappers
270
mGroupCache.put("n"+group.getSiteID()+"_"+group.getGroupname (), new JahiaGroupWrapper(group));
271                 }
272                 // 2004-23-07 : store wrappers
273
mGroupCache.put("k"+groupKey, new JahiaGroupWrapper(group));
274             } else {
275                 group = jgw.getGroup();
276             }
277         }
278         return group;
279     }
280
281     /**
282      * Find groups according to a table of name=value properties. If the left
283      * side value is "*" for a property then it will be tested against all the
284      * properties. ie *=test* will match every property that starts with "test"
285      *
286      * @param siteID site identifier
287      * @param searchCriterias a Properties object that contains search criterias
288      * in the format name,value (for example "*"="*" or "groupname"="*test*") or
289      * null to search without criterias
290      *
291      * @return Set a set of JahiaGroup elements that correspond to those
292      * search criterias
293      *
294      * @todo this code could be cleaner if groupname was a real group property
295      * but as it isn't we have to do a lot of custom handling.
296      */

297     public Set JavaDoc searchGroups (int siteID, Properties searchCriterias) {
298         /** @todo implement siteID into SQL request */
299         Set JavaDoc result = new HashSet ();
300         Set JavaDoc groupKeys = new HashSet ();
301
302         // Get a database connection
303
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.
304                 getConnection ();
305         if (dbConn == null) {
306             return result;
307         }
308
309         if (searchCriterias == null) {
310             searchCriterias = new Properties ();
311             searchCriterias.setProperty ("*", "*");
312         }
313
314         boolean haveWildCardProperty = false;
315         if (searchCriterias.getProperty ("*") != null) {
316             haveWildCardProperty = true;
317         }
318
319         // execute the SELECT query
320
Statement JavaDoc statement = null;
321         try {
322             statement = dbConn.createStatement ();
323             if (statement != null) {
324
325                 StringBuffer JavaDoc query;
326                 boolean onlyGroupNameInSelect = false;
327                 if ((searchCriterias.getProperty (GROUPNAME_PROPERTY_NAME) != null) ||
328                         (haveWildCardProperty)
329                 ) {
330
331                     String JavaDoc curCriteriaValue;
332                     if (haveWildCardProperty) {
333                         curCriteriaValue = makeLIKEString (searchCriterias.
334                                 getProperty ("*"));
335                     } else {
336                         curCriteriaValue = makeLIKEString (searchCriterias.
337                                 getProperty (GROUPNAME_PROPERTY_NAME));
338                     }
339                     query =
340                             new StringBuffer JavaDoc (
341                                     "SELECT DISTINCT key_jahia_grps AS result_key_jahia_grps FROM jahia_grps,jahia_sites_grps WHERE ");
342                     query.append ("name_jahia_grps LIKE '");
343                     query.append (curCriteriaValue);
344                     query.append ("'");
345                     query.append ("AND jahia_sites_grps.siteid_sites_grps=");
346                     query.append (siteID);
347                     query.append (
348                             " AND jahia_grps.key_jahia_grps=jahia_sites_grps.grpid_sites_grps");
349                     // logger.debug("Executing query [" + query.toString() + "]");
350
ResultSet JavaDoc rs = statement.executeQuery (query.toString ());
351                     if (rs != null) {
352                         while (rs.next ()) {
353                             String JavaDoc name = rs.getString ("result_key_jahia_grps");
354                             if (name != null) {
355                                 groupKeys.add (name);
356                             }
357                         }
358                     }
359
360                     if ((!haveWildCardProperty) &&
361                             (searchCriterias.size () == 1)) {
362                         onlyGroupNameInSelect = true;
363                     }
364                 } else {
365                     onlyGroupNameInSelect = false;
366                 }
367
368                 if (!onlyGroupNameInSelect) {
369
370                     query =
371                             new StringBuffer JavaDoc (
372                                     "SELECT DISTINCT jahia_grps.key_jahia_grps AS result_key_jahia_grps FROM jahia_grps, jahia_grp_prop, jahia_sites_grps WHERE ");
373                     Enumeration criteriaNames = searchCriterias.keys ();
374                     while (criteriaNames.hasMoreElements ()) {
375                         String JavaDoc curCriteriaName = (String JavaDoc) criteriaNames.
376                                 nextElement ();
377                         String JavaDoc curCriteriaValue = makeLIKEString (
378                                 searchCriterias.getProperty (curCriteriaName));
379                         if ("*".equals (curCriteriaName)) {
380                             // we must look in all columns, including special for
381
// the user.
382
query.append ("(jahia_grps.name_jahia_grps LIKE '");
383                             query.append (curCriteriaValue);
384                             query.append ("'");
385                             query.append (
386                                     " OR jahia_grp_prop.value_jahia_grp_prop LIKE '");
387                             query.append (curCriteriaValue);
388                             query.append ("') ");
389                             query.append (" AND ");
390                             onlyGroupNameInSelect = false;
391                         } else {
392                             if (GROUPNAME_PROPERTY_NAME.equals (curCriteriaName)) {
393                                 // group name filter is a special case and is not
394
// stored in the property table.
395
} else {
396                                 query.append (
397                                         "(jahia_grp_prop.name_jahia_grp_prop='");
398                                 query.append (makeLIKEString (curCriteriaName));
399                                 query.append (
400                                         "' AND jahia_grp_prop.value_jahia_grp_prop LIKE '");
401                                 query.append (curCriteriaValue);
402                                 query.append ("') ");
403                                 query.append (" AND ");
404                                 onlyGroupNameInSelect = false;
405                             }
406                         }
407                     }
408                     if (!(onlyGroupNameInSelect)) {
409                         if (!query.toString ().endsWith (" AND ")) {
410                             query.append (" AND ");
411                         }
412                     }
413                     query.append (
414                             "jahia_grps.id_jahia_grps=jahia_grp_prop.id_jahia_grp AND ");
415                     query.append ("jahia_sites_grps.siteid_sites_grps=");
416                     query.append (siteID);
417                     query.append (
418                             " AND jahia_grps.key_jahia_grps=jahia_sites_grps.grpid_sites_grps");
419
420                     ResultSet JavaDoc rs = statement.executeQuery (query.toString ());
421                     if (rs != null) {
422                         while (rs.next ()) {
423                             String JavaDoc name = rs.getString ("result_key_jahia_grps");
424                             if (name != null) {
425                                 groupKeys.add (name);
426                             }
427                         }
428                     }
429                 }
430             }
431         } catch (SQLException JavaDoc ex) {
432             logger.error ("Error while searching in groups for site " + siteID, ex);
433         } finally {
434             closeStatement (statement);
435         }
436
437         // now that we have all the keys, let's load all the groups.
438
Iterator groupKeyEnum = groupKeys.iterator ();
439         while (groupKeyEnum.hasNext ()) {
440             String JavaDoc curGroupKey = (String JavaDoc) groupKeyEnum.next ();
441             JahiaGroup group = lookupGroup (curGroupKey);
442             result.add (group);
443         }
444
445         return result;
446     }
447
448     //-------------------------------------------------------------------------
449
/**
450      * Delete a group from the system. Updates the database automatically, and
451      * signal the ACL Manager that the group no longer exists.
452      *
453      * @param group Reference to a JahiaGroup object.
454      *
455      * @return Return true on success, or false on any failure.
456      */

457     public synchronized boolean deleteGroup (JahiaGroup group) {
458         if (group == null) {
459             return false;
460         }
461
462         // cannot remove the super admin group
463
if ((group.getSiteID () == 0) &&
464                 (group.getGroupname ().equals (ADMINISTRATORS_GROUPNAME))) {
465             return false;
466         }
467
468         // It's not allowed to remover the admin, guest and users group !
469
/*
470              if ((group.getGroupname().equals(ADMINISTRATORS_GROUPNAME)) ||
471             (group.getGroupname().equals(USERS_GROUPNAME)) ||
472             (group.getGroupname().equals(GUEST_GROUPNAME)))
473                   {
474             return false;
475                   }
476          */

477
478         JahiaACLManagerService aclService = null;
479
480         // Get the ACL Manager Service.
481
try {
482             aclService = ServicesRegistry.getInstance ().
483                     getJahiaACLManagerService ();
484             if (aclService == null) {
485                 logger.error ("ACL Manager Service instance is null !!");
486                 return false;
487             }
488         } catch (NullPointerException JavaDoc ex) {
489             logger.error ("Could not get the ACL Manager Service !!", ex);
490             return false;
491         }
492
493         // delete the group from the database and from the cache.
494
boolean result = false;
495
496         if (deleteGroupFromDB (group)) {
497             // remove the gfroup from the cache
498
mGroupCache.remove ("k"+group.getName ());
499
500             mProvidersGroupCache.remove("k"+group.getName ());
501
502             mGroupCache.remove ("n"+group.getSiteID()+"_"+group.getGroupname ());
503
504             mProvidersGroupCache.remove("n"+group.getSiteID()+"_"+group.getGroupname ());
505
506             // invalidate the group in the ACL manager
507
aclService.removeGroupFromAllACLs (group);
508
509             // invalidate the group
510
group = null;
511             result = true;
512         }
513         return result;
514     }
515
516     //-------------------------------------------------------------------------
517
/**
518      * This function checks on a gived site if the groupname has already been
519      * assigned to another group.
520      *
521      * @param int siteID the site id
522      * @param groupname String representing the unique group name.
523      *
524      * @return Return true if the specified username has not been assigned yet,
525      * return false on any failure.
526      */

527     public boolean groupExists (int siteID, String JavaDoc name) {
528         return (lookupGroup (siteID, name) != null);
529     }
530
531     //-------------------------------------------------------------------------
532
/**
533      * Remove the specified user from all the membership lists of all the groups.
534      *
535      * @param user Reference on an existing user.
536      *
537      * @return Return true on success, or false on any failure.
538      */

539     public synchronized boolean removeUserFromAllGroups (JahiaUser user) {
540         // try to avoid a NullPointerException
541
if (user == null) {
542             return false;
543         }
544
545         boolean result = false;
546
547         // remove all the users from the database
548
String JavaDoc query = "DELETE FROM jahia_grp_access WHERE id_jahia_member='" +
549                 ((JahiaUser) user).getName () + "'";
550
551         result = makeQuery (query);
552
553         if (result) {
554             // remove the user from all the groups in the cache.
555
// Updated on 2004-16-06 to use cache
556
Object JavaDoc[] groupKeys = mGroupCache.keys ();
557             for (int i = 0; i < groupKeys.length; i++) {
558                 JahiaGroup group = ((JahiaGroupWrapper) mGroupCache.get (groupKeys[i])).getGroup();
559                 if (group != null) {
560                     group.removeMember(user);
561                 }
562             }
563             groupKeys = mProvidersGroupCache.keys ();
564             for (int i = 0; i < groupKeys.length; i++) {
565                 JahiaGroup group = (JahiaGroup) mProvidersGroupCache.get (groupKeys[i]);
566                 if (group != null) {
567                     group.removeMember(user);
568                 }
569             }
570         }
571         return result;
572     }
573
574     //-------------------------------------------------------------------------
575
/**
576      * Return a <code>Vector</code) of <code>String</code> representing all the
577      * group names.
578      *
579      * @return Return a vector of strings containing all the group names.
580      */

581     public Vector getGroupnameList () {
582         Vector result = new Vector ();
583
584         // Get a database connection
585
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.
586                 getConnection ();
587         if (dbConn == null) {
588             return result;
589         }
590
591         Statement JavaDoc statement = null;
592         try {
593             statement = dbConn.createStatement ();
594             if (statement != null) {
595                 // Get the basic user data
596
String JavaDoc query = "SELECT name_jahia_grps FROM jahia_grps";
597                 ResultSet JavaDoc rs = statement.executeQuery (query);
598                 if (rs != null) {
599                     String JavaDoc name;
600                     while (rs.next ()) {
601                         name = rs.getString ("name_jahia_grps");
602                         if (name != null) {
603                             result.add (name);
604                         }
605                     }
606                 }
607             }
608         } catch (SQLException JavaDoc sqlEx) {
609             // FIXME -Fulco- : Don't know yet what to do with this exception.
610
// It should be logged somewhere !
611
} finally {
612
613             closeStatement (statement);
614         }
615         return result;
616     }
617
618     //-------------------------------------------------------------------------
619
/**
620      * Return a <code>Vector</code) of <code>String</code> representing all the
621      * group names of a site.
622      *
623      * @param int the site id
624      *
625      * @return Return a vector of strings containing all the group names.
626      */

627     public Vector getGroupnameList (int siteID) {
628         Vector result = new Vector ();
629
630         // Get a database connection
631
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.
632                 getConnection ();
633         if (dbConn == null) {
634             return result;
635         }
636
637         Statement JavaDoc statement = null;
638         try {
639             statement = dbConn.createStatement ();
640             if (statement != null) {
641                 // Get the basic user data
642
String JavaDoc query =
643                         "SELECT name_jahia_grps FROM jahia_grps where siteid_jahia_grps=" +
644                         siteID;
645                 ResultSet JavaDoc rs = statement.executeQuery (query);
646                 if (rs != null) {
647                     String JavaDoc name;
648                     while (rs.next ()) {
649                         name = rs.getString ("name_jahia_grps");
650                         if (name != null) {
651                             result.add (name);
652                         }
653                     }
654                 }
655             }
656         } catch (SQLException JavaDoc sqlEx) {
657             // FIXME -Fulco- : Don't know yet what to do with this exception.
658
// It should be logged somewhere !
659
} finally {
660
661             closeStatement (statement);
662         }
663         return result;
664     }
665
666     //-------------------------------------------------------------------------
667
/**
668      * Return a <code>Vector</code) of <code>String</code> representing all the
669      * group keys of a site.
670      *
671      * @param int the site id
672      *
673      * @return Return a vector of identifier of all groups of this site.
674      *
675      * @auhtor NK
676      */

677     public Vector getGroupList (int siteID) {
678
679         Vector result = new Vector ();
680
681         // Get a database connection
682
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.
683                 getConnection ();
684         if (dbConn == null) {
685             return result;
686         }
687
688         Statement JavaDoc statement = null;
689         try {
690             statement = dbConn.createStatement ();
691             if (statement != null) {
692                 // Get the basic user data
693
String JavaDoc query =
694                         "SELECT key_jahia_grps FROM jahia_grps where siteid_jahia_grps=" +
695                         siteID;
696                 ResultSet JavaDoc rs = statement.executeQuery (query);
697                 if (rs != null) {
698                     String JavaDoc name;
699                     while (rs.next ()) {
700                         name = rs.getString ("key_jahia_grps");
701                         if (name != null) {
702                             result.add (name);
703                         }
704                     }
705                 }
706             }
707         } catch (SQLException JavaDoc sqlEx) {
708             // FIXME -Fulco- : Don't know yet what to do with this exception.
709
// It should be logged somewhere !
710
} finally {
711
712             closeStatement (statement);
713         }
714         return result;
715
716     }
717
718     //-------------------------------------------------------------------------
719
/**
720      * Return a <code>Vector</code) of <code>String</code> representing all the
721      * group keys of a site.
722      *
723      * @param int the site id
724      *
725      * @return Return a vector of identifier of all groups of this site.
726      *
727      * @auhtor NK
728      */

729     public Vector getGroupList () {
730
731         Vector result = new Vector ();
732
733         // Get a database connection
734
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.
735                 getConnection ();
736         if (dbConn == null) {
737             return result;
738         }
739
740         Statement JavaDoc statement = null;
741         try {
742             statement = dbConn.createStatement ();
743             if (statement != null) {
744                 // Get the basic user data
745
String JavaDoc query = "SELECT key_jahia_grps FROM jahia_grps ";
746                 ResultSet JavaDoc rs = statement.executeQuery (query);
747                 if (rs != null) {
748                     String JavaDoc name;
749                     while (rs.next ()) {
750                         name = rs.getString ("key_jahia_grps");
751                         if (name != null) {
752                             result.add (name);
753                         }
754                     }
755                 }
756             }
757         } catch (SQLException JavaDoc sqlEx) {
758             // FIXME -Fulco- : Don't know yet what to do with this exception.
759
// It should be logged somewhere !
760
} finally {
761
762             closeStatement (statement);
763         }
764         return result;
765
766     }
767
768     //-------------------------------------------------------------------------
769
/**
770      * Return the list of groups to which the specified user has access.
771      *
772      * @param user Valid reference on an existing group.
773      *
774      * @return Return a vector of strings holding all the group names to
775      * which the user as access. On any error, the returned vector
776      * might be null.
777      */

778     public Vector getUserMembership (JahiaUser user) {
779         // try to avoid a NullPointerException
780
if (user == null) {
781             return null;
782         }
783
784         Vector result = new Vector ();
785
786         // Get a database connection
787
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.
788                 getConnection ();
789         if (dbConn == null) {
790             return result;
791         }
792
793         Statement JavaDoc statement = null;
794
795         try {
796             statement = dbConn.createStatement ();
797             if (statement != null) {
798                 StringBuffer JavaDoc query = new StringBuffer JavaDoc (
799                         "SELECT id_jahia_grps FROM jahia_grp_access");
800                 query.append (" WHERE id_jahia_member='");
801                 query.append (((JahiaUser) user).getName ());
802                 query.append ("' AND membertype_grp_access=");
803                 query.append (mUSERTYPE);
804
805                 ResultSet JavaDoc rs = statement.executeQuery (query.toString ());
806                 if (rs != null) {
807                     while (rs.next ()) {
808                         String JavaDoc name = rs.getString ("id_jahia_grps");
809                         if (name != null) {
810                             result.add (name);
811                         }
812                     }
813                 }
814             }
815         } catch (SQLException JavaDoc ex) {
816             // FIXME -Fulco- : Don't know yet what to do with this exception.
817
// It should be logged somewhere !
818
} finally {
819
820             closeStatement (statement);
821         }
822         return result;
823     }
824
825     //-------------------------------------------------------------------------
826
/**
827      *
828      */

829     public JahiaGroup getAdministratorGroup (int siteID) {
830         return lookupGroup (siteID, ADMINISTRATORS_GROUPNAME);
831     }
832
833     //-------------------------------------------------------------------------
834
/**
835      * Get all JahiaSite objects where the user has an access.
836      *
837      * @param JahiaUser user, the user you want to get his access grantes sites list.
838      *
839      * @return Return a vector containing all JahiaSite objects where the user has an access.
840      *
841      * @author Alexandre Kraft
842      */

843     public Vector getAdminGrantedSites (JahiaUser user)
844             throws JahiaException {
845
846         Vector grantedSites = new Vector ();
847         Enumeration sitesList = ServicesRegistry.getInstance ().
848                 getJahiaSitesService ().getSites ();
849
850         while (sitesList.hasMoreElements ()) {
851             JahiaSite jahiaSite = (JahiaSite) sitesList.nextElement ();
852             logger.debug ("check granted site " + jahiaSite.getServerName ());
853
854             if ((JahiaSiteTools.getAdminGroup (jahiaSite) != null) &&
855                 JahiaSiteTools.getAdminGroup (jahiaSite).isMember (user)) {
856                 logger.debug ("granted site for " + jahiaSite.getServerName ());
857                 grantedSites.add (jahiaSite);
858             }
859         }
860
861         return grantedSites;
862     } // end getAdminGrantedSites
863

864     //-------------------------------------------------------------------------
865
/**
866      * Return an instance of the users group.
867      *
868      * @return Return the instance of the users group. Return null on any failure
869      */

870     public final JahiaGroup getUsersGroup (int siteID) {
871         return lookupGroup (siteID, USERS_GROUPNAME);
872     }
873
874     //-------------------------------------------------------------------------
875
/**
876      * Return an instance of the guest group
877      *
878      * @return Return the instance of the guest group. Return null on any failure.
879      */

880     public final JahiaGroup getGuestGroup (int siteID) {
881         return lookupGroup (siteID, GUEST_GROUPNAME);
882     }
883
884     public void updateCache(JahiaGroup jahiaGroup) {
885         mGroupCache.put("k"+jahiaGroup.getGroupKey(), new JahiaGroupWrapper(jahiaGroup));
886         mGroupCache.put("n"+jahiaGroup.getSiteID()+"_"+jahiaGroup.getGroupname(), new JahiaGroupWrapper(jahiaGroup));
887         mProvidersGroupCache.put ("k"+jahiaGroup.getGroupKey(), jahiaGroup);
888         mProvidersGroupCache.put ("n"+jahiaGroup.getSiteID()+"_"+jahiaGroup.getGroupname(), jahiaGroup);
889     }
890
891     //--------------------------------------------------------------------------
892
// Executes and INSERT, UPDATE or DELETE SQL operation. This method should not
893
// be used with and SELECT operation. This method lock the object on database
894
// write access.
895
private boolean makeQuery (String JavaDoc query) {
896         // Get a database connection
897
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.
898                 getConnection ();
899         if (dbConn == null) {
900             return false;
901         }
902
903         boolean result = false;
904         Statement JavaDoc statement = null;
905
906         try {
907             statement = dbConn.createStatement ();
908             if (statement != null) {
909                 synchronized (this) {
910                     statement.executeUpdate (query);
911                     result = true;
912                 }
913             }
914         } catch (SQLException JavaDoc sqlEx) {
915             logger.error ("SQL Exception occured for query [" + query + "]", sqlEx);
916         } finally {
917
918             closeStatement (statement);
919         }
920
921         return result;
922     }
923
924     //--------------------------------------------------------------------------
925
private boolean addGroupIntoDB (int id, String JavaDoc groupname, String JavaDoc groupKey,
926                                     int siteID, Properties properties) {
927         // Get a database connection
928
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.
929                 getConnection ();
930         if (dbConn == null) {
931             return false;
932         }
933
934         boolean result = true;
935         String JavaDoc grpIDStr = Integer.toString (id);
936         Statement JavaDoc statement = null;
937
938         try {
939             statement = dbConn.createStatement ();
940
941             String JavaDoc query = "INSERT INTO jahia_grps VALUES (" +
942                     grpIDStr + ",'" + groupname + "','" + groupKey +
943                     "'," + siteID + ")";
944             statement.executeUpdate (query);
945
946             // Add the grp's attributes
947
if (properties != null) {
948                 Enumeration enumeration = properties.propertyNames ();
949                 String JavaDoc name, value;
950
951                 if (enumeration.hasMoreElements ()) {
952                     while (enumeration.hasMoreElements ()) {
953                         name = (String JavaDoc) enumeration.nextElement ();
954                         value = properties.getProperty (name);
955
956                         try {
957                             JahiaGroupDBUtils.getInstance ().addProperty (name,
958                                     value, id, PROVIDER_NAME, groupKey);
959                         } catch (JahiaException je) {
960                             logger.error (
961                                     "Error while inserting group " + id + " properties into database",
962                                     je);
963                         }
964
965                     }
966                 }
967             }
968         } catch (SQLException JavaDoc sqlEx) {
969             logger.error ("SQL Exception occured!", sqlEx);
970             result = false;
971         } finally {
972
973             closeStatement (statement);
974         }
975         return result;
976     }
977
978     //--------------------------------------------------------------------------
979
// NK
980
private JahiaDBGroup lookupGroupInDB (String JavaDoc groupKey) {
981         JahiaDBGroup group = null;
982         Properties properties = new Properties ();
983
984         // Get a database connection
985
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.
986                 getConnection ();
987         if (dbConn == null) {
988             return null;
989         }
990
991         // execute the SELECT query
992
Statement JavaDoc statement = null;
993         String JavaDoc query = "";
994         try {
995             statement = dbConn.createStatement ();
996             if (statement != null) {
997                 query = "SELECT id_jahia_grps, name_jahia_grps,siteid_jahia_grps FROM jahia_grps WHERE key_jahia_grps='" +
998                         groupKey + "'";
999                 ResultSet JavaDoc rs = statement.executeQuery (query);
1000                if (rs != null) {
1001                    if (rs.next ()) {
1002                        int id = rs.getInt ("id_jahia_grps");
1003                        String JavaDoc name = rs.getString ("name_jahia_grps");
1004                        int siteID = rs.getInt ("siteid_jahia_grps");
1005                        Hashtable members = getGroupMembers (groupKey);
1006
1007                        try {
1008                            properties =
1009                                    JahiaGroupDBUtils.getInstance ().getGroupProperties (id,
1010                                            PROVIDER_NAME, groupKey);
1011                        } catch (JahiaException je) {
1012                            logger.error (
1013                                    "Error while inserting group " + id + " properties into database",
1014                                    je);
1015                        }
1016
1017                        try {
1018                            group = new JahiaDBGroup (id, name, groupKey, siteID,
1019                                    members, properties);
1020                            if (group != null) {
1021                                logger.debug ("Group [" + groupKey + "/" + name +
1022                                        "] loaded from database");
1023                            }
1024                        } catch (JahiaException ex) {
1025                            logger.error ("Could not create group [" + name +
1026                                    "] in lookupGroupInDB()", ex);
1027                        }
1028                    }
1029                }
1030            }
1031
1032        } catch (SQLException JavaDoc ex) {
1033            logger.error ("SQL Exception occured for query [" +
1034                    query + "]", ex);
1035        } finally {
1036
1037            closeStatement (statement);
1038        }
1039        return group;
1040    }
1041
1042    //--------------------------------------------------------------------------
1043
private JahiaDBGroup lookupGroupInDB (int siteID, String JavaDoc name) {
1044        JahiaDBGroup group = null;
1045        Properties properties = new Properties ();
1046
1047        // Get a database connection
1048
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.
1049                getConnection ();
1050        if (dbConn == null) {
1051            return null;
1052        }
1053
1054        // execute the SELECT query
1055
Statement JavaDoc statement = null;
1056        String JavaDoc query = "";
1057        try {
1058            statement = dbConn.createStatement ();
1059            if (statement != null) {
1060                query =
1061                        "SELECT id_jahia_grps, key_jahia_grps FROM jahia_grps WHERE name_jahia_grps='" +
1062                        name + "' and siteid_jahia_grps=" + siteID;
1063                ResultSet JavaDoc rs = statement.executeQuery (query);
1064                if (rs != null) {
1065                    if (rs.next ()) {
1066                        int groupID = rs.getInt ("id_jahia_grps");
1067                        String JavaDoc groupKey = rs.getString ("key_jahia_grps");
1068                        Hashtable members = getGroupMembers (groupKey);
1069
1070                        try {
1071                            properties = JahiaGroupDBUtils.getInstance ().
1072                                    getGroupProperties (groupID,
1073                                            PROVIDER_NAME, groupKey);
1074                        } catch (JahiaException je) {
1075                            logger.error (
1076                                    "Error while loading properties for group " + groupID, je);
1077                        }
1078
1079                        try {
1080                            group = new JahiaDBGroup (groupID, name, groupKey,
1081                                    siteID, members, properties);
1082                            if (group != null) {
1083                                logger.debug ("Group [" + Integer.toString (groupID) +
1084                                        "/" + name + "] loaded from database");
1085                            }
1086                        } catch (JahiaException ex) {
1087                            logger.error ("Could not create group [" + name +
1088                                    "] in lookupGroupInDB()", ex);
1089                        }
1090                    }
1091                }
1092            }
1093
1094        } catch (SQLException JavaDoc ex) {
1095            logger.error ("SQL Exception occured for query [" +
1096                    query + "]", ex);
1097        } finally {
1098
1099            closeStatement (statement);
1100        }
1101
1102        return group;
1103    }
1104
1105
1106    //--------------------------------------------------------------------------
1107
private Hashtable getGroupMembers (String JavaDoc groupKey) {
1108        Hashtable members = null;
1109
1110        // Get a database connection
1111
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.
1112                getConnection ();
1113        if (dbConn == null) {
1114            return null;
1115        }
1116
1117        // execute the SELECT query
1118
Statement JavaDoc statement = null;
1119        StringBuffer JavaDoc query = new StringBuffer JavaDoc ();
1120        try {
1121            members = new Hashtable ();
1122            Vector memberKeys = new Vector ();
1123            String JavaDoc idMember;
1124
1125            //-------------------------
1126
// GET THE USER MEMBER KEYS
1127
statement = dbConn.createStatement ();
1128            if (statement != null) {
1129                // load all the group's user members
1130

1131                query.append (
1132                        "SELECT id_jahia_member FROM jahia_grp_access WHERE id_jahia_grps='");
1133                query.append (groupKey);
1134                query.append ("' AND membertype_grp_access=");
1135                query.append (mUSERTYPE);
1136
1137                ResultSet JavaDoc rs = statement.executeQuery (query.toString ());
1138                if (rs != null) {
1139                    while (rs.next ()) {
1140                        String JavaDoc key = rs.getString ("id_jahia_member");
1141                        memberKeys.add (key);
1142                    }
1143                }
1144                rs = null;
1145                closeStatement (statement);
1146
1147                // add the users in the member list
1148
for (int i = 0; i < memberKeys.size (); i++) {
1149                    JahiaUser user = ServicesRegistry.getInstance ().
1150                            getJahiaUserManagerService ().
1151                            lookupUser ((String JavaDoc) memberKeys.get (i));
1152                    if (user != null) {
1153                        members.put (memberKeys.get (i), user);
1154                    }
1155                }
1156
1157                // remove all the user keys.
1158
memberKeys.clear ();
1159            }
1160            query.delete (0, query.length ());
1161
1162            //--------------------------
1163
// GET THE GROUP MEMBER KEYS
1164
statement = dbConn.createStatement ();
1165            if (statement != null) {
1166                // load all the group's group members
1167
query.append (
1168                        "SELECT id_jahia_member FROM jahia_grp_access WHERE id_jahia_grps='");
1169                query.append (groupKey);
1170                query.append ("' AND membertype_grp_access=");
1171                query.append (mGROUPTYPE);
1172
1173                ResultSet JavaDoc rs = statement.executeQuery (query.toString ());
1174                if (rs != null) {
1175                    while (rs.next ()) {
1176                        String JavaDoc key = rs.getString ("id_jahia_member");
1177                        memberKeys.add (key);
1178                    }
1179                }
1180                rs = null;
1181                closeStatement (statement);
1182
1183                // add the users in the member list
1184
for (int i = 0; i < memberKeys.size (); i++) {
1185                    JahiaGroup group = ServicesRegistry.getInstance ().
1186                            getJahiaGroupManagerService ().
1187                            lookupGroup ((String JavaDoc) memberKeys.get (i));
1188                    if (group != null) {
1189                        members.put (memberKeys.get (i), group);
1190                    }
1191                }
1192            }
1193            memberKeys = null;
1194            idMember = null;
1195        } catch (SQLException JavaDoc ex) {
1196            logger.error ("SQL Exception occured for query [" +
1197                    query + "]", ex);
1198        } finally {
1199
1200            closeStatement (statement);
1201        }
1202
1203        return members;
1204    }
1205
1206    //--------------------------------------------------------------------------
1207
/**
1208     *
1209     */

1210    private boolean deleteGroupFromDB (JahiaGroup group) {
1211        // Get a database connection
1212
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.
1213                getConnection ();
1214        if (dbConn == null) {
1215            return false;
1216        }
1217
1218        boolean result = true;
1219        Statement JavaDoc statement = null;
1220
1221        try {
1222            statement = dbConn.createStatement ();
1223
1224            if (statement != null) {
1225                String JavaDoc tmpStr = "WHERE key_jahia_grps='" +
1226                        ((JahiaDBGroup) group).getName () + "'";
1227                statement.executeUpdate ("DELETE FROM jahia_grps " + tmpStr);
1228
1229                tmpStr = "WHERE id_jahia_grps='" +
1230                        ((JahiaDBGroup) group).getName () + "'";
1231                statement.executeUpdate ("DELETE FROM jahia_grp_access " +
1232                        tmpStr);
1233                statement.executeUpdate (
1234                        "DELETE FROM jahia_grp_prop WHERE id_jahia_grp=" +
1235                        group.hashCode ());
1236
1237            } else {
1238                result = false;
1239            }
1240        } catch (SQLException JavaDoc sqlEx_1st) {
1241            result = false;
1242        } finally {
1243
1244            closeStatement (statement);
1245        }
1246
1247        return result;
1248    }
1249
1250    //--------------------------------------------------------------------------
1251
/**
1252     * return a DOM document of all groups of a site
1253     *
1254     * @param int the site id
1255     *
1256     * @return JahiaDOMObject a DOM representation of this object
1257     *
1258     * @author NK
1259     */

1260    public JahiaDOMObject getGroupsAsDOM (int siteID)
1261            throws JahiaException {
1262
1263        Connection JavaDoc dbConn = null;
1264        Statement JavaDoc statement = null;
1265
1266        String JavaDoc output = null;
1267        JahiaDBDOMObject dom = null;
1268
1269        try {
1270            String JavaDoc sqlQuery =
1271                    "SELECT * FROM jahia_grps where siteid_jahia_grps=" + siteID;
1272
1273            dbConn = org.jahia.services.database.ConnectionDispenser.
1274                    getConnection ();
1275            statement = dbConn.createStatement ();
1276            if (statement != null) {
1277                ResultSet JavaDoc rs = statement.executeQuery (sqlQuery);
1278                if (rs != null) {
1279                    dom = new JahiaDBDOMObject ();
1280                    dom.addTable ("jahia_grps", rs);
1281                    return dom;
1282                }
1283            }
1284        } catch (SQLException JavaDoc se) {
1285            String JavaDoc errorMsg = "Error in getGroupsAsDOM(int siteID) : " +
1286                    se.getMessage ();
1287            logger.error (errorMsg, se);
1288            throw new JahiaException ("Cannot load groups from the database",
1289                    errorMsg, JahiaException.DATABASE_ERROR,
1290                    JahiaException.CRITICAL_SEVERITY, se);
1291        } finally {
1292
1293            closeStatement (statement);
1294        }
1295
1296        return dom;
1297    }
1298
1299    //--------------------------------------------------------------------------
1300
/**
1301     * return a DOM document of all group props of a site
1302     *
1303     * @param int the site id
1304     *
1305     * @return JahiaDOMObject a DOM representation of this object
1306     *
1307     * @author NK
1308     */

1309    public JahiaDOMObject getGroupPropsAsDOM (int siteID)
1310            throws JahiaException {
1311
1312        Connection JavaDoc dbConn = null;
1313        Statement JavaDoc statement = null;
1314
1315        String JavaDoc output = null;
1316        JahiaDBDOMObject dom = null;
1317
1318        try {
1319
1320            String JavaDoc sqlQuery = "SELECT DISTINCT jahia_grp_prop.id_jahia_grp,jahia_grp_prop.name_jahia_grp_prop,jahia_grp_prop.value_jahia_grp_prop FROM jahia_grp_prop ,jahia_grps WHERE jahia_grp_prop.grpkey_jahia_grp_prop="
1321                    +
1322                    "jahia_grps.key_jahia_grps AND jahia_grps.siteid_jahia_grps=" +
1323                    siteID;
1324
1325            dbConn = org.jahia.services.database.ConnectionDispenser.
1326                    getConnection ();
1327            statement = dbConn.createStatement ();
1328            if (statement != null) {
1329                ResultSet JavaDoc rs = statement.executeQuery (sqlQuery);
1330                if (rs != null) {
1331                    dom = new JahiaDBDOMObject ();
1332                    dom.addTable ("jahia_grp_prop", rs);
1333                    return dom;
1334                }
1335            }
1336        } catch (SQLException JavaDoc se) {
1337            String JavaDoc errorMsg = "Error in getGroupPropsAsDOM(int siteID) : " +
1338                    se.getMessage ();
1339            logger.error (errorMsg, se);
1340            throw new JahiaException (
1341                    "Cannot load groups props from the database",
1342                    errorMsg, JahiaException.DATABASE_ERROR,
1343                    JahiaException.CRITICAL_SEVERITY, se);
1344        } finally {
1345
1346            closeStatement (statement);
1347        }
1348
1349        return dom;
1350    }
1351
1352    //--------------------------------------------------------------------------
1353
/**
1354     * return a DOM document of all application role groups of a site
1355     *
1356     * @param int the site id
1357     *
1358     * @return JahiaDOMObject a DOM representation of this object
1359     *
1360     * @author NK
1361     */

1362    public JahiaDOMObject getAppRoleGroupsAsDOM (int siteID)
1363            throws JahiaException {
1364
1365        Connection JavaDoc dbConn = null;
1366        Statement JavaDoc statement = null;
1367
1368        String JavaDoc output = null;
1369        JahiaDBDOMObject dom = null;
1370
1371        Vector grps = GroupsTools.getGroups (siteID, true);
1372
1373        try {
1374
1375            String JavaDoc sqlQuery = "";
1376            int size = grps.size ();
1377
1378            if (size == 0) {
1379                dom = new JahiaDBDOMObject ();
1380                dom.addTable ("jahia_grps", null);
1381                return dom;
1382            } else {
1383                StringBuffer JavaDoc buff = new StringBuffer JavaDoc (
1384                        "SELECT DISTINCT id_jahia_grps,name_jahia_grps,key_jahia_grps,siteid_jahia_grps FROM jahia_grps where key_jahia_grps IN(");
1385                JahiaGroup grp = null;
1386                for (int i = 0; i < size; i++) {
1387                    grp = (JahiaGroup) grps.get (i);
1388                    buff.append ("'");
1389                    buff.append (grp.getGroupKey ());
1390                    buff.append ("'");
1391                    if (i < (size - 1)) {
1392                        buff.append (",");
1393                    }
1394                }
1395                buff.append (")");
1396                sqlQuery = buff.toString ();
1397
1398            }
1399
1400            dbConn = org.jahia.services.database.ConnectionDispenser.
1401                    getConnection ();
1402            statement = dbConn.createStatement ();
1403            if (statement != null) {
1404                ResultSet JavaDoc rs = statement.executeQuery (sqlQuery);
1405                if (rs != null) {
1406                    dom = new JahiaDBDOMObject ();
1407                    dom.addTable ("jahia_grps", rs);
1408                    return dom;
1409                }
1410            }
1411        } catch (SQLException JavaDoc se) {
1412            String JavaDoc errorMsg = "Error in getAppRoleGroupsAsDOM(int siteID) : " +
1413                    se.getMessage ();
1414            logger.error (errorMsg, se);
1415            throw new JahiaException ("Cannot load groups from the database",
1416                    errorMsg, JahiaException.DATABASE_ERROR,
1417                    JahiaException.CRITICAL_SEVERITY, se);
1418        } finally {
1419
1420            closeStatement (statement);
1421        }
1422
1423        return dom;
1424    }
1425
1426    //--------------------------------------------------------------------------
1427
/**
1428     * return a DOM document of all user group access for a site
1429     *
1430     * @param int the site id
1431     *
1432     * @return JahiaDOMObject a DOM representation of this object
1433     *
1434     * @author NK
1435     */

1436    public JahiaDOMObject getUserGroupAccessAsDOM (int siteID)
1437            throws JahiaException {
1438
1439        Connection JavaDoc dbConn = null;
1440        Statement JavaDoc statement = null;
1441
1442        String JavaDoc output = null;
1443        JahiaDBDOMObject dom = null;
1444
1445        try {
1446
1447            String JavaDoc sqlQuery =
1448                    "SELECT DISTINCT jahia_grp_access.id_jahia_member,"
1449                    +
1450                    "jahia_grp_access.id_jahia_grps,jahia_grp_access.membertype_grp_access"
1451                    + " FROM jahia_grp_access,jahia_users,jahia_grps "
1452                    + "WHERE (jahia_grp_access.membertype_grp_access=1 "
1453                    + "AND jahia_grp_access.id_jahia_member="
1454                    +
1455                    "jahia_users.key_jahia_users AND jahia_users.siteid_jahia_users=" +
1456                    siteID + ") "
1457                    + "OR (jahia_grp_access.membertype_grp_access=2 AND jahia_grp_access.id_jahia_member="
1458                    + "jahia_grps.key_jahia_grps AND jahia_grps.siteid_jahia_grps=" +
1459                    siteID + ")";
1460
1461            dbConn = org.jahia.services.database.ConnectionDispenser.
1462                    getConnection ();
1463            statement = dbConn.createStatement ();
1464            if (statement != null) {
1465                ResultSet JavaDoc rs = statement.executeQuery (sqlQuery);
1466                if (rs != null) {
1467                    dom = new JahiaDBDOMObject ();
1468                    dom.addTable ("jahia_grp_access", rs);
1469                    return dom;
1470                }
1471            }
1472        } catch (SQLException JavaDoc se) {
1473            String JavaDoc errorMsg = "Error in getUserGroupAccessAsDOM(int siteID) : " +
1474                    se.getMessage ();
1475            logger.error (errorMsg, se);
1476            throw new JahiaException ("Cannot load groups from the database",
1477                    errorMsg, JahiaException.DATABASE_ERROR,
1478                    JahiaException.CRITICAL_SEVERITY, se);
1479        } finally {
1480
1481            closeStatement (statement);
1482        }
1483
1484        return dom;
1485    }
1486
1487    //--------------------------------------------------------------------------
1488
/**
1489     * return a DOM document of all application group access for a site
1490     * Here users and groups have access to application role groups ( not normal groups )
1491     *
1492     * @param int the site id
1493     *
1494     * @return JahiaDOMObject a DOM representation of this object
1495     *
1496     * @author NK
1497     */

1498    public JahiaDOMObject getAppGroupAccessAsDOM (int siteID)
1499            throws JahiaException {
1500
1501        Connection JavaDoc dbConn = null;
1502        Statement JavaDoc statement = null;
1503
1504        String JavaDoc output = null;
1505        JahiaDBDOMObject dom = null;
1506
1507        Vector grps = GroupsTools.getGroups (siteID, true);
1508
1509        try {
1510
1511            String JavaDoc sqlQuery = "";
1512            int size = grps.size ();
1513
1514            if (size == 0) {
1515                dom = new JahiaDBDOMObject ();
1516                dom.addTable ("jahia_grp_access", null);
1517                return dom;
1518            } else {
1519                StringBuffer JavaDoc buff = new StringBuffer JavaDoc (
1520                        "SELECT DISTINCT id_jahia_member,id_jahia_grps,membertype_grp_access FROM jahia_grp_access where id_jahia_grps IN(");
1521                JahiaGroup grp = null;
1522                for (int i = 0; i < size; i++) {
1523                    grp = (JahiaGroup) grps.get (i);
1524                    buff.append ("'");
1525                    buff.append (grp.getGroupKey ());
1526                    buff.append ("'");
1527                    if (i < (size - 1)) {
1528                        buff.append (",");
1529                    }
1530                }
1531                buff.append (")");
1532                sqlQuery = buff.toString ();
1533            }
1534
1535            dbConn = org.jahia.services.database.ConnectionDispenser.
1536                    getConnection ();
1537            statement = dbConn.createStatement ();
1538            if (statement != null) {
1539                ResultSet JavaDoc rs = statement.executeQuery (sqlQuery);
1540                if (rs != null) {
1541                    dom = new JahiaDBDOMObject ();
1542                    dom.addTable ("jahia_grp_access", rs);
1543                    return dom;
1544                }
1545            }
1546        } catch (SQLException JavaDoc se) {
1547            String JavaDoc errorMsg = "Error in getAppGroupAccessAsDOM(int siteID) : " +
1548                    se.getMessage ();
1549            logger.error (errorMsg, se);
1550            throw new JahiaException ("Cannot load groups from the database",
1551                    errorMsg, JahiaException.DATABASE_ERROR,
1552                    JahiaException.CRITICAL_SEVERITY, se);
1553        } finally {
1554
1555            closeStatement (statement);
1556        }
1557
1558        return dom;
1559    }
1560
1561    //-------------------------------------------------------------------------
1562
private boolean isNameValid (String JavaDoc name) {
1563
1564        if (name == null) {
1565            return false;
1566        }
1567
1568        if (name.length () == 0) {
1569            return false;
1570        }
1571
1572        String JavaDoc authorizedCharacters =
1573                "-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789";
1574        /* EP : 2004-17-06
1575        char[] chars = authorizedCharacters.toCharArray ();
1576        char[] nameBuffer = name.toCharArray ();*/

1577
1578        boolean badCharFound = false;
1579        for (int i = 0; i < name.length() && !badCharFound; i++) {
1580            badCharFound = authorizedCharacters.indexOf((int)name.charAt(i)) < 0;
1581            if (badCharFound) {
1582                logger.debug ("Bad character found in DB group name [" +
1583                        name +
1584                        "] at position " + i);
1585            }
1586        }
1587    /* end EP mods */
1588
1589        return (!badCharFound);
1590    }
1591
1592    //-------------------------------------------------------------------------
1593
private void closeStatement (Statement JavaDoc statement) {
1594        // Close the opened statement
1595
try {
1596            if (statement != null) {
1597                statement.close ();
1598            }
1599        } catch (SQLException JavaDoc sqlEx) {
1600            // FIXME -Fulco- : Don't know yet what to do with this exception.
1601
// It should be logged somewhere !
1602
}
1603    }
1604
1605    /**
1606     * Transforms a search with "*" characters into a valid LIKE statement
1607     * with "%" characters. Also escapes the string to remove all "'" and
1608     * other chars that might disturb the request construct.
1609     *
1610     * @param input the original String
1611     *
1612     * @return String a resulting string that has
1613     */

1614    private String JavaDoc makeLIKEString (String JavaDoc input) {
1615        String JavaDoc result = JahiaTools.replacePattern (input, "*", "%");
1616        result = JahiaTools.replacePattern (result, "'", "\\'");
1617        result = JahiaTools.replacePattern (result, "\"", "\\\"");
1618        result = JahiaTools.replacePattern (result, "_", "\\_");
1619        return result;
1620    }
1621
1622}
1623
Popular Tags