KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > alfresco > web > bean > users > UserMembersBean


1 /*
2  * Copyright (C) 2005 Alfresco, Inc.
3  *
4  * Licensed under the Mozilla Public License version 1.1
5  * with a permitted attribution clause. You may obtain a
6  * copy of the License at
7  *
8  * http://www.alfresco.org/legal/license.txt
9  *
10  * Unless required by applicable law or agreed to in writing,
11  * software distributed under the License is distributed on an
12  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13  * either express or implied. See the License for the specific
14  * language governing permissions and limitations under the
15  * License.
16  */

17 package org.alfresco.web.bean.users;
18
19 import java.text.MessageFormat JavaDoc;
20 import java.util.ArrayList JavaDoc;
21 import java.util.Collections JavaDoc;
22 import java.util.HashMap JavaDoc;
23 import java.util.List JavaDoc;
24 import java.util.Map JavaDoc;
25 import java.util.Set JavaDoc;
26
27 import javax.faces.application.FacesMessage;
28 import javax.faces.component.UISelectOne;
29 import javax.faces.context.FacesContext;
30 import javax.faces.event.ActionEvent;
31 import javax.faces.event.ValueChangeEvent;
32 import javax.faces.model.DataModel;
33 import javax.faces.model.ListDataModel;
34 import javax.transaction.UserTransaction JavaDoc;
35
36 import org.alfresco.model.ContentModel;
37 import org.alfresco.service.cmr.repository.InvalidNodeRefException;
38 import org.alfresco.service.cmr.repository.NodeRef;
39 import org.alfresco.service.cmr.repository.NodeService;
40 import org.alfresco.service.cmr.search.SearchService;
41 import org.alfresco.service.cmr.security.AccessPermission;
42 import org.alfresco.service.cmr.security.AccessStatus;
43 import org.alfresco.service.cmr.security.AuthorityType;
44 import org.alfresco.service.cmr.security.OwnableService;
45 import org.alfresco.service.cmr.security.PermissionService;
46 import org.alfresco.service.cmr.security.PersonService;
47 import org.alfresco.web.app.Application;
48 import org.alfresco.web.app.context.IContextListener;
49 import org.alfresco.web.app.context.UIContextService;
50 import org.alfresco.web.bean.BrowseBean;
51 import org.alfresco.web.bean.repository.MapNode;
52 import org.alfresco.web.bean.repository.Node;
53 import org.alfresco.web.bean.repository.Repository;
54 import org.alfresco.web.ui.common.Utils;
55 import org.alfresco.web.ui.common.component.UIActionLink;
56 import org.alfresco.web.ui.common.component.data.UIRichList;
57 import org.alfresco.web.ui.repo.WebResources;
58
59 /**
60  * @author Kevin Roast
61  */

