Eliminate goto in URLs
[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     /**
1128      * History support for folder navigation
1129      * adds a new browser history entry
1130      *
1131      * @param key
1132      */
1133     public void updateHistory(String key) {
1134 //              Replace any whitespace of the initial string to "+"
1135 //              String result = key.replaceAll("\\s","+");
1136 //              Add a new browser history entry.
1137 //              History.newItem(result);
1138         History.newItem(key);
1139     }
1140
1141     public void deleteFolder(final Folder folder, final Command callback) {
1142         final PleaseWaitPopup pwp = new PleaseWaitPopup();
1143         pwp.center();
1144         String path = "/" + folder.getContainer() + "/" + folder.getPrefix() + "?delimiter=/" + "&t=" + System.currentTimeMillis();
1145         DeleteRequest deleteFolder = new DeleteRequest(getStorageAPIURL(), folder.getOwnerID(), path) {
1146
1147             @Override
1148             protected void onUnauthorized(Response response) {
1149                 pwp.hide();
1150                 sessionExpired();
1151             }
1152
1153             @Override
1154             public void onSuccess(Resource result) {
1155                 updateFolder(folder.getParent(), true, new Command() {
1156
1157                     @Override
1158                     public void execute() {
1159                         folderTreeSelectionModel.setSelected(folder.getParent(), true);
1160                         updateStatistics();
1161                         if(callback != null) {
1162                             callback.execute();
1163                         }
1164                         pwp.hide();
1165                     }
1166                 }, true);
1167             }
1168
1169             @Override
1170             public void onError(Throwable t) {
1171                 LOG(t);
1172                 setError(t);
1173                 if(t instanceof RestException) {
1174                     if(((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND) {
1175                         displayError("Unable to delete folder: " + ((RestException) t).getHttpStatusText());
1176                     }
1177                     else {
1178                         onSuccess(null);
1179                     }
1180                 }
1181                 else {
1182                     displayError("System error unable to delete folder: " + t.getMessage());
1183                 }
1184                 pwp.hide();
1185             }
1186         };
1187         deleteFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1188         Scheduler.get().scheduleDeferred(deleteFolder);
1189     }
1190
1191     public FolderTreeView getFolderTreeView() {
1192         return folderTreeView;
1193     }
1194
1195     public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
1196         if(iter.hasNext()) {
1197             File file = iter.next();
1198             String path = targetUri + "/" + file.getName();
1199             PutRequest copyFile = new PutRequest(getStorageAPIURL(), targetUsername, path) {
1200                 @Override
1201                 public void onSuccess(Resource result) {
1202                     copyFiles(iter, targetUsername, targetUri, callback);
1203                 }
1204
1205                 @Override
1206                 public void onError(Throwable t) {
1207                     LOG(t);
1208                     setError(t);
1209                     if(t instanceof RestException) {
1210                         displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
1211                     }
1212                     else {
1213                         displayError("System error unable to copy file: " + t.getMessage());
1214                     }
1215                 }
1216
1217                 @Override
1218                 protected void onUnauthorized(Response response) {
1219                     sessionExpired();
1220                 }
1221             };
1222             copyFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1223             copyFile.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(file.getUri()));
1224             if(!file.getOwnerID().equals(targetUsername)) {
1225                 copyFile.setHeader(Const.X_SOURCE_ACCOUNT, URL.encodePathSegment(file.getOwnerID()));
1226             }
1227             copyFile.setHeader(Const.CONTENT_TYPE, file.getContentType());
1228             Scheduler.get().scheduleDeferred(copyFile);
1229         }
1230         else if(callback != null) {
1231             callback.execute();
1232         }
1233     }
1234
1235     public void copyFolder(final Folder f, final String targetUsername, final String targetUri, boolean move, final Command callback) {
1236         String path = targetUri + "?delimiter=/";
1237         PutRequest copyFolder = new PutRequest(getStorageAPIURL(), targetUsername, path) {
1238             @Override
1239             public void onSuccess(Resource result) {
1240                 if(callback != null) {
1241                     callback.execute();
1242                 }
1243             }
1244
1245             @Override
1246             public void onError(Throwable t) {
1247                 LOG(t);
1248                 setError(t);
1249                 if(t instanceof RestException) {
1250                     displayError("Unable to copy folder: " + ((RestException) t).getHttpStatusText());
1251                 }
1252                 else {
1253                     displayError("System error copying folder: " + t.getMessage());
1254                 }
1255             }
1256
1257             @Override
1258             protected void onUnauthorized(Response response) {
1259                 sessionExpired();
1260             }
1261         };
1262         copyFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1263         copyFolder.setHeader(Const.ACCEPT, "*/*");
1264         copyFolder.setHeader(Const.CONTENT_LENGTH, "0");
1265         copyFolder.setHeader(Const.CONTENT_TYPE, "application/directory");
1266         if(!f.getOwnerID().equals(targetUsername)) {
1267             copyFolder.setHeader(Const.X_SOURCE_ACCOUNT, f.getOwnerID());
1268         }
1269         if(move) {
1270             copyFolder.setHeader(Const.X_MOVE_FROM, URL.encodePathSegment(f.getUri()));
1271         }
1272         else {
1273             copyFolder.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(f.getUri()));
1274         }
1275         Scheduler.get().scheduleDeferred(copyFolder);
1276     }
1277
1278     public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1279         selectionModels.add(model);
1280     }
1281
1282     public OtherSharedTreeView getOtherSharedTreeView() {
1283         return otherSharedTreeView;
1284     }
1285
1286     public void updateTrash(boolean showFiles, Command callback) {
1287         updateFolder(trash, showFiles, callback, true);
1288     }
1289
1290     public void updateGroupsNode() {
1291         groupTreeView.updateGroupNode(null);
1292     }
1293
1294     public Group addGroup(String groupname) {
1295         Group newGroup = new Group(groupname);
1296         account.addGroup(newGroup);
1297         groupTreeView.updateGroupNode(null);
1298         return newGroup;
1299     }
1300
1301     public void removeGroup(Group group) {
1302         account.removeGroup(group);
1303         updateGroupsNode();
1304     }
1305
1306     public TreeView getSelectedTree() {
1307         return selectedTree;
1308     }
1309
1310     public void setSelectedTree(TreeView selected) {
1311         selectedTree = selected;
1312     }
1313
1314     public Folder getSelection() {
1315         if(selectedTree != null) {
1316             return selectedTree.getSelection();
1317         }
1318         return null;
1319     }
1320
1321     public void showFolderStatistics(int folderFileCount) {
1322         numOfFiles.setHTML(String.valueOf(folderFileCount));
1323     }
1324
1325     public GroupTreeView getGroupTreeView() {
1326         return groupTreeView;
1327     }
1328
1329     public void sessionExpired() {
1330         new SessionExpiredDialog(this).center();
1331     }
1332
1333     public void updateRootFolder(Command callback) {
1334         updateFolder(account.getPithos(), false, callback, true);
1335     }
1336
1337     void createMySharedTree() {
1338         LOG("Pithos::createMySharedTree()");
1339         mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1340         mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1341             @Override
1342             public void onSelectionChange(SelectionChangeEvent event) {
1343                 if(mysharedTreeSelectionModel.getSelectedObject() != null) {
1344                     deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1345                     upload.setEnabled(false);
1346                     disableUploadArea();
1347                     updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1348                     showRelevantToolbarButtons();
1349                 }
1350                 else {
1351                     if(getSelectedTree().equals(mysharedTreeView)) {
1352                         setSelectedTree(null);
1353                     }
1354                     if(getSelectedTree() == null) {
1355                         showRelevantToolbarButtons();
1356                     }
1357                 }
1358             }
1359         });
1360         selectionModels.add(mysharedTreeSelectionModel);
1361         mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1362         mysharedTreeViewModel.initialize(new Command() {
1363
1364             @Override
1365             public void execute() {
1366                 mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1367                 trees.insert(mysharedTreeView, 2);
1368                 treeViews.add(mysharedTreeView);
1369                 createOtherSharedTree();
1370             }
1371         });
1372     }
1373
1374     void createOtherSharedTree() {
1375         LOG("Pithos::createOtherSharedTree()");
1376         otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1377         otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1378             @Override
1379             public void onSelectionChange(SelectionChangeEvent event) {
1380                 if(otherSharedTreeSelectionModel.getSelectedObject() != null) {
1381                     deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1382                     applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1383                     updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true, null);
1384                     showRelevantToolbarButtons();
1385                 }
1386                 else {
1387                     if(getSelectedTree().equals(otherSharedTreeView)) {
1388                         setSelectedTree(null);
1389                     }
1390                     if(getSelectedTree() == null) {
1391                         showRelevantToolbarButtons();
1392                     }
1393                 }
1394             }
1395         });
1396         selectionModels.add(otherSharedTreeSelectionModel);
1397         otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1398         // #3784 We show it empty...
1399         otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel, true);
1400         trees.insert(otherSharedTreeView, 1);
1401
1402         LOG("Pithos::createOtherSharedTree(), initializing otherSharedTreeViewModel with a callback");
1403         otherSharedTreeViewModel.initialize(new Command() {
1404             @Override
1405             public void execute() {
1406                 // #3784 ... then remove the empty stuff and add a new view with the populated model
1407                 trees.remove(otherSharedTreeView);
1408
1409                 otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel, false);
1410                 trees.insert(otherSharedTreeView, 1);
1411                 treeViews.add(otherSharedTreeView);
1412                 scheduleRefresh();
1413             }
1414         });
1415     }
1416
1417     public String getErrorData() {
1418         final StringBuilder sb = new StringBuilder();
1419         final String NL = Const.NL;
1420         Throwable t = this.error;
1421         while(t != null) {
1422             sb.append(t.toString());
1423             sb.append(NL);
1424             StackTraceElement[] traces = t.getStackTrace();
1425             for(StackTraceElement trace : traces) {
1426                 sb.append("  [");
1427                 sb.append(trace.getClassName());
1428                 sb.append("::");
1429                 sb.append(trace.getMethodName());
1430                 sb.append("() at ");
1431                 sb.append(trace.getFileName());
1432                 sb.append(":");
1433                 sb.append(trace.getLineNumber());
1434                 sb.append("]");
1435                 sb.append(NL);
1436             }
1437             t = t.getCause();
1438         }
1439
1440         return sb.toString();
1441     }
1442
1443     public void setError(Throwable t) {
1444         error = t;
1445         LOG(t);
1446     }
1447
1448     public void showRelevantToolbarButtons() {
1449         toolbar.showRelevantButtons();
1450     }
1451
1452     public FileUploadDialog getFileUploadDialog() {
1453         if(fileUploadDialog == null) {
1454             fileUploadDialog = new FileUploadDialog(this);
1455         }
1456         return fileUploadDialog;
1457     }
1458
1459     public void hideUploadIndicator() {
1460         upload.removeStyleName("pithos-uploadButton-loading");
1461         upload.setTitle("");
1462     }
1463
1464     public void showUploadIndicator() {
1465         upload.addStyleName("pithos-uploadButton-loading");
1466         upload.setTitle("Upload in progress. Click for details.");
1467     }
1468
1469     public void scheduleFolderHeadCommand(final Folder folder, final Command callback) {
1470         if(folder == null) {
1471             if(callback != null) {
1472                 callback.execute();
1473             }
1474         }
1475         else {
1476             HeadRequest<Folder> headFolder = new HeadRequest<Folder>(Folder.class, getStorageAPIURL(), folder.getOwnerID(), folder.getUri(), folder) {
1477
1478                 @Override
1479                 public void onSuccess(Folder _result) {
1480                     if(callback != null) {
1481                         callback.execute();
1482                     }
1483                 }
1484
1485                 @Override
1486                 public void onError(Throwable t) {
1487                     if(t instanceof RestException) {
1488                         if(((RestException) t).getHttpStatusCode() == Response.SC_NOT_FOUND) {
1489                             final String path = folder.getUri();
1490                             PutRequest newFolder = new PutRequest(getStorageAPIURL(), folder.getOwnerID(), path) {
1491                                 @Override
1492                                 public void onSuccess(Resource _result) {
1493                                     scheduleFolderHeadCommand(folder, callback);
1494                                 }
1495
1496                                 @Override
1497                                 public void onError(Throwable _t) {
1498                                     setError(_t);
1499                                     if(_t instanceof RestException) {
1500                                         displayError("Unable to create folder: " + ((RestException) _t).getHttpStatusText());
1501                                     }
1502                                     else {
1503                                         displayError("System error creating folder: " + _t.getMessage());
1504                                     }
1505                                 }
1506
1507                                 @Override
1508                                 protected void onUnauthorized(Response response) {
1509                                     sessionExpired();
1510                                 }
1511                             };
1512                             newFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1513                             newFolder.setHeader(Const.CONTENT_TYPE, "application/folder");
1514                             newFolder.setHeader(Const.ACCEPT, "*/*");
1515                             newFolder.setHeader(Const.CONTENT_LENGTH, "0");
1516                             Scheduler.get().scheduleDeferred(newFolder);
1517                         }
1518                         else if(((RestException) t).getHttpStatusCode() == Response.SC_FORBIDDEN) {
1519                             onSuccess(folder);
1520                         }
1521                         else {
1522                             displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
1523                         }
1524                     }
1525                     else {
1526                         displayError("System error heading folder: " + t.getMessage());
1527                     }
1528
1529                     LOG("Error heading folder", t);
1530                     setError(t);
1531                 }
1532
1533                 @Override
1534                 protected void onUnauthorized(Response response) {
1535                     sessionExpired();
1536                 }
1537             };
1538             headFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1539             Scheduler.get().scheduleDeferred(headFolder);
1540         }
1541     }
1542
1543     public void scheduleFileHeadCommand(File f, final Command callback) {
1544         HeadRequest<File> headFile = new HeadRequest<File>(File.class, getStorageAPIURL(), f.getOwnerID(), f.getUri(), f) {
1545
1546             @Override
1547             public void onSuccess(File _result) {
1548                 if(callback != null) {
1549                     callback.execute();
1550                 }
1551             }
1552
1553             @Override
1554             public void onError(Throwable t) {
1555                 LOG("Error heading file", t);
1556                 setError(t);
1557                 if(t instanceof RestException) {
1558                     displayError("Error heading file: " + ((RestException) t).getHttpStatusText());
1559                 }
1560                 else {
1561                     displayError("System error heading file: " + t.getMessage());
1562                 }
1563             }
1564
1565             @Override
1566             protected void onUnauthorized(Response response) {
1567                 sessionExpired();
1568             }
1569         };
1570         headFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1571         Scheduler.get().scheduleDeferred(headFile);
1572     }
1573
1574     public boolean isMySharedSelected() {
1575         return getSelectedTree().equals(getMySharedTreeView());
1576     }
1577
1578     private Folder getUploadFolder() {
1579         if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1580             return getSelection();
1581         }
1582         return null;
1583     }
1584
1585     private void updateUploadFolder() {
1586         updateUploadFolder(null);
1587     }
1588
1589     private void updateUploadFolder(final JsArrayString urls) {
1590         if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1591             Folder f = getSelection();
1592             if(getSelectedTree().equals(getFolderTreeView())) {
1593                 updateFolder(f, true, new Command() {
1594
1595                     @Override
1596                     public void execute() {
1597                         updateStatistics();
1598                         if(urls != null) {
1599                             selectUploadedFiles(urls);
1600                         }
1601                     }
1602                 }, false);
1603             }
1604             else {
1605                 updateOtherSharedFolder(f, true, null);
1606             }
1607         }
1608     }
1609
1610     public native void disableUploadArea() /*-{
1611       var uploader = $wnd.$("#uploader").pluploadQueue();
1612       var dropElm = $wnd.document.getElementById('rightPanel');
1613       $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1614     }-*/;
1615
1616     public native void enableUploadArea() /*-{
1617       var uploader = $wnd.$("#uploader").pluploadQueue();
1618       var dropElm = $wnd.document.getElementById('rightPanel');
1619       $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1620       if (uploader.runtime == 'html5') {
1621         uploader.settings.drop_element = 'rightPanel';
1622         uploader.trigger('PostInit');
1623       }
1624     }-*/;
1625
1626     public void showUploadAlert(int nOfFiles) {
1627         if(uploadAlert == null) {
1628             uploadAlert = new UploadAlert(this, nOfFiles);
1629         }
1630         if(!uploadAlert.isShowing()) {
1631             uploadAlert.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
1632
1633                 @Override
1634                 public void setPosition(int offsetWidth, int offsetHeight) {
1635                     uploadAlert.setPopupPosition((Window.getClientWidth() - offsetWidth) / 2, statusPanel.getAbsoluteTop() - offsetHeight);
1636                 }
1637             });
1638         }
1639         uploadAlert.setNumOfFiles(nOfFiles);
1640     }
1641
1642     public void hideUploadAlert() {
1643         if(uploadAlert != null && uploadAlert.isShowing()) {
1644             uploadAlert.hide();
1645         }
1646     }
1647
1648     public void selectUploadedFiles(JsArrayString urls) {
1649         List<String> selectedUrls = new ArrayList<String>();
1650         for(int i = 0; i < urls.length(); i++) {
1651             selectedUrls.add(urls.get(i));
1652         }
1653         fileList.selectByUrl(selectedUrls);
1654     }
1655
1656     public void purgeContainer(final Folder container) {
1657         String path = "/" + container.getName() + "?delimiter=/";
1658         DeleteRequest delete = new DeleteRequest(getStorageAPIURL(), getUserID(), path) {
1659
1660             @Override
1661             protected void onUnauthorized(Response response) {
1662                 sessionExpired();
1663             }
1664
1665             @Override
1666             public void onSuccess(Resource result) {
1667                 updateFolder(container, true, null, true);
1668             }
1669
1670             @Override
1671             public void onError(Throwable t) {
1672                 LOG("Error deleting trash", t);
1673                 setError(t);
1674                 if(t instanceof RestException) {
1675                     displayError("Error deleting trash: " + ((RestException) t).getHttpStatusText());
1676                 }
1677                 else {
1678                     displayError("System error deleting trash: " + t.getMessage());
1679                 }
1680             }
1681         };
1682         delete.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1683         Scheduler.get().scheduleDeferred(delete);
1684     }
1685 }