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