Statistics
| Branch: | Tag: | Revision:

root / web_client / src / gr / grnet / pithos / web / client / GSS.java @ 33b61be6

History | View | Annotate | Download (32.6 kB)

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.SingleSelectionModel;
52
import gr.grnet.pithos.web.client.commands.GetUserCommand;
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
import gr.grnet.pithos.web.client.rest.resource.FileResource;
64
import gr.grnet.pithos.web.client.rest.resource.OtherUserResource;
65
import gr.grnet.pithos.web.client.rest.resource.RestResource;
66
import gr.grnet.pithos.web.client.rest.resource.RestResourceWrapper;
67
import gr.grnet.pithos.web.client.rest.resource.SharedResource;
68
import gr.grnet.pithos.web.client.rest.resource.TrashResource;
69
import gr.grnet.pithos.web.client.rest.resource.UserResource;
70

    
71
import java.util.ArrayList;
72
import java.util.Arrays;
73
import java.util.Date;
74
import java.util.HashMap;
75
import java.util.Iterator;
76
import java.util.List;
77

    
78
import com.google.gwt.core.client.EntryPoint;
79
import com.google.gwt.core.client.GWT;
80
import com.google.gwt.event.logical.shared.ResizeEvent;
81
import com.google.gwt.event.logical.shared.ResizeHandler;
82
import com.google.gwt.event.logical.shared.SelectionEvent;
83
import com.google.gwt.event.logical.shared.SelectionHandler;
84
import com.google.gwt.http.client.URL;
85
import com.google.gwt.i18n.client.DateTimeFormat;
86
import com.google.gwt.resources.client.ClientBundle;
87
import com.google.gwt.resources.client.ImageResource;
88
import com.google.gwt.user.client.Cookies;
89
import com.google.gwt.user.client.Event;
90
import com.google.gwt.user.client.History;
91
import com.google.gwt.user.client.Window;
92
import com.google.gwt.user.client.ui.AbstractImagePrototype;
93
import com.google.gwt.user.client.ui.DecoratedTabPanel;
94
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
95
import com.google.gwt.user.client.ui.HorizontalSplitPanel;
96
import com.google.gwt.user.client.ui.RootPanel;
97
import com.google.gwt.user.client.ui.TabPanel;
98
import com.google.gwt.user.client.ui.VerticalPanel;
99
import java.util.Set;
100

    
101
/**
102
 * Entry point classes define <code>onModuleLoad()</code>.
103
 */
