KickJava   Java API By Example, From Geeks To Geeks.

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


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.List JavaDoc;
23 import java.util.Map JavaDoc;
24
25 import javax.faces.context.FacesContext;
26 import javax.faces.event.ActionEvent;
27 import javax.transaction.UserTransaction JavaDoc;
28
29 import org.alfresco.model.ContentModel;
30 import org.alfresco.repo.security.authentication.AuthenticationException;
31 import org.alfresco.service.cmr.repository.InvalidNodeRefException;
32 import org.alfresco.service.cmr.repository.NodeRef;
33 import org.alfresco.service.cmr.repository.NodeService;
34 import org.alfresco.service.cmr.search.SearchParameters;
35 import org.alfresco.service.cmr.search.SearchService;
36 import org.alfresco.service.cmr.security.AuthenticationService;
37 import org.alfresco.service.cmr.security.PersonService;
38 import org.alfresco.web.app.Application;
39 import org.alfresco.web.app.context.IContextListener;
40 import org.alfresco.web.app.context.UIContextService;
41 import org.alfresco.web.bean.LoginBean;
42 import org.alfresco.web.bean.repository.MapNode;
43 import org.alfresco.web.bean.repository.Node;
44 import org.alfresco.web.bean.repository.Repository;
45 import org.alfresco.web.ui.common.Utils;
46 import org.alfresco.web.ui.common.component.UIActionLink;
47 import org.alfresco.web.ui.common.component.data.UIRichList;
48 import org.apache.log4j.Logger;
49
50 /**
51  * @author Kevin Roast
52  */

53 public class UsersBean implements IContextListener
54 {
55    private static Logger logger = Logger.getLogger(UsersBean.class);
56
57    public static final String JavaDoc ERROR_PASSWORD_MATCH = "error_password_match";
58    private static final String JavaDoc ERROR_DELETE = "error_delete_user";
59    private static final String JavaDoc ERROR_USER_DELETE = "error_delete_user_object";
60    
61    private static final String JavaDoc DEFAULT_OUTCOME = "manageUsers";
62
63    /** NodeService bean reference */
64    protected NodeService nodeService;
65
66    /** SearchService bean reference */
67    protected SearchService searchService;
68    
69    /** AuthenticationService bean reference */
70    protected AuthenticationService authenticationService;
71
72    /** PersonService bean reference */
73    protected PersonService personService;
74    
75    /** Component reference for Users RichList control */
76    protected UIRichList usersRichList;
77
78    /** action context */
79    private Node person = null;
80    
81    private List JavaDoc<Node> users = Collections.<Node>emptyList();
82    
83    private String JavaDoc password = null;
84    private String JavaDoc confirm = null;
85    private String JavaDoc searchCriteria = null;
86    
87    
88    // ------------------------------------------------------------------------------
89
// Construction
90

91    /**
92     * Default Constructor
93     */

94    public UsersBean()
95    {
96       UIContextService.getInstance(FacesContext.getCurrentInstance()).registerBean(this);
97    }
98
99    
100    // ------------------------------------------------------------------------------
101
// Bean property getters and setters
102

103    /**
104     * @param nodeService The NodeService to set.
105     */

106    public void setNodeService(NodeService nodeService)
107    {
108       this.nodeService = nodeService;
109    }
110
111    /**
112     * @param searchService the search service
113     */

114    public void setSearchService(SearchService searchService)
115    {
116       this.searchService = searchService;
117    }
118
119    /**
120     * @param authenticationService The AuthenticationService to set.
121     */

122    public void setAuthenticationService(AuthenticationService authenticationService)
123    {
124       this.authenticationService = authenticationService;
125    }
126
127    /**
128     * @param personService The PersonService to set.
129     */

130    public void setPersonService(PersonService personService)
131    {
132       this.personService = personService;
133    }
134
135    /**
136     * @return Returns the usersRichList.
137     */

138    public UIRichList getUsersRichList()
139    {
140       return this.usersRichList;
141    }
142
143    /**
144     * @param usersRichList The usersRichList to set.
145     */

146    public void setUsersRichList(UIRichList usersRichList)
147    {
148       this.usersRichList = usersRichList;
149    }
150
151    /**
152     * @return the list of user Nodes to display
153     */

154    public List JavaDoc<Node> getUsers()
155    {
156       if (this.users == null)
157       {
158          search();
159       }
160       
161       return this.users;
162    }
163    
164    /**
165     * @return Returns the search criteria
166     */

167    public String JavaDoc getSearchCriteria()
168    {
169       return searchCriteria;
170    }
171
172    /**
173     * @param searchCriteria The search criteria to select
174     */

175    public void setSearchCriteria(String JavaDoc searchCriteria)
176    {
177       this.searchCriteria = searchCriteria;
178    }
179
180    /**
181     * @return Returns the confirm password.
182     */

183    public String JavaDoc getConfirm()
184    {
185       return this.confirm;
186    }
187
188    /**
189     * @param confirm The confirm password to set.
190     */

191    public void setConfirm(String JavaDoc confirm)
192    {
193       this.confirm = confirm;
194    }
195
196    /**
197     * @return Returns the password.
198     */

199    public String JavaDoc getPassword()
200    {
201       return this.password;
202    }
203
204    /**
205     * @param password The password to set.
206     */

207    public void setPassword(String JavaDoc password)
208    {
209       this.password = password;
210    }
211
212    /**
213     * @return Returns the person context.
214     */

215    public Node getPerson()
216    {
217       return this.person;
218    }
219
220    /**
221     * @param person The person context to set.
222     */

223    public void setPerson(Node person)
224    {
225       this.person = person;
226    }
227
228    /**
229     * Action event called by all actions that need to setup a Person context on
230     * the Users bean before an action page is called. The context will be a
231     * Person Node in setPerson() which can be retrieved on the action page from
232     * UsersBean.getPerson().
233     */

234    public void setupUserAction(ActionEvent event)
235    {
236       UIActionLink link = (UIActionLink) event.getComponent();
237       Map JavaDoc<String JavaDoc, String JavaDoc> params = link.getParameterMap();
238       String JavaDoc id = params.get("id");
239       if (id != null && id.length() != 0)
240       {
241          if (logger.isDebugEnabled())
242             logger.debug("Setup for action, setting current Person to: " + id);
243
244          try
245          {
246             // create the node ref, then our node representation
247
NodeRef ref = new NodeRef(Repository.getStoreRef(), id);
248             Node node = new Node(ref);
249
250             // remember the Person node
251
setPerson(node);
252
253             // clear the UI state in preparation for finishing the action
254
// and returning to the main page
255
contextUpdated();
256          }
257          catch (InvalidNodeRefException refErr)
258          {
259             Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext
260                   .getCurrentInstance(), Repository.ERROR_NODEREF), new Object JavaDoc[] { id }));
261          }
262       }
263       else
264       {
265          setPerson(null);
266       }
267    }
268
269    /**
270     * Action handler called when the OK button is clicked on the Delete User page
271     */

