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