104
public class GSS implements EntryPoint, ResizeHandler {
105

    
106
        /**
107
         * A constant that denotes the completion of an IncrementalCommand.
108
         */
109
        public static final boolean DONE = false;
110

    
111
        public static final int VISIBLE_FILE_COUNT = 25;
112

    
113
        /**
114
         * Instantiate an application-level image bundle. This object will provide
115
         * programmatic access to all the images needed by widgets.
116
         */
117
        private static Images images = (Images) GWT.create(Images.class);
118

    
119
    public String getUsername() {
120
        return username;
121
    }
122

    
123
    public void setAccount(AccountResource acct) {
124
        account = acct;
125
    }
126

    
127
    public AccountResource getAccount() {
128
        return account;
129
    }
130

    
131
    public void updateFolder(Folder f) {
132
        folderTreeView.updateFolder(f);
133
    }
134

    
135
    /**
136
         * An aggregate image bundle that pulls together all the images for this
137
         * application into a single bundle.
138
         */
139
        public interface Images extends ClientBundle, TopPanel.Images, StatusPanel.Images, FileMenu.Images, EditMenu.Images, SettingsMenu.Images, FilePropertiesDialog.Images, MessagePanel.Images, FileList.Images, Search.Images, CellTreeView.Images {
140

    
141
                @Source("gr/grnet/pithos/resources/document.png")
142
                ImageResource folders();
143

    
144
                @Source("gr/grnet/pithos/resources/edit_group_22.png")
145
                ImageResource groups();
146

    
147
                @Source("gr/grnet/pithos/resources/search.png")
148
                ImageResource search();
149
        }
150

    
151
        /**
152
         * The single GSS instance.
153
         */
154
        private static GSS singleton;
155

    
156
        /**
157
         * Gets the singleton GSS instance.
158
         *
159
         * @return the GSS object
160
         */
161
        public static GSS get() {
162
                if (GSS.singleton == null)
163
                        GSS.singleton = new GSS();
164
                return GSS.singleton;
165
        }
166

    
167
        /**
168
         * The Application Clipboard implementation;
169
         */
170
        private Clipboard clipboard = new Clipboard();
171

    
172
        private UserResource currentUserResource;
173

    
174
        /**
175
         * The top panel that contains the menu bar.
176
         */
177
        private TopPanel topPanel;
178

    
179
        /**
180
         * The panel that contains the various system messages.
181
         */
182
        private MessagePanel messagePanel = new MessagePanel(GSS.images);
183

    
184
        /**
185
         * The bottom panel that contains the status bar.
186
         */
187
        private StatusPanel statusPanel = null;
188

    
189
        /**
190
         * The top right panel that displays the logged in user details
191
         */
192
        private UserDetailsPanel userDetailsPanel = new UserDetailsPanel();
193

    
194
        /**
195
         * The file list widget.
196
         */
197
        private FileList fileList;
198

    
199
        /**
200
         * The tab panel that occupies the right side of the screen.
201
         */
202
        private TabPanel inner = new DecoratedTabPanel(){
203
                
204
//                public void onBrowserEvent(com.google.gwt.user.client.Event event) {
205
//                        if (DOM.eventGetType(event) == Event.ONCONTEXTMENU){
206
//                                if(isFileListShowing()){
207
//                                        getFileList().showContextMenu(event);
208
//                                }
209
//                        }
210
//                };
211
        };
212

    
213

    
214
        /**
215
         * The split panel that will contain the left and right panels.
216
         */
217
        private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
218

    
219
        /**
220
         * The widget that displays the tree of folders.
221
         */
222
        
223
        private CellTreeView treeView = null;
224
        /**
225
         * The currently selected item in the application, for use by the Edit menu
226
         * commands. Potential types are Folder, File, User and Group.
227
         */
228
        private Object currentSelection;
229

    
230

    
231
        /**
232
         * The WebDAV password of the current user
233
         */
234
        private String webDAVPassword;
235

    
236
        public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
237

    
238
    private String username = null;
239

    
240
    /**
241
     * The authentication token of the current user.
242
     */
243
    private String token;
244

    
245
    private SingleSelectionModel<Folder> folderTreeSelectionModel;
246
    private FolderTreeViewModel folderTreeViewModel;
247
    private FolderTreeView folderTreeView;
248

    
249
    private AccountResource account;
250

    
251
        @Override
252
        public void onModuleLoad() {
253
                // Initialize the singleton before calling the constructors of the
254
                // various widgets that might call GSS.get().
255
                singleton = this;
256
                if (parseUserCredentials())
257
            initialize();
258
        }
259

    
260
    private void initialize() {
261
        topPanel = new TopPanel(GSS.images);
262
        topPanel.setWidth("100%");
263

    
264
        messagePanel.setWidth("100%");
265
        messagePanel.setVisible(false);
266

    
267

    
268
        // Inner contains the various lists.
269
        inner.sinkEvents(Event.ONCONTEXTMENU);
270
        inner.setAnimationEnabled(true);
271
        inner.getTabBar().addStyleName("pithos-MainTabBar");
272
        inner.getDeckPanel().addStyleName("pithos-MainTabPanelBottom");
273

    
274
        inner.setWidth("100%");
275

    
276
        inner.addSelectionHandler(new SelectionHandler<Integer>() {
277

    
278
            @Override
279
            public void onSelection(SelectionEvent<Integer> event) {
280
                int tabIndex = event.getSelectedItem();
281
                switch (tabIndex) {
282
                    case 0:
283
                        fileList.updateCurrentlyShowingStats();
284
                        break;
285
                }
286
            }
287
        });
288

    
289
        folderTreeSelectionModel = new SingleSelectionModel<Folder>();
290
        folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
291
            @Override
292
            public void onSelectionChange(SelectionChangeEvent event) {
293
                Folder f = folderTreeSelectionModel.getSelectedObject();
294
                updateFolder(f);
295
            }
296
        });
