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