62 public abstract class UserMembersBean implements IContextListener
63 {
64    private static final String JavaDoc MSG_SUCCESS_INHERIT_NOT = "success_not_inherit_permissions";
65    private static final String JavaDoc MSG_SUCCESS_INHERIT = "success_inherit_permissions";
66    
67    private static final String JavaDoc ERROR_DELETE = "error_remove_user";
68
69    private static final String JavaDoc OUTCOME_FINISH = "finish";
70
71    /** NodeService bean reference */
72    protected NodeService nodeService;
73
74    /** SearchService bean reference */
75    protected SearchService searchService;
76    
77    /** PermissionService bean reference */
78    protected PermissionService permissionService;
79    
80    /** PersonService bean reference */
81    protected PersonService personService;
82    
83    /** BrowseBean bean refernce */
84    protected BrowseBean browseBean;
85    
86    /** OwnableService bean reference */
87    protected OwnableService ownableService;
88    
89    /** Component reference for Users RichList control */
90    private UIRichList usersRichList;
91    
92    /** action context */
93    private String JavaDoc personAuthority = null;
94    
95    /** action context */
96    private String JavaDoc personName = null;
97    
98    /** datamodel for table of roles for current person */
99    private DataModel personRolesDataModel = null;
100    
101    /** roles for current person */
102    private List JavaDoc<PermissionWrapper> personRoles = null;
103    
104    
105    /**
106     * Default constructor
107     */

108    public UserMembersBean()
109    {
110       UIContextService.getInstance(FacesContext.getCurrentInstance()).registerBean(this);
111    }
112    
113    
114    // ------------------------------------------------------------------------------
115
// Abstract methods
116

117    /**
118     * Returns the node that is being acted upon
119     *
120     * @return The node to manage permissions for
121     */

122    public abstract Node getNode();
123    
124    
125    // ------------------------------------------------------------------------------
126
// Bean property getters and setters
127

128    /**
129     * @param nodeService The NodeService to set.
130     */

131    public void setNodeService(NodeService nodeService)
132    {
133       this.nodeService = nodeService;
134    }
135
136    /**
137     * @param searchService The search service
138     */

139    public void setSearchService(SearchService searchService)
140    {
141       this.searchService = searchService;
142    }
143    
144    /**
145     * @param permissionService The PermissionService to set.
146     */

147    public void setPermissionService(PermissionService permissionService)
148    {
149       this.permissionService = permissionService;
150    }
151    
152    /**
153     * @param ownableService The ownableService to set.
154     */

155    public void setOwnableService(OwnableService ownableService)
156    {
157       this.ownableService = ownableService;
158    }
159    
160    /**
161     * @param personService The personService to set.
162     */

163    public void setPersonService(PersonService personService)
164    {
165       this.personService = personService;
166    }
167    
168    /**
169     * @param browseBean The BrowseBean to set.
170     */

171    public void setBrowseBean(BrowseBean browseBean)
172    {
173       this.browseBean = browseBean;
174    }
175    
176    /**
177     * @return Returns the usersRichList.
178     */

179    public UIRichList getUsersRichList()
180    {
181       return this.usersRichList;
182    }
183
184    /**
185     * @param usersRichList The usersRichList to set.
186     */

187    public void setUsersRichList(UIRichList usersRichList)
188    {
189       this.usersRichList = usersRichList;
190    }
191    
192    /**
193     * Returns the properties for current Person roles JSF DataModel
194     *
195     * @return JSF DataModel representing the current Person roles
196     */

197    public DataModel getPersonRolesDataModel()
198    {
199       if (this.personRolesDataModel == null)
200       {
201          this.personRolesDataModel = new ListDataModel();
202       }
203       
204       this.personRolesDataModel.setWrappedData(this.personRoles);
205       
206       return this.personRolesDataModel;
207    }
208    
209    /**
210     * @return Returns the current person authority.
211     */

212    public String JavaDoc getPersonAuthority()
213    {
214       return this.personAuthority;
215    }
216
217    /**
218     * @param person The person person authority to set.
219     */

220    public void setPersonAuthority(String JavaDoc person)
221    {
222       this.personAuthority = person;
223    }
224    
225    /**
226     * @return Returns the personName.
227     */

228    public String JavaDoc getPersonName()
229    {
230       return this.personName;
231    }
232
233    /**
234     * @param personName The personName to set.
235     */

236    public void setPersonName(String JavaDoc personName)
237    {
238       this.personName = personName;
239    }
240    
241    /**
242     * @return true if the current user can change permissions on this Space
243     */

244    public boolean getHasChangePermissions()
245    {
246       return getNode().hasPermission(PermissionService.CHANGE_PERMISSIONS);
247    }
248    
249    /**
250     * @return Returns the inherit parent permissions flag set for the current space.
251     */

252    public boolean isInheritPermissions()
253    {
254       return this.permissionService.getInheritParentPermissions(getNode().getNodeRef());
255    }
256
257    /**
258     * @param inheritPermissions The inheritPermissions to set.
259     */

260    public void setInheritPermissions(boolean inheritPermissions)
261    {
262       // stub - no impl as changes are made immediately using a ValueChanged listener
263
}
264    
265    /**
266     * Return the owner username
267     */

268    public String JavaDoc getOwner()
269    {
270       return this.ownableService.getOwner(getNode().getNodeRef());
271    }
272    
273    /**
274     * @return the list of user nodes for list data binding
275     */

276    public List JavaDoc<Map JavaDoc> getUsers()
277    {
278       FacesContext context = FacesContext.getCurrentInstance();
279       
280       List JavaDoc<Map JavaDoc> personNodes = null;
281       
282       UserTransaction JavaDoc tx = null;
283       try
284       {
285          tx = Repository.getUserTransaction(context, true);
286          tx.begin();
287          
288          // Return all the permissions set against the current node
289
// for any authentication instance (user).
290
// Then combine them into a single list for each authentication found.
291
Map JavaDoc<String JavaDoc, List JavaDoc<String JavaDoc>> permissionMap = new HashMap JavaDoc<String JavaDoc, List JavaDoc<String JavaDoc>>(13, 1.0f);
292          Set JavaDoc<AccessPermission> permissions = permissionService.getAllSetPermissions(getNode().getNodeRef());
293          if (permissions != null)
294          {
295             for (AccessPermission permission : permissions)
296             {
297                // we are only interested in Allow and not groups/owner etc.
298
if (permission.getAccessStatus() == AccessStatus.ALLOWED &&
299                    (permission.getAuthorityType() == AuthorityType.USER ||
300                     permission.getAuthorityType() == AuthorityType.GROUP ||
301                     permission.getAuthorityType() == AuthorityType.GUEST ||
302                     permission.getAuthorityType() == AuthorityType.EVERYONE))
303                {
304                   String JavaDoc authority = permission.getAuthority();
305                   
306                   List JavaDoc<String JavaDoc> userPermissions = permissionMap.get(authority);
307                   if (userPermissions == null)
308                   {
309                      // create for first time
310
userPermissions = new ArrayList JavaDoc<String JavaDoc>(4);
311                      permissionMap.put(authority, userPermissions);
312                   }
313                   // add the permission name for this authority
314
userPermissions.add(permission.getPermission());
315                }
316             }
317          }
318          
319          // for each authentication (username key) found we get the Person
320
// node represented by it and use that for our list databinding object
321
personNodes = new ArrayList JavaDoc<Map JavaDoc>(permissionMap.size());
322          for (String JavaDoc authority : permissionMap.keySet())
323          {
324             // check if we are dealing with a person (User Authority)
325
if (AuthorityType.getAuthorityType(authority) == AuthorityType.GUEST ||
326                 personService.personExists(authority))
327             {
328                NodeRef nodeRef = personService.getPerson(authority);
329                if (nodeRef != null)
330                {
331                   // create our Node representation
332
MapNode node = new MapNode(nodeRef);
333                   
334                   // set data binding properties
335
// this will also force initialisation of the props now during the UserTransaction
336
// it is much better for performance to do this now rather than during page bind
337
Map JavaDoc<String JavaDoc, Object JavaDoc> props = node.getProperties();
338                   props.put("fullName", ((String JavaDoc)props.get("firstName")) + ' ' + ((String JavaDoc)props.get("lastName")));
339                   props.put("roles", listToString(context, permissionMap.get(authority)));
340                   props.put("icon", WebResources.IMAGE_PERSON);
341                   
342                   personNodes.add(node);
343                }
344             }
345             else
346             {
347                // need a map (dummy node) to represent props for this Group Authority
348
Map JavaDoc<String JavaDoc, Object JavaDoc> node = new HashMap JavaDoc<String JavaDoc, Object JavaDoc>(5, 1.0f);
349                if (authority.startsWith(PermissionService.GROUP_PREFIX) == true)
350                {
351                   node.put("fullName", authority.substring(PermissionService.GROUP_PREFIX.length()));
352                }
353                else
354                {
355                   node.put("fullName", authority);
356                }
357                node.put("userName", authority);
358                node.put("id", authority);
359                node.put("roles", listToString(context, permissionMap.get(authority)));
360                node.put("icon", WebResources.IMAGE_GROUP);
361                personNodes.add(node);
362             }
363          }
364          
365          // commit the transaction
366
tx.commit();
367       }
368       catch (InvalidNodeRefException refErr)
369       {
370          Utils.addErrorMessage(MessageFormat.format(Application.getMessage(
371                context, Repository.ERROR_NODEREF), new Object JavaDoc[] {"root"}) );
372          personNodes = Collections.<Map JavaDoc>emptyList();
373          try { if (tx != null) {tx.rollback();} } catch (Exception JavaDoc tex) {}
374       }
375       catch (Throwable JavaDoc err)
376       {
377          Utils.addErrorMessage(MessageFormat.format(Application.getMessage(
378                context, Repository.ERROR_GENERIC), err.getMessage()), err );
379          personNodes = Collections.<Map JavaDoc>emptyList();
380          try { if (tx != null) {tx.rollback();} } catch (Exception JavaDoc tex) {}
381       }
382       
383       return personNodes;
384    }
385    
386    private static String JavaDoc listToString(FacesContext context, List JavaDoc<String JavaDoc> list)
387    {
388       StringBuilder JavaDoc buf = new StringBuilder JavaDoc();
389       
390       if (list != null)
391       {
392          for (int i=0; i<list.size(); i++)
393          {
394             if (buf.length() != 0)
395             {
396                buf.append(", ");
397             }
398             buf.append(Application.getMessage(context, list.get(i)));
399          }
400       }
401       
402       return buf.toString();
403    }
404    
405    
406    // ------------------------------------------------------------------------------
407
// IContextListener implementation
408

409    /**
410     * @see org.alfresco.web.app.context.IContextListener#contextUpdated()
411     */

412    public void contextUpdated()
413    {
414       if (this.usersRichList != null)
415       {
416          this.usersRichList.setValue(null);
417       }
418    }
419    
420    
421    // ------------------------------------------------------------------------------
422
// Action event handlers
423

424    /**
425     * Action called to Close the dialog
426     */

427    public void close(ActionEvent event)
428    {
429       UIContextService.getInstance(FacesContext.getCurrentInstance()).notifyBeans();
430    }
431    
432    /**
433     * Action event called by all actions that need to setup a Person context on
434     * the UserMembers bean before an action page is called. The context will be a
435     * Authority in setPersonAuthority() which can be retrieved on the action page from
436     * UserMembersBean.setPersonAuthority().
437     */

438    public void setupUserAction(ActionEvent event)
439    {
440       FacesContext context = FacesContext.getCurrentInstance();
441       
442       UIActionLink link = (UIActionLink) event.getComponent();
443       Map JavaDoc<String JavaDoc, String JavaDoc> params = link.getParameterMap();
444       String JavaDoc authority = params.get("userName");
445       if (authority != null && authority.length() != 0)
446       {
447          try
448          {
449             if (this.personService.personExists(authority))
450             {
451                // create the node ref, then our node representation
452
NodeRef ref = personService.getPerson(authority);
453                Node node = new Node(ref);
454                
455                // setup convience function for current user full name
456
setPersonName((String JavaDoc)node.getProperties().get(ContentModel.PROP_FIRSTNAME) + ' ' +
457                              (String JavaDoc)node.getProperties().get(ContentModel.PROP_LASTNAME));
458             }
459             else
460             {
461                setPersonName(authority);
462             }
463             
464             // setup roles for this Authority
465
List JavaDoc<PermissionWrapper> userPermissions = new ArrayList JavaDoc<PermissionWrapper>(4);
466             Set JavaDoc<AccessPermission> permissions = permissionService.getAllSetPermissions(getNode().getNodeRef());
467             if (permissions != null)
468             {
469                for (AccessPermission permission : permissions)
470                {
471                   // we are only interested in Allow permissions
472
if (permission.getAccessStatus() == AccessStatus.ALLOWED)
473                   {
474                      if (authority.equals(permission.getAuthority()))
475                      {
476                         // found a permission for this user authentiaction
477
PermissionWrapper wrapper = new PermissionWrapper(
478                               permission.getPermission(),
479                               Application.getMessage(context, permission.getPermission()));
480                         userPermissions.add(wrapper);
481                      }
482                   }
483                }
484             }
485             // action context setup
486
this.personRoles = userPermissions;
487             setPersonAuthority(authority);
488          }
489          catch (Exception JavaDoc err)
490          {
491             Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext
492                   .getCurrentInstance(), Repository.ERROR_GENERIC), new Object JavaDoc[] { err.getMessage() }));
493          }
494       }
495       else
496       {
497          setPersonAuthority(null);
498       }
499       
500       // force refresh on return to this page
501
contextUpdated();
502    }
503       
504    /**
505     * Inherit parent Space permissions value changed by the user
506     */