297

    
298
        folderTreeViewModel = new FolderTreeViewModel(folderTreeSelectionModel);
299
        folderTreeView = new FolderTreeView(folderTreeViewModel);
300

    
301
        fileList = new FileList(images, folderTreeView);
302
        inner.add(fileList, createHeaderHTML(AbstractImagePrototype.create(images.folders()), "Files"), true);
303

    
304
        // Add the left and right panels to the split panel.
305
        splitPanel.setLeftWidget(folderTreeView);
306
        splitPanel.setRightWidget(inner);
307
        splitPanel.setSplitPosition("25%");
308
        splitPanel.setSize("100%", "100%");
309
        splitPanel.addStyleName("pithos-splitPanel");
310

    
311
        // Create a dock panel that will contain the menu bar at the top,
312
        // the shortcuts to the left, the status bar at the bottom and the
313
        // right panel taking the rest.
314
        VerticalPanel outer = new VerticalPanel();
315
        outer.add(topPanel);
316
        outer.add(messagePanel);
317
        outer.add(splitPanel);
318
        statusPanel = new StatusPanel(GSS.images);
319
        outer.add(statusPanel);
320
        outer.setWidth("100%");
321
        outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
322

    
323
        outer.setSpacing(4);
324

    
325
        // Hook the window resize event, so that we can adjust the UI.
326
        Window.addResizeHandler(this);
327
        // Clear out the window's built-in margin, because we want to take
328
        // advantage of the entire client area.
329
        Window.setMargin("0px");
330
        // Finally, add the outer panel to the RootPanel, so that it will be
331
        // displayed.
332
        RootPanel.get().add(outer);
333
        // Call the window resized handler to get the initial sizes setup. Doing
334
        // this in a deferred command causes it to occur after all widgets'
335
        // sizes have been computed by the browser.
336
        Scheduler.get().scheduleDeferred(new ScheduledCommand() {
337

    
338
            @Override
339
            public void execute() {
340
                onWindowResized(Window.getClientHeight());
341
            }
342
        });
343

    
344
        Scheduler.get().scheduleDeferred(new ScheduledCommand() {
345
            @Override
346
            public void execute() {
347
                fetchAccount();
348
            }
349
        });
350
    }
351

    
352
    public void showFiles(Folder f) {
353
        inner.selectTab(0);
354
        Set<File> files = f.getFiles();
355
        Iterator<File> iter = files.iterator();
356
        fetchFile(iter, files);
357
    }
358

    
359
    private void fetchFile(final Iterator<File> iter, final Set<File> files) {
360
        if (iter.hasNext()) {
361
            File file = iter.next();
362
            String path = getApiPath() + username + "/" + file.getContainer() + "/" + file.getPath() + "?format=json";
363
            GetRequest<File> getFile = new GetRequest<File>(File.class, path, file) {
364
                @Override
365
                public void onSuccess(File result) {
366
                    fetchFile(iter, files);
367
                }
368

    
369
                @Override
370
                public void onError(Throwable t) {
371
                    GWT.log("Error getting file", t);
372
                    if (t instanceof RestException)
373
                        GSS.get().displayError("Error getting file: " + ((RestException) t).getHttpStatusText());
374
                    else
375
                        GSS.get().displayError("System error fetching file: " + t.getMessage());
376
                }
377
            };
378
            getFile.setHeader("X-Auth-Token", "0000");
379
            Scheduler.get().scheduleDeferred(getFile);
380
        }
381
        else
382
            fileList.setFiles(new ArrayList<File>(files));
383
    }
384

    
385
    /**
386
         * Parse and store the user credentials to the appropriate fields.
387
         */