272    public String JavaDoc deleteOK()
273    {
274       UserTransaction JavaDoc tx = null;
275
276       try
277       {
278          FacesContext context = FacesContext.getCurrentInstance();
279          tx = Repository.getUserTransaction(context);
280          tx.begin();
281          
282          String JavaDoc userName = (String JavaDoc)getPerson().getProperties().get("userName");
283          
284          // we only delete the user auth if Alfresco is managing the authentication
285
Map JavaDoc session = context.getExternalContext().getSessionMap();
286          if (session.get(LoginBean.LOGIN_EXTERNAL_AUTH) == null)
287          {
288             // delete the User authentication
289
try
290             {
291                authenticationService.deleteAuthentication(userName);
292             }
293             catch (AuthenticationException authErr)
294             {
295                Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), ERROR_USER_DELETE));
296             }
297          }
298          
299          // delete the associated Person
300
this.personService.deletePerson(userName);
301          
302          // commit the transaction
303
tx.commit();
304          
305          // re-do the search to refresh the list
306
search();
307       }
308       catch (Throwable JavaDoc e)
309       {
310          // rollback the transaction
311
try { if (tx != null) {tx.rollback();} } catch (Exception JavaDoc tex) {}
312          Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext
313                .getCurrentInstance(), ERROR_DELETE), e.getMessage()), e);
314       }
315       
316       return DEFAULT_OUTCOME;
317    }
318    
319    /**
320     * Action handler called for OK button press on Change Password screen
321     */

322    public String JavaDoc changePasswordOK()
323    {
324       String JavaDoc outcome = DEFAULT_OUTCOME;
325       
326       if (this.password != null && this.confirm != null && this.password.equals(this.confirm))
327       {
328          try
329          {
330             String JavaDoc userName = (String JavaDoc)this.person.getProperties().get(ContentModel.PROP_USERNAME);
331             this.authenticationService.setAuthentication(userName, this.password.toCharArray());
332          }
333          catch (Exception JavaDoc e)
334          {
335             outcome = null;
336             Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext
337                   .getCurrentInstance(), Repository.ERROR_GENERIC), e.getMessage()), e);
338          }
339       }
340       else
341       {
342          outcome = null;
343          Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(),
344                ERROR_PASSWORD_MATCH));
345       }
346       
347       return outcome;
348    }
349
350    /**
351     * Event handler called when the user wishes to search for a user
352     *
353     * @return The outcome
354     */

