KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > data > viewhelper > principal > PrincipalViewHelper


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.data.viewhelper.principal;
15
16 import java.lang.reflect.Method JavaDoc;
17 import java.security.Principal JavaDoc;
18 import java.util.ArrayList JavaDoc;
19 import java.util.Enumeration JavaDoc;
20 import java.util.HashSet JavaDoc;
21 import java.util.Properties JavaDoc;
22 import java.util.Set JavaDoc;
23 import java.util.StringTokenizer JavaDoc;
24 import java.util.HashMap JavaDoc;
25 import java.util.Vector JavaDoc;
26 import javax.servlet.http.HttpServletRequest JavaDoc;
27
28 import org.jahia.registries.ServicesRegistry;
29 import org.jahia.services.acl.JahiaBaseACL;
30 import org.jahia.services.usermanager.JahiaGroup;
31 import org.jahia.services.usermanager.JahiaUser;
32 import org.jahia.services.usermanager.JahiaUserManagerService;
33 import org.jahia.services.usermanager.JahiaGroupManagerService;
34 import org.jahia.utils.JahiaString;
35 import org.jahia.utils.JahiaTools;
36 import java.io.Serializable JavaDoc;
37
38 /**
39  * <p>Title: Principal output formating view helper</p>
40  * <p>Description:
41  * The role of this class is to prepare and format user and group datas for
42  * display according to the JSP files needs in administration and engines.</p>
43  *
44  * The output can be formated to the following string sequence :<br>
45  * {"Principal", "Permissions", "Provider, 6", "Name, 10", "Properties, 20"]<br><br>
46  * The digit after identifiers are the number character for the output string.
47  * Where :
48  * <li>Principal, indicate if the pricipal is a user(u) or a group(g)<br>
49  * <li>Permissions, is the permissions sequence : Admin, write, rights accesses<br>
50  * <li>Pprovider, is the source where the user and the group are coming from<br>
51  * <li>Name, is the username or the groupname<br>
52  * <li>Properties, is the user firstname following by the user lastname or
53  * the user e-mail. Is the group member name for the group.<br><br>
54  *
55  * Example :<br>
56  * u jahia -wr gdupont G?rard Dupont<br>
57  *
58  * <p>Copyright: MAP (Jahia Solutions S?rl 2003)</p>
59  * <p>Company: Jahia Solutions S?rl</p>
60  * @author MAP
61  * @version 1.0
62  */

