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