355    public String JavaDoc search()
356    {
357       this.usersRichList.setValue(null);
358       
359       if (this.searchCriteria == null || this.searchCriteria.length() == 0)
360       {
361          this.users = Collections.<Node>emptyList();
362       }
363       else
364       {
365          FacesContext context = FacesContext.getCurrentInstance();
366          UserTransaction JavaDoc tx = null;
367          
368          try
369          {
370             tx = Repository.getUserTransaction(context, true);
371             tx.begin();
372             
373             // define the query to find people by their first or last name
374
String JavaDoc query = "( TYPE:\"{http://www.alfresco.org/model/content/1.0}person\") AND " +
375                            "((@\\{http\\://www.alfresco.org/model/content/1.0\\}firstName:" + this.searchCriteria +
376                            "*) OR (@\\{http\\://www.alfresco.org/model/content/1.0\\}lastName:" + this.searchCriteria +
377                            "*) OR (@\\{http\\://www.alfresco.org/model/content/1.0\\}userName:" + this.searchCriteria +
378                            "*)))";
379             
380             if (logger.isDebugEnabled())
381                logger.debug("Query: " + query);
382    
383             // define the search parameters
384
SearchParameters params = new SearchParameters();
385             params.setLanguage(SearchService.LANGUAGE_LUCENE);
386             params.addStore(Repository.getStoreRef());
387             params.setQuery(query);
388             
389             List JavaDoc<NodeRef> people = this.searchService.query(params).getNodeRefs();
390             
391             if (logger.isDebugEnabled())
392                logger.debug("Found " + people.size() + " users");
393             
394             this.users = new ArrayList JavaDoc<Node>(people.size());
395             
396             for (NodeRef nodeRef : people)
397             {
398                // create our Node representation
399
MapNode node = new MapNode(nodeRef);
400                
401                // set data binding properties
402
// this will also force initialisation of the props now during the UserTransaction
403
// it is much better for performance to do this now rather than during page bind
404
Map JavaDoc<String JavaDoc, Object JavaDoc> props = node.getProperties();
405                props.put("fullName", ((String JavaDoc)props.get("firstName")) + ' ' + ((String JavaDoc)props.get("lastName")));
406                NodeRef homeFolderNodeRef = (NodeRef)props.get("homeFolder");
407                if (homeFolderNodeRef != null)
408                {
409                   props.put("homeSpace", homeFolderNodeRef);
410                }
411                
412                this.users.add(node);
413             }
414    
415             // commit the transaction
416
tx.commit();
417          }
418          catch (InvalidNodeRefException refErr)
419          {
420             Utils.addErrorMessage(MessageFormat.format(Application.getMessage(
421                   context, Repository.ERROR_NODEREF), new Object JavaDoc[] {"root"}) );
422             this.users = Collections.<Node>emptyList();
423             try { if (tx != null) {tx.rollback();} } catch (Exception JavaDoc tex) {}
424          }
425          catch (Exception JavaDoc err)
426          {
427             Utils.addErrorMessage(MessageFormat.format(Application.getMessage(
428                   context, Repository.ERROR_GENERIC), err.getMessage()), err );
429             this.users = Collections.<Node>emptyList();
430             try { if (tx != null) {tx.rollback();} } catch (Exception JavaDoc tex) {}
431          }
432       }
433       
434       // return null to stay on the same page
435
return null;
436    }
437    
438    /**
439     * Action handler to show all the users currently in the system
440     *
441     * @return The outcome
442     */

443    public String JavaDoc showAll()
444    {
445       this.usersRichList.setValue(null);
446       
447       this.users = Repository.getUsers(FacesContext.getCurrentInstance(),
448             this.nodeService, this.searchService);
449       
450       // return null to stay on the same page
451
return null;
452    }
453    
454    
455    // ------------------------------------------------------------------------------
456
// IContextListener implementation
457

458    /**
459     * @see org.alfresco.web.app.context.IContextListener#contextUpdated()
460     */

461    public void contextUpdated()
462    {
463       if (this.usersRichList != null)
464       {
465          this.usersRichList.setValue(null);
466          this.users = null;
467       }
468    }
469 }
470
Popular Tags