053afd3ee4e9eaec5785a8d367c0ab789b1e6033
[pithos-web-client] / src / gr / grnet / pithos / web / client / Pithos.java
1 /*
2  * Copyright 2011-2013 GRNET S.A. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or
5  * without modification, are permitted provided that the following
6  * conditions are met:
7  *
8  *   1. Redistributions of source code must retain the above
9  *      copyright notice, this list of conditions and the following
10  *      disclaimer.
11  *
12  *   2. Redistributions in binary form must reproduce the above
13  *      copyright notice, this list of conditions and the following
14  *      disclaimer in the documentation and/or other materials
15  *      provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
18  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
21  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
24  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  *
30  * The views and conclusions contained in the software and
31  * documentation are those of the authors and should not be
32  * interpreted as representing official policies, either expressed
33  * or implied, of GRNET S.A.
34  */
35 package gr.grnet.pithos.web.client;
36
37 import com.google.gwt.core.client.EntryPoint;
38 import com.google.gwt.core.client.GWT;
39 import com.google.gwt.core.client.JsArrayString;
40 import com.google.gwt.core.client.Scheduler;
41 import com.google.gwt.core.client.Scheduler.RepeatingCommand;
42 import com.google.gwt.core.client.Scheduler.ScheduledCommand;
43 import com.google.gwt.event.dom.client.ClickEvent;
44 import com.google.gwt.event.dom.client.ClickHandler;
45 import com.google.gwt.event.logical.shared.ResizeEvent;
46 import com.google.gwt.event.logical.shared.ResizeHandler;
47 import com.google.gwt.http.client.Response;
48 import com.google.gwt.http.client.URL;
49 import com.google.gwt.i18n.client.DateTimeFormat;
50 import com.google.gwt.i18n.client.Dictionary;
51 import com.google.gwt.i18n.client.TimeZone;
52 import com.google.gwt.resources.client.ClientBundle;
53 import com.google.gwt.resources.client.CssResource;
54 import com.google.gwt.resources.client.ImageResource;
55 import com.google.gwt.resources.client.ImageResource.ImageOptions;
56 import com.google.gwt.user.client.*;
57 import com.google.gwt.user.client.ui.*;
58 import com.google.gwt.view.client.SelectionChangeEvent;
59 import com.google.gwt.view.client.SelectionChangeEvent.Handler;
60 import com.google.gwt.view.client.SingleSelectionModel;
61 import gr.grnet.pithos.web.client.catalog.UpdateUserCatalogs;
62 import gr.grnet.pithos.web.client.catalog.UserCatalogs;
63 import gr.grnet.pithos.web.client.commands.UploadFileCommand;
64 import gr.grnet.pithos.web.client.foldertree.*;
65 import gr.grnet.pithos.web.client.grouptree.Group;
66 import gr.grnet.pithos.web.client.grouptree.GroupTreeView;
67 import gr.grnet.pithos.web.client.grouptree.GroupTreeViewModel;
68 import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeView;
69 import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeViewModel;
70 import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeView;
71 import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeViewModel;
72 import gr.grnet.pithos.web.client.rest.*;
73 import org.apache.http.HttpStatus;
74
75 import java.util.*;
76
77 /**
78  * Entry point classes define <code>onModuleLoad()</code>.
79  */
80 public class Pithos implements EntryPoint, ResizeHandler {
81     private static final boolean IsLOGEnabled = false;
82     public static final boolean IsDetailedHTTPLOGEnabled = true;
83     public static final boolean IsFullResponseBodyLOGEnabled = true;
84     private static final boolean EnableScheduledRefresh = true; // Make false only for debugging purposes.
85
86     public static final Set<String> HTTPHeadersToIgnoreInLOG = new HashSet<String>();
87     static {
88         HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_CONNECTION);
89         HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_DATE);
90         HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_KEEP_ALIVE);
91         HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_SERVER);
92         HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_VARY);
93         HTTPHeadersToIgnoreInLOG.add(Const.IF_MODIFIED_SINCE);
94     }
95
96     public static final Configuration config = GWT.create(Configuration.class);
97     public static final String CONFIG_API_PATH = config.apiPath();
98     static {
99         LOG("CONFIG_API_PATH = ", CONFIG_API_PATH);
100     }
101
102     public static final Dictionary otherProperties = Dictionary.getDictionary(Const.OTHER_PROPERTIES);
103     public static String getFromOtherPropertiesOrDefault(String key, String def) {
104         try {
105             final String value = otherProperties.get(key);
106             return value == null ? def : value;
107         }
108         catch(Exception e) {
109             return def;
110         }
111     }
112
113     public static String getFromOtherPropertiesOrNull(String key) {
114         return getFromOtherPropertiesOrDefault(key, null);
115     }
116
117     private static final boolean SHOW_COPYRIGHT;
118     static {
119         final String valueStr = getFromOtherPropertiesOrDefault("SHOW_COPYRIGHT", "true").trim().toLowerCase();
120         SHOW_COPYRIGHT = "true".equals(valueStr);
121         LOG("SHOW_COPYRIGHT = '", valueStr, "' ==> ", SHOW_COPYRIGHT);
122     }
123
124     public static final String OTHERPROPS_STORAGE_API_URL = getFromOtherPropertiesOrNull("STORAGE_API_URL");
125     public static final String OTHERPROPS_USER_CATALOGS_API_URL = getFromOtherPropertiesOrNull("USER_CATALOGS_API_URL");
126     static {
127         LOG("STORAGE_API_URL = ", OTHERPROPS_STORAGE_API_URL);
128         LOG("USER_CATALOGS_API_URL = ", OTHERPROPS_USER_CATALOGS_API_URL);
129     }
130
131     public static final String STORAGE_API_URL;
132     static {
133         if(OTHERPROPS_STORAGE_API_URL != null) {
134             STORAGE_API_URL = OTHERPROPS_STORAGE_API_URL;
135         }
136         else if(CONFIG_API_PATH != null) {
137             STORAGE_API_URL = CONFIG_API_PATH;
138         }
139         else {
140             throw new RuntimeException("Unknown STORAGE_API_URL");
141         }
142
143         LOG("Computed STORAGE_API_URL = ", STORAGE_API_URL);
144     }
145
146     public static final String STORAGE_VIEW_URL;
147     static {
148         final String viewURL = getFromOtherPropertiesOrNull("STORAGE_VIEW_URL");
149         if(viewURL != null) {
150             STORAGE_VIEW_URL = viewURL;
151         }
152         else {
153             STORAGE_VIEW_URL = STORAGE_API_URL;
154         }
155
156         LOG("Computed STORAGE_VIEW_URL = ", STORAGE_VIEW_URL);
157     }
158
159     public static final String PUBLIC_LINK_VIEW_PREFIX = getFromOtherPropertiesOrDefault("PUBLIC_LINK_VIEW_PREFIX", "");
160
161     public static final String USER_CATALOGS_API_URL;
162     static {
163         if(OTHERPROPS_USER_CATALOGS_API_URL != null) {
164             USER_CATALOGS_API_URL = OTHERPROPS_USER_CATALOGS_API_URL;
165         }
166         else if(OTHERPROPS_STORAGE_API_URL != null) {
167             throw new RuntimeException("STORAGE_API_URL is defined but USER_CATALOGS_API_URL is not");
168         }
169         else {
170             // https://server.com/v1/ --> https://server.com
171             String url = CONFIG_API_PATH;
172             url = Helpers.stripTrailing(url, "/");
173             url = Helpers.upToIncludingLastPart(url, "/");
174             url = Helpers.stripTrailing(url, "/");
175             url = url + "/user_catalogs";
176
177             USER_CATALOGS_API_URL = url;
178
179             LOG("Computed USER_CATALOGS_API_URL = ", USER_CATALOGS_API_URL);
180         }
181     }
182
183     public interface Style extends CssResource {
184         String commandAnchor();
185
186         String statistics();
187
188         @ClassName("gwt-HTML")
189         String html();
190
191         String uploadAlert();
192
193         String uploadAlertLink();
194
195         String uploadAlertProgress();
196
197         String uploadAlertPercent();
198
199         String uploadAlertClose();
200     }
201
202     public interface Resources extends ClientBundle {
203         @Source("Pithos.css")
204         Style pithosCss();
205
206         @Source("gr/grnet/pithos/resources/close-popup.png")
207         ImageResource closePopup();
208     }
209
210     public static Resources resources = GWT.create(Resources.class);
211
212     /**
213      * Instantiate an application-level image bundle. This object will provide
214      * programmatic access to all the images needed by widgets.
215      */
216     static Images images = (Images) GWT.create(Images.class);
217
218     public String getUserID() {
219         return userID;
220     }
221
222     public UserCatalogs getUserCatalogs() {
223         return userCatalogs;
224     }
225
226     public String getCurrentUserDisplayNameOrID() {
227         final String displayName = userCatalogs.getDisplayName(getUserID());
228         return displayName == null ? getUserID() : displayName;
229     }
230
231     public boolean hasDisplayNameForUserID(String userID) {
232         return userCatalogs.getDisplayName(userID) != null;
233     }
234
235     public boolean hasIDForUserDisplayName(String userDisplayName) {
236         return userCatalogs.getID(userDisplayName) != null;
237     }
238
239     public String getDisplayNameForUserID(String userID) {
240         return userCatalogs.getDisplayName(userID);
241     }
242
243     public String getIDForUserDisplayName(String userDisplayName) {
244         return userCatalogs.getID(userDisplayName);
245     }
246
247     public List<String> getDisplayNamesForUserIDs(List<String> userIDs) {
248         if(userIDs == null) {
249             userIDs = new ArrayList<String>();
250         }
251         final List<String> userDisplayNames = new ArrayList<String>();
252         for(String userID : userIDs) {
253             final String displayName = getDisplayNameForUserID(userID);
254             userDisplayNames.add(displayName);
255         }
256
257         return userDisplayNames;
258     }
259
260     public List<String> filterUserIDsWithUnknownDisplayName(Collection<String> userIDs) {
261         if(userIDs == null) {
262             userIDs = new ArrayList<String>();
263         }
264         final List<String> filtered = new ArrayList<String>();
265         for(String userID : userIDs) {
266             if(!this.userCatalogs.hasID(userID)) {
267                 filtered.add(userID);
268             }
269         }
270         return filtered;
271     }
272
273     public void setAccount(AccountResource acct) {
274         account = acct;
275     }
276
277     public AccountResource getAccount() {
278         return account;
279     }
280
281     public void updateFolder(Folder f, boolean showfiles, Command callback, final boolean openParent) {
282         folderTreeView.updateFolder(f, showfiles, callback, openParent);
283     }
284
285     public void updateGroupNode(Group group) {
286         groupTreeView.updateGroupNode(group);
287     }
288
289     public void updateMySharedRoot() {
290         mysharedTreeView.updateRoot();
291     }
292
293     public void updateSharedFolder(Folder f, boolean showfiles, Command callback) {
294         mysharedTreeView.updateFolder(f, showfiles, callback);
295     }
296
297     public void updateSharedFolder(Folder f, boolean showfiles) {
298         updateSharedFolder(f, showfiles, null);
299     }
300
301     public void updateOtherSharedFolder(Folder f, boolean showfiles, Command callback) {
302         otherSharedTreeView.updateFolder(f, showfiles, callback);
303     }
304
305     public MysharedTreeView getMySharedTreeView() {
306         return mysharedTreeView;
307     }
308
309     /**
310      * An aggregate image bundle that pulls together all the images for this
311      * application into a single bundle.
312      */
313     public interface Images extends TopPanel.Images, FileList.Images, ToolsMenu.Images {
314
315         @Source("gr/grnet/pithos/resources/document.png")
316         ImageResource folders();
317
318         @Source("gr/grnet/pithos/resources/advancedsettings.png")
319         @ImageOptions(width = 32, height = 32)
320         ImageResource tools();
321     }
322
323     private Throwable error;
324
325     /**
326      * The Application Clipboard implementation;
327      */
328     private Clipboard clipboard = new Clipboard();
329
330     /**
331      * The top panel that contains the menu bar.
332      */
333     private TopPanel topPanel;
334
335     /**
336      * The panel that contains the various system messages.
337      */
338     private MessagePanel messagePanel = new MessagePanel(this, Pithos.images);
339
340     /**
341      * The bottom panel that contains the status bar.
342      */
343     StatusPanel statusPanel = null;
344
345     /**
346      * The file list widget.
347      */
348     private FileList fileList;
349
350     /**
351      * The tab panel that occupies the right side of the screen.
352      */
353     private VerticalPanel inner = new VerticalPanel();
354
355
356     /**
357      * The split panel that will contain the left and right panels.
358      */
359     private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
360
361     /**
362      * The currently selected item in the application, for use by the Edit menu
363      * commands. Potential types are Folder, File, User and Group.
364      */
365     private Object currentSelection;
366
367     public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
368
369     /**
370      * The ID that uniquely identifies the user in Pithos+.
371      * Currently this is a UUID. It used to be the user's email.
372      */
373     private String userID = null;
374
375     /**
376      * Holds mappings from user UUIDs to emails and vice-versa.
377      */
378     private UserCatalogs userCatalogs = new UserCatalogs();
379
380     /**
381      * The authentication token of the current user.
382      */
383     private String userToken;
384
385     VerticalPanel trees;
386
387     SingleSelectionModel<Folder> folderTreeSelectionModel;
388     FolderTreeViewModel folderTreeViewModel;
389     FolderTreeView folderTreeView;
390
391     SingleSelectionModel<Folder> mysharedTreeSelectionModel;
392     MysharedTreeViewModel mysharedTreeViewModel;
393     MysharedTreeView mysharedTreeView = null;
394
395     protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
396     OtherSharedTreeViewModel otherSharedTreeViewModel;
397     OtherSharedTreeView otherSharedTreeView = null;
398
399     GroupTreeViewModel groupTreeViewModel;
400     GroupTreeView groupTreeView;
401
402     TreeView selectedTree;
403     protected AccountResource account;
404
405     Folder trash;
406
407     List<Composite> treeViews = new ArrayList<Composite>();
408
409     @SuppressWarnings("rawtypes")
410     List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
411
412     public Button upload;
413
414     private HTML numOfFiles;
415
416     private Toolbar toolbar;
417
418     private FileUploadDialog fileUploadDialog = new FileUploadDialog(this);
419
420     UploadAlert uploadAlert;
421
422     Date lastModified;
423
424     @Override
425     public void onModuleLoad() {
426         if(parseUserCredentials()) {
427             initialize();
428         }
429     }
430
431     static native void __ConsoleLog(String message) /*-{
432       try { console.log(message); } catch (e) {}
433     }-*/;
434
435     public static void LOGError(Throwable error, StringBuilder sb) {
436         if(!isLOGEnabled()) { return; }
437
438         sb.append("\nException: [" + error.toString().replace("\n", "\n  ") + "]");
439         Throwable cause = error.getCause();
440         if(cause != null) {
441             sb.append("\nCauses:\n");
442             while(cause != null) {
443                 sb.append("  ");
444                 sb.append("[" + cause.toString().replace("\n", "\n  ")  + "]");
445                 sb.append("\n");
446                 cause = cause.getCause();
447             }
448         }
449         else {
450             sb.append("\n");
451         }
452
453         StackTraceElement[] stackTrace = error.getStackTrace();
454         sb.append("Stack trace (" + stackTrace.length + " elements):\n");
455         for(int i = 0; i < stackTrace.length; i++) {
456             StackTraceElement errorElem = stackTrace[i];
457             sb.append("  [" + i + "] ");
458             sb.append(errorElem.toString());
459             sb.append("\n");
460         }
461     }
462
463     public static void LOGError(Throwable error) {
464         if(!isLOGEnabled()) { return; }
465
466         final StringBuilder sb = new StringBuilder();
467         LOGError(error, sb);
468         if(sb.length() > 0) {
469             __ConsoleLog(sb.toString());
470         }
471     }
472
473     public static boolean isLOGEnabled() {
474         return IsLOGEnabled;
475     }
476
477     public static void LOG(Object ...args) {
478         if(!isLOGEnabled()) { return; }
479
480         final StringBuilder sb = new StringBuilder();
481         for(Object arg : args) {
482             if(arg instanceof Throwable) {
483                 LOGError((Throwable) arg, sb);
484             }
485             else {
486                 sb.append(arg);
487             }
488         }
489
490         if(sb.length() > 0) {
491             __ConsoleLog(sb.toString());
492         }
493     }
494
495     private void initialize() {
496         userCatalogs.updateWithIDAndName("*", "All Pithos users");
497
498         lastModified = new Date(); //Initialize if-modified-since value with now.
499         resources.pithosCss().ensureInjected();
500         boolean bareContent = Window.Location.getParameter("noframe") != null;
501         String contentWidth = bareContent ? Const.PERCENT_100 : Const.PERCENT_75;
502
503         VerticalPanel outer = new VerticalPanel();
504         outer.setWidth(Const.PERCENT_100);
505         if(!bareContent) {
506             outer.addStyleName("pithos-outer");
507         }
508
509         if(!bareContent) {
510             topPanel = new TopPanel(this, Pithos.images);
511             topPanel.setWidth(Const.PERCENT_100);
512             outer.add(topPanel);
513             outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
514         }
515
516         messagePanel.setVisible(false);
517         outer.add(messagePanel);
518         outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
519         outer.setCellVerticalAlignment(messagePanel, HasVerticalAlignment.ALIGN_MIDDLE);
520
521         HorizontalPanel header = new HorizontalPanel();
522         header.addStyleName("pithos-header");
523         header.setWidth(contentWidth);
524         if(bareContent) {
525             header.addStyleName("pithos-header-noframe");
526         }
527         upload = new Button("Upload", new ClickHandler() {
528             @Override
529             public void onClick(ClickEvent event) {
530                 if(getSelection() != null) {
531                     new UploadFileCommand(Pithos.this, null, getSelection()).execute();
532                 }
533             }
534         });
535         upload.addStyleName("pithos-uploadButton");
536         header.add(upload);
537         header.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_LEFT);
538         header.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
539
540         toolbar = new Toolbar(this);
541         header.add(toolbar);
542         header.setCellHorizontalAlignment(toolbar, HasHorizontalAlignment.ALIGN_CENTER);
543         header.setCellVerticalAlignment(toolbar, HasVerticalAlignment.ALIGN_MIDDLE);
544
545         HorizontalPanel folderStatistics = new HorizontalPanel();
546         folderStatistics.addStyleName("pithos-folderStatistics");
547         numOfFiles = new HTML();
548         folderStatistics.add(numOfFiles);
549         folderStatistics.setCellVerticalAlignment(numOfFiles, HasVerticalAlignment.ALIGN_MIDDLE);
550         HTML numOfFilesLabel = new HTML("&nbsp;Files");
551         folderStatistics.add(numOfFilesLabel);
552         folderStatistics.setCellVerticalAlignment(numOfFilesLabel, HasVerticalAlignment.ALIGN_MIDDLE);
553         header.add(folderStatistics);
554         header.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
555         header.setCellVerticalAlignment(folderStatistics, HasVerticalAlignment.ALIGN_MIDDLE);
556         header.setCellWidth(folderStatistics, "40px");
557         outer.add(header);
558         outer.setCellHorizontalAlignment(header, HasHorizontalAlignment.ALIGN_CENTER);
559         // Inner contains the various lists
560         inner.sinkEvents(Event.ONCONTEXTMENU);
561         inner.setWidth(Const.PERCENT_100);
562
563         folderTreeSelectionModel = new SingleSelectionModel<Folder>();
564         folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
565             @Override
566             public void onSelectionChange(SelectionChangeEvent event) {
567                 if(folderTreeSelectionModel.getSelectedObject() != null) {
568                     deselectOthers(folderTreeView, folderTreeSelectionModel);
569                     applyPermissions(folderTreeSelectionModel.getSelectedObject());
570                     Folder f = folderTreeSelectionModel.getSelectedObject();
571                     updateFolder(f, true, new Command() {
572
573                         @Override
574                         public void execute() {
575                             updateStatistics();
576                         }
577                     }, true);
578                     showRelevantToolbarButtons();
579                 }
580                 else {
581                     if(getSelectedTree().equals(folderTreeView)) {
582                         setSelectedTree(null);
583                     }
584                     if(getSelectedTree() == null) {
585                         showRelevantToolbarButtons();
586                     }
587                 }
588             }
589         });
590         selectionModels.add(folderTreeSelectionModel);
591
592         folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
593         folderTreeView = new FolderTreeView(folderTreeViewModel);
594         treeViews.add(folderTreeView);
595
596         fileList = new FileList(this, images);
597         inner.add(fileList);
598
599         trees = new VerticalPanel();
600         trees.setWidth(Const.PERCENT_100);
601
602         // Add the left and right panels to the split panel.
603         splitPanel.setLeftWidget(trees);
604         FlowPanel right = new FlowPanel();
605         right.getElement().setId("rightPanel");
606         right.add(inner);
607         splitPanel.setRightWidget(right);
608         splitPanel.setSplitPosition("219px");
609         splitPanel.setSize(Const.PERCENT_100, Const.PERCENT_100);
610         splitPanel.addStyleName("pithos-splitPanel");
611         splitPanel.setWidth(contentWidth);
612         outer.add(splitPanel);
613         outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
614
615         if(!bareContent) {
616             statusPanel = new StatusPanel();
617             statusPanel.setWidth(Const.PERCENT_100);
618             outer.add(statusPanel);
619             outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
620         }
621         else {
622             splitPanel.addStyleName("pithos-splitPanel-noframe");
623         }
624
625         // Hook the window resize event, so that we can adjust the UI.
626         Window.addResizeHandler(this);
627         // Clear out the window's built-in margin, because we want to take
628         // advantage of the entire client area.
629         Window.setMargin("0px");
630         // Finally, add the outer panel to the RootPanel, so that it will be
631         // displayed.
632         RootPanel.get().add(outer);
633         // Call the window resized handler to get the initial sizes setup. Doing
634         // this in a deferred command causes it to occur after all widgets'
635         // sizes have been computed by the browser.
636         Scheduler.get().scheduleIncremental(new RepeatingCommand() {
637
638             @Override
639             public boolean execute() {
640                 if(!isCloudbarReady()) {
641                     return true;
642                 }
643                 onWindowResized(Window.getClientHeight());
644                 return false;
645             }
646         });
647
648         Scheduler.get().scheduleDeferred(new ScheduledCommand() {
649             @Override
650             public void execute() {
651                 LOG("Pithos::initialize() Calling Pithos::fetchAccount()");
652                 fetchAccount(new Command() {
653
654                     @Override
655                     public void execute() {
656                         if(!account.hasHomeContainer()) {
657                             createHomeContainer(account, this);
658                         }
659                         else if(!account.hasTrashContainer()) {
660                             createTrashContainer(this);
661                         }
662                         else {
663                             for(Folder f : account.getContainers()) {
664                                 if(f.getName().equals(Const.TRASH_CONTAINER)) {
665                                     trash = f;
666                                     break;
667                                 }
668                             }
669                             trees.add(folderTreeView);
670                             folderTreeViewModel.initialize(account, new Command() {
671
672                                 @Override
673                                 public void execute() {
674                                     createMySharedTree();
675                                 }
676                             });
677
678                             HorizontalPanel separator = new HorizontalPanel();
679                             separator.addStyleName("pithos-statisticsSeparator");
680                             separator.add(new HTML(""));
681                             trees.add(separator);
682
683                             groupTreeViewModel = new GroupTreeViewModel(Pithos.this);
684                             groupTreeView = new GroupTreeView(groupTreeViewModel);
685                             treeViews.add(groupTreeView);
686                             trees.add(groupTreeView);
687                             folderTreeView.showStatistics(account);
688                         }
689                     }
690                 });
691             }
692         });
693     }
694
695     public void scheduleRefresh() {
696         if(!Pithos.EnableScheduledRefresh) { return; }
697
698         Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {
699
700             @Override
701             public boolean execute() {
702                 final Folder f = getSelection();
703                 if(f == null) {
704                     return true;
705                 }
706
707                 HeadRequest<Folder> head = new HeadRequest<Folder>(Folder.class, getStorageAPIURL(), f.getOwnerID(), "/" + f.getContainer()) {
708
709                     @Override
710                     public void onSuccess(Folder _result) {
711                         lastModified = new Date();
712                         if(getSelectedTree().equals(folderTreeView)) {
713                             updateFolder(f, true, new Command() {
714
715                                 @Override
716                                 public void execute() {
717                                     scheduleRefresh();
718                                 }
719
720                             }, false);
721                         }
722                         else if(getSelectedTree().equals(mysharedTreeView)) {
723                             updateSharedFolder(f, true, new Command() {
724
725                                 @Override
726                                 public void execute() {
727                                     scheduleRefresh();
728                                 }
729                             });
730                         }
731                         else {
732                             scheduleRefresh();
733                         }
734                     }
735
736                     @Override
737                     public void onError(Throwable t) {
738                         if(t instanceof RestException && ((RestException) t).getHttpStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
739                             scheduleRefresh();
740                         }
741                         else if(retries >= MAX_RETRIES) {
742                             LOG("Error heading folder. ", t);
743                             setError(t);
744                             if(t instanceof RestException) {
745                                 displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
746                             }
747                             else {
748                                 displayError("System error heading folder: " + t.getMessage());
749                             }
750                         }
751                         else {//retry
752                             LOG("Retry ", retries);
753                             Scheduler.get().scheduleDeferred(this);
754                         }
755                     }
756
757                     @Override
758                     protected void onUnauthorized(Response response) {
759                         if(retries >= MAX_RETRIES) {
760                             sessionExpired();
761                         }
762                         else //retry
763                         {
764                             Scheduler.get().scheduleDeferred(this);
765                         }
766                     }
767                 };
768                 head.setHeader(Const.X_AUTH_TOKEN, getUserToken());
769                 head.setHeader(Const.IF_MODIFIED_SINCE, DateTimeFormat.getFormat(Const.DATE_FORMAT_1).format(lastModified, TimeZone.createTimeZone(0)) + " GMT");
770                 Scheduler.get().scheduleDeferred(head);
771
772                 return false;
773             }
774         }, 3000);
775     }
776
777     public void applyPermissions(Folder f) {
778         if(f != null) {
779             if(f.isInTrash()) {
780                 upload.setEnabled(false);
781                 disableUploadArea();
782             }
783             else {
784                 Boolean[] perms = f.getPermissions().get(userID);
785                 if(f.getOwnerID().equals(userID) || (perms != null && perms[1] != null && perms[1])) {
786                     upload.setEnabled(true);
787                     enableUploadArea();
788                 }
789                 else {
790                     upload.setEnabled(false);
791                     disableUploadArea();
792                 }
793             }
794         }
795         else {
796             upload.setEnabled(false);
797             disableUploadArea();
798         }
799     }
800
801     @SuppressWarnings({"rawtypes", "unchecked"})
802     public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
803         selectedTree = _selectedTree;
804
805         for(SingleSelectionModel s : selectionModels) {
806             if(!s.equals(model) && s.getSelectedObject() != null) {
807                 s.setSelected(s.getSelectedObject(), false);
808             }
809         }
810     }
811
812     public void showFiles(final Folder f) {
813         Set<File> files = f.getFiles();
814         showFiles(files);
815     }
816
817     public void showFiles(Set<File> files) {
818         fileList.setFiles(new ArrayList<File>(files));
819     }
820
821     /**
822      * Parse and store the user credentials to the appropriate fields.
823      */
824     private boolean parseUserCredentials() {
825         final String cookie = otherProperties.get(Const.AUTH_COOKIE);
826         String auth = Cookies.getCookie(cookie);
827         if(auth == null) {
828             authenticateUser();
829             return false;
830         }
831         if(auth.startsWith("\"")) {
832             auth = auth.substring(1);
833         }
834         if(auth.endsWith("\"")) {
835             auth = auth.substring(0, auth.length() - 1);
836         }
837         String[] authSplit = auth.split("\\" + config.cookieSeparator(), 2);
838         if(authSplit.length != 2) {
839             authenticateUser();
840             return false;
841         }
842         this.userID = authSplit[0];
843         this.userToken = authSplit[1];
844
845         return true;
846     }
847
848     /**
849      * Redirect the user to the login page for authentication.
850      */
851     protected void authenticateUser() {
852         Dictionary otherProperties = Dictionary.getDictionary(Const.OTHER_PROPERTIES);
853         Window.Location.assign(otherProperties.get(Const.LOGIN_URL) + Window.Location.getHref());
854     }
855
856     public void fetchAccount(final Command callback) {
857         String path = "?format=json";
858
859         GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getStorageAPIURL(), userID, path) {
860             @Override
861             public void onSuccess(AccountResource accountResource) {
862                 account = accountResource;
863                 if(callback != null) {
864                     callback.execute();
865                 }
866
867                 final List<String> memberIDs = new ArrayList<String>();
868                 final List<Group> groups = account.getGroups();
869                 for(Group group : groups) {
870                     memberIDs.addAll(group.getMemberIDs());
871                 }
872                 memberIDs.add(Pithos.this.getUserID());
873
874                 final List<String> theUnknown = Pithos.this.filterUserIDsWithUnknownDisplayName(memberIDs);
875                 // Initialize the user catalog
876                 new UpdateUserCatalogs(Pithos.this, theUnknown).scheduleDeferred();
877                 LOG("Called new UpdateUserCatalogs(Pithos.this, theUnknown).scheduleDeferred();");
878             }
879
880             @Override
881             public void onError(Throwable t) {
882                 LOG("Error getting account", t);
883                 setError(t);
884                 if(t instanceof RestException) {
885                     displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
886                 }
887                 else {
888                     displayError("System error fetching user data: " + t.getMessage());
889                 }
890             }
891
892             @Override
893             protected void onUnauthorized(Response response) {
894                 sessionExpired();
895             }
896         };
897         getAccount.setHeader(Const.X_AUTH_TOKEN, userToken);
898         Scheduler.get().scheduleDeferred(getAccount);
899     }
900
901     public void updateStatistics() {
902         HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getStorageAPIURL(), userID, "", account) {
903
904             @Override
905             public void onSuccess(AccountResource _result) {
906                 folderTreeView.showStatistics(account);
907             }
908
909             @Override
910             public void onError(Throwable t) {
911                 LOG("Error getting account", t);
912                 setError(t);
913                 if(t instanceof RestException) {
914                     displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
915                 }
916                 else {
917                     displayError("System error fetching user data: " + t.getMessage());
918                 }
919             }
920
921             @Override
922             protected void onUnauthorized(Response response) {
923                 sessionExpired();
924             }
925         };
926         headAccount.setHeader(Const.X_AUTH_TOKEN, userToken);
927         Scheduler.get().scheduleDeferred(headAccount);
928     }
929
930     protected void createHomeContainer(final AccountResource _account, final Command callback) {
931         String path = "/" + Const.HOME_CONTAINER;
932         PutRequest createPithos = new PutRequest(getStorageAPIURL(), getUserID(), path) {
933             @Override
934             public void onSuccess(Resource result) {
935                 if(!_account.hasTrashContainer()) {
936                     createTrashContainer(callback);
937                 }
938                 else {
939                     fetchAccount(callback);
940                 }
941             }
942
943             @Override
944             public void onError(Throwable t) {
945                 LOG("Error creating pithos", t);
946                 setError(t);
947                 if(t instanceof RestException) {
948                     displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
949                 }
950                 else {
951                     displayError("System error Error creating pithos: " + t.getMessage());
952                 }
953             }
954
955             @Override
956             protected void onUnauthorized(Response response) {
957                 sessionExpired();
958             }
959         };
960         createPithos.setHeader(Const.X_AUTH_TOKEN, getUserToken());
961         Scheduler.get().scheduleDeferred(createPithos);
962     }
963
964     protected void createTrashContainer(final Command callback) {
965         String path = "/" + Const.TRASH_CONTAINER;
966         PutRequest createPithos = new PutRequest(getStorageAPIURL(), getUserID(), path) {
967             @Override
968             public void onSuccess(Resource result) {
969                 fetchAccount(callback);
970             }
971
972             @Override
973             public void onError(Throwable t) {
974                 LOG("Error creating pithos", t);
975                 setError(t);
976                 if(t instanceof RestException) {
977                     displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
978                 }
979                 else {
980                     displayError("System error Error creating pithos: " + t.getMessage());
981                 }
982             }
983
984             @Override
985             protected void onUnauthorized(Response response) {
986                 sessionExpired();
987             }
988         };
989         createPithos.setHeader(Const.X_AUTH_TOKEN, getUserToken());
990         Scheduler.get().scheduleDeferred(createPithos);
991     }
992
993     /**
994      * Creates an HTML fragment that places an image & caption together, for use
995      * in a group header.
996      *
997      * @param imageProto an image prototype for an image
998      * @param caption    the group caption
999      * @return the header HTML fragment
1000      */
1001     private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
1002         String captionHTML = "<table class='caption' cellpadding='0' "
1003             + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
1004             + "</td><td id =" + caption + " class='rcaption'><b style='white-space:nowrap'>&nbsp;"
1005             + caption + "</b></td></tr></table>";
1006         return captionHTML;
1007     }
1008
1009     protected void onWindowResized(int height) {
1010         // Adjust the split panel to take up the available room in the window.
1011         int newHeight = height - splitPanel.getAbsoluteTop() - 153;
1012         if(newHeight < 1) {
1013             newHeight = 1;
1014         }
1015         splitPanel.setHeight("" + newHeight);
1016         inner.setHeight("" + newHeight);
1017     }
1018
1019     native boolean isCloudbarReady()/*-{
1020       if ($wnd.$("div.cloudbar") && $wnd.$("div.cloudbar").height() > 0)
1021         return true;
1022       return false;
1023     }-*/;
1024
1025     @Override
1026     public void onResize(ResizeEvent event) {
1027         int height = event.getHeight();
1028         onWindowResized(height);
1029     }
1030
1031     /**
1032      * Display an error message.
1033      *
1034      * @param msg the message to display
1035      */
1036     public void displayError(String msg) {
1037         messagePanel.displayError(msg);
1038         onWindowResized(Window.getClientHeight());
1039     }
1040
1041     /**
1042      * Display a warning message.
1043      *
1044      * @param msg the message to display
1045      */
1046     public void displayWarning(String msg) {
1047         messagePanel.displayWarning(msg);
1048         onWindowResized(Window.getClientHeight());
1049     }
1050
1051     /**
1052      * Display an informational message.
1053      *
1054      * @param msg the message to display
1055      */
1056     public void displayInformation(String msg) {
1057         messagePanel.displayInformation(msg);
1058         onWindowResized(Window.getClientHeight());
1059     }
1060
1061     /**
1062      * Retrieve the fileList.
1063      *
1064      * @return the fileList
1065      */
1066     public FileList getFileList() {
1067         return fileList;
1068     }
1069
1070     /**
1071      * Retrieve the topPanel.
1072      *
1073      * @return the topPanel
1074      */
1075     TopPanel getTopPanel() {
1076         return topPanel;
1077     }
1078
1079     /**
1080      * Retrieve the clipboard.
1081      *
1082      * @return the clipboard
1083      */
1084     public Clipboard getClipboard() {
1085         return clipboard;
1086     }
1087
1088     public StatusPanel getStatusPanel() {
1089         return statusPanel;
1090     }
1091
1092     public String getUserToken() {
1093         return userToken;
1094     }
1095
1096     public static native void preventIESelection() /*-{
1097       $doc.body.onselectstart = function () {
1098         return false;
1099       };
1100     }-*/;
1101
1102     public static native void enableIESelection() /*-{
1103       if ($doc.body.onselectstart != null)
1104         $doc.body.onselectstart = null;
1105     }-*/;
1106
1107     public static String getStorageAPIURL() {
1108         return STORAGE_API_URL;
1109     }
1110
1111     public static String getStorageViewURL() {
1112         return STORAGE_VIEW_URL;
1113     }
1114
1115     public static boolean isShowCopyrightMessage() {
1116         return SHOW_COPYRIGHT;
1117     }
1118
1119     public static String getUserCatalogsURL() {
1120         return USER_CATALOGS_API_URL;
1121     }
1122
1123     public static String getFileViewURL(File file) {
1124         return Pithos.getStorageViewURL() + file.getOwnerID() + file.getUri();
1125     }
1126
1127     public static String getVersionedFileViewURL(File file, int version) {
1128         return getFileViewURL(file) + "?version=" + version;
1129     }
1130
1131     /**
1132      * History support for folder navigation
1133      * adds a new browser history entry
1134      *
1135      * @param key
1136      */
1137     public void updateHistory(String key) {
1138 //              Replace any whitespace of the initial string to "+"
1139 //              String result = key.replaceAll("\\s","+");
1140 //              Add a new browser history entry.
1141 //              History.newItem(result);
1142         History.newItem(key);
1143     }
1144
1145     public void deleteFolder(final Folder folder, final Command callback) {
1146         final PleaseWaitPopup pwp = new PleaseWaitPopup();
1147         pwp.center();
1148         String path = "/" + folder.getContainer() + "/" + folder.getPrefix() + "?delimiter=/" + "&t=" + System.currentTimeMillis();
1149         DeleteRequest deleteFolder = new DeleteRequest(getStorageAPIURL(), folder.getOwnerID(), path) {
1150
1151             @Override
1152             protected void onUnauthorized(Response response) {
1153                 pwp.hide();
1154                 sessionExpired();
1155             }
1156
1157             @Override
1158             public void onSuccess(Resource result) {
1159                 updateFolder(folder.getParent(), true, new Command() {
1160
1161                     @Override
1162                     public void execute() {
1163                         folderTreeSelectionModel.setSelected(folder.getParent(), true);
1164                         updateStatistics();
1165                         if(callback != null) {
1166                             callback.execute();
1167                         }
1168                         pwp.hide();
1169                     }
1170                 }, true);
1171             }
1172
1173             @Override
1174             public void onError(Throwable t) {
1175                 LOG(t);
1176                 setError(t);
1177                 if(t instanceof RestException) {
1178                     if(((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND) {
1179                         displayError("Unable to delete folder: " + ((RestException) t).getHttpStatusText());
1180                     }
1181                     else {
1182                         onSuccess(null);
1183                     }
1184                 }
1185                 else {
1186                     displayError("System error unable to delete folder: " + t.getMessage());
1187                 }
1188                 pwp.hide();
1189             }
1190         };
1191         deleteFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1192         Scheduler.get().scheduleDeferred(deleteFolder);
1193     }
1194
1195     public FolderTreeView getFolderTreeView() {
1196         return folderTreeView;
1197     }
1198
1199     public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
1200         if(iter.hasNext()) {
1201             File file = iter.next();
1202             String path = targetUri + "/" + file.getName();
1203             PutRequest copyFile = new PutRequest(getStorageAPIURL(), targetUsername, path) {
1204                 @Override
1205                 public void onSuccess(Resource result) {
1206                     copyFiles(iter, targetUsername, targetUri, callback);
1207                 }
1208
1209                 @Override
1210                 public void onError(Throwable t) {
1211                     LOG(t);
1212                     setError(t);
1213                     if(t instanceof RestException) {
1214                         displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
1215                     }
1216                     else {
1217                         displayError("System error unable to copy file: " + t.getMessage());
1218                     }
1219                 }
1220
1221                 @Override
1222                 protected void onUnauthorized(Response response) {
1223                     sessionExpired();
1224                 }
1225             };
1226             copyFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1227             copyFile.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(file.getUri()));
1228             if(!file.getOwnerID().equals(targetUsername)) {
1229                 copyFile.setHeader(Const.X_SOURCE_ACCOUNT, URL.encodePathSegment(file.getOwnerID()));
1230             }
1231             copyFile.setHeader(Const.CONTENT_TYPE, file.getContentType());
1232             Scheduler.get().scheduleDeferred(copyFile);
1233         }
1234         else if(callback != null) {
1235             callback.execute();
1236         }
1237     }
1238
1239     public void copyFolder(final Folder f, final String targetUsername, final String targetUri, boolean move, final Command callback) {
1240         String path = targetUri + "?delimiter=/";
1241         PutRequest copyFolder = new PutRequest(getStorageAPIURL(), targetUsername, path) {
1242             @Override
1243             public void onSuccess(Resource result) {
1244                 if(callback != null) {
1245                     callback.execute();
1246                 }
1247             }
1248
1249             @Override
1250             public void onError(Throwable t) {
1251                 LOG(t);
1252                 setError(t);
1253                 if(t instanceof RestException) {
1254                     displayError("Unable to copy folder: " + ((RestException) t).getHttpStatusText());
1255                 }
1256                 else {
1257                     displayError("System error copying folder: " + t.getMessage());
1258                 }
1259             }
1260
1261             @Override
1262             protected void onUnauthorized(Response response) {
1263                 sessionExpired();
1264             }
1265         };
1266         copyFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1267         copyFolder.setHeader(Const.ACCEPT, "*/*");
1268         copyFolder.setHeader(Const.CONTENT_LENGTH, "0");
1269         copyFolder.setHeader(Const.CONTENT_TYPE, "application/directory");
1270         if(!f.getOwnerID().equals(targetUsername)) {
1271             copyFolder.setHeader(Const.X_SOURCE_ACCOUNT, f.getOwnerID());
1272         }
1273         if(move) {
1274             copyFolder.setHeader(Const.X_MOVE_FROM, URL.encodePathSegment(f.getUri()));
1275         }
1276         else {
1277             copyFolder.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(f.getUri()));
1278         }
1279         Scheduler.get().scheduleDeferred(copyFolder);
1280     }
1281
1282     public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1283         selectionModels.add(model);
1284     }
1285
1286     public OtherSharedTreeView getOtherSharedTreeView() {
1287         return otherSharedTreeView;
1288     }
1289
1290     public void updateTrash(boolean showFiles, Command callback) {
1291         updateFolder(trash, showFiles, callback, true);
1292     }
1293
1294     public void updateGroupsNode() {
1295         groupTreeView.updateGroupNode(null);
1296     }
1297
1298     public Group addGroup(String groupname) {
1299         Group newGroup = new Group(groupname);
1300         account.addGroup(newGroup);
1301         groupTreeView.updateGroupNode(null);
1302         return newGroup;
1303     }
1304
1305     public void removeGroup(Group group) {
1306         account.removeGroup(group);
1307         updateGroupsNode();
1308     }
1309
1310     public TreeView getSelectedTree() {
1311         return selectedTree;
1312     }
1313
1314     public void setSelectedTree(TreeView selected) {
1315         selectedTree = selected;
1316     }
1317
1318     public Folder getSelection() {
1319         if(selectedTree != null) {
1320             return selectedTree.getSelection();
1321         }
1322         return null;
1323     }
1324
1325     public void showFolderStatistics(int folderFileCount) {
1326         numOfFiles.setHTML(String.valueOf(folderFileCount));
1327     }
1328
1329     public GroupTreeView getGroupTreeView() {
1330         return groupTreeView;
1331     }
1332
1333     public void sessionExpired() {
1334         new SessionExpiredDialog(this).center();
1335     }
1336
1337     public void updateRootFolder(Command callback) {
1338         updateFolder(account.getPithos(), false, callback, true);
1339     }
1340
1341     void createMySharedTree() {
1342         LOG("Pithos::createMySharedTree()");
1343         mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1344         mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1345             @Override
1346             public void onSelectionChange(SelectionChangeEvent event) {
1347                 if(mysharedTreeSelectionModel.getSelectedObject() != null) {
1348                     deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1349                     upload.setEnabled(false);
1350                     disableUploadArea();
1351                     updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1352                     showRelevantToolbarButtons();
1353                 }
1354                 else {
1355                     if(getSelectedTree().equals(mysharedTreeView)) {
1356                         setSelectedTree(null);
1357                     }
1358                     if(getSelectedTree() == null) {
1359                         showRelevantToolbarButtons();
1360                     }
1361                 }
1362             }
1363         });
1364         selectionModels.add(mysharedTreeSelectionModel);
1365         mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1366         mysharedTreeViewModel.initialize(new Command() {
1367
1368             @Override
1369             public void execute() {
1370                 mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1371                 trees.insert(mysharedTreeView, 2);
1372                 treeViews.add(mysharedTreeView);
1373                 createOtherSharedTree();
1374             }
1375         });
1376     }
1377
1378     void createOtherSharedTree() {
1379         LOG("Pithos::createOtherSharedTree()");
1380         otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1381         otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1382             @Override
1383             public void onSelectionChange(SelectionChangeEvent event) {
1384                 if(otherSharedTreeSelectionModel.getSelectedObject() != null) {
1385                     deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1386                     applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1387                     updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true, null);
1388                     showRelevantToolbarButtons();
1389                 }
1390                 else {
1391                     if(getSelectedTree().equals(otherSharedTreeView)) {
1392                         setSelectedTree(null);
1393                     }
1394                     if(getSelectedTree() == null) {
1395                         showRelevantToolbarButtons();
1396                     }
1397                 }
1398             }
1399         });
1400         selectionModels.add(otherSharedTreeSelectionModel);
1401         otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1402         // #3784 We show it empty...
1403         otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel, true);
1404         trees.insert(otherSharedTreeView, 1);
1405
1406         LOG("Pithos::createOtherSharedTree(), initializing otherSharedTreeViewModel with a callback");
1407         otherSharedTreeViewModel.initialize(new Command() {
1408             @Override
1409             public void execute() {
1410                 // #3784 ... then remove the empty stuff and add a new view with the populated model
1411                 trees.remove(otherSharedTreeView);
1412
1413                 otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel, false);
1414                 trees.insert(otherSharedTreeView, 1);
1415                 treeViews.add(otherSharedTreeView);
1416                 scheduleRefresh();
1417             }
1418         });
1419     }
1420
1421     public String getErrorData() {
1422         final StringBuilder sb = new StringBuilder();
1423         final String NL = Const.NL;
1424         Throwable t = this.error;
1425         while(t != null) {
1426             sb.append(t.toString());
1427             sb.append(NL);
1428             StackTraceElement[] traces = t.getStackTrace();
1429             for(StackTraceElement trace : traces) {
1430                 sb.append("  [");
1431                 sb.append(trace.getClassName());
1432                 sb.append("::");
1433                 sb.append(trace.getMethodName());
1434                 sb.append("() at ");
1435                 sb.append(trace.getFileName());
1436                 sb.append(":");
1437                 sb.append(trace.getLineNumber());
1438                 sb.append("]");
1439                 sb.append(NL);
1440             }
1441             t = t.getCause();
1442         }
1443
1444         return sb.toString();
1445     }
1446
1447     public void setError(Throwable t) {
1448         error = t;
1449         LOG(t);
1450     }
1451
1452     public void showRelevantToolbarButtons() {
1453         toolbar.showRelevantButtons();
1454     }
1455
1456     public FileUploadDialog getFileUploadDialog() {
1457         if(fileUploadDialog == null) {
1458             fileUploadDialog = new FileUploadDialog(this);
1459         }
1460         return fileUploadDialog;
1461     }
1462
1463     public void hideUploadIndicator() {
1464         upload.removeStyleName("pithos-uploadButton-loading");
1465         upload.setTitle("");
1466     }
1467
1468     public void showUploadIndicator() {
1469         upload.addStyleName("pithos-uploadButton-loading");
1470         upload.setTitle("Upload in progress. Click for details.");
1471     }
1472
1473     public void scheduleFolderHeadCommand(final Folder folder, final Command callback) {
1474         if(folder == null) {
1475             if(callback != null) {
1476                 callback.execute();
1477             }
1478         }
1479         else {
1480             HeadRequest<Folder> headFolder = new HeadRequest<Folder>(Folder.class, getStorageAPIURL(), folder.getOwnerID(), folder.getUri(), folder) {
1481
1482                 @Override
1483                 public void onSuccess(Folder _result) {
1484                     if(callback != null) {
1485                         callback.execute();
1486                     }
1487                 }
1488
1489                 @Override
1490                 public void onError(Throwable t) {
1491                     if(t instanceof RestException) {
1492                         if(((RestException) t).getHttpStatusCode() == Response.SC_NOT_FOUND) {
1493                             final String path = folder.getUri();
1494                             PutRequest newFolder = new PutRequest(getStorageAPIURL(), folder.getOwnerID(), path) {
1495                                 @Override
1496                                 public void onSuccess(Resource _result) {
1497                                     scheduleFolderHeadCommand(folder, callback);
1498                                 }
1499
1500                                 @Override
1501                                 public void onError(Throwable _t) {
1502                                     setError(_t);
1503                                     if(_t instanceof RestException) {
1504                                         displayError("Unable to create folder: " + ((RestException) _t).getHttpStatusText());
1505                                     }
1506                                     else {
1507                                         displayError("System error creating folder: " + _t.getMessage());
1508                                     }
1509                                 }
1510
1511                                 @Override
1512                                 protected void onUnauthorized(Response response) {
1513                                     sessionExpired();
1514                                 }
1515                             };
1516                             newFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1517                             newFolder.setHeader(Const.CONTENT_TYPE, "application/folder");
1518                             newFolder.setHeader(Const.ACCEPT, "*/*");
1519                             newFolder.setHeader(Const.CONTENT_LENGTH, "0");
1520                             Scheduler.get().scheduleDeferred(newFolder);
1521                         }
1522                         else if(((RestException) t).getHttpStatusCode() == Response.SC_FORBIDDEN) {
1523                             onSuccess(folder);
1524                         }
1525                         else {
1526                             displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
1527                         }
1528                     }
1529                     else {
1530                         displayError("System error heading folder: " + t.getMessage());
1531                     }
1532
1533                     LOG("Error heading folder", t);
1534                     setError(t);
1535                 }
1536
1537                 @Override
1538                 protected void onUnauthorized(Response response) {
1539                     sessionExpired();
1540                 }
1541             };
1542             headFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1543             Scheduler.get().scheduleDeferred(headFolder);
1544         }
1545     }
1546
1547     public void scheduleFileHeadCommand(File f, final Command callback) {
1548         HeadRequest<File> headFile = new HeadRequest<File>(File.class, getStorageAPIURL(), f.getOwnerID(), f.getUri(), f) {
1549
1550             @Override
1551             public void onSuccess(File _result) {
1552                 if(callback != null) {
1553                     callback.execute();
1554                 }
1555             }
1556
1557             @Override
1558             public void onError(Throwable t) {
1559                 LOG("Error heading file", t);
1560                 setError(t);
1561                 if(t instanceof RestException) {
1562                     displayError("Error heading file: " + ((RestException) t).getHttpStatusText());
1563                 }
1564                 else {
1565                     displayError("System error heading file: " + t.getMessage());
1566                 }
1567             }
1568
1569             @Override
1570             protected void onUnauthorized(Response response) {
1571                 sessionExpired();
1572             }
1573         };
1574         headFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1575         Scheduler.get().scheduleDeferred(headFile);
1576     }
1577
1578     public boolean isMySharedSelected() {
1579         return getSelectedTree().equals(getMySharedTreeView());
1580     }
1581
1582     private Folder getUploadFolder() {
1583         if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1584             return getSelection();
1585         }
1586         return null;
1587     }
1588
1589     private void updateUploadFolder() {
1590         updateUploadFolder(null);
1591     }
1592
1593     private void updateUploadFolder(final JsArrayString urls) {
1594         if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1595             Folder f = getSelection();
1596             if(getSelectedTree().equals(getFolderTreeView())) {
1597                 updateFolder(f, true, new Command() {
1598
1599                     @Override
1600                     public void execute() {
1601                         updateStatistics();
1602                         if(urls != null) {
1603                             selectUploadedFiles(urls);
1604                         }
1605                     }
1606                 }, false);
1607             }
1608             else {
1609                 updateOtherSharedFolder(f, true, null);
1610             }
1611         }
1612     }
1613
1614     public native void disableUploadArea() /*-{
1615       var uploader = $wnd.$("#uploader").pluploadQueue();
1616       var dropElm = $wnd.document.getElementById('rightPanel');
1617       $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1618     }-*/;
1619
1620     public native void enableUploadArea() /*-{
1621       var uploader = $wnd.$("#uploader").pluploadQueue();
1622       var dropElm = $wnd.document.getElementById('rightPanel');
1623       $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1624       if (uploader.runtime == 'html5') {
1625         uploader.settings.drop_element = 'rightPanel';
1626         uploader.trigger('PostInit');
1627       }
1628     }-*/;
1629
1630     public void showUploadAlert(int nOfFiles) {
1631         if(uploadAlert == null) {
1632             uploadAlert = new UploadAlert(this, nOfFiles);
1633         }
1634         if(!uploadAlert.isShowing()) {
1635             uploadAlert.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
1636
1637                 @Override
1638                 public void setPosition(int offsetWidth, int offsetHeight) {
1639                     uploadAlert.setPopupPosition((Window.getClientWidth() - offsetWidth) / 2, statusPanel.getAbsoluteTop() - offsetHeight);
1640                 }
1641             });
1642         }
1643         uploadAlert.setNumOfFiles(nOfFiles);
1644     }
1645
1646     public void hideUploadAlert() {
1647         if(uploadAlert != null && uploadAlert.isShowing()) {
1648             uploadAlert.hide();
1649         }
1650     }
1651
1652     public void selectUploadedFiles(JsArrayString urls) {
1653         List<String> selectedUrls = new ArrayList<String>();
1654         for(int i = 0; i < urls.length(); i++) {
1655             selectedUrls.add(urls.get(i));
1656         }
1657         fileList.selectByUrl(selectedUrls);
1658     }
1659
1660     public void purgeContainer(final Folder container) {
1661         String path = "/" + container.getName() + "?delimiter=/";
1662         DeleteRequest delete = new DeleteRequest(getStorageAPIURL(), getUserID(), path) {
1663
1664             @Override
1665             protected void onUnauthorized(Response response) {
1666                 sessionExpired();
1667             }
1668
1669             @Override
1670             public void onSuccess(Resource result) {
1671                 updateFolder(container, true, null, true);
1672             }
1673
1674             @Override
1675             public void onError(Throwable t) {
1676                 LOG("Error deleting trash", t);
1677                 setError(t);
1678                 if(t instanceof RestException) {
1679                     displayError("Error deleting trash: " + ((RestException) t).getHttpStatusText());
1680                 }
1681                 else {
1682                     displayError("System error deleting trash: " + t.getMessage());
1683                 }
1684             }
1685         };
1686         delete.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1687         Scheduler.get().scheduleDeferred(delete);
1688     }
1689 }