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