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