63 public class PrincipalViewHelper implements Serializable JavaDoc {
64
65     public static String JavaDoc PRINCIPAL = "Principal";
66     public static String JavaDoc PERMISSIONS = "Permissions";
67     public static String JavaDoc PROVIDER = "Provider";
68     public static String JavaDoc NAME = "Name";
69     public static String JavaDoc PROPERTIES = "Properties";
70
71     /**
72      * Create the view helper with a given string format given by the following
73      * syntax :
74      * textFormat ::= (principal)? (permissions)? (provider)? (name)? (properties)?
75      * principal ::= "Principal"
76      * permissions ::= "Permissions"
77      * provider ::= "Provider," size
78      * name ::= "Name," size
79      * properties ::= "Properties," size
80      * size ::= number{2..n}
81      *
82      * @param textFormat The string format given by the above syntax.
83      */

84     public PrincipalViewHelper(String JavaDoc[] textFormat) {
85         for (int i = 0; i < textFormat.length; i++) {
86             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(textFormat[i], ",");
87             String JavaDoc fieldToDisplay = (String JavaDoc)st.nextElement();
88             if (selectBoxFieldsHeading.contains(fieldToDisplay)) {
89                 if (st.hasMoreElements()) {
90                     selectBoxFieldsSize.add(Integer.valueOf(((String JavaDoc)st.nextElement()).trim()));
91                 } else {
92                     selectBoxFieldsSize.add(new Integer JavaDoc(-1));
93                 }
94                 try {
95                     selectBoxFieldsMethod.add(PrincipalViewHelper.class.getMethod(
96                         "get" + fieldToDisplay, new Class JavaDoc[] {Principal JavaDoc.class, Integer JavaDoc.class}));
97                 } catch (java.lang.NoSuchMethodException JavaDoc nsme) {
98                     logger.fatal("Internal class error ! Please check Jahia code", nsme);
99                 }
100             } else {
101                 // ignore token
102
}
103         }
104     }
105
106     /**
107      * Prepare the princiapl string output for display according to the "textFormat".
108      * N.B. Usually used in Jahia for the HTML "select" tag.
109      *
110      * @param p The principal (user or group) to format
111      * @return The principal formated
112      */

113     public String JavaDoc getPrincipalTextOption(Principal JavaDoc p) {
114         String JavaDoc authUserText = "";
115         for (int i = 0; i < selectBoxFieldsMethod.size(); i++) {
116             Method JavaDoc m = (Method JavaDoc)selectBoxFieldsMethod.get(i);
117             Integer JavaDoc size = (Integer JavaDoc)selectBoxFieldsSize.get(i);
118             Object JavaDoc[] args = { p, size };
119             try {
120                 authUserText += (String JavaDoc)m.invoke(this, args);
121             } catch (java.lang.reflect.InvocationTargetException JavaDoc ite) {
122                 logger.fatal("Internal class error !", ite);
123             } catch (java.lang.IllegalAccessException JavaDoc iae) {
124                 logger.fatal("Internal class error !", iae);
125             }
126             if (i + 1 < selectBoxFieldsHeading.size()) {
127                 authUserText += " ";
128             }
129         }
130         return JahiaTools.replacePattern(authUserText, " ", "&nbsp;");
131     }
132
133     /**
134      * Prepare the "value" string output.
135      * N.B. Usually used in Jahia for the HTML "select" tag.
136      *
137      * @param p The principal (user or group) to format
138      * @return The user/group key depending from principal type.
139      */

140     public String JavaDoc getPrincipalValueOption(Principal JavaDoc p) {
141         if (p instanceof JahiaUser) {
142             return "u" + ((JahiaUser)p).getUserKey();
143         } else {
144             return "g" + ((JahiaGroup)p).getGroupKey();
145         }
146     }
147
148     /**
149      * Construct a displayable principal name string
150      * @param p The user object
151      * @param size The principal string size that should be displayed.
152      * @return The displayable principal string.
153      */

154     public static String JavaDoc getName(Principal JavaDoc p, Integer JavaDoc size) {
155         if (p instanceof JahiaUser) {
156             return JahiaString.adjustStringSize(((JahiaUser)p).getUsername(), size.intValue());
157         } else {
158             return JahiaString.adjustStringSize(((JahiaGroup)p).getGroupname(), size.intValue());
159         }
160     }
161
162     /**
163      * Construct a displayable provider name string
164      * @param p The principal object
165      * @param size The provider string size that should be displayed.
166      * @return The displayable provider string.
167      */

168     public static String JavaDoc getProvider(Principal JavaDoc p, Integer JavaDoc size) {
169         if (p instanceof JahiaUser) {
170             return JahiaString.adjustStringSize(((JahiaUser)p).getProviderName(),
171                                                 size.intValue());
172         } else {
173             return JahiaString.adjustStringSize(((JahiaGroup)p).getProviderName(),
174                                                 size.intValue());
175         }
176     }
177
178     /**
179      * Get the kind of principal given by one char u = user, g = group
180      * @param p The principal object
181      * @param size For method call compatibility
182      * @return The principal type
183      */

184     public static String JavaDoc getPrincipal(Principal JavaDoc p, Integer JavaDoc size) {
185         if (p instanceof JahiaUser) {
186             return "u";
187         } else {
188             return "g";
189         }
190     }
191
192     /**
193      * Get a principal displayable properties. A user displays its
194      * first name and a last name or e-mail to display.
195      * A group should displays its users or groups.
196      *
197      * @param p The principal object
198      * @param size The size the properties should be displayed
199      * @return The displayable properties.
200      */

201     public static String JavaDoc getProperties(Principal JavaDoc p, Integer JavaDoc size) {
202         String JavaDoc properties = "";
203         if (p instanceof JahiaUser) {
204             JahiaUser user = (JahiaUser)p;
205             // Find a displayable user property
206
String JavaDoc firstname = user.getProperty("firstname");
207             String JavaDoc lastname = user.getProperty("lastname");
208             if (firstname != null) {
209                 properties += firstname;
210                 if (firstname.length() < size.intValue()) {
211                     properties += " ";
212                 }
213             }
214             if (lastname != null)
215                 properties += lastname;
216             if ("".equals(properties)) {
217                 String JavaDoc email = user.getProperty("email");
218                 if (email != null)
219                     properties += email;
220             }
221             return JahiaString.adjustStringSize(properties, size.intValue());
222         } else {
223             JahiaGroup group = (JahiaGroup)p;
224             // Find some group members for properties
225
Enumeration JavaDoc grpMembers = group.members();
226             String JavaDoc members = "(";
227             while (grpMembers.hasMoreElements()) {
228                 Object JavaDoc obj = (Object JavaDoc)grpMembers.nextElement();
229                 if (obj instanceof JahiaUser) {
230                     JahiaUser tmpUser = (JahiaUser)obj;
231                     members += tmpUser.getUsername();
232                 } else {
233                     JahiaGroup tmpGroup = (JahiaGroup)obj;
234                     members += tmpGroup.getGroupname();
235                 }
236                 if (members.length() > 20)
237                     break;
238                 if (grpMembers.hasMoreElements())
239                     members += ", ";
240             }
241             members += ")";
242             return JahiaString.adjustStringSize(members, 20);
243         }
244     }
245
246     /**
247      * Translate the ACL entry permissions setting to a string.
248      * @param p the user/group which have permissions
249      * @param aclID the corresponding DB acl id
250      * @return a string permissions.
251      */

252     public String JavaDoc getPermissions(Principal JavaDoc p, Integer JavaDoc size) {
253         Integer JavaDoc permissions = (Integer JavaDoc) perms.get(p);
254
255         String JavaDoc permStr = "";
256
257         boolean inherited = (permissions.intValue() >> 3 & 1) != 0;
258         if (inherited) {
259             permStr += (permissions.intValue() >> JahiaBaseACL.READ_RIGHTS & 1) != 0 ? "r" : "-";
260             permStr += (permissions.intValue() >> JahiaBaseACL.WRITE_RIGHTS & 1) != 0 ? "w" : "-";
261             permStr += (permissions.intValue() >> JahiaBaseACL.ADMIN_RIGHTS & 1) != 0 ? "A*" : "-*";
262         } else {
263             permStr += (permissions.intValue() >> JahiaBaseACL.READ_RIGHTS & 1) != 0 ? "r" : "-";
264             permStr += (permissions.intValue() >> JahiaBaseACL.WRITE_RIGHTS & 1) != 0 ? "w" : "-";
265             permStr += (permissions.intValue() >> JahiaBaseACL.ADMIN_RIGHTS & 1) != 0 ? "A&nbsp;" : "-&nbsp;";
266         }
267
268         return permStr;
269     }
270
271     private HashMap JavaDoc perms;
272     public void setPermissions(HashMap JavaDoc perms) {
273         this.perms = perms;
274     }
275
276
277     /**
278      * Get the user search result from the parameter form given by the request.
279      * If the form is not in the request then all the Jahia users will be search.
280      *
281      * @param request the request that should contain the HTML formular with the
282      * following fields :
283      * - searchString
284      * - searchIn
285      * - properties
286      * - storedOn
287      * - providers
288      * @param siteID The site ID containing the principal to search
289      * @return a Properties object that contain the search criterium
290      */

291     public static Set JavaDoc getSearchResult(HttpServletRequest JavaDoc request, int siteID) {
292
293         String JavaDoc searchString = request.getParameter("searchString");
294         String JavaDoc searchIn = request.getParameter("searchIn");
295         String JavaDoc[] searchInProps = request.getParameterValues("properties");
296         String JavaDoc storedOn = request.getParameter("storedOn");
297         String JavaDoc[] providers = request.getParameterValues("providers");
298
299         return getSearchResult(searchString, searchIn, searchInProps, storedOn, providers, siteID);
300     }
301
302     public static Set JavaDoc getSearchResult(String JavaDoc searchString,
303                                       String JavaDoc searchIn,
304                                       String JavaDoc[] searchInProps,
305                                       String JavaDoc storedOn,
306                                       String JavaDoc[] providers,
307                                       int siteID) {
308
309         JahiaUserManagerService jahiaUserManagerService =
310             ServicesRegistry.getInstance().getJahiaUserManagerService();
311         Properties JavaDoc searchParameters = new Properties JavaDoc();
312         Set JavaDoc searchResults = new HashSet JavaDoc();
313         if (searchIn == null) { // Necessary condition to say there is no formular.
314
logger.debug("No formular transmited. Finding all Jahia DB users.");
315             searchParameters.setProperty("*", "*");
316             searchResults.addAll(jahiaUserManagerService.
317                 searchUsers("jahia_db", siteID, searchParameters));
318         } else {
319             //if (searchString == null || "".equals(searchString)) {
320
if ("".equals(searchString)) {
321                 searchString = "*";
322             }
323             if ("allProps".equals(searchIn) || searchInProps == null) {
324                 searchParameters.setProperty("*", searchString);
325             } else {
326                 for (int i = 0; i < searchInProps.length; i++) {
327                     searchParameters.setProperty(searchInProps[i], searchString);
328                 }
329             }
330             if ("everywhere".equals(storedOn) || providers == null) {
331                 searchResults.addAll(jahiaUserManagerService.
332                     searchUsers(siteID, searchParameters));
333             } else {
334                 for (int i = 0; i < providers.length; i++) {
335                     String JavaDoc curServer = providers[i];
336                     Set JavaDoc curSearchResults = jahiaUserManagerService.
337                         searchUsers(curServer, siteID, searchParameters);
338                     if (curSearchResults != null) {
339                         searchResults.addAll(curSearchResults);
340                     }
341                 }
342             }
343         }
344         return searchResults;
345     }
346
347
348     /**
349      * Get the group search result from the parameter form given by the request.
350      * If the form is not in the request then all the Jahia groups will be search.
351      *
352      * @param request the request that should contain the HTML formular with the
353      * following fields :
354      * - searchString
355      * - searchIn
356      * - properties
357      * - storedOn
358      * - providers
359      * @param siteID The site ID containing the principal to search
360      * @return a Properties object that contain the search criterium
361      */

362     public static Set JavaDoc getGroupSearchResult(HttpServletRequest JavaDoc request, int siteID) {
363
364         String JavaDoc searchString = request.getParameter("searchString");
365         String JavaDoc searchIn = request.getParameter("searchIn");
366         String JavaDoc[] searchInProps = request.getParameterValues("properties");
367         String JavaDoc storedOn = request.getParameter("storedOn");
368         String JavaDoc[] providers = request.getParameterValues("providers");
369
370         return getGroupSearchResult(searchString, searchIn, searchInProps, storedOn, providers, siteID);
371
372     }
373
374     public static Set JavaDoc getGroupSearchResult(String JavaDoc searchString, String JavaDoc searchIn, String JavaDoc[] searchInProps, String JavaDoc storedOn, String JavaDoc[] providers, int siteID) {
375
376         JahiaGroupManagerService jahiaGroupManagerService =
377             ServicesRegistry.getInstance().getJahiaGroupManagerService();
378         Properties JavaDoc searchParameters = new Properties JavaDoc();
379         Set JavaDoc searchResults = new HashSet JavaDoc();
380         if (searchIn == null) { // Necessary condition to say there is no formular.
381
logger.debug("No formular transmited. Finding all Jahia DB users.");
382             searchParameters.setProperty("*", "*");
383             searchResults.addAll(jahiaGroupManagerService.
384                 searchGroups("jahia_db", siteID, searchParameters));
385         } else {
386             //if (searchString == null || "".equals(searchString)) {
387
if ("".equals(searchString)) {
388                 searchString = "*";
389             }
390             if ("allProps".equals(searchIn) || searchInProps == null) {
391                 searchParameters.setProperty("*", searchString);
392             } else {
393                 for (int i = 0; i < searchInProps.length; i++) {
394                     searchParameters.setProperty(searchInProps[i], searchString);
395                 }
396             }
397             if ("everywhere".equals(storedOn) || providers == null) {
398                 searchResults.addAll(jahiaGroupManagerService.
399                     searchGroups(siteID, searchParameters));
400             } else {
401                 for (int i = 0; i < providers.length; i++) {
402                     String JavaDoc curServer = providers[i];
403                     Set JavaDoc curSearchResults = jahiaGroupManagerService.
404                         searchGroups(curServer, siteID, searchParameters);
405                     if (curSearchResults != null) {
406                         searchResults.addAll(curSearchResults);
407                     }
408                 }
409             }
410         }
411         return searchResults;
412     }
413
414     /**
415      * Utility method to remove from a set of users all the members of the
416      * Jahia Administrators group. This is used when we don't want to display
417      * this set of users.
418      * @param users a set of users that we will remove the Jahia administrators
419      * from
420      * @return a set of users without the Jahia Administrators
421      */

422     public static Set JavaDoc removeJahiaAdministrators(Set JavaDoc users) {
423         Set JavaDoc usersWithoutJahiaAdmin = new HashSet JavaDoc(users);
424         JahiaGroup jahiaAdminGroup = ServicesRegistry.getInstance().getJahiaGroupManagerService().getAdministratorGroup(0);
425         Enumeration JavaDoc memberEnum = jahiaAdminGroup.members();
426         while (memberEnum.hasMoreElements()) {
427             Object JavaDoc curMemberObject = memberEnum.nextElement();
428             if (curMemberObject instanceof JahiaUser) {
429                 usersWithoutJahiaAdmin.remove((JahiaUser) curMemberObject);
430             }
431         }
432         return usersWithoutJahiaAdmin;
433     }
434
435     public static Set JavaDoc getUserGroupMembership(JahiaUser usr, int site) {
436         Set JavaDoc groups = new HashSet JavaDoc();
437         JahiaGroupManagerService jahiaGroupManagerService = ServicesRegistry.getInstance().getJahiaGroupManagerService();
438         Vector JavaDoc v = jahiaGroupManagerService.getUserMembership(usr);
439         Enumeration JavaDoc en = v.elements();
440         while (en.hasMoreElements()) {
441             String JavaDoc gname = (String JavaDoc) en.nextElement();
442             JahiaGroup g = jahiaGroupManagerService.lookupGroup(gname);
443             if (g != null && (g.getSiteID() == site || g.getSiteID() ==0)) {
444                 groups.add(g);
445             }
446         }
447         return groups;
448     }
449
450     private static HashSet JavaDoc selectBoxFieldsHeading = new HashSet JavaDoc();
451     private ArrayList JavaDoc selectBoxFieldsSize = new ArrayList JavaDoc();
452     private ArrayList JavaDoc selectBoxFieldsMethod = new ArrayList JavaDoc();
453
454     private static org.apache.log4j.Logger logger =
455         org.apache.log4j.Logger.getLogger(PrincipalViewHelper.class);
456
457     static {
458         selectBoxFieldsHeading.add(PRINCIPAL);
459         selectBoxFieldsHeading.add(PERMISSIONS);
460         selectBoxFieldsHeading.add(PROVIDER);
461         selectBoxFieldsHeading.add(NAME);
462         selectBoxFieldsHeading.add(PROPERTIES);
463     }
464
465 }
466
Popular Tags