View Javadoc
1   /*
2    * Copyright (C) 2003-2007 eXo Platform SAS.
3    *
4    * This program is free software; you can redistribute it and/or
5    * modify it under the terms of the GNU Affero General Public License
6    * as published by the Free Software Foundation; either version 3
7    * of the License, or (at your option) any later version.
8    *
9    * This program is distributed in the hope that it will be useful,
10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   * GNU General Public License for more details.
13   *
14   * You should have received a copy of the GNU General Public License
15   * along with this program; if not, see<http://www.gnu.org/licenses/>.
16   */
17  package org.exoplatform.ecm.webui.component.explorer ;
18  
19  import org.exoplatform.ecm.jcr.TypeNodeComparator;
20  import org.exoplatform.ecm.jcr.model.Preference;
21  import org.exoplatform.ecm.resolver.JCRResourceResolver;
22  import org.exoplatform.ecm.utils.comparator.PropertyValueComparator;
23  import org.exoplatform.ecm.utils.lock.LockUtil;
24  import org.exoplatform.ecm.utils.text.Text;
25  import org.exoplatform.ecm.webui.comparator.DateComparator;
26  import org.exoplatform.ecm.webui.comparator.NodeSizeComparator;
27  import org.exoplatform.ecm.webui.comparator.NodeTitleComparator;
28  import org.exoplatform.ecm.webui.comparator.StringComparator;
29  import org.exoplatform.ecm.webui.component.explorer.control.UIActionBar;
30  import org.exoplatform.ecm.webui.component.explorer.control.UIAddressBar;
31  import org.exoplatform.ecm.webui.component.explorer.control.UIControl;
32  import org.exoplatform.ecm.webui.component.explorer.popup.actions.UIDocumentForm;
33  import org.exoplatform.ecm.webui.component.explorer.popup.actions.UIDocumentFormController;
34  import org.exoplatform.ecm.webui.component.explorer.popup.actions.UISelectDocumentForm;
35  import org.exoplatform.ecm.webui.component.explorer.sidebar.UISideBar;
36  import org.exoplatform.ecm.webui.component.explorer.sidebar.UITreeExplorer;
37  import org.exoplatform.ecm.webui.component.explorer.sidebar.UITreeNodePageIterator;
38  import org.exoplatform.ecm.webui.utils.PermissionUtil;
39  import org.exoplatform.ecm.webui.utils.Utils;
40  import org.exoplatform.portal.webui.util.Util;
41  import org.exoplatform.services.cms.drives.DriveData;
42  import org.exoplatform.services.cms.folksonomy.NewFolksonomyService;
43  import org.exoplatform.services.cms.impl.DMSConfiguration;
44  import org.exoplatform.services.cms.impl.DMSRepositoryConfiguration;
45  import org.exoplatform.services.cms.link.ItemLinkAware;
46  import org.exoplatform.services.cms.link.LinkUtils;
47  import org.exoplatform.services.cms.link.NodeFinder;
48  import org.exoplatform.services.cms.link.NodeLinkAware;
49  import org.exoplatform.services.cms.templates.TemplateService;
50  import org.exoplatform.services.jcr.RepositoryService;
51  import org.exoplatform.services.jcr.access.PermissionType;
52  import org.exoplatform.services.jcr.core.ExtendedNode;
53  import org.exoplatform.services.jcr.core.ManageableRepository;
54  import org.exoplatform.services.jcr.ext.common.SessionProvider;
55  import org.exoplatform.services.log.ExoLogger;
56  import org.exoplatform.services.log.Log;
57  import org.exoplatform.services.wcm.core.NodetypeConstant;
58  import org.exoplatform.services.wcm.utils.WCMCoreUtils;
59  import org.exoplatform.web.application.ApplicationMessage;
60  import org.exoplatform.webui.application.WebuiRequestContext;
61  import org.exoplatform.webui.application.portlet.PortletRequestContext;
62  import org.exoplatform.webui.config.annotation.ComponentConfig;
63  import org.exoplatform.webui.core.*;
64  import org.exoplatform.webui.core.lifecycle.UIContainerLifecycle;
65  import org.exoplatform.webui.event.Event;
66  
67  import javax.jcr.*;
68  import javax.jcr.nodetype.NodeType;
69  import javax.portlet.PortletPreferences;
70  import javax.servlet.http.Cookie;
71  import javax.servlet.http.HttpServletRequest;
72  import java.security.AccessControlException;
73  import java.util.*;
74  
75  /**
76   * Created by The eXo Platform SARL
77   * Author : nqhungvn
78   *          nguyenkequanghung@yahoo.com
79   * July 3, 2006
80   * 10:07:15 AM
81   */
82  
83  @ComponentConfig(lifecycle = UIContainerLifecycle.class)
84  public class UIJCRExplorer extends UIContainer {
85  
86    /**
87     * Logger.
88     */
89    private static final Log LOG  = ExoLogger.getLogger(UIJCRExplorer.class.getName());
90  
91    private LinkedList<String> nodesHistory_ = new LinkedList<String>() ;
92    private LinkedList<String> wsHistory_ = new LinkedList<String>();
93    private PortletPreferences pref_ ;
94    private Preference preferences_;
95    private Map<String, Integer> pageIndexHistory_ = new HashMap<String, Integer>();
96    private Map<String, HistoryEntry> addressPath_ = new HashMap<String, HistoryEntry>() ;
97    private JCRResourceResolver jcrTemplateResourceResolver_ ;
98  
99    private String currentRootPath_ ;
100   private String currentPath_ ;
101   private String currentStatePath_ ;
102   private String currentStateWorkspaceName_ ;
103   private String lastWorkspaceName_ ;
104   private String currentDriveRootPath_ ;
105   private String currentDriveWorkspaceName_ ;
106   private String currentDriveRepositoryName_ ;
107   private String documentInfoTemplate_ ;
108   private String language_ ;
109   private Set<String> tagPaths_ = new HashSet<>();
110   private String referenceWorkspace_ ;
111 
112   private boolean isViewTag_;
113   private boolean isHidePopup_;
114   private boolean isReferenceNode_;
115   private DriveData driveData_ ;
116 
117   private boolean isFilterSave_ ;
118   private boolean  isShowDocumentViewForFile_ = true;
119   private boolean preferencesSaved_ = false;
120 
121   private int tagScope;
122 
123   private List<String> checkedSupportType = new ArrayList<String>();
124   private Set<String> allItemFilterMap = new HashSet<String>();
125   private Set<String> allItemByTypeFilterMap = new HashSet<String>();
126 
127   public Set<String> getAllItemFilterMap() { return allItemFilterMap; }
128   public Set<String> getAllItemByTypeFilterMap() { return allItemByTypeFilterMap; }
129 
130   public int getTagScope() { return tagScope; }
131   public void setTagScope(int scope) { tagScope = scope; }
132 
133   public boolean isFilterSave() { return isFilterSave_; }
134   public void setFilterSave(boolean isFilterSave) { isFilterSave_ = isFilterSave; }
135 
136   public boolean  isShowDocumentViewForFile() { return isShowDocumentViewForFile_; }
137   public void setShowDocumentViewForFile(boolean value) { isShowDocumentViewForFile_ = value; }
138 
139   public boolean isPreferencesSaved() { return preferencesSaved_; }
140   public void setPreferencesSaved(boolean value) { preferencesSaved_ = value; }
141 
142   public boolean isAddingDocument() {
143     UIPopupContainer uiPopupContainer = this.getChild(UIPopupContainer.class);
144     UIPopupWindow uiPopup = uiPopupContainer.getChild(UIPopupWindow.class);
145 
146     UIWorkingArea uiWorkingArea = this.getChild(UIWorkingArea.class);
147     UIDocumentWorkspace uiDocumentWorkspace = uiWorkingArea.getChild(UIDocumentWorkspace.class);
148     //check if edit with popup
149     UIComponent uiComp = uiPopup.getUIComponent();
150     if (uiComp instanceof UIDocumentFormController && ((UIDocumentFormController)uiComp).isRendered()) {
151       return ((UIDocumentFormController)uiComp).getChild(UIDocumentForm.class).isAddNew();
152     }
153     //check if edit without popup
154     if (uiDocumentWorkspace.isRendered()) {
155       UIDocumentFormController controller = uiDocumentWorkspace.getChild(UIDocumentFormController.class);
156       if (controller != null && controller.isRendered()) {
157         return controller.getChild(UIDocumentForm.class).isAddNew();
158       }
159     }
160     return false;
161   }
162 
163   public boolean isEditingDocument() {
164     UIPopupContainer uiPopupContainer = this.getChild(UIPopupContainer.class);
165     UIPopupWindow uiPopup = uiPopupContainer.getChild(UIPopupWindow.class);
166 
167     UIWorkingArea uiWorkingArea = this.getChild(UIWorkingArea.class);
168     UIDocumentWorkspace uiDocumentWorkspace = uiWorkingArea.getChild(UIDocumentWorkspace.class);
169     //check if edit with popup
170     UIComponent uiComp = uiPopup.getUIComponent();
171 
172     if (uiPopup.isShow() && uiPopup.isRendered() &&
173         uiComp instanceof UIDocumentFormController && ((UIDocumentFormController)uiComp).isRendered()) {
174       return true;
175     }
176     //check if edit without popup
177     if (uiDocumentWorkspace.isRendered()) {
178       UIDocumentFormController controller = uiDocumentWorkspace.getChild(UIDocumentFormController.class);
179       if (controller != null && controller.isRendered()) {
180         return true;
181       }
182     }
183     return false;
184   }
185 
186   public List<String> getCheckedSupportType() {
187     return checkedSupportType;
188   }
189 
190   public void setCheckedSupportType(List<String> checkedSupportType) {
191     this.checkedSupportType = checkedSupportType;
192   }
193 
194   public UIJCRExplorer() throws Exception {
195     addChild(UIControl.class, null, null);
196     addChild(UIWorkingArea.class, null, null);
197     addChild(UIPopupContainer.class, null, null);
198     UIPopupWindow uiPopup = addChild(UIPopupWindow.class, null, null);
199     uiPopup.setId(uiPopup.getId() + "-" + UUID.randomUUID().toString().replaceAll("-", ""));
200     PortletRequestContext pcontext = (PortletRequestContext)WebuiRequestContext.getCurrentInstance() ;
201     pref_ = pcontext.getRequest().getPreferences();
202     getChild(UIWorkingArea.class).initialize();
203   }
204 
205   public String filterPath(String currentPath) throws Exception {
206     if(LinkUtils.getDepth(currentRootPath_) == 0) return currentPath ;
207     if(currentRootPath_.equals(currentPath_)) return "/" ;
208     return currentPath.replaceFirst(currentRootPath_, "") ;
209   }
210 
211   /**
212    * Sets the root path
213    */
214   public void setRootPath(String rootPath) {
215     currentDriveRootPath_ = rootPath;
216     setCurrentRootPath(rootPath);
217   }
218 
219   private void setCurrentRootPath(String rootPath) {
220     currentRootPath_ = rootPath ;
221   }
222 
223   /**
224    * @return the root node itself if it is not a link otherwise the target node (= resolve the link)
225    */
226   public Node getRootNode() throws Exception {
227     return getNodeByPath(currentRootPath_, getSystemSession()) ;
228   }
229 
230   /**
231    * @return the root path
232    */
233   public String getRootPath() { return currentRootPath_; }
234 
235 
236   private String getDefaultRootPath() { return "/"; }
237 
238   /**
239    * @return the current node itself if it is not a link otherwise the target node (= resolve the link)
240    */
241   public Node getCurrentNode() throws Exception { return getNodeByPath(currentPath_, getSession()) ; }
242 
243   /**
244    * @return the current node even if it is a link (= don't resolve the link)
245    */
246   public Node getRealCurrentNode() throws Exception {
247     return getNodeByPath(currentPath_, getSession(), false);
248   }
249 
250   /**
251    * @return the virtual current path
252    */
253   public String getCurrentPath() { return currentPath_ ; }
254 
255   /**
256    * Sets the virtual current path
257    */
258   public void setCurrentPath(String  currentPath) {
259     if (currentPath_ == null || !currentPath_.equals(currentPath)) {
260       isShowDocumentViewForFile_ = true;
261     }
262     currentPath_ = currentPath;
263   }
264 
265   /**
266    * Indicates if the current node is a referenced node
267    */
268   public boolean isReferenceNode() { return isReferenceNode_ ; }
269 
270   /**
271    * Tells that the current node is a referenced node
272    */
273   public void setIsReferenceNode(boolean isReferenceNode) { isReferenceNode_ = isReferenceNode ; }
274 
275   /**
276    * Sets the workspace name the referenced node
277    */
278   public void setReferenceWorkspace(String referenceWorkspace) { referenceWorkspace_ = referenceWorkspace ; }
279   public String getReferenceWorkspace() { return referenceWorkspace_ ; }
280 
281   private String setTargetWorkspaceProperties(String workspaceName) {
282     if (workspaceName != null && workspaceName.length() > 0) {
283       if (!workspaceName.equals(getCurrentDriveWorkspace())) {
284         setIsReferenceNode(true);
285         setReferenceWorkspace(workspaceName);
286         setCurrentRootPath(getDefaultRootPath());
287         return workspaceName;
288       } else if(isReferenceNode()) {
289         setIsReferenceNode(false);
290         setCurrentRootPath(currentDriveRootPath_);
291       }
292     }
293     return getCurrentDriveWorkspace();
294   }
295 
296   /**
297    * Tells to go back to the given location
298    */
299   public void setBackNodePath(String previousWorkspaceName, String previousPath) throws Exception {
300     setBackSelectNode(previousWorkspaceName, previousPath);
301     refreshExplorer();
302 
303     // Back to last pageIndex if previous path has paginator
304     if (pageIndexHistory_.containsKey(previousPath) && hasPaginator(previousPath, previousWorkspaceName)) {
305       UIPageIterator contentPageIterator = this.findComponentById(UIDocumentInfo.CONTENT_PAGE_ITERATOR_ID);
306       if (contentPageIterator != null ) {
307         // Get last pageIndex
308         int previousPageIndex = pageIndexHistory_.get(previousPath);
309         int avaiablePage = contentPageIterator.getAvailablePage();
310         previousPageIndex = (avaiablePage >= previousPageIndex)? previousPageIndex : avaiablePage;
311 
312         // Set last pageIndex for paginator of UIDocumentInfo
313         contentPageIterator.setCurrentPage(previousPageIndex);
314 
315         // Set last pageIndex for UITreeNodePageIterator
316         UITreeExplorer uiTreeExplorer = this.findFirstComponentOfType(UITreeExplorer.class);
317         if (uiTreeExplorer != null) {
318           UITreeNodePageIterator extendedPageIterator =
319               uiTreeExplorer.getUIPageIterator(previousPath);
320           if (extendedPageIterator != null) {
321             extendedPageIterator.setCurrentPage(previousPageIndex);
322           }
323         }
324       }
325     }
326   }
327 
328   /**
329    * Check if node has paginator when viewing it's children.
330    *
331    * @param nodePath
332    * @param workspaceName
333    * @return
334    * @throws Exception
335    */
336   public boolean hasPaginator(String nodePath, String workspaceName) throws Exception {
337     int nodePerPages = this.getPreference().getNodesPerPage();
338     Node node = getNodeByPath(nodePath, this.getSessionByWorkspace(workspaceName));
339     if (node != null) {
340       return node.getNodes().getSize() > nodePerPages;
341     } else {
342       return false;
343     }
344   }
345 
346   public void setDriveData(DriveData driveData) { driveData_ = driveData ; }
347   public DriveData getDriveData() { return driveData_ ; }
348 
349   public void setLanguage(String language) { language_ = language ; }
350   public String getLanguage() { return language_ ; }
351 
352   public LinkedList<String> getNodesHistory() { return nodesHistory_ ; }
353 
354   public LinkedList<String> getWorkspacesHistory() { return wsHistory_; }
355 
356   public Collection<HistoryEntry> getHistory() { return addressPath_.values() ; }
357 
358   public SessionProvider getSessionProvider() {
359     return WCMCoreUtils.getUserSessionProvider();
360   }
361 
362   public SessionProvider getSystemProvider() { return WCMCoreUtils.getSystemSessionProvider(); }
363 
364   /**
365    * @return the session of the current node (= UIJCRExplorer.getCurrentNode())
366    */
367   public Session getTargetSession() throws Exception {
368     return getCurrentNode().getSession();
369   }
370 
371   public Session getSession() throws Exception {
372     return getSessionProvider().getSession(getWorkspaceName(), getRepository()) ;
373   }
374 
375   public String getWorkspaceName() {
376     return (isReferenceNode_ ? referenceWorkspace_ : currentDriveWorkspaceName_);
377   }
378 
379   public Session getSystemSession() throws Exception {
380     return getSystemProvider().getSession(getWorkspaceName(), getRepository()) ;
381   }
382 
383   public String getDocumentInfoTemplate() { return documentInfoTemplate_ ; }
384   public void setRenderTemplate(String template) {
385     newJCRTemplateResourceResolver() ;
386     documentInfoTemplate_  = template ;
387   }
388 
389   public void setCurrentState() {
390     setCurrentState(currentDriveWorkspaceName_, currentPath_);
391   }
392 
393   public void setCurrentState(String currentStateWorkspaceName, String currentStatePath) {
394     currentStateWorkspaceName_ = currentStateWorkspaceName;
395     currentStatePath_ =  currentStatePath ;
396   }
397 
398   public String getCurrentStatePath() { return currentStatePath_;};
399   public void setCurrentStatePath(String currentStatePath) {
400     setCurrentState(currentDriveWorkspaceName_, currentStatePath);
401   }
402 
403   public Node getCurrentStateNode() throws Exception {
404     return getNodeByPath(currentStatePath_, getSessionProvider().getSession(currentStateWorkspaceName_, getRepository())) ;
405   }
406 
407   public JCRResourceResolver getJCRTemplateResourceResolver() { return jcrTemplateResourceResolver_; }
408   public void newJCRTemplateResourceResolver() {
409     try{
410       DMSConfiguration dmsConfiguration = getApplicationComponent(DMSConfiguration.class);
411       DMSRepositoryConfiguration dmsRepoConfig =
412           dmsConfiguration.getConfig();
413       String workspace =  dmsRepoConfig.getSystemWorkspace();
414       jcrTemplateResourceResolver_ = new JCRResourceResolver(workspace) ;
415     } catch(Exception e) {
416       if (LOG.isErrorEnabled()) {
417         LOG.error("Cannot instantiate the JCRResourceResolver", e);
418       }
419     }
420   }
421 
422   /**
423    * Sets the repository of the current drive
424    */
425   public void setRepositoryName(String repositoryName) { currentDriveRepositoryName_ = repositoryName ; }
426   /**
427    * @return the repository of the current drive
428    */
429   public String getRepositoryName() {
430     try {
431       return getApplicationComponent(RepositoryService.class).getCurrentRepository().getConfiguration().getName();
432     } catch (RepositoryException e) {
433       String repoName = System.getProperty("gatein.tenant.repository.name");
434       if (repoName!=null)
435         return repoName;
436       return currentDriveRepositoryName_;
437     }
438   }
439 
440   /**
441    * Sets the workspace of the current drive
442    */
443   public void setWorkspaceName(String workspaceName) {
444     currentDriveWorkspaceName_ = workspaceName ;
445     if (lastWorkspaceName_ == null) {
446       setLastWorkspace(workspaceName);
447     }
448   }
449 
450   private void setLastWorkspace(String lastWorkspaceName) {
451     lastWorkspaceName_ = lastWorkspaceName;
452   }
453 
454   /**
455    * @return the workspace of the current drive
456    */
457   public String getCurrentDriveWorkspace() { return currentDriveWorkspaceName_ ; }
458 
459   /**
460    * @return the workspace of the session of the current node (= UIJCRExplorer.getCurrentNode())
461    */
462   public String getCurrentWorkspace() {
463     try {
464       return getCurrentNode().getSession().getWorkspace().getName();
465     } catch (Exception e) {
466       if (LOG.isWarnEnabled()) {
467         LOG.warn("The workspace of the current node cannot be found, the workspace of the drive will be used", e);
468       }
469     }
470     return getCurrentDriveWorkspace();
471   }
472 
473   public ManageableRepository getRepository() throws Exception{
474     RepositoryService repositoryService  = getApplicationComponent(RepositoryService.class) ;
475     return repositoryService.getCurrentRepository();
476   }
477 
478   public Session getSessionByWorkspace(String wsName) throws Exception{
479     if(wsName == null ) return getSession() ;
480     return getSessionProvider().getSession(wsName,getRepository()) ;
481   }
482 
483   public boolean isSystemWorkspace() throws Exception {
484     RepositoryService repositoryService = getApplicationComponent(RepositoryService.class) ;
485     String systemWS = repositoryService.getCurrentRepository()
486         .getConfiguration()
487         .getSystemWorkspaceName();
488     if(getCurrentWorkspace().equals(systemWS)) return true ;
489     return false ;
490   }
491 
492   public void refreshExplorer() throws Exception {
493     refreshExplorer(null, true);
494   }
495 
496   public void refreshExplorerWithoutClosingPopup() throws Exception {
497     refreshExplorer(null, false);
498   }
499 
500   public void setPathToAddressBar(String path) throws Exception {
501     findFirstComponentOfType(UIAddressBar.class).getUIStringInput(
502                                                                   UIAddressBar.FIELD_ADDRESS).setValue(Text.unescapeIllegalJcrChars(filterPath(path))) ;
503     findFirstComponentOfType(UIAddressBar.class).getUIInput(
504                                                             UIAddressBar.FIELD_ADDRESS_HIDDEN).setValue(filterPath(path)) ;
505   }
506 
507   private void refreshExplorer(Node currentNode) throws Exception {
508     refreshExplorer(currentNode, true);
509   }
510 
511   public void refreshExplorer(Node currentNode, boolean closePopup) throws Exception {
512     try {
513       Node nodeGet = currentNode == null ? getCurrentNode() : currentNode;
514       if(nodeGet.hasProperty(Utils.EXO_LANGUAGE)) {
515         setLanguage(nodeGet.getProperty(Utils.EXO_LANGUAGE).getValue().getString());
516       }
517     } catch(PathNotFoundException path) {
518       if (LOG.isErrorEnabled()) {
519         LOG.error("The node cannot be found ", path);
520       }
521       setCurrentPath(currentRootPath_);
522     }
523     findFirstComponentOfType(UIAddressBar.class).getUIStringInput(UIAddressBar.FIELD_ADDRESS).
524     setValue(Text.unescapeIllegalJcrChars(filterPath(currentPath_))) ;
525     findFirstComponentOfType(UIAddressBar.class).getUIInput(UIAddressBar.FIELD_ADDRESS_HIDDEN).
526     setValue(filterPath(currentPath_)) ;
527     UIWorkingArea uiWorkingArea = getChild(UIWorkingArea.class);
528     UIDocumentWorkspace uiDocumentWorkspace = uiWorkingArea.getChild(UIDocumentWorkspace.class);
529 
530     UIDocumentContainer uiDocumentContainer = uiDocumentWorkspace.getChild(UIDocumentContainer.class);
531     UIDocumentWithTree uiDocumentWithTree = uiDocumentContainer.getChildById("UIDocumentWithTree");
532     UIDocumentInfo uiDocumentInfo = uiDocumentContainer.getChildById("UIDocumentInfo") ;
533     uiDocumentInfo.updatePageListData();
534 
535     if(uiDocumentWorkspace.isRendered()) {
536       if (uiDocumentWorkspace.getChild(UIDocumentFormController.class) == null ||
537           !uiDocumentWorkspace.getChild(UIDocumentFormController.class).isRendered()) {
538         if(isShowViewFile() &&  !(isShowDocumentViewForFile())) {
539           uiDocumentContainer.setRenderedChild("UIDocumentWithTree");
540         } else {
541           uiDocumentContainer.setRenderedChild("UIDocumentInfo") ;
542         }
543         if(getCurrentNode().isNodeType(Utils.NT_FOLDER) || getCurrentNode().isNodeType(Utils.NT_UNSTRUCTURED))
544           uiDocumentWorkspace.setRenderedChild(UIDocumentContainer.class) ;
545       } else {
546         UIDocumentFormController uiDocController = uiDocumentWorkspace.getChild(UIDocumentFormController.class);
547         UISelectDocumentForm uiSelectDoc = uiDocController.getChild(UISelectDocumentForm.class);
548         if (uiSelectDoc != null && uiSelectDoc.isRendered()) {
549           uiSelectDoc.updatePageListData();
550         }
551       }
552     }
553     UISideBar uiSideBar = uiWorkingArea.findFirstComponentOfType(UISideBar.class);
554     uiSideBar.setRendered(preferences_.isShowSideBar());
555     if(preferences_.isShowSideBar()) {
556       UITreeExplorer treeExplorer = findFirstComponentOfType(UITreeExplorer.class);
557       if (treeExplorer.equals(uiSideBar.getChildById(uiSideBar.getCurrentComp()))) {
558         treeExplorer.buildTree();
559       }
560       uiSideBar.updateSideBarView();
561     }
562     if (closePopup) {
563       UIPopupContainer popupAction = getChild(UIPopupContainer.class);
564       popupAction.deActivate();
565     }
566   }
567 
568   public boolean nodeIsLocked(String path, Session session) throws Exception {
569     Node node = getNodeByPath(path, session) ;
570     return nodeIsLocked(node);
571   }
572 
573   public boolean nodeIsLocked(Node node) throws Exception {
574     if(!node.isLocked()) return false;
575     String lockToken = LockUtil.getLockTokenOfUser(node);
576     if(lockToken != null) {
577       node.getSession().addLockToken(LockUtil.getLockToken(node));
578       return false;
579     }
580     return true;
581   }
582 
583   /**
584    * Allows you to add a lock token to the given node
585    */
586   public void addLockToken(Node node) throws Exception {
587     org.exoplatform.wcm.webui.Utils.addLockToken(node);
588   }
589 
590   public boolean hasAddPermission() {
591     try {
592       ((ExtendedNode)getCurrentNode()).checkPermission(PermissionType.ADD_NODE) ;
593     } catch(Exception e) {
594       return false ;
595     }
596     return true ;
597   }
598 
599   public boolean hasEditPermission() {
600     try {
601       ((ExtendedNode)getCurrentNode()).checkPermission(PermissionType.SET_PROPERTY) ;
602     } catch(Exception e) {
603       return false ;
604     }
605     return true ;
606   }
607 
608   public boolean hasRemovePermission() {
609     try {
610       ((ExtendedNode)getCurrentNode()).checkPermission(PermissionType.REMOVE) ;
611     } catch(Exception e) {
612       return false ;
613     }
614     return true ;
615   }
616 
617   public boolean hasReadPermission() {
618     try {
619       ((ExtendedNode)getCurrentNode()).checkPermission(PermissionType.READ) ;
620     } catch(Exception e) {
621       return false ;
622     }
623     return true ;
624   }
625 
626   public Node getViewNode(String nodeType) throws Exception {
627     try {
628       Item primaryItem = getCurrentNode().getPrimaryItem() ;
629       if(primaryItem == null || !primaryItem.isNode()) return getCurrentNode() ;
630       if(primaryItem != null && primaryItem.isNode()) {
631         Node primaryNode = (Node) primaryItem ;
632         if(primaryNode.isNodeType(nodeType)) return primaryNode ;
633       }
634     } catch(ItemNotFoundException item) {
635       if (LOG.isErrorEnabled()) {
636         LOG.error("Primary item not found for " + getCurrentNode().getPath());
637       }
638       return getCurrentNode() ;
639     } catch(Exception e) {
640       if (LOG.isErrorEnabled()) {
641         LOG.error("The node cannot be seen", e);
642       }
643       return getCurrentNode() ;
644     }
645     return getCurrentNode() ;
646   }
647 
648   public List<String> getMultiValues(Node node, String name) throws Exception {
649     List<String> list = new ArrayList<String>();
650     if(!node.hasProperty(name)) return list;
651     if (!node.getProperty(name).getDefinition().isMultiple()) {
652       try {
653         if (node.hasProperty(name)) {
654           list.add(node.getProperty(name).getString());
655         }
656       } catch(Exception e) {
657         if (LOG.isErrorEnabled()) {
658           LOG.error("The property '" + name + "' cannot be found ", e);
659         }
660         list.add("") ;
661       }
662       return list;
663     }
664     Value[] values = node.getProperty(name).getValues();
665     for (Value value : values) {
666       list.add(value.getString());
667     }
668     return list;
669   }
670 
671   public void setIsHidePopup(boolean isHidePopup) { isHidePopup_ = isHidePopup ; }
672 
673   public void updateAjax(Event<?> event) throws Exception {
674     UIJCRExplorerPortlet uiPortlet = getAncestorOfType(UIJCRExplorerPortlet.class);
675     UIAddressBar uiAddressBar = findFirstComponentOfType(UIAddressBar.class) ;
676     UIWorkingArea uiWorkingArea = getChild(UIWorkingArea.class) ;
677     UIActionBar uiActionBar = findFirstComponentOfType(UIActionBar.class) ;
678     UISideBar uiSideBar = findFirstComponentOfType(UISideBar.class);
679     UITreeExplorer uiTreeExplorer = findFirstComponentOfType(UITreeExplorer.class);
680 
681     uiAddressBar.getUIStringInput(UIAddressBar.FIELD_ADDRESS).setValue(
682                                                                        Text.unescapeIllegalJcrChars(filterPath(currentPath_))) ;
683     uiAddressBar.getUIInput(UIAddressBar.FIELD_ADDRESS_HIDDEN).setValue(
684 	    filterPath(currentPath_)) ;
685     event.getRequestContext().addUIComponentToUpdateByAjax(getChild(UIControl.class)) ;
686     UIPageIterator contentPageIterator = this.findComponentById(UIDocumentInfo.CONTENT_PAGE_ITERATOR_ID);
687     int currentPage = contentPageIterator.getCurrentPage();
688     int currentPageInTree = 1;
689     
690     UITreeNodePageIterator extendedPageIterator =
691         uiTreeExplorer.findFirstComponentOfType(UITreeNodePageIterator.class);
692     if(extendedPageIterator != null) currentPageInTree = extendedPageIterator.getCurrentPage();
693     
694     if(preferences_.isShowSideBar()) {
695       UITreeExplorer treeExplorer = findFirstComponentOfType(UITreeExplorer.class);
696       if (treeExplorer.equals(uiSideBar.getChildById(uiSideBar.getCurrentComp()))) {
697         treeExplorer.buildTree();
698       }
699     }
700     UIDocumentWorkspace uiDocWorkspace = uiWorkingArea.getChild(UIDocumentWorkspace.class);
701     if(uiDocWorkspace.isRendered()) {
702       if (uiDocWorkspace.getChild(UIDocumentFormController.class) == null ||
703           !uiDocWorkspace.getChild(UIDocumentFormController.class).isRendered()) {
704         UIDocumentContainer uiDocumentContainer = uiDocWorkspace.getChild(UIDocumentContainer.class) ;
705         UIDocumentWithTree uiDocumentWithTree = uiDocumentContainer.getChildById("UIDocumentWithTree");
706         if(isShowViewFile() &&  !(isShowDocumentViewForFile())) {
707           uiDocumentContainer.setRenderedChild("UIDocumentWithTree");
708         } else {
709           UIDocumentInfo uiDocumentInfo = uiDocumentContainer.getChildById("UIDocumentInfo") ;
710           uiDocumentInfo.updatePageListData();
711           if(contentPageIterator.getAvailablePage() < currentPage) currentPage = contentPageIterator.getAvailablePage();
712           contentPageIterator.setCurrentPage(currentPage);
713           uiDocumentContainer.setRenderedChild("UIDocumentInfo") ;
714         }
715         if(getCurrentNode().isNodeType(Utils.NT_FOLDER) || getCurrentNode().isNodeType(Utils.NT_UNSTRUCTURED))
716           uiDocumentWithTree.updatePageListData();
717         uiDocWorkspace.setRenderedChild(UIDocumentContainer.class) ;
718       } else {
719         UIDocumentFormController uiDocController = uiDocWorkspace.getChild(UIDocumentFormController.class);
720         UISelectDocumentForm uiSelectDoc = uiDocController.getChild(UISelectDocumentForm.class);
721         if (uiSelectDoc != null && uiSelectDoc.isRendered()) {
722           uiSelectDoc.updatePageListData();
723         }
724       }
725     }
726     uiActionBar.setRendered(uiPortlet.isShowActionBar());
727     uiAddressBar.setRendered(uiPortlet.isShowTopBar());
728     uiSideBar.setRendered(preferences_.isShowSideBar());
729     if(extendedPageIterator != null) extendedPageIterator.setCurrentPage(currentPageInTree);
730     event.getRequestContext().addUIComponentToUpdateByAjax(uiWorkingArea);
731     if (uiSideBar.isRendered()) event.getRequestContext().addUIComponentToUpdateByAjax(uiSideBar);
732     event.getRequestContext().addUIComponentToUpdateByAjax(getChild(UIControl.class)) ;
733 
734     if(!isHidePopup_) {
735       UIPopupContainer popupAction = getChild(UIPopupContainer.class) ;
736       if(popupAction.isRendered()) {
737         popupAction.deActivate();
738         event.getRequestContext().addUIComponentToUpdateByAjax(popupAction) ;
739       }
740       UIPopupWindow popupWindow = getChild(UIPopupWindow.class) ;
741       if(popupWindow != null && popupWindow.isShow()) {
742         popupWindow.setShow(false);
743         event.getRequestContext().addUIComponentToUpdateByAjax(popupWindow);
744       }
745     }
746     isHidePopup_ = false ;
747   }
748 
749   public boolean isShowViewFile() throws Exception {
750     TemplateService templateService = getApplicationComponent(TemplateService.class) ;
751     NodeType nodeType = getCurrentNode().getPrimaryNodeType() ;
752     NodeType[] superTypes = nodeType.getSupertypes() ;
753     boolean isFolder = false ;
754     for(NodeType superType : superTypes) {
755       if(superType.getName().equals(Utils.NT_FOLDER) || superType.getName().equals(Utils.NT_UNSTRUCTURED)) {
756         isFolder = true ;
757       }
758     }
759     if(isFolder && templateService.getDocumentTemplates().contains(nodeType.getName())) {
760       return true ;
761     }
762     return false;
763   }
764 
765   public void cancelAction() throws Exception {
766     WebuiRequestContext context = WebuiRequestContext.getCurrentInstance() ;
767     UIPopupContainer popupAction = getChild(UIPopupContainer.class) ;
768     popupAction.deActivate() ;
769     context.addUIComponentToUpdateByAjax(popupAction);
770     context.getJavascriptManager().require("SHARED/uiFileView", "uiFileView").
771     addScripts("uiFileView.UIFileView.clearCheckboxes();");
772   }
773 
774   public void record(String str, String ws) {
775     /**
776      * Uncomment this line if you have problem with the history
777      *
778      */
779     //LOG.info("record(" + str + ", " + ws + ")", new Exception());
780     nodesHistory_.add(str);
781     wsHistory_.add(ws);
782     addressPath_.put(str, new HistoryEntry(ws, str));
783   }
784 
785   public void record(String str, String ws, int pageIndex) {
786     record(str, ws);
787     pageIndexHistory_.put(str, pageIndex);
788   }
789 
790   public void clearNodeHistory(String currentPath) {
791     nodesHistory_.clear();
792     wsHistory_.clear();
793     pageIndexHistory_.clear();
794     addressPath_.clear();
795     currentPath_ = currentPath;
796   }
797 
798   public void clearTagSelection() {
799     tagPaths_.clear();
800   }
801 
802   public String rewind() { return nodesHistory_.removeLast() ; }
803 
804   public String previousWsName() { return wsHistory_.removeLast(); }
805 
806   public void setSelectNode(String workspaceName, String uri) throws Exception {
807     String lastWorkspaceName = setTargetWorkspaceProperties(workspaceName);
808     setSelectNode(uri);
809     setLastWorkspace(lastWorkspaceName);
810   }
811 
812   public void setSelectNode(String workspaceName, String uri, String homePath) throws Exception {
813     String lastWorkspaceName = setTargetWorkspaceProperties(workspaceName);
814     setSelectNode(uri, homePath, false);
815     setLastWorkspace(lastWorkspaceName);
816   }
817 
818   public void setBackSelectNode(String workspaceName, String uri) throws Exception {
819     String lastWorkspaceName = setTargetWorkspaceProperties(workspaceName);
820     setSelectNode(uri, true);
821     setLastWorkspace(lastWorkspaceName);
822   }
823 
824   public void setSelectRootNode() throws Exception {
825     setSelectNode(getCurrentDriveWorkspace(), getRootPath());
826   }
827 
828   public void setSelectNode(String uri) throws Exception {
829     setSelectNode(uri, false);
830   }
831 
832   private boolean checkTargetForSymlink(String uri) throws Exception {
833     Node testedNode;
834     NodeFinder nodeFinder = getApplicationComponent(NodeFinder.class);
835     try {
836       testedNode = (Node) nodeFinder.getItem(this.getSession(), uri, true);
837     } catch (Exception e) {
838       if (LOG.isWarnEnabled()) {
839         LOG.warn("Cannot find the node at " + uri);
840       }
841       UIApplication uiApp = this.getAncestorOfType(UIApplication.class);
842       uiApp.addMessage(new ApplicationMessage("UIJCRExplorer.msg.target-path-not-found",
843                                               null,
844                                               ApplicationMessage.WARNING));
845       return false;
846     }
847     if (testedNode.isNodeType(Utils.EXO_RESTORELOCATION)) {
848       UIApplication uiApp = this.getAncestorOfType(UIApplication.class);
849       uiApp.addMessage(new ApplicationMessage("UIJCRExplorer.msg.target-path-not-found",
850                                               null,
851                                               ApplicationMessage.WARNING));
852       return false;
853     }
854     return true;
855   }
856 
857   public void setSelectNode(String uri, boolean back) throws Exception {
858     Node currentNode = null;
859     if(uri == null || uri.length() == 0) uri = "/";
860     String previousPath = currentPath_;
861     if (checkTargetForSymlink(uri)) {
862       try {
863         setCurrentPath(uri);
864         currentNode = getCurrentNode();
865       } catch (Exception e) {
866         if (LOG.isErrorEnabled()) {
867           LOG.error("Cannot find the node at " + uri, e);
868         }
869         setCurrentPath(LinkUtils.getParentPath(currentPath_));
870         currentNode = getCurrentNode();
871       }
872     } else {
873       currentNode = getCurrentNode();
874     }
875     if(currentNode.hasProperty(Utils.EXO_LANGUAGE)) {
876       setLanguage(currentNode.getProperty(Utils.EXO_LANGUAGE).getValue().getString());
877     }
878 
879     // Store previous node path to history for backing
880     if(previousPath != null && !currentPath_.equals(previousPath) && !back) {
881       // If previous node path has paginator, store last page index to history
882       try{
883         if(this.hasPaginator(previousPath, lastWorkspaceName_)){
884           UIPageIterator pageIterator = this.findComponentById(UIDocumentInfo.CONTENT_PAGE_ITERATOR_ID);
885           if (pageIterator != null) {
886             record(previousPath, lastWorkspaceName_, pageIterator.getCurrentPage());
887           }
888         }else{
889           record(previousPath, lastWorkspaceName_);
890         }
891       }catch(PathNotFoundException e){
892         LOG.info("This node " + previousPath +" is no longer accessible ");
893       }
894     }
895   }
896 
897   public void setSelectNode(String uri, String homePath, boolean back) throws Exception {
898     Node currentNode = null;
899     if(uri == null || uri.length() == 0) uri = "/";
900     // retrieve the path history to node from uri
901     String previousPath = uri.substring(0, uri.lastIndexOf("/"));
902     if (checkTargetForSymlink(uri)) {
903       try {
904         setCurrentPath(uri);
905         currentNode = getCurrentNode();
906       } catch (Exception e) {
907         if (LOG.isErrorEnabled()) {
908           LOG.error("Cannot find the node at " + uri, e);
909         }
910         setCurrentPath(LinkUtils.getParentPath(currentPath_));
911         currentNode = getCurrentNode();
912       }
913     } else {
914       currentNode = getCurrentNode();
915     }
916     if(currentNode.hasProperty(Utils.EXO_LANGUAGE)) {
917       setLanguage(currentNode.getProperty(Utils.EXO_LANGUAGE).getValue().getString());
918     }
919 
920     // Store previous node path to history for backing
921     if(previousPath != null && !previousPath.isEmpty() && !back) {
922       try {
923         String historyPath = "";
924         // get the home path if the node is in personal drive of a user
925         if (homePath.contains("${userId}")) {
926           homePath = org.exoplatform.services.cms.impl.Utils.getPersonalDrivePath(homePath, previousPath.split("/")[5]);
927         }
928         if (!(uri.equals(homePath) || homePath.equals("/"))) {
929           // retrieve the relaive path to node from the home path
930           // (the logic is previousPath = previousPath - homePath)
931           previousPath = previousPath.replace(homePath, "");
932           historyPath = homePath;
933         }
934         // Store the home path at the head of history
935         if (this.hasPaginator(homePath, lastWorkspaceName_)) {
936           UIPageIterator pageIterator = this.findComponentById(UIDocumentInfo.CONTENT_PAGE_ITERATOR_ID);
937           if (pageIterator != null) {
938             record(homePath, lastWorkspaceName_, pageIterator.getCurrentPage());
939           }
940         } else {
941           record(homePath, lastWorkspaceName_);
942         }
943         // for each folder from the relative path to node, store the path to history
944         for (String folder : previousPath.split("/")) {
945           if (folder == null || folder.isEmpty()) continue;
946           historyPath += "/" + folder;
947           if (this.hasPaginator(historyPath, lastWorkspaceName_)) {
948             UIPageIterator pageIterator = this.findComponentById(UIDocumentInfo.CONTENT_PAGE_ITERATOR_ID);
949             if (pageIterator != null) {
950               record(historyPath, lastWorkspaceName_, pageIterator.getCurrentPage());
951             }
952           } else {
953             record(historyPath, lastWorkspaceName_);
954           }
955         }
956       }catch(PathNotFoundException e){
957         LOG.info("This node " + previousPath +" is no longer accessible ");
958       }
959     }
960   }
961 
962   public List<Node> getChildrenList(String path, boolean isReferences) throws Exception {
963     RepositoryService repositoryService = getApplicationComponent(RepositoryService.class) ;
964     TemplateService templateService = getApplicationComponent(TemplateService.class) ;
965     Node node = (Node) ItemLinkAware.newInstance(getWorkspaceName(), path, getNodeByPath(path, getSession()));
966     NodeIterator childrenIterator = node.getNodes();
967     List<Node> childrenList  = new ArrayList<Node>() ;
968     NodeType nodeType = node.getPrimaryNodeType();
969     boolean isFolder = node.isNodeType(Utils.NT_FOLDER) || node.isNodeType(Utils.NT_UNSTRUCTURED) ;
970     if(!preferences_.isJcrEnable() &&
971         templateService.isManagedNodeType(nodeType.getName()) && !isFolder) {
972       return childrenList ;
973     }
974     if(!preferences_.isShowNonDocumentType()) {
975       List<String> documentTypes = templateService.getDocumentTemplates() ;
976       while(childrenIterator.hasNext()){
977         Node child = (Node)childrenIterator.next() ;
978         if(PermissionUtil.canRead(child)) {
979           NodeType type = child.getPrimaryNodeType() ;
980           String typeName = type.getName();
981           String primaryTypeName = typeName;
982 
983           if(typeName.equals(Utils.EXO_SYMLINK)) {
984             primaryTypeName = child.getProperty(Utils.EXO_PRIMARYTYPE).getString();
985           }
986           if(child.isNodeType(Utils.NT_UNSTRUCTURED) || child.isNodeType(Utils.NT_FOLDER)) {
987             childrenList.add(child) ;
988           } else if(typeName.equals(Utils.EXO_SYMLINK) &&
989               documentTypes.contains(primaryTypeName)) {
990             childrenList.add(child);
991           } else if(documentTypes.contains(typeName)) {
992             childrenList.add(child) ;
993           }
994         }
995       }
996     } else {
997       while(childrenIterator.hasNext()) {
998         Node child = (Node)childrenIterator.next() ;
999         if(PermissionUtil.canRead(child))  childrenList.add(child) ;
1000       }
1001     }
1002     List<Node> childList = new ArrayList<Node>() ;
1003     if(!preferences_.isShowHiddenNode()) {
1004       for(Node child : childrenList) {
1005         Node realChild = child instanceof NodeLinkAware ? ((NodeLinkAware) child).getRealNode() : child;
1006         if(PermissionUtil.canRead(child) && !realChild.isNodeType(Utils.EXO_HIDDENABLE)) {
1007           childList.add(child) ;
1008         }
1009       }
1010     } else {
1011       childList = childrenList ;
1012     }
1013     sort(childList);
1014     return childList ;
1015   }
1016 
1017   private void sort(List<Node> childrenList) {
1018     if (NodetypeConstant.SORT_BY_NODENAME.equals(preferences_.getSortType())) {
1019       Collections.sort(childrenList, new NodeTitleComparator(preferences_.getOrder())) ;
1020     } else if (NodetypeConstant.SORT_BY_NODETYPE.equals(preferences_.getSortType())) {
1021       Collections.sort(childrenList, new TypeNodeComparator(preferences_.getOrder())) ;
1022     } else if (NodetypeConstant.SORT_BY_NODESIZE.equals(preferences_.getSortType())) {
1023       Collections.sort(childrenList, new NodeSizeComparator(preferences_.getOrder())) ;
1024     } else if (NodetypeConstant.SORT_BY_VERSIONABLE.equals(preferences_.getSortType())) {
1025       Collections.sort(childrenList, new StringComparator(preferences_.getOrder(), NodetypeConstant.SORT_BY_VERSIONABLE));
1026     } else if (NodetypeConstant.SORT_BY_AUDITING.equals(preferences_.getSortType())) {
1027       Collections.sort(childrenList, new StringComparator(preferences_.getOrder(), NodetypeConstant.SORT_BY_AUDITING));
1028     } else if (NodetypeConstant.SORT_BY_CREATED_DATE.equals(preferences_.getSortType())) {
1029         Collections.sort(childrenList, new PropertyValueComparator(Utils.EXO_CREATED_DATE, preferences_.getOrder()));
1030     } else if (NodetypeConstant.SORT_BY_MODIFIED_DATE.equals(preferences_.getSortType())) {
1031         Collections.sort(childrenList, 
1032                          new PropertyValueComparator(NodetypeConstant.EXO_LAST_MODIFIED_DATE, preferences_.getOrder()));
1033     } else if (NodetypeConstant.SORT_BY_DATE.equals(preferences_.getSortType())) {
1034       Collections.sort(childrenList, new DateComparator(preferences_.getOrder()));
1035     } else {
1036       Collections.sort(childrenList, new PropertyValueComparator(preferences_.getSortType(), preferences_.getOrder()));
1037     }
1038   }
1039 
1040   public boolean isReferenceableNode(Node node) throws Exception {
1041     return node.isNodeType(Utils.MIX_REFERENCEABLE) ;
1042   }
1043 
1044   public boolean isPreferenceNode(Node node) {
1045     try {
1046       return (getCurrentNode().hasNode(node.getName())) ? false : true ;
1047     } catch(Exception e) {
1048       return false ;
1049     }
1050   }
1051 
1052   public Node getNodeByPath(String nodePath, Session session) throws Exception {
1053     return getNodeByPath(nodePath, session, true);
1054   }
1055 
1056   public Node getNodeByPath(String nodePath, Session session, boolean giveTarget) throws Exception {
1057     return getNodeByPath(nodePath.trim(), session, giveTarget, true);
1058   }
1059 
1060   private Node getNodeByPath(String nodePath, Session session, boolean giveTarget, boolean firstTime) throws Exception {
1061     NodeFinder nodeFinder = getApplicationComponent(NodeFinder.class);
1062     Node node = null;
1063     if (nodeFinder.itemExists(session, nodePath)) {
1064       node = (Node) nodeFinder.getItem(session, nodePath, giveTarget);
1065     } else {
1066       if (nodePath.equals(currentPath_) && !nodePath.equals(currentRootPath_)) {
1067         setCurrentPath(LinkUtils.getParentPath(currentPath_));
1068         return getNodeByPath(currentPath_, session, giveTarget, false);
1069       }
1070       try {
1071         if (nodeFinder.itemExists(session, nodePath)) {
1072           node = (Node) nodeFinder.getItem(session, nodePath, !giveTarget);
1073           return node;
1074         }
1075       } catch (Exception e3) {
1076         if (LOG.isWarnEnabled()) {
1077           LOG.warn(e3.getMessage());
1078         }
1079       }
1080       if (firstTime) {
1081         String workspace = session.getWorkspace().getName();
1082         if (LOG.isWarnEnabled()) {
1083           LOG.warn("The node cannot be found at " + nodePath
1084                   + " into the workspace " + workspace);
1085         }
1086       }
1087     }
1088 
1089     if (node != null && !firstTime) {
1090       refreshExplorer(node);
1091     }
1092     return node;
1093   }
1094 
1095   public void setTagPath(String tagPath) {
1096     if (tagPaths_.contains(tagPath)) {
1097       tagPaths_.remove(tagPath);
1098     } else {
1099       tagPaths_.add(tagPath);
1100     }
1101   }
1102 
1103   public Set<String> getTagPaths() {
1104     return tagPaths_;
1105   }
1106 
1107   public String getTagPath() {
1108     return tagPaths_.size() == 0 ? null : tagPaths_.iterator().next();
1109   }
1110 
1111   public void removeTagPath(String tagPath) {
1112     tagPaths_.remove(tagPath);
1113   }
1114 
1115   public List<Node> getDocumentByTag()throws Exception {
1116     NewFolksonomyService newFolksonomyService = getApplicationComponent(NewFolksonomyService.class) ;
1117     TemplateService templateService = getApplicationComponent(TemplateService.class) ;
1118     List<String> documentsType = templateService.getDocumentTemplates() ;
1119     List<Node> documentsOnTag = new ArrayList<Node>() ;
1120     WebuiRequestContext ctx = WebuiRequestContext.getCurrentInstance();
1121     SessionProvider sessionProvider = (ctx.getRemoteUser() == null) ?
1122                                                                      WCMCoreUtils.createAnonimProvider() :
1123                                                                        WCMCoreUtils.getUserSessionProvider();
1124                                                                      
1125                                                                      for (Node node : newFolksonomyService.getAllDocumentsByTagsAndPath(getCurrentPath(),
1126                                                                                                                                          tagPaths_,
1127                                                                                                                                          getRepository().getConfiguration().getDefaultWorkspaceName(),
1128                                                                                                                                          sessionProvider)) {
1129                                                                        if (documentsType.contains(node.getPrimaryNodeType().getName())
1130                                                                            && PermissionUtil.canRead(node)) {
1131                                                                          documentsOnTag.add(node);
1132                                                                        }
1133                                                                      }
1134                                                                      return documentsOnTag ;
1135   }
1136 
1137   public void setIsViewTag(boolean isViewTag) {
1138     isViewTag_ = isViewTag;
1139     if (!isViewTag_) {
1140       tagPaths_.clear();
1141     }
1142   }
1143 
1144   public boolean isViewTag() { return isViewTag_ ; }
1145 
1146   public PortletPreferences getPortletPreferences() { return pref_ ; }
1147 
1148   public boolean isReadAuthorized(ExtendedNode node) throws RepositoryException {
1149     try {
1150       node.checkPermission(PermissionType.READ);
1151       return true;
1152     } catch(AccessControlException e) {
1153       return false;
1154     }
1155   }
1156 
1157   public static Cookie getCookieByCookieName(String cookieName, Cookie[] cookies) {
1158     String userId = Util.getPortalRequestContext().getRemoteUser();
1159     cookieName += userId;
1160     for(int loopIndex = 0; loopIndex < cookies.length; loopIndex++) {
1161       Cookie cookie1 = cookies[loopIndex];
1162       if (cookie1.getName().equals(cookieName)) return cookie1;
1163     }
1164     return null;
1165   }
1166 
1167   public Preference getPreference() {
1168     if (preferencesSaved_) {
1169       if (preferences_ != null && !this.getAncestorOfType(UIJCRExplorerPortlet.class).isShowSideBar())
1170         preferences_.setShowSideBar(false);
1171       return preferences_;
1172     }
1173     HttpServletRequest request = Util.getPortalRequestContext().getRequest();
1174     Cookie[] cookies = request.getCookies();
1175     Cookie getCookieForUser;
1176     getCookieForUser = getCookieByCookieName(Preference.PREFERENCE_ENABLESTRUCTURE, cookies);
1177     if ((getCookieForUser != null) && (preferences_ != null)) {
1178       if (getCookieForUser.getValue().equals("true"))
1179         preferences_.setJcrEnable(true);
1180       else
1181         preferences_.setJcrEnable(false);
1182     }
1183     getCookieForUser = getCookieByCookieName(Preference.PREFERENCE_SHOWSIDEBAR, cookies);
1184     if ((getCookieForUser != null) && (preferences_ != null)) {
1185       if (getCookieForUser.getValue().equals("true"))
1186         preferences_.setShowSideBar(true);
1187       else
1188         preferences_.setShowSideBar(false);
1189     }
1190     if (preferences_ != null && !this.getAncestorOfType(UIJCRExplorerPortlet.class).isShowSideBar())
1191       preferences_.setShowSideBar(false);
1192     getCookieForUser = getCookieByCookieName(Preference.SHOW_NON_DOCUMENTTYPE, cookies);
1193     if ((getCookieForUser != null) && (preferences_ != null)) {
1194       if (getCookieForUser.getValue().equals("true"))
1195         preferences_.setShowNonDocumentType(true);
1196       else
1197         preferences_.setShowNonDocumentType(false);
1198     }
1199     getCookieForUser = getCookieByCookieName(Preference.PREFERENCE_SHOWREFDOCUMENTS, cookies);
1200     if ((getCookieForUser != null) && (preferences_ != null)) {
1201       if (getCookieForUser.getValue().equals("true"))
1202         preferences_.setShowPreferenceDocuments(true);
1203       else
1204         preferences_.setShowPreferenceDocuments(false);
1205     }
1206     getCookieForUser = getCookieByCookieName(Preference.PREFERENCE_SHOW_HIDDEN_NODE, cookies);
1207     if ((getCookieForUser != null) && (preferences_ != null)) {
1208       if (getCookieForUser.getValue().equals("true"))
1209         preferences_.setShowHiddenNode(true);
1210       else
1211         preferences_.setShowHiddenNode(false);
1212     }
1213     getCookieForUser = getCookieByCookieName(Preference.ENABLE_DRAG_AND_DROP, cookies);
1214     if ((getCookieForUser != null) && (preferences_ != null)) {
1215       if (getCookieForUser.getValue().equals("true"))
1216         preferences_.setEnableDragAndDrop(true);
1217       else
1218         preferences_.setEnableDragAndDrop(false);
1219     }
1220     getCookieForUser = getCookieByCookieName(Preference.PREFERENCE_QUERY_TYPE, cookies);
1221     if ((getCookieForUser != null) && (preferences_ != null)) preferences_.setQueryType(getCookieForUser.getValue());
1222     getCookieForUser = getCookieByCookieName(Preference.PREFERENCE_SORT_BY, cookies);
1223     if ((getCookieForUser != null) && (preferences_ != null)) preferences_.setSortType(getCookieForUser.getValue());
1224     getCookieForUser = getCookieByCookieName(Preference.PREFERENCE_ORDER_BY, cookies);
1225     if ((getCookieForUser != null) && (preferences_ != null)) preferences_.setOrder(getCookieForUser.getValue());
1226     getCookieForUser = getCookieByCookieName(Preference.NODES_PER_PAGE, cookies);
1227     if ((getCookieForUser != null) && (preferences_ != null))
1228       preferences_.setNodesPerPage(Integer.parseInt(getCookieForUser.getValue()));
1229 
1230     return preferences_;
1231   }
1232   public void setPreferences(Preference preference) {this.preferences_ = preference; }
1233 
1234   public void closeEditingFile() throws Exception {
1235 
1236     UIPopupContainer uiPopupContainer = this.getChild(UIPopupContainer.class);
1237     UIPopupWindow uiPopup = uiPopupContainer.getChild(UIPopupWindow.class);
1238 
1239     UIWorkingArea uiWorkingArea = this.getChild(UIWorkingArea.class);
1240     UIDocumentWorkspace uiDocumentWorkspace = uiWorkingArea.getChild(UIDocumentWorkspace.class);
1241 
1242     //check if edit with popup
1243     UIComponent uiComp = uiPopup.getUIComponent();
1244     if (uiComp instanceof UIDocumentFormController && ((UIDocumentFormController)uiComp).isRendered()) {
1245       uiPopupContainer.deActivate();
1246       this.refreshExplorer();
1247       return;
1248     }
1249 
1250     //check if edit without popup
1251     if (uiDocumentWorkspace.isRendered()) {
1252       UIDocumentFormController controller = uiDocumentWorkspace.getChild(UIDocumentFormController.class);
1253       if (controller != null) {
1254         uiDocumentWorkspace.removeChild(UIDocumentFormController.class).deActivate();
1255         uiDocumentWorkspace.setRenderedChild(UIDocumentContainer.class);
1256         this.refreshExplorer();
1257       }
1258     }
1259   }
1260 
1261   public static class HistoryEntry {
1262     private final String workspace;
1263     private final String path;
1264 
1265     private HistoryEntry(String workspace, String path) {
1266       this.workspace = workspace;
1267       this.path = path;
1268     }
1269 
1270     public String getWorkspace() {
1271       return workspace;
1272     }
1273 
1274     public String getPath() {
1275       return path;
1276     }
1277   }
1278 
1279 }