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