388
        private boolean parseUserCredentials() {
389
                Configuration conf = (Configuration) GWT.create(Configuration.class);
390
                String cookie = conf.authCookie();
391
                String auth = Cookies.getCookie(cookie);
392
                if (auth == null) {
393
                        authenticateUser();
394
            return false;
395
        }
396
        else {
397
            String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
398
            if (authSplit.length != 2) {
399
                authenticateUser();
400
                return false;
401
            }
402
            else {
403
                username = authSplit[0];
404
                token = authSplit[1];
405
                return true;
406
            }
407
        }
408
        }
409

    
410
    /**
411
         * Redirect the user to the login page for authentication.
412
         */
413
        protected void authenticateUser() {
414
                Configuration conf = (Configuration) GWT.create(Configuration.class);
415

    
416
//        Window.Location.assign(GWT.getModuleBaseURL() + conf.loginUrl() + "?next=" + Window.Location.getHref());
417
        Cookies.setCookie(conf.authCookie(), "test" + conf.cookieSeparator() + "0000");
418
        Window.Location.assign(GWT.getModuleBaseURL() + "GSS.html");
419
        }
420

    
421
    private void fetchAccount() {
422
        String path = getApiPath() + username + "?format=json";
423

    
424
        GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, path) {
425
            @Override
426
            public void onSuccess(AccountResource result) {
427
                account = result;
428
                statusPanel.displayStats(account);
429
                folderTreeViewModel.initialize(account);
430
                inner.selectTab(0);
431
            }
432

    
433
            @Override
434
            public void onError(Throwable t) {
435
                GWT.log("Error getting account", t);
436
                if (t instanceof RestException)
437
                    GSS.get().displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
438
                else
439
                    GSS.get().displayError("System error fetching user data: " + t.getMessage());
440
            }
441
        };
442
        getAccount.setHeader("X-Auth-Token", token);
443
        Scheduler.get().scheduleDeferred(getAccount);
444
    }
445

    
446
        /**
447
         * Clear the cookie and redirect the user to the logout page.
448
         */
449
        void logout() {
450
                Configuration conf = (Configuration) GWT.create(Configuration.class);
451
                String cookie = conf.authCookie();
452
                String domain = Window.Location.getHostName();
453
                String path = Window.Location.getPath();
454
                Cookies.setCookie(cookie, "", null, domain, path, false);
455
        String baseUrl = GWT.getModuleBaseURL();
456
        String homeUrl = baseUrl.substring(0, baseUrl.indexOf(path));
457
                Window.Location.assign(homeUrl + conf.logoutUrl());
458
        }
459

    
460
        /**
461
         * Creates an HTML fragment that places an image & caption together, for use
462
         * in a group header.
463
         *
464
         * @param imageProto an image prototype for an image
465
         * @param caption the group caption
466
         * @return the header HTML fragment
467
         */
468
        private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
469
                String captionHTML = "<table class='caption' cellpadding='0' " 
470
                + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML() 
471
                + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'>&nbsp;" 
472
                + caption + "</b></td></tr></table>";
473
                return captionHTML;
474
        }
475

    
476
        private void onWindowResized(int height) {
477
                // Adjust the split panel to take up the available room in the window.
478
                int newHeight = height - splitPanel.getAbsoluteTop() - 44;
479
                if (newHeight < 1)
480
                        newHeight = 1;
481
                splitPanel.setHeight("" + newHeight);
482
                inner.setHeight("" + newHeight);
483
        }
484

    
485
        @Override
486
        public void onResize(ResizeEvent event) {
487
                int height = event.getHeight();
488
                onWindowResized(height);
489
        }
490

    
491
        public boolean isFileListShowing() {
492
                int tab = inner.getTabBar().getSelectedTab();
493
                if (tab == 0)
494
                        return true;
495
                return false;
496
        }
497

    
498
        public boolean isSearchResultsShowing() {
499
                int tab = inner.getTabBar().getSelectedTab();
500
                if (tab == 2)
501
                        return true;
502
                return false;
503
        }
504

    
505
        /**
506
         * Make the file list visible.
507
         *
508
         * @param update
509
         */
