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