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