510
        public void showFileList(boolean update) {
511
                if(update){
512
                        getTreeView().refreshCurrentNode(true);
513
                }
514
                else{
515
                        RestResource currentFolder = getTreeView().getSelection();
516
                        if(currentFolder!=null){
517
                                showFileList(currentFolder);
518
                }
519
                }
520

    
521
        }
522
        
523
        public void showFileList(RestResource r) {
524
                showFileList(r,true);
525
        }
526
        
527
        public void showFileList(RestResource r, boolean clearSelection) {
528
                RestResource currentFolder = r;
529
                if(currentFolder!=null){
530
                        List<FileResource> files = null;
531
                        if (currentFolder instanceof RestResourceWrapper) {
532
                                RestResourceWrapper folder = (RestResourceWrapper) currentFolder;
533
                                files = folder.getResource().getFiles();
534
                        }
535
                }
536
                inner.selectTab(0);
537
        }
538

    
539
        /**
540
         * Display the 'loading' indicator.
541
         */
542
        public void showLoadingIndicator(String message, String path) {
543
                if(path!=null){
544
                        String[] split = path.split("/");
545
                        message = message +" "+URL.decode(split[split.length-1]);
546
                }
547
                topPanel.getLoading().show(message);
548
        }
549

    
550
        /**
551
         * Hide the 'loading' indicator.
552
         */
553
        public void hideLoadingIndicator() {
554
                topPanel.getLoading().hide();
555
        }
556

    
557
        /**
558
         * A native JavaScript method to reach out to the browser's window and
559
         * invoke its resizeTo() method.
560
         *
561
         * @param x the new width
562
         * @param y the new height
563
         */
564
        public static native void resizeTo(int x, int y) /*-{
565
                $wnd.resizeTo(x,y);
566
        }-*/;
567

    
568
        /**
569
         * A helper method that returns true if the user's list is currently visible
570
         * and false if it is hidden.
571
         *
572
         * @return true if the user list is visible
573
         */
574
        public boolean isUserListVisible() {
575
                return inner.getTabBar().getSelectedTab() == 1;
576
        }
577

    
578
        /**
579
         * Display an error message.
580
         *
581
         * @param msg the message to display
582
         */
583
        public void displayError(String msg) {
584
                messagePanel.displayError(msg);
585
        }
586

    
587
        /**
588
         * Display a warning message.
589
         *
590
         * @param msg the message to display
591
         */
592
        public void displayWarning(String msg) {
593
                messagePanel.displayWarning(msg);
594
        }
595

    
596
        /**
597
         * Display an informational message.
598
         *
599
         * @param msg the message to display
600
         */
601
        public void displayInformation(String msg) {
602
                messagePanel.displayInformation(msg);
603
        }
604

    
605
        /**
606
         * Retrieve the folders.
607
         *
608
         * @return the folders
609
         
610
        public Folders getFolders() {
611
                return folders;
612
        }*/
613

    
614
        /**
615
         * Retrieve the currentSelection.
616
         *
617
         * @return the currentSelection
618
         */
619
        public Object getCurrentSelection() {
620
                return currentSelection;
621
        }
622

    
623
        /**
624
         * Modify the currentSelection.
625
         *
626
         * @param newCurrentSelection the currentSelection to set
627
         */
628
        public void setCurrentSelection(Object newCurrentSelection) {
629
                currentSelection = newCurrentSelection;
630
        }
631

    
632
        /**
633
         * Retrieve the fileList.
634
         *
635
         * @return the fileList
636
         */
637
        public FileList getFileList() {
638
                return fileList;
639
        }
640

    
641
        /**
642
         * Retrieve the topPanel.
643
         *
644
         * @return the topPanel
645
         */
646
        TopPanel getTopPanel() {
647
                return topPanel;
648
        }
649

    
650
        /**
651
         * Retrieve the clipboard.
652
         *
653
         * @return the clipboard
654
         */
655
        public Clipboard getClipboard() {
656
                return clipboard;
657
        }
658

    
659
        public StatusPanel getStatusPanel() {
660
                return statusPanel;
661
        }
662

    
663
        /**
664
         * Retrieve the userDetailsPanel.
665
         *
666
         * @return the userDetailsPanel
667
         */