507    public void inheritPermissionsValueChanged(ValueChangeEvent event)
508    {
509       try
510       {
511          // change the value to the new selected value
512
boolean inheritPermissions = (Boolean JavaDoc)event.getNewValue();
513          this.permissionService.setInheritParentPermissions(getNode().getNodeRef(), inheritPermissions);
514          
515          // inform the user that the change occured
516
FacesContext context = FacesContext.getCurrentInstance();
517          String JavaDoc msg;
518          if (inheritPermissions)
519          {
520             msg = Application.getMessage(context, MSG_SUCCESS_INHERIT);
521          }
522          else
523          {
524             msg = Application.getMessage(context, MSG_SUCCESS_INHERIT_NOT);
525          }
526          FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg);
527          context.addMessage(event.getComponent().getClientId(context), facesMsg);
528       }
529       catch (Throwable JavaDoc e)
530       {
531          Utils.addErrorMessage(MessageFormat.format(Application.getMessage(
532                FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), e.getMessage()), e);
533       }
534    }
535    
536    /**
537     * Action handler called when the Add Role button is pressed to process the current selection
538     */

539    public void addRole(ActionEvent event)
540    {
541       UISelectOne rolePicker = (UISelectOne)event.getComponent().findComponent("roles");
542       
543       String JavaDoc role = (String JavaDoc)rolePicker.getValue();
544       if (role != null)
545       {
546          FacesContext context = FacesContext.getCurrentInstance();
547          PermissionWrapper wrapper = new PermissionWrapper(role, Application.getMessage(context, role));
548          this.personRoles.add(wrapper);
549       }
550       
551       // force refresh on return to this page
552
contextUpdated();
553    }
554    
555    /**
556     * Action handler called when the Remove button is pressed to remove a role from current user
557     */

