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