668
        public UserDetailsPanel getUserDetailsPanel() {
669
                return userDetailsPanel;
670
        }
671

    
672
        
673

    
674
        public String getToken() {
675
                return token;
676
        }
677

    
678
        public String getWebDAVPassword() {
679
                return webDAVPassword;
680
        }
681

    
682
        /**
683
         * Retrieve the currentUserResource.
684
         *
685
         * @return the currentUserResource
686
         */
687
        public UserResource getCurrentUserResource() {
688
                return currentUserResource;
689
        }
690

    
691
        /**
692
         * Modify the currentUserResource.
693
         *
694
         * @param newUser the new currentUserResource
695
         */
696
        public void setCurrentUserResource(UserResource newUser) {
697
                currentUserResource = newUser;
698
        }
699

    
700
        public static native void preventIESelection() /*-{
701
                $doc.body.onselectstart = function () { return false; };
702
        }-*/;
703

    
704
        public static native void enableIESelection() /*-{
705
                if ($doc.body.onselectstart != null)
706
                $doc.body.onselectstart = null;
707
        }-*/;
708

    
709
        /**
710
         * @return the absolute path of the API root URL
711
         */
712
        public String getApiPath() {
713
                Configuration conf = (Configuration) GWT.create(Configuration.class);
714
                return conf.apiPath();
715
        }
716

    
717
        /**
718
         * Convert server date to local time according to browser timezone
719
         * and format it according to localized pattern.
720
         * Time is always formatted to 24hr format.
721
         * NB: This assumes that server runs in UTC timezone. Otherwise
722
         * we would need to adjust for server time offset as well.
723
         *
724
         * @param date
725
         * @return String
726
         */
727
        public static String formatLocalDateTime(Date date) {
728
                Date convertedDate = new Date(date.getTime() - date.getTimezoneOffset());
729
                final DateTimeFormat dateFormatter = DateTimeFormat.getShortDateFormat();
730
                final DateTimeFormat timeFormatter = DateTimeFormat.getFormat("HH:mm");
731
                String datePart = dateFormatter.format(convertedDate);
732
                String timePart = timeFormatter.format(convertedDate);
733
                return datePart + " " + timePart;
734
        }
735
        
736
        /**
737
         * History support for folder navigation
738
         * adds a new browser history entry
739
         *
740
         * @param key
741
         */
742
        public void updateHistory(String key){
743
//                Replace any whitespace of the initial string to "+"
744
//                String result = key.replaceAll("\\s","+");
745
//                Add a new browser history entry.
746
//                History.newItem(result);
747
                History.newItem(key);
748
        }
749

    
750
        /**
751
         * This method examines the token input and add a "/" at the end in case it's omitted.
752
         * This happens only in Files/trash/, Files/shared/, Files/others.
753
         *
754
         * @param tokenInput
755
         * @return the formated token with a "/" at the end or the same tokenInput parameter
756
         */
757

    
758
        private String handleSpecialFolderNames(String tokenInput){
759
                List<String> pathsToCheck = Arrays.asList("Files/trash", "Files/shared", "Files/others");
760
                if(pathsToCheck.contains(tokenInput))
761
                        return tokenInput + "/";
762
                return tokenInput;
763

    
764
        }
765

    
766
        /**
767
         * Reject illegal resource names, like '.' or '..' or slashes '/'.
768
         */
769
        static boolean isValidResourceName(String name) {
770
                if (".".equals(name) ||        "..".equals(name) || name.contains("/"))
771
                        return false;
772
                return true;
773
        }
774

    
775
        public void putUserToMap(String _userName, String _userFullName){
776
                userFullNameMap.put(_userName, _userFullName);
777
        }
778

    
779
        public String findUserFullName(String _userName){
780
                return userFullNameMap.get(_userName);
781
        }
782
        public String getUserFullName(String _userName) {
783
                
784
        if (GSS.get().findUserFullName(_userName) == null)
785
                //if there is no userFullName found then the map fills with the given _userName,
786
                //so userFullName = _userName
787
                GSS.get().putUserToMap(_userName, _userName);
788
        else if(GSS.get().findUserFullName(_userName).indexOf('@') != -1){
789
                //if the userFullName = _userName the GetUserCommand updates the userFullName in the map
790
                GetUserCommand guc = new GetUserCommand(_userName);
791
                guc.execute();
792
        }
793
        return GSS.get().findUserFullName(_userName);
794
        }
