Various experiments with asynchronous data providers
[pithos-web-client] / src / gr / grnet / pithos / web / client / Pithos.java
1 /*
2  * Copyright 2011 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 import gr.grnet.pithos.web.client.tagtree.Tag;
57 import gr.grnet.pithos.web.client.tagtree.TagTreeView;
58 import gr.grnet.pithos.web.client.tagtree.TagTreeViewModel;
59
60 import java.util.ArrayList;
61 import java.util.HashMap;
62 import java.util.Iterator;
63 import java.util.List;
64 import java.util.Set;
65
66 import com.google.gwt.core.client.EntryPoint;
67 import com.google.gwt.core.client.GWT;
68 import com.google.gwt.core.client.Scheduler;
69 import com.google.gwt.core.client.Scheduler.ScheduledCommand;
70 import com.google.gwt.event.dom.client.ClickEvent;
71 import com.google.gwt.event.dom.client.ClickHandler;
72 import com.google.gwt.event.logical.shared.ResizeEvent;
73 import com.google.gwt.event.logical.shared.ResizeHandler;
74 import com.google.gwt.http.client.Request;
75 import com.google.gwt.http.client.RequestBuilder;
76 import com.google.gwt.http.client.RequestCallback;
77 import com.google.gwt.http.client.RequestException;
78 import com.google.gwt.http.client.Response;
79 import com.google.gwt.http.client.URL;
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.ImageResource;
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.HTML;
95 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
96 import com.google.gwt.user.client.ui.HasVerticalAlignment;
97 import com.google.gwt.user.client.ui.HorizontalPanel;
98 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
99 import com.google.gwt.user.client.ui.RootPanel;
100 import com.google.gwt.user.client.ui.VerticalPanel;
101 import com.google.gwt.view.client.SelectionChangeEvent;
102 import com.google.gwt.view.client.SelectionChangeEvent.Handler;
103 import com.google.gwt.view.client.SingleSelectionModel;
104
105 /**
106  * Entry point classes define <code>onModuleLoad()</code>.
107  */
108 public class Pithos implements EntryPoint, ResizeHandler {
109
110         public static final String HOME_CONTAINER = "pithos";
111
112         public static final String TRASH_CONTAINER = "trash";
113         
114         /**
115          * Instantiate an application-level image bundle. This object will provide
116          * programmatic access to all the images needed by widgets.
117          */
118         static Images images = (Images) GWT.create(Images.class);
119
120     public String getUsername() {
121         return username;
122     }
123
124     public void setAccount(AccountResource acct) {
125         account = acct;
126     }
127
128     public AccountResource getAccount() {
129         return account;
130     }
131
132     public void updateFolder(Folder f, boolean showfiles, Command callback) {
133         folderTreeView.updateFolder(f, showfiles, callback);
134     }
135
136     public void updateGroupNode(Group group) {
137         groupTreeView.updateGroupNode(group);
138     }
139
140     public void updateSharedFolder(Folder f, boolean showfiles) {
141         mysharedTreeView.updateFolder(f, showfiles);
142     }
143     
144     public void updateOtherSharedFolder(Folder f, boolean showfiles) {
145         otherSharedTreeView.updateFolder(f, showfiles);
146     }
147
148     public List<Tag> getAllTags() {
149         List<Tag> tagList = new ArrayList<Tag>();
150         for (Folder f : account.getContainers()) {
151             for (String t : f.getTags()) {
152                 tagList.add(new Tag(t));
153             }
154         }
155         return tagList;
156     }
157
158     public MysharedTreeView getMySharedTreeView() {
159         return mysharedTreeView;
160     }
161
162     /**
163          * An aggregate image bundle that pulls together all the images for this
164          * application into a single bundle.
165          */
166         public interface Images extends TopPanel.Images, FileList.Images, ToolsMenu.Images {
167
168                 @Source("gr/grnet/pithos/resources/document.png")
169                 ImageResource folders();
170
171                 @Source("gr/grnet/pithos/resources/advancedsettings.png")
172                 ImageResource tools();
173         }
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(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     private GroupTreeView groupTreeView;
242
243     private TreeView selectedTree;
244     protected AccountResource account;
245     
246     Folder trash;
247
248     @SuppressWarnings("rawtypes") List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
249     
250     Button upload;
251     
252     private HTML totalFiles;
253     
254     private HTML usedBytes;
255     
256     private HTML totalBytes;
257     
258     private HTML usedPercent;
259     
260     private HTML numOfFiles;
261     
262     private Button toolsButton;
263
264         @Override
265         public void onModuleLoad() {
266                 if (parseUserCredentials())
267             initialize();
268         }
269
270     private void initialize() {
271         VerticalPanel outer = new VerticalPanel();
272         outer.setWidth("100%");
273
274         topPanel = new TopPanel(this, Pithos.images);
275         topPanel.setWidth("100%");
276         outer.add(topPanel);
277         outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
278         
279         messagePanel.setWidth("75%");
280         messagePanel.setVisible(false);
281         outer.add(messagePanel);
282         outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
283
284
285         // Inner contains the various lists.
286         inner.sinkEvents(Event.ONCONTEXTMENU);
287         inner.setWidth("100%");
288
289         HorizontalPanel rightside = new HorizontalPanel();
290         rightside.addStyleName("pithos-rightSide");
291         rightside.setSpacing(5);
292
293         toolsButton = new Button(AbstractImagePrototype.create(images.tools()).getHTML());
294         toolsButton.addClickHandler(new ClickHandler() {
295                         
296                         @Override
297                         public void onClick(ClickEvent event) {
298                 ToolsMenu menu = new ToolsMenu(Pithos.this, images, getSelectedTree(), getSelectedTree().getSelection(), getFileList().getSelectedFiles());
299                 if (!menu.isEmpty()) {
300                             menu.setPopupPosition(event.getClientX(), event.getClientY());
301                             menu.show();
302                 }
303                         }
304                 });
305         rightside.add(toolsButton);
306         rightside.setCellHorizontalAlignment(toolsButton, HasHorizontalAlignment.ALIGN_LEFT);
307         
308         HorizontalPanel folderStatistics = new HorizontalPanel();
309         folderStatistics.addStyleName("pithos-folderStatistics");
310         numOfFiles = new HTML();
311         folderStatistics.add(numOfFiles);
312         HTML numOfFilesLabel = new HTML("&nbsp;Files");
313         folderStatistics.add(numOfFilesLabel);
314         rightside.add(folderStatistics);
315         rightside.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
316
317         inner.add(rightside);
318         inner.setCellVerticalAlignment(rightside, HasVerticalAlignment.ALIGN_MIDDLE);
319         inner.setCellHeight(rightside, "60px");
320
321         folderTreeSelectionModel = new SingleSelectionModel<Folder>();
322         folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
323             @Override
324             public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
325                 if (folderTreeSelectionModel.getSelectedObject() != null) {
326                     deselectOthers(folderTreeView, folderTreeSelectionModel);
327                     applyPermissions(folderTreeSelectionModel.getSelectedObject());
328                     Folder f = folderTreeSelectionModel.getSelectedObject();
329                     updateFolder(f, true, null);
330                 }
331             }
332         });
333         selectionModels.add(folderTreeSelectionModel);
334
335         folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
336         folderTreeView = new FolderTreeView(folderTreeViewModel);
337
338         fileList = new FileList(this, images, folderTreeView);
339         inner.add(fileList);
340
341         groupTreeViewModel = new GroupTreeViewModel(this);
342         groupTreeView = new GroupTreeView(groupTreeViewModel);
343
344         trees = new VerticalPanel();
345         trees.setWidth("100%");
346
347         VerticalPanel uploadButtonPanel = new VerticalPanel();
348         upload = new Button("Upload File", new ClickHandler() {
349             @Override
350             public void onClick(@SuppressWarnings("unused") ClickEvent event) {
351                 new UploadFileCommand(Pithos.this, null, getSelection()).execute();
352             }
353         });
354         uploadButtonPanel.add(upload);
355         uploadButtonPanel.setWidth("100%");
356         uploadButtonPanel.setHeight("60px");
357         uploadButtonPanel.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_CENTER);
358         uploadButtonPanel.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
359         upload.addStyleName("pithos-uploadButton");
360         trees.add(uploadButtonPanel);
361         
362         HorizontalPanel treeHeader = new HorizontalPanel();
363         treeHeader.addStyleName("pithos-treeHeader");
364         treeHeader.setWidth("100%");
365         treeHeader.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
366         HorizontalPanel statistics = new HorizontalPanel();
367         statistics.add(new HTML("Total Objects:&nbsp;"));
368         totalFiles = new HTML();
369         statistics.add(totalFiles);
370         statistics.add(new HTML("&nbsp;|&nbsp;Used:&nbsp;"));
371         usedBytes = new HTML();
372         statistics.add(usedBytes);
373         statistics.add(new HTML("&nbsp;of&nbsp;"));
374         totalBytes = new HTML();
375         statistics.add(totalBytes);
376         statistics.add(new HTML("&nbsp;("));
377         usedPercent = new HTML();
378         statistics.add(usedPercent);
379         statistics.add(new HTML(")"));
380         treeHeader.add(statistics);
381         treeHeader.setCellHorizontalAlignment(statistics, HasHorizontalAlignment.ALIGN_LEFT);
382         trees.add(treeHeader);
383
384         trees.add(folderTreeView);
385         trees.add(groupTreeView);
386         // Add the left and right panels to the split panel.
387         splitPanel.setLeftWidget(trees);
388         splitPanel.setRightWidget(inner);
389         splitPanel.setSplitPosition("35%");
390         splitPanel.setSize("100%", "100%");
391         splitPanel.addStyleName("pithos-splitPanel");
392         splitPanel.setWidth("75%");
393         outer.add(splitPanel);
394         outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
395
396         statusPanel = new StatusPanel();
397         statusPanel.setWidth("100%");
398         outer.add(statusPanel);
399         outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
400
401         // Hook the window resize event, so that we can adjust the UI.
402         Window.addResizeHandler(this);
403         // Clear out the window's built-in margin, because we want to take
404         // advantage of the entire client area.
405         Window.setMargin("0px");
406         // Finally, add the outer panel to the RootPanel, so that it will be
407         // displayed.
408         RootPanel.get().add(outer);
409         // Call the window resized handler to get the initial sizes setup. Doing
410         // this in a deferred command causes it to occur after all widgets'
411         // sizes have been computed by the browser.
412         Scheduler.get().scheduleDeferred(new ScheduledCommand() {
413
414             @Override
415             public void execute() {
416                 onWindowResized(Window.getClientHeight());
417             }
418         });
419
420         Scheduler.get().scheduleDeferred(new ScheduledCommand() {
421             @Override
422             public void execute() {
423                 fetchAccount(new Command() {
424                                         
425                                         @Override
426                                         public void execute() {
427                                 if (!account.hasHomeContainer())
428                                     createHomeContainer(account, this);
429                                 else if (!account.hasTrashContainer())
430                                         createTrashContainer(this);
431                                 else {
432                                         for (Folder f : account.getContainers())
433                                                 if (f.getName().equals(Pithos.TRASH_CONTAINER)) {
434                                                         trash = f;
435                                                         break;
436                                                 }
437                                     folderTreeViewModel.initialize(account, new Command() {
438                                                                 
439                                                                 @Override
440                                                                 public void execute() {
441                                                     createMySharedTree();
442                                                                 }
443                                                         });
444                                     groupTreeViewModel.initialize();
445                                     showStatistics();
446                                 }
447                                         }
448                                 });
449             }
450         });
451     }
452
453     public void applyPermissions(Folder f) {
454         if (f != null) {
455                 if (f.isInTrash())
456                         upload.setEnabled(false);
457                 else {
458                         Boolean[] perms = f.getPermissions().get(username);
459                         if (f.getOwner().equals(username) || (perms != null && perms[1] != null && perms[1])) {
460                                 upload.setEnabled(true);
461                         }
462                         else
463                                 upload.setEnabled(false);
464                 }
465         }
466         else
467                 upload.setEnabled(false);
468         }
469
470         @SuppressWarnings({ "rawtypes", "unchecked" })
471         public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
472         selectedTree = _selectedTree;
473         for (SingleSelectionModel s : selectionModels)
474             if (!s.equals(model))
475                 s.setSelected(s.getSelectedObject(), false);
476     }
477
478     public void showFiles(Folder f) {
479         Set<File> files = f.getFiles();
480         showFiles(files);
481     }
482
483     public void showFiles(Set<File> files) {
484         //Iterator<File> iter = files.iterator();
485         //fetchFile(iter, files);
486         fileList.setFiles(new ArrayList<File>(files));
487     }
488
489     protected void fetchFile(final Iterator<File> iter, final Set<File> files) {
490         if (iter.hasNext()) {
491             File file = iter.next();
492             String path = file.getUri() + "?format=json";
493             GetRequest<File> getFile = new GetRequest<File>(File.class, getApiPath(), username, path, file) {
494                 @Override
495                 public void onSuccess(@SuppressWarnings("unused") File _result) {
496                     fetchFile(iter, files);
497                 }
498
499                 @Override
500                 public void onError(Throwable t) {
501                     GWT.log("Error getting file", t);
502                     if (t instanceof RestException)
503                         displayError("Error getting file: " + ((RestException) t).getHttpStatusText());
504                     else
505                         displayError("System error fetching file: " + t.getMessage());
506                 }
507
508                                 @Override
509                                 protected void onUnauthorized(Response response) {
510                                         sessionExpired();
511                                 }
512             };
513             getFile.setHeader("X-Auth-Token", "0000");
514             Scheduler.get().scheduleDeferred(getFile);
515         }
516         else
517             fileList.setFiles(new ArrayList<File>(files));
518     }
519
520     /**
521          * Parse and store the user credentials to the appropriate fields.
522          */
523         private boolean parseUserCredentials() {
524         username = Window.Location.getParameter("user");
525         token = Window.Location.getParameter("token");
526         Configuration conf = (Configuration) GWT.create(Configuration.class);
527         if (username == null || username.length() == 0 || token == null || token.length() == 0) {
528             String cookie = conf.authCookie();
529             String auth = Cookies.getCookie(cookie);
530             if (auth == null) {
531                 authenticateUser();
532                 return false;
533             }
534                         String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
535                         if (authSplit.length != 2) {
536                             authenticateUser();
537                             return false;
538                         }
539                         username = authSplit[0];
540                         token = authSplit[1];
541                         return true;
542         }
543                 Cookies.setCookie(conf.authCookie(), username + conf.cookieSeparator() + token);
544                 return true;
545     }
546
547     /**
548          * Redirect the user to the login page for authentication.
549          */
550         protected void authenticateUser() {
551                 Configuration conf = (Configuration) GWT.create(Configuration.class);
552         Window.Location.assign(conf.loginUrl() + "?next=" + Window.Location.getHref());
553         }
554
555         protected void fetchAccount(final Command callback) {
556         String path = "?format=json";
557
558         GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getApiPath(), username, path) {
559             @Override
560             public void onSuccess(AccountResource _result) {
561                 account = _result;
562                 if (callback != null)
563                         callback.execute();
564             }
565
566             @Override
567             public void onError(Throwable t) {
568                 GWT.log("Error getting account", t);
569                 if (t instanceof RestException)
570                     displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
571                 else
572                     displayError("System error fetching user data: " + t.getMessage());
573             }
574
575                         @Override
576                         protected void onUnauthorized(Response response) {
577                                 sessionExpired();
578                         }
579         };
580         getAccount.setHeader("X-Auth-Token", token);
581         Scheduler.get().scheduleDeferred(getAccount);
582     }
583
584     public void updateStatistics() {
585         HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getApiPath(), username, "", account) {
586
587                         @Override
588                         public void onSuccess(@SuppressWarnings("unused") AccountResource _result) {
589                                 showStatistics();
590                         }
591
592                         @Override
593                         public void onError(Throwable t) {
594                 GWT.log("Error getting account", t);
595                 if (t instanceof RestException)
596                     displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
597                 else
598                     displayError("System error fetching user data: " + t.getMessage());
599                         }
600
601                         @Override
602                         protected void onUnauthorized(Response response) {
603                                 sessionExpired();
604                         }
605                 };
606                 headAccount.setHeader("X-Auth-Token", token);
607                 Scheduler.get().scheduleDeferred(headAccount);
608         }
609
610         protected void showStatistics() {
611         totalFiles.setHTML(String.valueOf(account.getNumberOfObjects()));
612         usedBytes.setHTML(String.valueOf(account.getFileSizeAsString()));
613         totalBytes.setHTML(String.valueOf(account.getQuotaAsString()));
614         NumberFormat nf = NumberFormat.getPercentFormat();
615         usedPercent.setHTML(nf.format(account.getUsedPercentage()));
616         }
617
618         protected void createHomeContainer(final AccountResource _account, final Command callback) {
619         String path = "/" + Pithos.HOME_CONTAINER;
620         PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
621             @Override
622             public void onSuccess(@SuppressWarnings("unused") Resource result) {
623                 if (!_account.hasTrashContainer())
624                         createTrashContainer(callback);
625                 else
626                         fetchAccount(callback);
627             }
628
629             @Override
630             public void onError(Throwable t) {
631                 GWT.log("Error creating pithos", t);
632                 if (t instanceof RestException)
633                     displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
634                 else
635                     displayError("System error Error creating pithos: " + t.getMessage());
636             }
637
638                         @Override
639                         protected void onUnauthorized(Response response) {
640                                 sessionExpired();
641                         }
642         };
643         createPithos.setHeader("X-Auth-Token", getToken());
644         Scheduler.get().scheduleDeferred(createPithos);
645     }
646
647     protected void createTrashContainer(final Command callback) {
648         String path = "/" + Pithos.TRASH_CONTAINER;
649         PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
650             @Override
651             public void onSuccess(@SuppressWarnings("unused") Resource result) {
652                         fetchAccount(callback);
653             }
654
655             @Override
656             public void onError(Throwable t) {
657                 GWT.log("Error creating pithos", t);
658                 if (t instanceof RestException)
659                     displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
660                 else
661                     displayError("System error Error creating pithos: " + t.getMessage());
662             }
663
664                         @Override
665                         protected void onUnauthorized(Response response) {
666                                 sessionExpired();
667                         }
668         };
669         createPithos.setHeader("X-Auth-Token", getToken());
670         Scheduler.get().scheduleDeferred(createPithos);
671     }
672
673     /**
674          * Creates an HTML fragment that places an image & caption together, for use
675          * in a group header.
676          *
677          * @param imageProto an image prototype for an image
678          * @param caption the group caption
679          * @return the header HTML fragment
680          */
681         private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
682                 String captionHTML = "<table class='caption' cellpadding='0' " 
683                 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML() 
684                 + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'>&nbsp;" 
685                 + caption + "</b></td></tr></table>";
686                 return captionHTML;
687         }
688
689         protected void onWindowResized(int height) {
690                 // Adjust the split panel to take up the available room in the window.
691                 int newHeight = height - splitPanel.getAbsoluteTop() - 60;
692                 if (newHeight < 1)
693                         newHeight = 1;
694                 splitPanel.setHeight("" + newHeight);
695                 inner.setHeight("" + newHeight);
696         }
697
698         @Override
699         public void onResize(ResizeEvent event) {
700                 int height = event.getHeight();
701                 onWindowResized(height);
702         }
703
704         /**
705          * Display an error message.
706          *
707          * @param msg the message to display
708          */
709         public void displayError(String msg) {
710                 messagePanel.displayError(msg);
711         }
712
713         /**
714          * Display a warning message.
715          *
716          * @param msg the message to display
717          */
718         public void displayWarning(String msg) {
719                 messagePanel.displayWarning(msg);
720         }
721
722         /**
723          * Display an informational message.
724          *
725          * @param msg the message to display
726          */
727         public void displayInformation(String msg) {
728                 messagePanel.displayInformation(msg);
729         }
730
731         /**
732          * Retrieve the fileList.
733          *
734          * @return the fileList
735          */
736         public FileList getFileList() {
737                 return fileList;
738         }
739
740         /**
741          * Retrieve the topPanel.
742          *
743          * @return the topPanel
744          */
745         TopPanel getTopPanel() {
746                 return topPanel;
747         }
748
749         /**
750          * Retrieve the clipboard.
751          *
752          * @return the clipboard
753          */
754         public Clipboard getClipboard() {
755                 return clipboard;
756         }
757
758         public StatusPanel getStatusPanel() {
759                 return statusPanel;
760         }
761
762         public String getToken() {
763                 return token;
764         }
765
766         public static native void preventIESelection() /*-{
767                 $doc.body.onselectstart = function () { return false; };
768         }-*/;
769
770         public static native void enableIESelection() /*-{
771                 if ($doc.body.onselectstart != null)
772                 $doc.body.onselectstart = null;
773         }-*/;
774
775         /**
776          * @return the absolute path of the API root URL
777          */
778         public String getApiPath() {
779                 Configuration conf = (Configuration) GWT.create(Configuration.class);
780                 return conf.apiPath();
781         }
782
783         /**
784          * History support for folder navigation
785          * adds a new browser history entry
786          *
787          * @param key
788          */
789         public void updateHistory(String key){
790 //              Replace any whitespace of the initial string to "+"
791 //              String result = key.replaceAll("\\s","+");
792 //              Add a new browser history entry.
793 //              History.newItem(result);
794                 History.newItem(key);
795         }
796
797     public void deleteFolder(final Folder folder) {
798         String path = getApiPath() + folder.getOwner() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(folder.getPrefix()) + "&t=" + System.currentTimeMillis();
799         RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
800         builder.setHeader("X-Auth-Token", getToken());
801         try {
802             builder.sendRequest("", new RequestCallback() {
803                 @Override
804                 public void onResponseReceived(@SuppressWarnings("unused") Request request, Response response) {
805                     if (response.getStatusCode() == Response.SC_OK) {
806                         JSONValue json = JSONParser.parseStrict(response.getText());
807                         JSONArray array = json.isArray();
808                         int i = 0;
809                         if (array != null) {
810                             deleteObject(folder, i, array);
811                         }
812                     }
813                 }
814
815                 @Override
816                 public void onError(@SuppressWarnings("unused") Request request, Throwable exception) {
817                     displayError("System error unable to delete folder: " + exception.getMessage());
818                 }
819             });
820         }
821         catch (RequestException e) {
822         }
823     }
824
825     void deleteObject(final Folder folder, final int i, final JSONArray array) {
826         if (i < array.size()) {
827             JSONObject o = array.get(i).isObject();
828             if (o != null && !o.containsKey("subdir")) {
829                 JSONString name = o.get("name").isString();
830                 String path = "/" + folder.getContainer() + "/" + name.stringValue();
831                 DeleteRequest delete = new DeleteRequest(getApiPath(), folder.getOwner(), path) {
832                     @Override
833                     public void onSuccess(@SuppressWarnings("unused") Resource result) {
834                         deleteObject(folder, i + 1, array);
835                     }
836
837                     @Override
838                     public void onError(Throwable t) {
839                         GWT.log("", t);
840                         displayError("System error unable to delete folder: " + t.getMessage());
841                     }
842
843                                 @Override
844                                 protected void onUnauthorized(Response response) {
845                                         sessionExpired();
846                                 }
847                 };
848                 delete.setHeader("X-Auth-Token", getToken());
849                 Scheduler.get().scheduleDeferred(delete);
850             }
851             else if (o != null) {
852                 String subdir = o.get("subdir").isString().stringValue();
853                 subdir = subdir.substring(0, subdir.length() - 1);
854                 String path = getApiPath() + getUsername() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(subdir) + "&t=" + System.currentTimeMillis();
855                 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
856                 builder.setHeader("X-Auth-Token", getToken());
857                 try {
858                     builder.sendRequest("", new RequestCallback() {
859                         @Override
860                         public void onResponseReceived(@SuppressWarnings("unused") Request request, Response response) {
861                             if (response.getStatusCode() == Response.SC_OK) {
862                                 JSONValue json = JSONParser.parseStrict(response.getText());
863                                 JSONArray array2 = json.isArray();
864                                 if (array2 != null) {
865                                     int l = array.size();
866                                     for (int j=0; j<array2.size(); j++) {
867                                         array.set(l++, array2.get(j));
868                                     }
869                                 }
870                                 deleteObject(folder, i + 1, array);
871                             }
872                         }
873
874                         @Override
875                         public void onError(@SuppressWarnings("unused") Request request, Throwable 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(), path) {
887                 @Override
888                 public void onSuccess(@SuppressWarnings("unused") Resource result) {
889 //                      folderTreeSelectionModel.setSelected(folder.getParent(), true);
890                     updateFolder(folder.getParent(), true, new Command() {
891                                                 
892                                                 @Override
893                                                 public void execute() {
894                                                         updateStatistics();
895                                                 }
896                                         });
897                 }
898
899                 @Override
900                 public void onError(Throwable t) {
901                     GWT.log("", t);
902                     if (t instanceof RestException) {
903                         if (((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND)
904                                 displayError("Unable to delete folder: "+((RestException) t).getHttpStatusText());
905                         else
906                                 onSuccess(null);
907                     }
908                     else
909                         displayError("System error unable to delete folder: " + t.getMessage());
910                 }
911
912                                 @Override
913                                 protected void onUnauthorized(Response response) {
914                                         sessionExpired();
915                                 }
916             };
917             deleteFolder.setHeader("X-Auth-Token", getToken());
918             Scheduler.get().scheduleDeferred(deleteFolder);
919         }
920     }
921
922     public FolderTreeView getFolderTreeView() {
923         return folderTreeView;
924     }
925
926     public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
927         if (iter.hasNext()) {
928             File file = iter.next();
929             String path = targetUri + "/" + file.getName();
930             PutRequest copyFile = new PutRequest(getApiPath(), targetUsername, path) {
931                 @Override
932                 public void onSuccess(@SuppressWarnings("unused") Resource result) {
933                     copyFiles(iter, targetUsername, targetUri, callback);
934                 }
935
936                 @Override
937                 public void onError(Throwable t) {
938                     GWT.log("", t);
939                     if (t instanceof RestException) {
940                         displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
941                     }
942                     else
943                         displayError("System error unable to copy file: "+t.getMessage());
944                 }
945
946                                 @Override
947                                 protected void onUnauthorized(Response response) {
948                                         sessionExpired();
949                                 }
950             };
951             copyFile.setHeader("X-Auth-Token", getToken());
952             copyFile.setHeader("X-Copy-From", file.getUri());
953             if (!file.getOwner().equals(targetUsername))
954                 copyFile.setHeader("X-Source-Account", file.getOwner());
955             Scheduler.get().scheduleDeferred(copyFile);
956         }
957         else  if (callback != null) {
958             callback.execute();
959         }
960     }
961
962     public void copySubfolders(final Iterator<Folder> iter, final String targetUsername, final String targetUri, final Command callback) {
963         if (iter.hasNext()) {
964             final Folder f = iter.next();
965             copyFolder(f, targetUsername, targetUri, new Command() {
966                                 
967                                 @Override
968                                 public void execute() {
969                                         copySubfolders(iter, targetUsername, targetUri, callback);
970                                 }
971                         });
972         }
973         else  if (callback != null) {
974             callback.execute();
975         }
976     }
977
978     public void copyFolder(final Folder f, final String targetUsername, final String targetUri, final Command callback) {
979         String path = targetUri + "/" + f.getName();
980         PutRequest createFolder = new PutRequest(getApiPath(), targetUsername, path) {
981             @Override
982             public void onSuccess(@SuppressWarnings("unused") Resource result) {
983                 GetRequest<Folder> getFolder = new GetRequest<Folder>(Folder.class, getApiPath(), f.getOwner(), "/" + f.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(f.getPrefix()), f) {
984
985                                         @Override
986                                         public void onSuccess(final Folder _f) {
987                                 Iterator<File> iter = _f.getFiles().iterator();
988                                 copyFiles(iter, targetUsername, targetUri + "/" + _f.getName(), new Command() {
989                                     @Override
990                                     public void execute() {
991                                         Iterator<Folder> iterf = _f.getSubfolders().iterator();
992                                         copySubfolders(iterf, targetUsername, targetUri + "/" + _f.getName(), callback);
993                                     }
994                                 });
995                                         }
996
997                                         @Override
998                                         public void onError(Throwable t) {
999                                 GWT.log("", t);
1000                                 if (t instanceof RestException) {
1001                                     displayError("Unable to get folder: " + ((RestException) t).getHttpStatusText());
1002                                 }
1003                                 else
1004                                     displayError("System error getting folder: " + t.getMessage());
1005                                         }
1006
1007                                         @Override
1008                                         protected void onUnauthorized(Response response) {
1009                                                 sessionExpired();
1010                                         }
1011                                 };
1012                                 getFolder.setHeader("X-Auth-Token", getToken());
1013                                 Scheduler.get().scheduleDeferred(getFolder);
1014             }
1015
1016             @Override
1017             public void onError(Throwable t) {
1018                 GWT.log("", t);
1019                 if (t instanceof RestException) {
1020                     displayError("Unable to create folder: " + ((RestException) t).getHttpStatusText());
1021                 }
1022                 else
1023                     displayError("System error creating folder: " + t.getMessage());
1024             }
1025
1026                         @Override
1027                         protected void onUnauthorized(Response response) {
1028                                 sessionExpired();
1029                         }
1030         };
1031         createFolder.setHeader("X-Auth-Token", getToken());
1032         createFolder.setHeader("Accept", "*/*");
1033         createFolder.setHeader("Content-Length", "0");
1034         createFolder.setHeader("Content-Type", "application/folder");
1035         Scheduler.get().scheduleDeferred(createFolder);
1036     }
1037     
1038     public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1039         selectionModels.add(model);
1040     }
1041
1042         public OtherSharedTreeView getOtherSharedTreeView() {
1043                 return otherSharedTreeView;
1044         }
1045
1046         public void updateTrash(boolean showFiles, Command callback) {
1047                 updateFolder(trash, showFiles, callback);
1048         }
1049
1050         public void updateGroupsNode() {
1051                 groupTreeView.updateGroupNode(null);
1052         }
1053
1054         public void addGroup(String groupname) {
1055                 Group newGroup = new Group(groupname);
1056                 account.addGroup(newGroup);
1057                 groupTreeView.updateGroupNode(null);
1058         }
1059
1060         public void removeGroup(Group group) {
1061                 account.removeGroup(group);
1062                 updateGroupsNode();
1063         }
1064
1065         public TreeView getSelectedTree() {
1066                 return selectedTree;
1067         }
1068         
1069         public Folder getSelection() {
1070                 return selectedTree.getSelection();
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);
1087         }
1088
1089         void createMySharedTree() {
1090                 mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1091                 mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1092                     @Override
1093                     public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
1094                         if (mysharedTreeSelectionModel.getSelectedObject() != null) {
1095                             deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1096                             upload.setEnabled(false);
1097                             updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1098                         }
1099                     }
1100                 });
1101                 selectionModels.add(mysharedTreeSelectionModel);
1102                 mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1103                 mysharedTreeViewModel.initialize(new Command() {
1104                         
1105                         @Override
1106                         public void execute() {
1107                             mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1108                                 trees.insert(mysharedTreeView, 3);
1109                                 createOtherSharedTree();
1110                         }
1111                 });
1112         }
1113
1114         void createOtherSharedTree() {
1115                 otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1116                 otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1117                     @Override
1118                     public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
1119                         if (otherSharedTreeSelectionModel.getSelectedObject() != null) {
1120                             deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1121                             applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1122                             updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true);
1123                         }
1124                     }
1125                 });
1126                 selectionModels.add(otherSharedTreeSelectionModel);
1127                 otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1128                 otherSharedTreeViewModel.initialize(new Command() {
1129                         
1130                         @Override
1131                         public void execute() {
1132                             otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel);
1133                                 trees.insert(otherSharedTreeView, 4);
1134                         }
1135                 });
1136         }
1137
1138         public void logoff() {
1139         Configuration conf = (Configuration) GWT.create(Configuration.class);
1140                 Cookies.removeCookie(conf.authCookie());
1141                 Cookies.removeCookie(conf.authTokenCookie(), "/");
1142                 for (String s: Cookies.getCookieNames())
1143                         if (s.startsWith(conf.shibSessionCookiePrefix()))
1144                                 Cookies.removeCookie(s, "/");
1145                 Window.Location.assign(Window.Location.getPath());
1146         }
1147 }