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