558    public void removeRole(ActionEvent event)
559    {
560       PermissionWrapper wrapper = (PermissionWrapper)this.personRolesDataModel.getRowData();
561       if (wrapper != null)
562       {
563          this.personRoles.remove(wrapper);
564       }
565       
566       // force refresh on return to this page
567
contextUpdated();
568    }
569    
570    /**
571     * Action handler called when the Finish button is clicked on the Edit User Roles page
572     */

573    public String JavaDoc finishOK()
574    {
575       String JavaDoc outcome = OUTCOME_FINISH;
576       
577       FacesContext context = FacesContext.getCurrentInstance();
578       
579       // persist new user permissions
580
if (this.personRoles != null && getPersonAuthority() != null)
581       {
582          UserTransaction JavaDoc tx = null;
583          try
584          {
585             tx = Repository.getUserTransaction(context);
586             tx.begin();
587             
588             // clear the currently set permissions for this user
589
// and add each of the new permissions in turn
590
NodeRef nodeRef = getNode().getNodeRef();
591             this.permissionService.clearPermission(nodeRef, getPersonAuthority());
592             for (PermissionWrapper wrapper : personRoles)
593             {
594                this.permissionService.setPermission(
595                      nodeRef,
596                      getPersonAuthority(),
597                      wrapper.getPermission(),
598                      true);
599             }
600             
601             tx.commit();
602          }
603          catch (Exception JavaDoc err)
604          {
605             Utils.addErrorMessage(MessageFormat.format(Application.getMessage(
606                   context, Repository.ERROR_GENERIC), err.getMessage()), err );
607             try { if (tx != null) {tx.rollback();} } catch (Exception JavaDoc tex) {}
608             
609             outcome = null;
610          }
611       }
612       
613       return outcome;
614    }
615    
616    /**
617     * Action handler called when the OK button is clicked on the Remove User page
618     */

