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