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