KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > engines > users > SelectUG_Engine


1 package org.jahia.engines.users;
2
3 import java.util.ArrayList JavaDoc;
4 import java.util.Enumeration JavaDoc;
5 import java.util.HashMap JavaDoc;
6 import java.util.Iterator JavaDoc;
7 import java.util.Set JavaDoc;
8 import java.util.Vector JavaDoc;
9 import java.util.HashSet JavaDoc;
10 import java.util.List JavaDoc;
11
12 import javax.servlet.http.HttpSession JavaDoc;
13
14 import org.jahia.data.JahiaData;
15 import org.jahia.data.viewhelper.principal.PrincipalViewHelper;
16 import org.jahia.engines.EngineToolBox;
17 import org.jahia.engines.JahiaEngine;
18 import org.jahia.exceptions.JahiaException;
19 import org.jahia.exceptions.JahiaSessionExpirationException;
20 import org.jahia.params.ParamBean;
21 import org.jahia.registries.ServicesRegistry;
22 import org.jahia.services.usermanager.JahiaGroup;
23 import org.jahia.services.usermanager.JahiaGroupManagerService;
24 import org.jahia.services.usermanager.JahiaUser;
25 import org.jahia.services.usermanager.JahiaUserManagerService;
26 import org.jahia.utils.JahiaString;
27 import org.jahia.utils.JahiaTools;
28
29
30 /**
31  * <p>Title: An engine to do user selection.</p> <p>Description: This engine is sort of like a
32  * "File Open" window under Windows, where you can select multiple users. This should be generic
33  * enough to be used both in ACL management and in the administration component for example for
34  * group management.</p> <p>Copyright: Copyright (c) 2002</p> <p>Company: Jahia Ltd</p>
35  *
36  * @author Serge Huber
37  * @version 3.0
38  */

