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