795
        /**
796
         * Retrieve the treeView.
797
         *
798
         * @return the treeView
799
         */
800
        public CellTreeView getTreeView() {
801
                return treeView;
802
        }
803
        
804
        public void onResourceUpdate(RestResource resource,boolean clearSelection){
805
                if(resource instanceof RestResourceWrapper || resource instanceof OtherUserResource || resource instanceof TrashResource || resource instanceof SharedResource){
806
                        if(getTreeView().getSelection()!=null&&getTreeView().getSelection().getUri().equals(resource.getUri()))
807
                                showFileList(resource,clearSelection);
808
                }
809
                
810
        }
811

    
812
    public void deleteFolder(final Folder folder) {
813
        String path = getApiPath() + getUsername() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + folder.getPrefix();
814
        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
815
        builder.setHeader("If-Modified-Since", "0");
816
        builder.setHeader("X-Auth-Token", getToken());
817
        try {
818
            builder.sendRequest("", new RequestCallback() {
819
                @Override
820
                public void onResponseReceived(Request request, Response response) {
821
                    if (response.getStatusCode() == Response.SC_OK) {
822
                        JSONValue json = JSONParser.parseStrict(response.getText());
823
                        JSONArray array = json.isArray();
824
                        int i = 0;
825
                        if (array != null) {
826
                            deleteObject(folder, i, array);
827
                        }
828
                    }
829
                }
830

    
831
                @Override
832
                public void onError(Request request, Throwable exception) {
833
                    GSS.get().displayError("System error unable to delete folder: " + exception.getMessage());
834
                }
835
            });
836
        }
837
        catch (RequestException e) {
838
        }
839
    }
840

    
841
    public void deleteObject(final Folder folder, final int i, final JSONArray array) {
842
        if (i < array.size()) {
843
            JSONObject o = array.get(i).isObject();
844
            if (o != null && !o.containsKey("subdir")) {
845
                JSONString name = o.get("name").isString();
846
                String path = getApiPath() + getUsername() + "/" + folder.getContainer() + "/" + name.stringValue();
847
                DeleteRequest delete = new DeleteRequest(path) {
848
                    @Override
849
                    public void onSuccess(Resource result) {
850
                        deleteObject(folder, i + 1, array);
851
                    }
852

    
853
                    @Override
854
                    public void onError(Throwable t) {
855
                        GWT.log("", t);
856
                        GSS.get().displayError("System error unable to delete folder: " + t.getMessage());
857
                    }
858
                };
859
                delete.setHeader("X-Auth-Token", getToken());
860
                Scheduler.get().scheduleDeferred(delete);
861
            }
862
            else {
863
                String subdir = o.get("subdir").isString().stringValue();
864
                subdir = subdir.substring(0, subdir.length() - 1);
865
                String path = getApiPath() + getUsername() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + subdir;
866
                RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
867
                builder.setHeader("If-Modified-Since", "0");
868
                builder.setHeader("X-Auth-Token", getToken());
869
                try {
870
                    builder.sendRequest("", new RequestCallback() {
871
                        @Override
872
                        public void onResponseReceived(Request request, Response response) {
873
                            if (response.getStatusCode() == Response.SC_OK) {
874
                                JSONValue json = JSONParser.parseStrict(response.getText());
875
                                JSONArray array2 = json.isArray();
876
                                if (array2 != null) {
877
                                    int l = array.size();
878
                                    for (int j=0; j<array2.size(); j++) {
879
                                        array.set(l++, array2.get(j));
880
                                    }
881
                                }
882
                                deleteObject(folder, i + 1, array);
883
                            }
884
                        }
885

    
886
                        @Override
887
                        public void onError(Request request, Throwable exception) {
888
                            GSS.get().displayError("System error unable to delete folder: " + exception.getMessage());
889
                        }
890
                    });
891
                }
892
                catch (RequestException e) {
893
                }
894
            }
895
        }
896
        else {
897
            String prefix = folder.getPrefix();
898
            String path = getApiPath() + getUsername() + "/" + folder.getContainer() + (prefix.length() == 0 ? "" : "/" + prefix);
899
            DeleteRequest deleteFolder = new DeleteRequest(path) {
900
                @Override
901
                public void onSuccess(Resource result) {
902
                    updateFolder(folder.getParent());
903
                }
904

    
905
                @Override
906
                public void onError(Throwable t) {
907
                    GWT.log("", t);
908
                    if (t instanceof RestException) {
909
                        displayError("Unable to delete folder: "+((RestException) t).getHttpStatusText());
910
                    }
911
                    else
912
                        GSS.get().displayError("System error unable to delete folder: " + t.getMessage());
913
                }
914
            };
915
            deleteFolder.setHeader("X-Auth-Token", getToken());
916
            Scheduler.get().scheduleDeferred(deleteFolder);
917
        }
918
    }