39
40 public class SelectUG_Engine implements JahiaEngine {
41     private static final String JavaDoc TEMPLATE_JSP = "selectUG";
42     private static final String JavaDoc CLOSE_JSP = "selectusers_close";
43     private static SelectUG_Engine theObject = null;
44     public static final String JavaDoc ENGINE_NAME = "selectUG";
45     private EngineToolBox toolBox;
46
47     /** logging */
48     private static final org.apache.log4j.Logger logger =
49             org.apache.log4j.Logger.getLogger (SelectUG_Engine.class);
50
51     /**
52      * Private constructor for singleton pattern
53      */

54     private SelectUG_Engine () {
55         logger.debug ("***** Starting " + SelectUG_Engine.class.getName () + " engine *****");
56         toolBox = EngineToolBox.getInstance ();
57     }
58
59
60     /**
61      * Returns the singleton instance
62      *
63      * @return SelectUG_Engine the singleton object instance.
64      */

65     public static synchronized SelectUG_Engine getInstance () {
66         if (theObject == null) {
67             theObject = new SelectUG_Engine ();
68         }
69         return theObject;
70     } // end getInstance
71

72
73     /**
74      * Check if we have the rights to view this engine
75      *
76      * @param jParams ParamBean object
77      *
78      * @return boolean if we are allowed to render this engine, false otherwise
79      */

80     public boolean authoriseRender (ParamBean jParams) {
81         return toolBox.authoriseRender (jParams);
82     } // end authoriseRender
83

84
85     /**
86      * Renders a link to this engine.
87      *
88      * @param jParams ParamBean object to be used to generate URL.
89      * @param theObj
90      *
91      * @return
92      *
93      * @throws JahiaException
94      */

95     public String JavaDoc renderLink (ParamBean jParams, Object JavaDoc theObj)
96             throws JahiaException {
97         String JavaDoc rightParams = (String JavaDoc) theObj;
98         String JavaDoc params = EMPTY_STRING;
99         params += "?mode=display&screen=searchGroups";
100         params += rightParams;
101         return jParams.composeEngineUrl (ENGINE_NAME, params);
102     } // end renderLink
103

104
105     /**
106      * needsJahiaData
107      */

108     public boolean needsJahiaData (ParamBean jParams) {
109         return false;
110     } // end needsJahiaData
111

112
113     /**
114      * handles the engine actions
115      *
116      * @param jParams a ParamBean object
117      * @param jData a JahiaData object (not mandatory)
118      */

119     public void handleActions (ParamBean jParams, JahiaData jData)
120             throws JahiaException,
121             JahiaSessionExpirationException {
122         // initalizes the hashmap
123
HashMap JavaDoc engineMap = initEngineMap (jParams);
124
125         processLastScreen (jParams, engineMap);
126         processCurrentScreen (jParams, engineMap);
127
128         // displays the screen
129
toolBox.displayScreen (jParams, engineMap);
130
131     } // end handleActions
132

133     /**
134      * Retrieve the engine name.
135      *
136      * @return the engine name.
137      */

138     public final String JavaDoc getName () {
139         return ENGINE_NAME;
140     }
141
142
143     /**
144      * processes the last screen sent by the user
145      *
146      * @param jParams a ParamBean object
147      */

148     public void processLastScreen (ParamBean jParams, HashMap JavaDoc engineMap)
149             throws JahiaException {
150         // gets engineMap values
151
String JavaDoc theScreen = (String JavaDoc) engineMap.get ("screen");
152         if (theScreen == null) {
153             throw new JahiaException ("SelectUG_Engine.processLastScreen",
154                     "Error in parameters",
155                     JahiaException.PARAMETER_ERROR,
156                     JahiaException.CRITICAL_SEVERITY);
157         }
158
159         // read search parameters.
160
String JavaDoc searchString = jParams.getRequest().getParameter("searchString");
161         jParams.getRequest().setAttribute("searchString", searchString);
162         String JavaDoc searchIn = jParams.getRequest().getParameter("searchIn");
163         String JavaDoc[] searchInProps = jParams.getRequest().getParameterValues("properties");
164         String JavaDoc storedOn = jParams.getRequest().getParameter("storedOn");
165         String JavaDoc[] providers = jParams.getRequest().getParameterValues("providers");
166
167         // let's do storage stuff here... Most notably insert into engine
168
// map the result of the user selection.
169
String JavaDoc[] selectedUsers = jParams.getRequest().getParameterValues("selectedUG");
170         Set JavaDoc userKeySet = new HashSet JavaDoc();
171         if (selectedUsers != null) {
172             for (int i=0; i < selectedUsers.length; i++) {
173                 userKeySet.add(selectedUsers[i]);
174             }
175         }
176         engineMap.put("alreadySelectedUsers", userKeySet);
177
178         Integer JavaDoc userNameWidth = (Integer JavaDoc) jParams.getRequest ().getSession ().getAttribute (
179                 "userNameWidth");
180         if ("searchUsers".equals (theScreen)) {
181
182             // first let's detect if we are coming from the group view, with a double-click
183
// on a user, in which case we must select the appropriate entry by performing
184
// a search for the selected user.
185
String JavaDoc selectedGroupMember = (String JavaDoc) jParams.getParameter("memberList");
186             if (selectedGroupMember != null) {
187                 userKeySet.clear();
188                 userKeySet.add(selectedGroupMember);
189                 String JavaDoc userName = extractPrincipalName(selectedGroupMember, userNameWidth);
190                 JahiaUser selectedUser = ServicesRegistry.getInstance().getJahiaUserManagerService().lookupUser(userName);
191                 searchString = selectedUser.getUsername();
192                 jParams.getRequest().setAttribute("searchString", searchString);
193             }
194
195             // now let's build the view of group membership for the selected users
196
String JavaDoc groupMembershipValue = (String JavaDoc) jParams.getParameter("viewGroupMembership");
197             if ((groupMembershipValue != null) || (selectedGroupMember != null)) {
198                 // we will display the group membership of the selected user
199
List JavaDoc groupList = new ArrayList JavaDoc();
200                 Iterator JavaDoc userKeySetIter = userKeySet.iterator();
201                 while (userKeySetIter.hasNext()) {
202                     String JavaDoc curUserKey = (String JavaDoc) userKeySetIter.next();
203                     String JavaDoc userName = extractPrincipalName(curUserKey, userNameWidth);
204                     JahiaUser selectedUser = ServicesRegistry.getInstance().getJahiaUserManagerService().lookupUser(userName);
205                     Set JavaDoc groupMembership = PrincipalViewHelper.getUserGroupMembership(selectedUser, jParams.getSiteID());
206                     Iterator JavaDoc groupMembershipIter = groupMembership.iterator();
207                     while (groupMembershipIter.hasNext()) {
208                         JahiaGroup group = (JahiaGroup) groupMembershipIter.next();
209                         buildGroupListEntry(group, userNameWidth, groupList);
210                     }
211                 }
212                 engineMap.put("groupList", groupList);
213             }
214
215             // now let's perform the search for the users
216
Set JavaDoc searchResults = PrincipalViewHelper.getSearchResult (searchString, searchIn, searchInProps, storedOn, providers,
217                     jParams.getSiteID ());
218             if (searchResults != null) {
219                 ArrayList JavaDoc resultList = new ArrayList JavaDoc ();
220                 Iterator JavaDoc resultListEnum = searchResults.iterator ();
221                 while (resultListEnum.hasNext ()) {
222                     JahiaUser user = (JahiaUser) resultListEnum.next ();
223                     buildUserListEntry(user, userNameWidth, resultList);
224                 }
225                 engineMap.put ("resultList", resultList);
226                 engineMap.put ("selectUGEngine", "selectUsers");
227             }
228             engineMap.put ("screen", "edit");
229         } else if (theScreen.equals ("searchGroups")) {
230
231             // first let's detect if we are coming from the user view, with a double-click
232
// on a group, in which case we must select the appropriate entry, by performing a
233
// search for the selected group
234
String JavaDoc selectedMembershipGroup = (String JavaDoc) jParams.getParameter("groupMembership");
235             if (selectedMembershipGroup != null) {
236                 userKeySet.clear();
237                 userKeySet.add(selectedMembershipGroup);
238                 String JavaDoc groupName = extractPrincipalName(selectedMembershipGroup, userNameWidth);
239                 JahiaGroup selectedGroup = ServicesRegistry.getInstance().getJahiaGroupManagerService().lookupGroup(groupName);
240                 searchString = selectedGroup.getGroupname();
241                 jParams.getRequest().setAttribute("searchString", searchString);
242             }
243
244             // now let's build the view of the members of the selected group.
245
String JavaDoc groupValueStr = (String JavaDoc) jParams.getParameter("viewMembers");
246             if ((groupValueStr != null) || (selectedMembershipGroup != null)) {
247                 // we will display the members of the selected group
248
List JavaDoc memberList = new ArrayList JavaDoc();
249                 Iterator JavaDoc userKeySetIter = userKeySet.iterator();
250                 while (userKeySetIter.hasNext()) {
251                     String JavaDoc curUserKey = (String JavaDoc) userKeySetIter.next();
252                     String JavaDoc groupName = extractPrincipalName(curUserKey, userNameWidth);
253                     JahiaGroup selectedGroup = ServicesRegistry.getInstance().getJahiaGroupManagerService().lookupGroup(groupName);
254                     Enumeration JavaDoc membersEnum = selectedGroup.members();
255                     while (membersEnum.hasMoreElements()) {
256                         Object JavaDoc curMember = membersEnum.nextElement();
257                         // @todo for the moment we don't process embedded groups !!!!
258
if (curMember instanceof JahiaUser) {
259                             JahiaUser user = (JahiaUser) curMember;
260                             buildUserListEntry(user, userNameWidth, memberList);
261                         }
262                     }
263                 }
264                 engineMap.put("memberList", memberList);
265             }
266
267             // now let's perform the search for the groups
268
Set JavaDoc searchResults = PrincipalViewHelper.getGroupSearchResult (searchString, searchIn, searchInProps, storedOn, providers,
269                     jParams.getSiteID ());
270             if (searchResults != null) {
271                 ArrayList JavaDoc resultList = new ArrayList JavaDoc ();
272                 Iterator JavaDoc resultListEnum = searchResults.iterator ();
273                 while (resultListEnum.hasNext ()) {
274                     JahiaGroup group = (JahiaGroup) resultListEnum.next ();
275                     buildGroupListEntry(group, userNameWidth, resultList);
276                 }
277                 engineMap.put ("resultList", resultList);
278                 engineMap.put ("selectUGEngine", "selectGroups");
279             }
280             engineMap.put ("screen", "edit");
281
282         } else if (theScreen.equals ("save")) {
283
284             // Another way to paste selection to the ACL entries is used
285

286         }
287     } // end processLastScreen
288

289     private String JavaDoc extractPrincipalName(String JavaDoc curPrincipalKey, Integer JavaDoc userNameWidth) {
290         return curPrincipalKey.substring("10000000r-- ".length() + userNameWidth.intValue() + 1);
291     }
292
293     private void buildUserListEntry(JahiaUser user, Integer JavaDoc userNameWidth, List JavaDoc memberList) {
294         String JavaDoc provider = JahiaString.adjustStringSize (user.getProviderName (), 6) +
295                 " ";
296         String JavaDoc usrname = JahiaString.adjustStringSize (user.getUsername (),
297                 userNameWidth.intValue ());
298         // Find a displayable user property
299
String JavaDoc properties = EMPTY_STRING;
300         String JavaDoc firstname = user.getProperty ("firstname");
301         String JavaDoc lastname = user.getProperty ("lastname");
302         if (firstname != null) {
303             properties += firstname;
304             if (firstname.length () < 20) properties += " ";
305         }
306         if (lastname != null) properties += lastname;
307         if (EMPTY_STRING.equals (properties)) {
308             String JavaDoc email = user.getProperty ("email");
309             if (email != null) properties += email;
310         }
311         properties = JahiaString.adjustStringSize (properties, 20);
312         String JavaDoc resultValue = "10000000r-- " + usrname + "u" + user.getName ();
313         String JavaDoc result = " " + provider + usrname + " " + properties;
314         memberList.add (JahiaTools.replacePattern (resultValue, " ", "&nbsp;"));
315         memberList.add (JahiaTools.replacePattern (result, " ", "&nbsp;"));
316     }
317
318     private void buildGroupListEntry(JahiaGroup group, Integer JavaDoc userNameWidth, List JavaDoc resultList) {
319         String JavaDoc provider = JahiaString.adjustStringSize (group.getProviderName (), 6) +
320                 " ";
321         // Construct a displayable groupname
322
String JavaDoc grpname = JahiaString.adjustStringSize (group.getGroupname (),
323                 userNameWidth.intValue ());
324         // Find some group members for properties
325
Enumeration JavaDoc grpMembers = group.members ();
326         String JavaDoc members = "(";
327         while (grpMembers.hasMoreElements ()) {
328             Object JavaDoc obj = grpMembers.nextElement ();
329             if (obj instanceof JahiaUser) {
330                 JahiaUser tmpUser = (JahiaUser) obj;
331                 members += tmpUser.getUsername ();
332             } else {
333                 JahiaGroup tmpGroup = (JahiaGroup) obj;
334                 members += tmpGroup.getGroupname ();
335             }
336             if (members.length () > 20) break;
337             if (grpMembers.hasMoreElements ()) members += ", ";
338         }
339         members += ")";
340         members = JahiaString.adjustStringSize (members, 20);
341         String JavaDoc resultValue = "10000000r-- " + grpname + "g" + group.getName ();
342         String JavaDoc result = " " + provider + grpname + " " + members;
343         resultList.add (JahiaTools.replacePattern (resultValue, " ", "&nbsp;"));
344         resultList.add (JahiaTools.replacePattern (result, " ", "&nbsp;"));
345     }
346
347
348     /**
349      * prepares the screen requested by the user
350      *
351      * @param jParams a ParamBean object
352      */

353     public void processCurrentScreen (ParamBean jParams, HashMap JavaDoc engineMap)
354             throws JahiaException {
355         //String theScreen = (String) engineMap.get( "screen" );
356

357         JahiaUserManagerService uMgr = ServicesRegistry.getInstance ()
358                 .getJahiaUserManagerService ();
359         JahiaGroupManagerService gMgr = ServicesRegistry.getInstance ()
360                 .getJahiaGroupManagerService ();
361         Vector JavaDoc providerList = uMgr.getProviderList ();
362         engineMap.put ("providerList", providerList);
363         Vector JavaDoc group_providerList = gMgr.getProviderList ();
364         engineMap.put ("groupProviderList", group_providerList);
365
366         jParams.getRequest ().setAttribute ("jahia_session_engineMap", engineMap);
367
368     } // end processCurrentScreen
369

370
371     /**
372      * inits the engine map
373      *
374      * @param jParams a ParamBean object (with request and response)
375      *
376      * @return a HashMap object containing all the basic values needed by an engine
377      */

378     private HashMap JavaDoc initEngineMap (ParamBean jParams)
379             throws JahiaException,
380             JahiaSessionExpirationException {
381         String JavaDoc theScreen = jParams.getRequest ().getParameter ("screen");
382
383         // gets session values
384
//HttpSession theSession = jParams.getRequest().getSession (true);
385
HttpSession JavaDoc theSession = jParams.getSession ();
386
387         HashMap JavaDoc engineMap = (HashMap JavaDoc) theSession.getAttribute ("jahia_session_engineMap");
388
389         if (engineMap == null) {
390             theScreen = "edit";
391             // init engine map
392
engineMap = new HashMap JavaDoc ();
393         }
394         engineMap.put (RENDER_TYPE_PARAM, new Integer JavaDoc (JahiaEngine.RENDERTYPE_FORWARD));
395         engineMap.put (ENGINE_NAME_PARAM, ENGINE_NAME);
396         engineMap.put (ENGINE_URL_PARAM, jParams.composeEngineUrl (ENGINE_NAME));
397         engineMap.put ("selectUGEngine", "selectGroups");
398         theSession.setAttribute ("jahia_session_engineMap", engineMap);
399
400         if (theScreen == null) {
401             theScreen = "edit";
402         }
403
404         // sets screen
405
engineMap.put ("screen", theScreen);
406         if (theScreen.equals ("cancel")) {
407             engineMap.put ("jspSource", CLOSE_JSP);
408         } else if (theScreen.equals ("save")) {
409             engineMap.put ("jspSource", CLOSE_JSP);
410         } else {
411             engineMap.put ("jspSource", TEMPLATE_JSP);
412         }
413
414         // sets engineMap for JSPs
415
jParams.getRequest ().setAttribute ("engineTitle", "Select Users");
416         jParams.getRequest ().setAttribute ("org.jahia.engines.EngineHashMap", engineMap);
417
418         return engineMap;
419     } // end initEngineMap
420

421
422 }
423
Popular Tags