Group creation forces the user to add the first member (issue #2375)
[pithos-web-client] / src / gr / grnet / pithos / web / client / Pithos.java
1 /*
2  * Copyright 2011-2012 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 gr.grnet.pithos.web.client.PithosDisclosurePanel.Style;
38 import gr.grnet.pithos.web.client.commands.UploadFileCommand;
39 import gr.grnet.pithos.web.client.foldertree.AccountResource;
40 import gr.grnet.pithos.web.client.foldertree.File;
41 import gr.grnet.pithos.web.client.foldertree.Folder;
42 import gr.grnet.pithos.web.client.foldertree.FolderTreeView;
43 import gr.grnet.pithos.web.client.foldertree.FolderTreeViewModel;
44 import gr.grnet.pithos.web.client.foldertree.Resource;
45 import gr.grnet.pithos.web.client.grouptree.Group;
46 import gr.grnet.pithos.web.client.grouptree.GroupTreeView;
47 import gr.grnet.pithos.web.client.grouptree.GroupTreeViewModel;
48 import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeView;
49 import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeViewModel;
50 import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeView;
51 import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeViewModel;
52 import gr.grnet.pithos.web.client.rest.DeleteRequest;
53 import gr.grnet.pithos.web.client.rest.GetRequest;
54 import gr.grnet.pithos.web.client.rest.HeadRequest;
55 import gr.grnet.pithos.web.client.rest.PutRequest;
56 import gr.grnet.pithos.web.client.rest.RestException;
57
58 import java.util.ArrayList;
59 import java.util.HashMap;
60 import java.util.Iterator;
61 import java.util.List;
62 import java.util.Set;
63
64 import com.google.gwt.core.client.EntryPoint;
65 import com.google.gwt.core.client.GWT;
66 import com.google.gwt.core.client.Scheduler;
67 import com.google.gwt.core.client.Scheduler.RepeatingCommand;
68 import com.google.gwt.core.client.Scheduler.ScheduledCommand;
69 import com.google.gwt.event.dom.client.ClickEvent;
70 import com.google.gwt.event.dom.client.ClickHandler;
71 import com.google.gwt.event.logical.shared.ResizeEvent;
72 import com.google.gwt.event.logical.shared.ResizeHandler;
73 import com.google.gwt.http.client.Request;
74 import com.google.gwt.http.client.RequestBuilder;
75 import com.google.gwt.http.client.RequestCallback;
76 import com.google.gwt.http.client.RequestException;
77 import com.google.gwt.http.client.Response;
78 import com.google.gwt.http.client.URL;
79 import com.google.gwt.i18n.client.Dictionary;
80 import com.google.gwt.i18n.client.NumberFormat;
81 import com.google.gwt.json.client.JSONArray;
82 import com.google.gwt.json.client.JSONObject;
83 import com.google.gwt.json.client.JSONParser;
84 import com.google.gwt.json.client.JSONString;
85 import com.google.gwt.json.client.JSONValue;
86 import com.google.gwt.resources.client.ClientBundle;
87 import com.google.gwt.resources.client.CssResource;
88 import com.google.gwt.resources.client.ImageResource;
89 import com.google.gwt.resources.client.ClientBundle.Source;
90 import com.google.gwt.resources.client.ImageResource.ImageOptions;
91 import com.google.gwt.user.client.Command;
92 import com.google.gwt.user.client.Cookies;
93 import com.google.gwt.user.client.Event;
94 import com.google.gwt.user.client.History;
95 import com.google.gwt.user.client.Window;
96 import com.google.gwt.user.client.ui.AbstractImagePrototype;
97 import com.google.gwt.user.client.ui.Button;
98 import com.google.gwt.user.client.ui.Composite;
99 import com.google.gwt.user.client.ui.HTML;
100 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
101 import com.google.gwt.user.client.ui.HasVerticalAlignment;
102 import com.google.gwt.user.client.ui.HorizontalPanel;
103 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
104 import com.google.gwt.user.client.ui.RootPanel;
105 import com.google.gwt.user.client.ui.VerticalPanel;
106 import com.google.gwt.view.client.SelectionChangeEvent;
107 import com.google.gwt.view.client.SelectionChangeEvent.Handler;
108 import com.google.gwt.view.client.SingleSelectionModel;
109
110 /**
111  * Entry point classes define <code>onModuleLoad()</code>.
112  */
113 public class Pithos implements EntryPoint, ResizeHandler {
114
115         public static final String HOME_CONTAINER = "pithos";
116
117         public static final String TRASH_CONTAINER = "trash";
118
119         public static final Configuration config = GWT.create(Configuration.class);
120         
121         public interface Style extends CssResource {
122                 String commandAnchor();
123         }
124         
125         public interface Resources extends ClientBundle {
126                 @Source("Pithos.css")
127                 Style pithosCss();
128         }
129
130         public static Resources resources = GWT.create(Resources.class);
131         
132         /**
133          * Instantiate an application-level image bundle. This object will provide
134          * programmatic access to all the images needed by widgets.
135          */
136         static Images images = (Images) GWT.create(Images.class);
137
138     public String getUsername() {
139         return username;
140     }
141
142     public void setAccount(AccountResource acct) {
143         account = acct;
144     }
145
146     public AccountResource getAccount() {
147         return account;
148     }
149
150     public void updateFolder(Folder f, boolean showfiles, Command callback, final boolean openParent) {
151         folderTreeView.updateFolder(f, showfiles, callback, openParent);
152     }
153
154     public void updateGroupNode(Group group) {
155         groupTreeView.updateGroupNode(group);
156     }
157
158     public void updateMySharedRoot() {
159         mysharedTreeView.updateRoot();
160     }
161     
162     public void updateSharedFolder(Folder f, boolean showfiles, Command callback) {
163         mysharedTreeView.updateFolder(f, showfiles, callback);
164     }
165     
166     public void updateSharedFolder(Folder f, boolean showfiles) {
167         updateSharedFolder(f, showfiles, null);
168     }
169
170     public void updateOtherSharedFolder(Folder f, boolean showfiles) {
171         otherSharedTreeView.updateFolder(f, showfiles);
172     }
173
174     public MysharedTreeView getMySharedTreeView() {
175         return mysharedTreeView;
176     }
177
178     /**
179          * An aggregate image bundle that pulls together all the images for this
180          * application into a single bundle.
181          */
182         public interface Images extends TopPanel.Images, FileList.Images, ToolsMenu.Images {
183
184                 @Source("gr/grnet/pithos/resources/document.png")
185                 ImageResource folders();
186
187                 @Source("gr/grnet/pithos/resources/advancedsettings.png")
188                 @ImageOptions(width=32, height=32)
189                 ImageResource tools();
190         }
191
192         private Throwable error;
193         
194         /**
195          * The Application Clipboard implementation;
196          */
197         private Clipboard clipboard = new Clipboard();
198
199         /**
200          * The top panel that contains the menu bar.
201          */
202         private TopPanel topPanel;
203
204         /**
205          * The panel that contains the various system messages.
206          */
207         private MessagePanel messagePanel = new MessagePanel(this, Pithos.images);
208
209         /**
210          * The bottom panel that contains the status bar.
211          */
212         private StatusPanel statusPanel = null;
213
214         /**
215          * The file list widget.
216          */
217         private FileList fileList;
218
219         /**
220          * The tab panel that occupies the right side of the screen.
221          */
222         private VerticalPanel inner = new VerticalPanel();
223
224
225         /**
226          * The split panel that will contain the left and right panels.
227          */
228         private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
229
230         /**
231          * The currently selected item in the application, for use by the Edit menu
232          * commands. Potential types are Folder, File, User and Group.
233          */
234         private Object currentSelection;
235
236         public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
237
238     private String username = null;
239
240     /**
241      * The authentication token of the current user.
242      */
243     private String token;
244
245     VerticalPanel trees;
246     
247     SingleSelectionModel<Folder> folderTreeSelectionModel;
248     FolderTreeViewModel folderTreeViewModel;
249     FolderTreeView folderTreeView;
250
251     SingleSelectionModel<Folder> mysharedTreeSelectionModel;
252     MysharedTreeViewModel mysharedTreeViewModel;
253     MysharedTreeView mysharedTreeView = null;;
254
255     protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
256     OtherSharedTreeViewModel otherSharedTreeViewModel;
257     OtherSharedTreeView otherSharedTreeView = null;
258
259     GroupTreeViewModel groupTreeViewModel;
260     GroupTreeView groupTreeView;
261
262     TreeView selectedTree;
263     protected AccountResource account;
264     
265     Folder trash;
266     
267     List<Composite> treeViews = new ArrayList<Composite>();
268
269     @SuppressWarnings("rawtypes") List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
270     
271     Button upload;
272     
273     private HTML numOfFiles;
274     
275     private Toolbar toolbar;
276     
277     private FileUploadDialog fileUploadDialog;
278     
279         @Override
280         public void onModuleLoad() {
281                 if (parseUserCredentials())
282             initialize();
283         }
284
285     private void initialize() {
286         resources.pithosCss().ensureInjected();
287         boolean bareContent = Window.Location.getParameter("noframe") != null;
288         String contentWidth = bareContent ? "100%" : "75%";
289
290         VerticalPanel outer = new VerticalPanel();
291         outer.setWidth("100%");
292         if (!bareContent) {
293                 outer.addStyleName("pithos-outer");
294         }
295
296         if (!bareContent) {
297                 topPanel = new TopPanel(this, Pithos.images);
298                 topPanel.setWidth("100%");
299                 outer.add(topPanel);
300                 outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
301         }
302         
303         messagePanel.setVisible(false);
304         outer.add(messagePanel);
305         outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
306         outer.setCellVerticalAlignment(messagePanel, HasVerticalAlignment.ALIGN_MIDDLE);
307
308         HorizontalPanel header = new HorizontalPanel();
309         header.addStyleName("pithos-header");
310         header.setWidth(contentWidth);
311         if (bareContent)
312                 header.addStyleName("pithos-header-noframe");
313         upload = new Button("Upload", new ClickHandler() {
314             @Override
315             public void onClick(ClickEvent event) {
316                 if (getSelection() != null)
317                         new UploadFileCommand(Pithos.this, null, getSelection()).execute();
318             }
319         });
320         upload.addStyleName("pithos-uploadButton");
321         header.add(upload);
322         header.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_LEFT);
323         header.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
324
325         toolbar = new Toolbar(this);
326         header.add(toolbar);
327         header.setCellHorizontalAlignment(toolbar, HasHorizontalAlignment.ALIGN_CENTER);
328         header.setCellVerticalAlignment(toolbar, HasVerticalAlignment.ALIGN_MIDDLE);
329         
330         HorizontalPanel folderStatistics = new HorizontalPanel();
331         folderStatistics.addStyleName("pithos-folderStatistics");
332         numOfFiles = new HTML();
333         folderStatistics.add(numOfFiles);
334         folderStatistics.setCellVerticalAlignment(numOfFiles, HasVerticalAlignment.ALIGN_MIDDLE);
335         HTML numOfFilesLabel = new HTML("&nbsp;Files");
336         folderStatistics.add(numOfFilesLabel);
337         folderStatistics.setCellVerticalAlignment(numOfFilesLabel, HasVerticalAlignment.ALIGN_MIDDLE);
338         header.add(folderStatistics);
339         header.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
340         header.setCellVerticalAlignment(folderStatistics, HasVerticalAlignment.ALIGN_MIDDLE);
341         header.setCellWidth(folderStatistics, "40px");
342         outer.add(header);
343         outer.setCellHorizontalAlignment(header, HasHorizontalAlignment.ALIGN_CENTER);
344         // Inner contains the various lists.nner
345         inner.sinkEvents(Event.ONCONTEXTMENU);
346         inner.setWidth("100%");
347
348         folderTreeSelectionModel = new SingleSelectionModel<Folder>();
349         folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
350             @Override
351             public void onSelectionChange(SelectionChangeEvent event) {
352                 if (folderTreeSelectionModel.getSelectedObject() != null) {
353                     deselectOthers(folderTreeView, folderTreeSelectionModel);
354                     applyPermissions(folderTreeSelectionModel.getSelectedObject());
355                     Folder f = folderTreeSelectionModel.getSelectedObject();
356                         updateFolder(f, true, new Command() {
357                                 
358                                 @Override
359                                 public void execute() {
360                                         updateStatistics();
361                                 }
362                         }, true);
363                         showRelevantToolbarButtons();
364                 }
365                                 else {
366                                         if (getSelectedTree().equals(folderTreeView))
367                                                 setSelectedTree(null);
368                                         if (getSelectedTree() == null)
369                                                 showRelevantToolbarButtons();
370                                 }
371             }
372         });
373         selectionModels.add(folderTreeSelectionModel);
374
375         folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
376         folderTreeView = new FolderTreeView(folderTreeViewModel);
377         treeViews.add(folderTreeView);
378         
379         fileList = new FileList(this, images);
380         inner.add(fileList);
381
382         trees = new VerticalPanel();
383         trees.setWidth("100%");
384         
385         // Add the left and right panels to the split panel.
386         splitPanel.setLeftWidget(trees);
387         splitPanel.setRightWidget(inner);
388         splitPanel.setSplitPosition("219px");
389         splitPanel.setSize("100%", "100%");
390         splitPanel.addStyleName("pithos-splitPanel");
391         splitPanel.setWidth(contentWidth);
392         outer.add(splitPanel);
393         outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
394
395         if (!bareContent) {
396                 statusPanel = new StatusPanel();
397                 statusPanel.setWidth("100%");
398                 outer.add(statusPanel);
399                 outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
400         }
401         else
402                 splitPanel.addStyleName("pithos-splitPanel-noframe");
403
404         // Hook the window resize event, so that we can adjust the UI.
405         Window.addResizeHandler(this);
406         // Clear out the window's built-in margin, because we want to take
407         // advantage of the entire client area.
408         Window.setMargin("0px");
409         // Finally, add the outer panel to the RootPanel, so that it will be
410         // displayed.
411         RootPanel.get().add(outer);
412         // Call the window resized handler to get the initial sizes setup. Doing
413         // this in a deferred command causes it to occur after all widgets'
414         // sizes have been computed by the browser.
415         Scheduler.get().scheduleDeferred(new ScheduledCommand() {
416
417             @Override
418             public void execute() {
419                 onWindowResized(Window.getClientHeight());
420             }
421         });
422
423         Scheduler.get().scheduleDeferred(new ScheduledCommand() {
424             @Override
425             public void execute() {
426                 fetchAccount(new Command() {
427                                         
428                                         @Override
429                                         public void execute() {
430                                 if (!account.hasHomeContainer())
431                                     createHomeContainer(account, this);
432                                 else if (!account.hasTrashContainer())
433                                         createTrashContainer(this);
434                                 else {
435                                         for (Folder f : account.getContainers())
436                                                 if (f.getName().equals(Pithos.TRASH_CONTAINER)) {
437                                                         trash = f;
438                                                         break;
439                                                 }
440                                     trees.add(folderTreeView);
441                                     folderTreeViewModel.initialize(account, new Command() {
442                                                                 
443                                                                 @Override
444                                                                 public void execute() {
445                                                     createMySharedTree();
446                                                                 }
447                                                         });
448
449                                     HorizontalPanel separator = new HorizontalPanel();
450                                     separator.addStyleName("pithos-statisticsSeparator");
451                                     separator.add(new HTML(""));
452                                     trees.add(separator);
453
454                                     groupTreeViewModel = new GroupTreeViewModel(Pithos.this);
455                                     groupTreeView = new GroupTreeView(groupTreeViewModel);
456                                     treeViews.add(groupTreeView);
457                                     trees.add(groupTreeView);
458                                     folderTreeView.showStatistics(account);
459                                 }
460                                         }
461                                 });
462             }
463         });
464         
465         Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {
466                         
467                         @Override
468                         public boolean execute() {
469                                 Folder f = getSelection();
470                                 if (f != null) {
471                                         if (getSelectedTree().equals(folderTreeView))
472                                                 updateFolder(f, true, null, false);
473                                         else if (getSelectedTree().equals(mysharedTreeView))
474                                                 updateSharedFolder(f, true);
475                                 }
476                                 return true;
477                         }
478                 }, 3000);
479     }
480
481     public void applyPermissions(Folder f) {
482         if (f != null) {
483                 if (f.isInTrash())
484                         upload.setEnabled(false);
485                 else {
486                         Boolean[] perms = f.getPermissions().get(username);
487                         if (f.getOwner().equals(username) || (perms != null && perms[1] != null && perms[1])) {
488                                 upload.setEnabled(true);
489                         }
490                         else
491                                 upload.setEnabled(false);
492                 }
493         }
494         else
495                 upload.setEnabled(false);
496         }
497
498         @SuppressWarnings({ "rawtypes", "unchecked" })
499         public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
500         selectedTree = _selectedTree;
501         
502         for (SingleSelectionModel s : selectionModels)
503             if (!s.equals(model) && s.getSelectedObject() != null)
504                 s.setSelected(s.getSelectedObject(), false);
505     }
506
507     public void showFiles(final Folder f) {
508         Set<File> files = f.getFiles();
509         showFiles(files);
510     }
511
512     public void showFiles(Set<File> files) {
513         fileList.setFiles(new ArrayList<File>(files));
514     }
515
516     /**
517          * Parse and store the user credentials to the appropriate fields.
518          */
519         private boolean parseUserCredentials() {
520         Configuration conf = (Configuration) GWT.create(Configuration.class);
521                 Dictionary otherProperties = Dictionary.getDictionary("otherProperties");
522         String cookie = otherProperties.get("authCookie");
523         String auth = Cookies.getCookie(cookie);
524         if (auth == null) {
525             authenticateUser();
526             return false;
527         }
528         if (auth.startsWith("\""))
529                 auth = auth.substring(1);
530         if (auth.endsWith("\""))
531                 auth = auth.substring(0, auth.length() - 1);
532                 String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
533                 if (authSplit.length != 2) {
534                     authenticateUser();
535                     return false;
536                 }
537                 username = authSplit[0];
538                 token = authSplit[1];
539
540         String gotoUrl = Window.Location.getParameter("goto");
541                 if (gotoUrl != null && gotoUrl.length() > 0) {
542                         Window.Location.assign(gotoUrl);
543                         return false;
544                 }
545                 return true;
546     }
547
548     /**
549          * Redirect the user to the login page for authentication.
550          */
551         protected void authenticateUser() {
552                 Dictionary otherProperties = Dictionary.getDictionary("otherProperties");
553         Window.Location.assign(otherProperties.get("loginUrl") + Window.Location.getHref());
554         }
555
556         protected void fetchAccount(final Command callback) {
557         String path = "?format=json";
558
559         GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getApiPath(), username, path) {
560             @Override
561             public void onSuccess(AccountResource _result) {
562                 account = _result;
563                 if (callback != null)
564                         callback.execute();
565             }
566
567             @Override
568             public void onError(Throwable t) {
569                 GWT.log("Error getting account", t);
570                                 setError(t);
571                 if (t instanceof RestException)
572                     displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
573                 else
574                     displayError("System error fetching user data: " + t.getMessage());
575             }
576
577                         @Override
578                         protected void onUnauthorized(Response response) {
579                                 sessionExpired();
580                         }
581         };
582         getAccount.setHeader("X-Auth-Token", token);
583         Scheduler.get().scheduleDeferred(getAccount);
584     }
585
586     public void updateStatistics() {
587         HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getApiPath(), username, "", account) {
588
589                         @Override
590                         public void onSuccess(AccountResource _result) {
591                                 folderTreeView.showStatistics(account);
592                         }
593
594                         @Override
595                         public void onError(Throwable t) {
596                 GWT.log("Error getting account", t);
597                                 setError(t);
598                 if (t instanceof RestException)
599                     displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
600                 else
601                     displayError("System error fetching user data: " + t.getMessage());
602                         }
603
604                         @Override
605                         protected void onUnauthorized(Response response) {
606                                 sessionExpired();
607                         }
608                 };
609                 headAccount.setHeader("X-Auth-Token", token);
610                 Scheduler.get().scheduleDeferred(headAccount);
611         }
612
613         protected void createHomeContainer(final AccountResource _account, final Command callback) {
614         String path = "/" + Pithos.HOME_CONTAINER;
615         PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
616             @Override
617             public void onSuccess(Resource result) {
618                 if (!_account.hasTrashContainer())
619                         createTrashContainer(callback);
620                 else
621                         fetchAccount(callback);
622             }
623
624             @Override
625             public void onError(Throwable t) {
626                 GWT.log("Error creating pithos", t);
627                                 setError(t);
628                 if (t instanceof RestException)
629                     displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
630                 else
631                     displayError("System error Error creating pithos: " + t.getMessage());
632             }
633
634                         @Override
635                         protected void onUnauthorized(Response response) {
636                                 sessionExpired();
637                         }
638         };
639         createPithos.setHeader("X-Auth-Token", getToken());
640         Scheduler.get().scheduleDeferred(createPithos);
641     }
642
643     protected void createTrashContainer(final Command callback) {
644         String path = "/" + Pithos.TRASH_CONTAINER;
645         PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
646             @Override
647             public void onSuccess(Resource result) {
648                         fetchAccount(callback);
649             }
650
651             @Override
652             public void onError(Throwable t) {
653                 GWT.log("Error creating pithos", t);
654                                 setError(t);
655                 if (t instanceof RestException)
656                     displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
657                 else
658                     displayError("System error Error creating pithos: " + t.getMessage());
659             }
660
661                         @Override
662                         protected void onUnauthorized(Response response) {
663                                 sessionExpired();
664                         }
665         };
666         createPithos.setHeader("X-Auth-Token", getToken());
667         Scheduler.get().scheduleDeferred(createPithos);
668     }
669
670     /**
671          * Creates an HTML fragment that places an image & caption together, for use
672          * in a group header.
673          *
674          * @param imageProto an image prototype for an image
675          * @param caption the group caption
676          * @return the header HTML fragment
677          */
678         private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
679                 String captionHTML = "<table class='caption' cellpadding='0' " 
680                 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML() 
681                 + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'>&nbsp;" 
682                 + caption + "</b></td></tr></table>";
683                 return captionHTML;
684         }
685
686         protected void onWindowResized(int height) {
687                 // Adjust the split panel to take up the available room in the window.
688                 int newHeight = height - splitPanel.getAbsoluteTop();
689                 if (newHeight < 1)
690                         newHeight = 1;
691                 splitPanel.setHeight("" + newHeight);
692                 inner.setHeight("" + newHeight);
693         }
694
695         @Override
696         public void onResize(ResizeEvent event) {
697                 int height = event.getHeight();
698                 onWindowResized(height);
699         }
700
701         /**
702          * Display an error message.
703          *
704          * @param msg the message to display
705          */
706         public void displayError(String msg) {
707                 messagePanel.displayError(msg);
708         }
709
710         /**
711          * Display a warning message.
712          *
713          * @param msg the message to display
714          */
715         public void displayWarning(String msg) {
716                 messagePanel.displayWarning(msg);
717         }
718
719         /**
720          * Display an informational message.
721          *
722          * @param msg the message to display
723          */
724         public void displayInformation(String msg) {
725                 messagePanel.displayInformation(msg);
726         }
727
728         /**
729          * Retrieve the fileList.
730          *
731          * @return the fileList
732          */
733         public FileList getFileList() {
734                 return fileList;
735         }
736
737         /**
738          * Retrieve the topPanel.
739          *
740          * @return the topPanel
741          */
742         TopPanel getTopPanel() {
743                 return topPanel;
744         }
745
746         /**
747          * Retrieve the clipboard.
748          *
749          * @return the clipboard
750          */
751         public Clipboard getClipboard() {
752                 return clipboard;
753         }
754
755         public StatusPanel getStatusPanel() {
756                 return statusPanel;
757         }
758
759         public String getToken() {
760                 return token;
761         }
762
763         public static native void preventIESelection() /*-{
764                 $doc.body.onselectstart = function () { return false; };
765         }-*/;
766
767         public static native void enableIESelection() /*-{
768                 if ($doc.body.onselectstart != null)
769                 $doc.body.onselectstart = null;
770         }-*/;
771
772         /**
773          * @return the absolute path of the API root URL
774          */
775         public String getApiPath() {
776                 Configuration conf = (Configuration) GWT.create(Configuration.class);
777                 return conf.apiPath();
778         }
779
780         /**
781          * History support for folder navigation
782          * adds a new browser history entry
783          *
784          * @param key
785          */
786         public void updateHistory(String key){
787 //              Replace any whitespace of the initial string to "+"
788 //              String result = key.replaceAll("\\s","+");
789 //              Add a new browser history entry.
790 //              History.newItem(result);
791                 History.newItem(key);
792         }
793
794     public void deleteFolder(final Folder folder, final Command callback) {
795         String path = getApiPath() + folder.getOwner() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(folder.getPrefix()) + "&t=" + System.currentTimeMillis();
796         RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
797         builder.setHeader("X-Auth-Token", getToken());
798         try {
799             builder.sendRequest("", new RequestCallback() {
800                 @Override
801                 public void onResponseReceived(Request request, Response response) {
802                     if (response.getStatusCode() == Response.SC_OK) {
803                         JSONValue json = JSONParser.parseStrict(response.getText());
804                         JSONArray array = json.isArray();
805                         int i = 0;
806                         if (array != null) {
807                             deleteObject(folder, i, array, callback);
808                         }
809                     }
810                 }
811
812                 @Override
813                 public void onError(Request request, Throwable exception) {
814                         setError(exception);
815                     displayError("System error unable to delete folder: " + exception.getMessage());
816                 }
817             });
818         }
819         catch (RequestException e) {
820         }
821     }
822
823     void deleteObject(final Folder folder, final int i, final JSONArray array, final Command callback) {
824         if (i < array.size()) {
825             JSONObject o = array.get(i).isObject();
826             if (o != null && !o.containsKey("subdir")) {
827                 JSONString name = o.get("name").isString();
828                 String path = "/" + folder.getContainer() + "/" + name.stringValue();
829                 DeleteRequest delete = new DeleteRequest(getApiPath(), folder.getOwner(), URL.encode(path)) {
830                     @Override
831                     public void onSuccess(Resource result) {
832                         deleteObject(folder, i + 1, array, callback);
833                     }
834
835                     @Override
836                     public void onError(Throwable t) {
837                         GWT.log("", t);
838                                                 setError(t);
839                         displayError("System error unable to delete folder: " + t.getMessage());
840                     }
841
842                                 @Override
843                                 protected void onUnauthorized(Response response) {
844                                         sessionExpired();
845                                 }
846                 };
847                 delete.setHeader("X-Auth-Token", getToken());
848                 Scheduler.get().scheduleDeferred(delete);
849             }
850             else if (o != null) {
851                 String subdir = o.get("subdir").isString().stringValue();
852                 subdir = subdir.substring(0, subdir.length() - 1);
853                 String path = getApiPath() + getUsername() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(subdir) + "&t=" + System.currentTimeMillis();
854                 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
855                 builder.setHeader("X-Auth-Token", getToken());
856                 try {
857                     builder.sendRequest("", new RequestCallback() {
858                         @Override
859                         public void onResponseReceived(Request request, Response response) {
860                             if (response.getStatusCode() == Response.SC_OK) {
861                                 JSONValue json = JSONParser.parseStrict(response.getText());
862                                 JSONArray array2 = json.isArray();
863                                 if (array2 != null) {
864                                     int l = array.size();
865                                     for (int j=0; j<array2.size(); j++) {
866                                         array.set(l++, array2.get(j));
867                                     }
868                                 }
869                                 deleteObject(folder, i + 1, array, callback);
870                             }
871                         }
872
873                         @Override
874                         public void onError(Request request, Throwable exception) {
875                                 setError(exception);
876                             displayError("System error unable to delete folder: " + exception.getMessage());
877                         }
878                     });
879                 }
880                 catch (RequestException e) {
881                 }
882             }
883         }
884         else {
885             String path = folder.getUri();
886             DeleteRequest deleteFolder = new DeleteRequest(getApiPath(), getUsername(), URL.encode(path)) {
887                 @Override
888                 public void onSuccess(Resource result) {
889                     updateFolder(folder.getParent(), true, new Command() {
890                                                 
891                                                 @Override
892                                                 public void execute() {
893                                                         folderTreeSelectionModel.setSelected(folder.getParent(), true);
894                                                         updateStatistics();
895                                                         if (callback != null)
896                                                                 callback.execute();
897                                                 }
898                                         }, true);
899                 }
900
901                 @Override
902                 public void onError(Throwable t) {
903                     GWT.log("", t);
904                                         setError(t);
905                     if (t instanceof RestException) {
906                         if (((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND)
907                                 displayError("Unable to delete folder: "+((RestException) t).getHttpStatusText());
908                         else
909                                 onSuccess(null);
910                     }
911                     else
912                         displayError("System error unable to delete folder: " + t.getMessage());
913                 }
914
915                                 @Override
916                                 protected void onUnauthorized(Response response) {
917                                         sessionExpired();
918                                 }
919             };
920             deleteFolder.setHeader("X-Auth-Token", getToken());
921             Scheduler.get().scheduleDeferred(deleteFolder);
922         }
923     }
924
925     public FolderTreeView getFolderTreeView() {
926         return folderTreeView;
927     }
928
929     public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
930         if (iter.hasNext()) {
931             File file = iter.next();
932             String path = targetUri + "/" + file.getName();
933             PutRequest copyFile = new PutRequest(getApiPath(), targetUsername, path) {
934                 @Override
935                 public void onSuccess(Resource result) {
936                     copyFiles(iter, targetUsername, targetUri, callback);
937                 }
938
939                 @Override
940                 public void onError(Throwable t) {
941                     GWT.log("", t);
942                                         setError(t);
943                     if (t instanceof RestException) {
944                         displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
945                     }
946                     else
947                         displayError("System error unable to copy file: "+t.getMessage());
948                 }
949
950                                 @Override
951                                 protected void onUnauthorized(Response response) {
952                                         sessionExpired();
953                                 }
954             };
955             copyFile.setHeader("X-Auth-Token", getToken());
956             copyFile.setHeader("X-Copy-From", URL.encodePathSegment(file.getUri()));
957             if (!file.getOwner().equals(targetUsername))
958                 copyFile.setHeader("X-Source-Account", URL.encodePathSegment(file.getOwner()));
959             copyFile.setHeader("Content-Type", file.getContentType());
960             Scheduler.get().scheduleDeferred(copyFile);
961         }
962         else  if (callback != null) {
963             callback.execute();
964         }
965     }
966
967     public void copySubfolders(final Iterator<Folder> iter, final String targetUsername, final String targetUri, final Command callback) {
968         if (iter.hasNext()) {
969             final Folder f = iter.next();
970             copyFolder(f, targetUsername, targetUri, new Command() {
971                                 
972                                 @Override
973                                 public void execute() {
974                                         copySubfolders(iter, targetUsername, targetUri, callback);
975                                 }
976                         });
977         }
978         else  if (callback != null) {
979             callback.execute();
980         }
981     }
982
983     public void copyFolder(final Folder f, final String targetUsername, final String targetUri, final Command callback) {
984         String path = targetUri + "/" + f.getName();
985         PutRequest createFolder = new PutRequest(getApiPath(), targetUsername, path) {
986             @Override
987             public void onSuccess(Resource result) {
988                 GetRequest<Folder> getFolder = new GetRequest<Folder>(Folder.class, getApiPath(), f.getOwner(), "/" + f.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(f.getPrefix()), f) {
989
990                                         @Override
991                                         public void onSuccess(final Folder _f) {
992                                 Iterator<File> iter = _f.getFiles().iterator();
993                                 copyFiles(iter, targetUsername, targetUri + "/" + _f.getName(), new Command() {
994                                     @Override
995                                     public void execute() {
996                                         Iterator<Folder> iterf = _f.getSubfolders().iterator();
997                                         copySubfolders(iterf, targetUsername, targetUri + "/" + _f.getName(), callback);
998                                     }
999                                 });
1000                                         }
1001
1002                                         @Override
1003                                         public void onError(Throwable t) {
1004                                 GWT.log("", t);
1005                                                 setError(t);
1006                                 if (t instanceof RestException) {
1007                                     displayError("Unable to get folder: " + ((RestException) t).getHttpStatusText());
1008                                 }
1009                                 else
1010                                     displayError("System error getting folder: " + t.getMessage());
1011                                         }
1012
1013                                         @Override
1014                                         protected void onUnauthorized(Response response) {
1015                                                 sessionExpired();
1016                                         }
1017                                 };
1018                                 getFolder.setHeader("X-Auth-Token", getToken());
1019                                 Scheduler.get().scheduleDeferred(getFolder);
1020             }
1021
1022             @Override
1023             public void onError(Throwable t) {
1024                 GWT.log("", t);
1025                                 setError(t);
1026                if (t instanceof RestException) {
1027                     displayError("Unable to create folder: " + ((RestException) t).getHttpStatusText());
1028                 }
1029                 else
1030                     displayError("System error creating folder: " + t.getMessage());
1031             }
1032
1033                         @Override
1034                         protected void onUnauthorized(Response response) {
1035                                 sessionExpired();
1036                         }
1037         };
1038         createFolder.setHeader("X-Auth-Token", getToken());
1039         createFolder.setHeader("Accept", "*/*");
1040         createFolder.setHeader("Content-Length", "0");
1041         createFolder.setHeader("Content-Type", "application/folder");
1042         Scheduler.get().scheduleDeferred(createFolder);
1043     }
1044     
1045     public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1046         selectionModels.add(model);
1047     }
1048
1049         public OtherSharedTreeView getOtherSharedTreeView() {
1050                 return otherSharedTreeView;
1051         }
1052
1053         public void updateTrash(boolean showFiles, Command callback) {
1054                 updateFolder(trash, showFiles, callback, true);
1055         }
1056
1057         public void updateGroupsNode() {
1058                 groupTreeView.updateGroupNode(null);
1059         }
1060
1061         public Group addGroup(String groupname) {
1062                 Group newGroup = new Group(groupname);
1063                 account.addGroup(newGroup);
1064                 groupTreeView.updateGroupNode(null);
1065                 return newGroup;
1066         }
1067
1068         public void removeGroup(Group group) {
1069                 account.removeGroup(group);
1070                 updateGroupsNode();
1071         }
1072
1073         public TreeView getSelectedTree() {
1074                 return selectedTree;
1075         }
1076         
1077         public void setSelectedTree(TreeView selected) {
1078                 selectedTree = selected;
1079         }
1080
1081         public Folder getSelection() {
1082                 if (selectedTree != null)
1083                         return selectedTree.getSelection();
1084                 return null;
1085         }
1086
1087         public void showFolderStatistics(int folderFileCount) {
1088                 numOfFiles.setHTML(String.valueOf(folderFileCount));
1089         }
1090
1091         public GroupTreeView getGroupTreeView() {
1092                 return groupTreeView;
1093         }
1094
1095         public void sessionExpired() {
1096                 new SessionExpiredDialog(this).center();
1097         }
1098
1099         public void updateRootFolder(Command callback) {
1100                 updateFolder(account.getPithos(), false, callback, true);
1101         }
1102
1103         void createMySharedTree() {
1104                 mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1105                 mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1106                     @Override
1107                     public void onSelectionChange(SelectionChangeEvent event) {
1108                         if (mysharedTreeSelectionModel.getSelectedObject() != null) {
1109                             deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1110                             upload.setEnabled(false);
1111                             updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1112                                         showRelevantToolbarButtons();
1113                         }
1114                                 else {
1115                                         if (getSelectedTree().equals(mysharedTreeView))
1116                                                 setSelectedTree(null);
1117                                         if (getSelectedTree() == null)
1118                                                 showRelevantToolbarButtons();
1119                                 }
1120                     }
1121                 });
1122                 selectionModels.add(mysharedTreeSelectionModel);
1123                 mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1124                 mysharedTreeViewModel.initialize(new Command() {
1125                         
1126                         @Override
1127                         public void execute() {
1128                             mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1129                                 trees.insert(mysharedTreeView, 2);
1130                                 treeViews.add(mysharedTreeView);
1131                                 createOtherSharedTree();
1132                         }
1133                 });
1134         }
1135
1136         void createOtherSharedTree() {
1137                 otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1138                 otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1139                     @Override
1140                     public void onSelectionChange(SelectionChangeEvent event) {
1141                         if (otherSharedTreeSelectionModel.getSelectedObject() != null) {
1142                             deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1143                             applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1144                             updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true);
1145                                         showRelevantToolbarButtons();
1146                         }
1147                                 else {
1148                                         if (getSelectedTree().equals(otherSharedTreeView))
1149                                                 setSelectedTree(null);
1150                                         if (getSelectedTree() == null)
1151                                                 showRelevantToolbarButtons();
1152                                 }
1153                     }
1154                 });
1155                 selectionModels.add(otherSharedTreeSelectionModel);
1156                 otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1157                 otherSharedTreeViewModel.initialize(new Command() {
1158                         
1159                         @Override
1160                         public void execute() {
1161                             otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel);
1162                                 trees.insert(otherSharedTreeView, 1);
1163                                 treeViews.add(otherSharedTreeView);
1164                         }
1165                 });
1166         }
1167
1168         public native void log1(String message)/*-{
1169                 $wnd.console.log(message);
1170         }-*/;
1171
1172         public String getErrorData() {
1173                 if (error != null)
1174                         return error.toString();
1175                 return "";
1176         }
1177         
1178         public void setError(Throwable t) {
1179                 error = t;
1180         }
1181         
1182         public void showRelevantToolbarButtons() {
1183                 toolbar.showRelevantButtons();
1184         }
1185
1186         public FileUploadDialog getFileUploadDialog() {
1187                 if (fileUploadDialog == null)
1188                         fileUploadDialog = new FileUploadDialog(this);
1189                 return fileUploadDialog;
1190         }
1191
1192         public void hideUploadIndicator() {
1193                 upload.removeStyleName("pithos-uploadButton-loading");
1194                 upload.setTitle("");
1195         }
1196         
1197         public void showUploadIndicator() {
1198                 upload.addStyleName("pithos-uploadButton-loading");
1199                 upload.setTitle("Upload in progress. Click for details.");
1200         }
1201
1202         public void scheduleFolderHeadCommand(final Folder folder, final Command callback) {
1203                 if (folder == null) {
1204                         if (callback != null)
1205                                 callback.execute();
1206                 }
1207                 else {
1208                         HeadRequest<Folder> headFolder = new HeadRequest<Folder>(Folder.class, getApiPath(), folder.getOwner(), folder.getUri(), folder) {
1209         
1210                                 @Override
1211                                 public void onSuccess(Folder _result) {
1212                                         if (callback != null)
1213                                                 callback.execute();
1214                                 }
1215         
1216                                 @Override
1217                                 public void onError(Throwable t) {
1218                                 if (t instanceof RestException) {
1219                                         if (((RestException) t).getHttpStatusCode() == Response.SC_NOT_FOUND) {
1220                                 final String path = folder.getUri();
1221                                 PutRequest newFolder = new PutRequest(getApiPath(), folder.getOwner(), path) {
1222                                     @Override
1223                                     public void onSuccess(Resource _result) {
1224                                         scheduleFolderHeadCommand(folder, callback);
1225                                     }
1226         
1227                                     @Override
1228                                     public void onError(Throwable _t) {
1229                                         GWT.log("", _t);
1230                                                                 setError(_t);
1231                                         if(_t instanceof RestException){
1232                                             displayError("Unable to create folder: " + ((RestException) _t).getHttpStatusText());
1233                                         }
1234                                         else
1235                                             displayError("System error creating folder: " + _t.getMessage());
1236                                     }
1237         
1238                                                 @Override
1239                                                 protected void onUnauthorized(Response response) {
1240                                                         sessionExpired();
1241                                                 }
1242                                 };
1243                                 newFolder.setHeader("X-Auth-Token", getToken());
1244                                 newFolder.setHeader("Content-Type", "application/folder");
1245                                 newFolder.setHeader("Accept", "*/*");
1246                                 newFolder.setHeader("Content-Length", "0");
1247                                 Scheduler.get().scheduleDeferred(newFolder);
1248                                         }
1249                                         else
1250                                                 displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
1251                                 }
1252                                 else
1253                                     displayError("System error heading folder: " + t.getMessage());
1254         
1255                                 GWT.log("Error heading folder", t);
1256                                         setError(t);
1257                                 }
1258         
1259                                 @Override
1260                                 protected void onUnauthorized(Response response) {
1261                                         sessionExpired();
1262                                 }
1263                         };
1264                         headFolder.setHeader("X-Auth-Token", getToken());
1265                         Scheduler.get().scheduleDeferred(headFolder);
1266                 }
1267         }
1268
1269         public void scheduleFileHeadCommand(File f, final Command callback) {
1270                 HeadRequest<File> headFile = new HeadRequest<File>(File.class, getApiPath(), f.getOwner(), f.getUri(), f) {
1271
1272                         @Override
1273                         public void onSuccess(File _result) {
1274                                 if (callback != null)
1275                                         callback.execute();
1276                         }
1277
1278                         @Override
1279                         public void onError(Throwable t) {
1280                         GWT.log("Error heading file", t);
1281                                 setError(t);
1282                         if (t instanceof RestException)
1283                             displayError("Error heading file: " + ((RestException) t).getHttpStatusText());
1284                         else
1285                             displayError("System error heading file: " + t.getMessage());
1286                         }
1287
1288                         @Override
1289                         protected void onUnauthorized(Response response) {
1290                                 sessionExpired();
1291                         }
1292                 };
1293                 headFile.setHeader("X-Auth-Token", getToken());
1294                 Scheduler.get().scheduleDeferred(headFile);
1295         }
1296
1297         public boolean isMySharedSelected() {
1298                 return getSelectedTree().equals(getMySharedTreeView());
1299         }
1300 }