KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > alfresco > web > bean > UserShortcutsBean


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;
18
19 import java.io.Serializable JavaDoc;
20 import java.text.MessageFormat JavaDoc;
21 import java.util.ArrayList 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.permissions.AccessDeniedException;
31 import org.alfresco.service.cmr.dictionary.DictionaryService;
32 import org.alfresco.service.cmr.repository.InvalidNodeRefException;
33 import org.alfresco.service.cmr.repository.NodeRef;
34 import org.alfresco.service.cmr.repository.NodeService;
35 import org.alfresco.service.cmr.security.AccessStatus;
36 import org.alfresco.service.cmr.security.PermissionService;
37 import org.alfresco.service.namespace.NamespaceService;
38 import org.alfresco.service.namespace.QName;
39 import org.alfresco.web.app.Application;
40 import org.alfresco.web.bean.repository.Node;
41 import org.alfresco.web.bean.repository.Repository;
42 import org.alfresco.web.ui.common.Utils;
43 import org.alfresco.web.ui.common.component.UIActionLink;
44 import org.alfresco.web.ui.repo.component.shelf.UIShortcutsShelfItem;
45 import org.apache.log4j.Logger;
46
47 /**
48  * This bean manages the user defined list of Recent Spaces in the Shelf component.
49  *
50  * @author Kevin Roast
51  */

