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