619    public String JavaDoc removeOK()
620    {
621       UserTransaction JavaDoc tx = null;
622
623       try
624       {
625          FacesContext context = FacesContext.getCurrentInstance();
626          tx = Repository.getUserTransaction(context);
627          tx.begin();
628          
629          // remove the invited User
630
if (getPersonAuthority() != null)
631          {
632             // clear permissions for the specified Authority
633
this.permissionService.clearPermission(getNode().getNodeRef(), getPersonAuthority());
634          }
635          
636          // commit the transaction
637
tx.commit();
638       }
639       catch (Exception JavaDoc e)
640       {
641          // rollback the transaction
642
try { if (tx != null) {tx.rollback();} } catch (Exception JavaDoc tex) {}
643          Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext
644                .getCurrentInstance(), ERROR_DELETE), e.getMessage()), e);
645       }
646       
647       return OUTCOME_FINISH;
648    }
649    
650    
651    // ------------------------------------------------------------------------------
652
// Inner classes
653

654    /**
655     * Wrapper class for list data model to display current roles for user
656     */

657    public static class PermissionWrapper
658    {
659       public PermissionWrapper(String JavaDoc permission, String JavaDoc label)
660       {
661          this.permission = permission;
662          this.label = label;
663       }
664       
665       public String JavaDoc getRole()
666       {
667          return this.label;
668       }
669       
670       public String JavaDoc getPermission()
671       {
672          return this.permission;
673       }
674       
675       private String JavaDoc label;
676       private String JavaDoc permission;
677    }
678 }
679
Popular Tags