52 public class UserShortcutsBean
53 {
54    private static Logger logger = Logger.getLogger(UserShortcutsBean.class);
55    
56    /** The NodeService to be used by the bean */
57    protected NodeService nodeService;
58    
59    /** The BrowseBean reference */
60    protected BrowseBean browseBean;
61    
62    /** The PermissionService reference */
63    protected PermissionService permissionService;
64    
65    /** List of shortcut nodes */
66    private List JavaDoc<Node> shortcuts = null;
67    
68    private QName QNAME_SHORTCUTS = QName.createQName(NamespaceService.APP_MODEL_1_0_URI, "shortcuts");
69    
70    
71    // ------------------------------------------------------------------------------
72
// Bean property getters and setters
73

74    /**
75     * @param nodeService The NodeService to set.
76     */

77    public void setNodeService(NodeService nodeService)
78    {
79       this.nodeService = nodeService;
80    }
81
82    /**
83     * @param browseBean The BrowseBean to set.
84     */

85    public void setBrowseBean(BrowseBean browseBean)
86    {
87       this.browseBean = browseBean;
88    }
89    
90    /**
91     * @param permissionService The PermissionService to set.
92     */

93    public void setPermissionService(PermissionService permissionService)
94    {
95       this.permissionService = permissionService;
96    }
97    
98    /**
99     * @return the List of shortcut Nodes
100     */

101    public List JavaDoc<Node> getShortcuts()
102    {
103       if (this.shortcuts == null)
104       {
105          List JavaDoc<String JavaDoc> shortcuts = null;
106          NodeRef prefRef = null;
107          UserTransaction JavaDoc tx = null;
108          boolean rollback = false;
109          try
110          {
111             FacesContext context = FacesContext.getCurrentInstance();
112             tx = Repository.getUserTransaction(context);
113             tx.begin();
114             
115             // get the shortcuts from the preferences for this user
116
prefRef = getShortcutsNodeRef();
117             shortcuts = (List JavaDoc<String JavaDoc>)this.nodeService.getProperty(prefRef, QNAME_SHORTCUTS);
118             if (shortcuts != null)
119             {
120                // each shortcut node ID is persisted as a list item in a well known property
121
this.shortcuts = new ArrayList JavaDoc<Node>(shortcuts.size());
122                for (int i=0; i<shortcuts.size(); i++)
123                {
124                   NodeRef ref = new NodeRef(Repository.getStoreRef(), shortcuts.get(i));
125                   try
126                   {
127                      if (this.nodeService.exists(ref) == true)
128                      {
129                         Node node = new Node(ref);
130                         
131                         // quick init properties while in the usertransaction
132
node.getProperties();
133                         
134                         // save ref to the Node for rendering
135
this.shortcuts.add(node);
136                      }
137                      else
138                      {
139                         // ignore this shortcut node - no longer exists in the system!
140
// we write the node list back again afterwards to correct this
141
if (logger.isDebugEnabled())
142                            logger.debug("Found invalid shortcut node Id: " + ref.getId());
143                      }
144                   }
145                   catch (AccessDeniedException accessErr)
146                   {
147                      // ignore this shortcut node - no longer exists in the system!
148
// we write the node list back again afterwards to correct this
149
if (logger.isDebugEnabled())
150                         logger.debug("Found invalid shortcut node Id: " + ref.getId());
151                      rollback = true;
152                   }
153                }
154             }
155             else
156             {
157                this.shortcuts = new ArrayList JavaDoc<Node>(5);
158             }
159             
160             if (rollback == false)
161             {
162                tx.commit();
163             }
164             else
165             {
166                tx.rollback();
167             }
168          }
169          catch (Throwable JavaDoc err)
170          {
171             Utils.addErrorMessage(MessageFormat.format(Application.getMessage(
172                   FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err);
173             try { if (tx != null) {tx.rollback();} } catch (Exception JavaDoc tex) {}
174          }
175          
176          // if the count of accessable shortcuts is different to our original list then
177
// write the valid shortcut IDs back to correct invalid node refs
178
if (shortcuts != null && shortcuts.size() != this.shortcuts.size())
179          {
180             try
181             {
182                shortcuts = new ArrayList JavaDoc<String JavaDoc>(this.shortcuts.size());
183                for (int i=0; i<this.shortcuts.size(); i++)
184                {
185                   shortcuts.add(this.shortcuts.get(i).getId());
186                }
187                this.nodeService.setProperty(prefRef, QNAME_SHORTCUTS, (Serializable JavaDoc)shortcuts);
188             }
189             catch (Exception JavaDoc err)
190             {
191                Utils.addErrorMessage(MessageFormat.format(Application.getMessage(
192                      FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err);
193             }
194          }
195       }
196       
197       return this.shortcuts;
198    }
199    
200    /**
201     * @param spaces List of shortcuts Nodes
202     */

203    public void setShortcuts(List JavaDoc<Node> nodes)
204    {
205       this.shortcuts = nodes;
206    }
207    
208    
209    // ------------------------------------------------------------------------------
210
// Action method handlers
211

212    /**
213     * Action handler called when a new shortcut is to be added to the list
214     */

215    public void createShortcut(ActionEvent event)
216    {
217       // TODO: add this action to the Details screen for Space and Document
218
UIActionLink link = (UIActionLink)event.getComponent();
219       Map JavaDoc<String JavaDoc, String JavaDoc> params = link.getParameterMap();
220       String JavaDoc id = params.get("id");
221       if (id != null && id.length() != 0)
222       {
223          try
224          {
225             NodeRef ref = new NodeRef(Repository.getStoreRef(), id);
226             Node node = new Node(ref);
227             
228             boolean foundShortcut = false;
229             for (int i=0; i<getShortcuts().size(); i++)
230             {
231                if (node.getId().equals(getShortcuts().get(i).getId()))
232                {
233                   // found same node already in the list - so we don't need to add it again
234
foundShortcut = true;
235                   break;
236                }
237             }
238             
239             if (foundShortcut == false)
240             {
241                // add to persistent store
242
UserTransaction JavaDoc tx = null;
243                try
244                {
245                   FacesContext context = FacesContext.getCurrentInstance();
246                   tx = Repository.getUserTransaction(context);
247                   tx.begin();
248                   
249                   NodeRef prefRef = getShortcutsNodeRef();
250                   List JavaDoc<String JavaDoc> shortcuts = (List JavaDoc<String JavaDoc>)this.nodeService.getProperty(prefRef, QNAME_SHORTCUTS);
251                   if (shortcuts == null)
252                   {
253                      shortcuts = new ArrayList JavaDoc<String JavaDoc>(1);
254                   }
255                   shortcuts.add(node.getNodeRef().getId());
256                   this.nodeService.setProperty(prefRef, QNAME_SHORTCUTS, (Serializable JavaDoc)shortcuts);
257                   
258                   // commit the transaction
259
tx.commit();
260                   
261                   // add our new shortcut Node to the in-memory list
262
getShortcuts().add(node);
263                   
264                   if (logger.isDebugEnabled())
265                      logger.debug("Added node: " + node.getName() + " to the user shortcuts list.");
266                }
267                catch (Throwable JavaDoc err)
268                {
269                   Utils.addErrorMessage(MessageFormat.format(Application.getMessage(
270                         FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err);
271                   try { if (tx != null) {tx.rollback();} } catch (Exception JavaDoc tex) {}
272                }
273             }
274          }
275          catch (InvalidNodeRefException refErr)
276          {
277             Utils.addErrorMessage(MessageFormat.format(Application.getMessage(
278                FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object JavaDoc[] {id}) );
279          }
280       }
281    }
282    
283    /**
284     * Get the node we need to store our user preferences
285     */

286    private NodeRef getShortcutsNodeRef()
287    {
288       return Application.getCurrentUser(FacesContext.getCurrentInstance()).getUserPreferencesRef();
289    }
290    
291    /**
292     * Action handler bound to the user shortcuts Shelf component called when a node is removed
293     */

294    public void removeShortcut(ActionEvent event)
295    {
296       UIShortcutsShelfItem.ShortcutEvent shortcutEvent = (UIShortcutsShelfItem.ShortcutEvent)event;
297       
298       // remove from persistent store
299
UserTransaction JavaDoc tx = null;
300       try
301       {
302          FacesContext context = FacesContext.getCurrentInstance();
303          tx = Repository.getUserTransaction(context);
304          tx.begin();
305          
306          NodeRef prefRef = getShortcutsNodeRef();
307          List JavaDoc<String JavaDoc> shortcuts = (List JavaDoc<String JavaDoc>)this.nodeService.getProperty(prefRef, QNAME_SHORTCUTS);
308          if (shortcuts != null && shortcuts.size() > shortcutEvent.Index)
309          {
310             // remove the shortcut from the saved list and persist back
311
shortcuts.remove(shortcutEvent.Index);
312             this.nodeService.setProperty(prefRef, QNAME_SHORTCUTS, (Serializable JavaDoc)shortcuts);
313             
314             // commit the transaction
315
tx.commit();
316             
317             // remove shortcut Node from the in-memory list
318
Node node = getShortcuts().remove(shortcutEvent.Index);
319             
320             if (logger.isDebugEnabled())
321                logger.debug("Removed node: " + node.getName() + " from the user shortcuts list.");
322          }
323       }
324       catch (Throwable JavaDoc err)
325       {
326          Utils.addErrorMessage(MessageFormat.format(Application.getMessage(
327                FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err);
328          try { if (tx != null) {tx.rollback();} } catch (Exception JavaDoc tex) {}
329       }
330    }
331    
332    /**
333     * Action handler bound to the user shortcuts Shelf component called when a node is clicked
334     */

335    public void click(ActionEvent event)
336    {
337       // work out which node was clicked from the event data
338
UIShortcutsShelfItem.ShortcutEvent shortcutEvent = (UIShortcutsShelfItem.ShortcutEvent)event;
339       Node selectedNode = getShortcuts().get(shortcutEvent.Index);
340       
341       try
342       {
343          if (permissionService.hasPermission(selectedNode.getNodeRef(), PermissionService.READ) == AccessStatus.ALLOWED)
344          {
345             if (nodeService.exists(selectedNode.getNodeRef()) == false)
346             {
347                throw new InvalidNodeRefException(selectedNode.getNodeRef());
348             }
349             
350             DictionaryService dd = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getDictionaryService();
351             if (dd.isSubClass(selectedNode.getType(), ContentModel.TYPE_FOLDER))
352             {
353                // then navigate to the appropriate node in UI
354
// use browse bean functionality for this as it will update the breadcrumb for us
355
this.browseBean.updateUILocation(selectedNode.getNodeRef());
356             }
357             else if (dd.isSubClass(selectedNode.getType(), ContentModel.TYPE_CONTENT))
358             {
359                // view details for document
360
this.browseBean.setupContentAction(selectedNode.getId(), true);
361                FacesContext fc = FacesContext.getCurrentInstance();
362                fc.getApplication().getNavigationHandler().handleNavigation(fc, null, "dialog:showDocDetails");
363             }
364          }
365          else
366          {
367             Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), "error_shortcut_permissions"));
368          }
369       }
370       catch (InvalidNodeRefException refErr)
371       {
372          Utils.addErrorMessage(MessageFormat.format(Application.getMessage(
373                FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object JavaDoc[] {selectedNode.getId()}) );
374          
375          // remove item from the shortcut list
376
UserTransaction JavaDoc tx = null;
377          try
378          {
379             FacesContext context = FacesContext.getCurrentInstance();
380             tx = Repository.getUserTransaction(context);
381             tx.begin();
382             
383             NodeRef prefRef = getShortcutsNodeRef();
384             List JavaDoc<String JavaDoc> shortcuts = (List JavaDoc<String JavaDoc>)this.nodeService.getProperty(prefRef, QNAME_SHORTCUTS);
385             if (shortcuts != null && shortcuts.size() > shortcutEvent.Index)
386             {
387                // remove the shortcut from the saved list and persist back
388
shortcuts.remove(shortcutEvent.Index);
389                this.nodeService.setProperty(prefRef, QNAME_SHORTCUTS, (Serializable JavaDoc)shortcuts);
390                
391                // commit the transaction
392
tx.commit();
393                
394                // remove shortcut Node from the in-memory list
395
Node node = getShortcuts().remove(shortcutEvent.Index);
396                
397                if (logger.isDebugEnabled())
398                   logger.debug("Removed deleted node: " + node.getName() + " from the user shortcuts list.");
399             }
400          }
401          catch (Throwable JavaDoc err)
402          {
403             try { if (tx != null) {tx.rollback();} } catch (Exception JavaDoc tex) {}
404          }
405       }
406    }
407 }
408
Popular Tags