919

    
920
    public FolderTreeView getFolderTreeView() {
921
        return folderTreeView;
922
    }
923

    
924
    public void copyFiles(final Iterator<File> iter, final String targetUri, final Command callback) {
925
        if (iter.hasNext()) {
926
            File file = iter.next();
927
            String path = getApiPath() + getUsername() + targetUri + "/" + file.getName();
928
            PutRequest copyFile = new PutRequest(path) {
929
                @Override
930
                public void onSuccess(Resource result) {
931
                    copyFiles(iter, targetUri, callback);
932
                }
933

    
934
                @Override
935
                public void onError(Throwable t) {
936
                    GWT.log("", t);
937
                    if (t instanceof RestException) {
938
                        GSS.get().displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
939
                    }
940
                    else
941
                        GSS.get().displayError("System error unable to copy file: "+t.getMessage());
942
                }
943
            };
944
            copyFile.setHeader("X-Auth-Token", getToken());
945
            copyFile.setHeader("X-Copy-From", file.getUri());
946
            Scheduler.get().scheduleDeferred(copyFile);
947
        }
948
        else  if (callback != null) {
949
            callback.execute();
950
        }
951
    }
952

    
953
    public void copySubfolders(final Iterator<Folder> iter, final String targetUri, final Command callback) {
954
        if (iter.hasNext()) {
955
            final Folder f = iter.next();
956
            copyFolder(f, targetUri, callback);
957
        }
958
        else  if (callback != null) {
959
            callback.execute();
960
        }
961
    }
962

    
963
    public void copyFolder(final Folder f, final String targetUri, final Command callback) {
964
        String path = getApiPath() + getUsername() + targetUri + "/" + f.getName();
965
        PutRequest createFolder = new PutRequest(path) {
966
            @Override
967
            public void onSuccess(Resource result) {
968
                Iterator<File> iter = f.getFiles().iterator();
969
                copyFiles(iter, targetUri + "/" + f.getName(), new Command() {
970
                    @Override
971
                    public void execute() {
972
                        Iterator<Folder> iterf = f.getSubfolders().iterator();
973
                        copySubfolders(iterf, targetUri + "/" + f.getName(), new Command() {
974
                            @Override
975
                            public void execute() {
976
                                callback.execute();
977
                            }
978
                        });
979
                    }
980
                });
981
            }
982

    
983
            @Override
984
            public void onError(Throwable t) {
985
                GWT.log("", t);
986
                if (t instanceof RestException) {
987
                    displayError("Unable to create folder:" + ((RestException) t).getHttpStatusText());
988
                }
989
                else
990
                    displayError("System error creating folder:" + t.getMessage());
991
            }
992
        };
993
        createFolder.setHeader("X-Auth-Token", getToken());
994
        createFolder.setHeader("Accept", "*/*");
995
        createFolder.setHeader("Content-Length", "0");
996
        createFolder.setHeader("Content-Type", "application/folder");
997
        Scheduler.get().scheduleDeferred(createFolder);
998
    }
999
}