Statistics
| Branch: | Tag: | Revision:

root / web_client / src / gr / grnet / pithos / web / client / GSS.java @ 5eef5c8a

History | View | Annotate | Download (32.7 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
        if (f.isTrash()) {
355
            fileList.showTrash();
356
        }
357
        else
358
            fileList.showFiles();
359
        Set<File> files = f.getFiles();
360
        Iterator<File> iter = files.iterator();
361
        fetchFile(iter, files);
362
    }
363

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

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

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

    
415
    /**
416
         * Redirect the user to the login page for authentication.
417
         */
418
        protected void authenticateUser() {
419
                Configuration conf = (Configuration) GWT.create(Configuration.class);
420

    
421
//        Window.Location.assign(GWT.getModuleBaseURL() + conf.loginUrl() + "?next=" + Window.Location.getHref());
422
        Cookies.setCookie(conf.authCookie(), "test" + conf.cookieSeparator() + "0000");
423
        Window.Location.assign(GWT.getModuleBaseURL() + "GSS.html");
424
        }
425

    
426
    private void fetchAccount() {
427
        String path = getApiPath() + username + "?format=json";
428

    
429
        GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, path) {
430
            @Override
431
            public void onSuccess(AccountResource result) {
432
                account = result;
433
                statusPanel.displayStats(account);
434
                folderTreeViewModel.initialize(account);
435
                inner.selectTab(0);
436
            }
437

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

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

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

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

    
490
        @Override
491
        public void onResize(ResizeEvent event) {
492
                int height = event.getHeight();
493
                onWindowResized(height);
494
        }
495

    
496
        public boolean isFileListShowing() {
497
                int tab = inner.getTabBar().getSelectedTab();
498
                if (tab == 0)
499
                        return true;
500
                return false;
501
        }
502

    
503
        public boolean isSearchResultsShowing() {
504
                int tab = inner.getTabBar().getSelectedTab();
505
                if (tab == 2)
506
                        return true;
507
                return false;
508
        }
509

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

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

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

    
555
        /**
556
         * Hide the 'loading' indicator.
557
         */
558
        public void hideLoadingIndicator() {
559
                topPanel.getLoading().hide();
560
        }
561

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

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

    
583
        /**
584
         * Display an error message.
585
         *
586
         * @param msg the message to display
587
         */
588
        public void displayError(String msg) {
589
                messagePanel.displayError(msg);
590
        }
591

    
592
        /**
593
         * Display a warning message.
594
         *
595
         * @param msg the message to display
596
         */
597
        public void displayWarning(String msg) {
598
                messagePanel.displayWarning(msg);
599
        }
600

    
601
        /**
602
         * Display an informational message.
603
         *
604
         * @param msg the message to display
605
         */
606
        public void displayInformation(String msg) {
607
                messagePanel.displayInformation(msg);
608
        }
609

    
610
        /**
611
         * Retrieve the folders.
612
         *
613
         * @return the folders
614
         
615
        public Folders getFolders() {
616
                return folders;
617
        }*/
618

    
619
        /**
620
         * Retrieve the currentSelection.
621
         *
622
         * @return the currentSelection
623
         */
624
        public Object getCurrentSelection() {
625
                return currentSelection;
626
        }
627

    
628
        /**
629
         * Modify the currentSelection.
630
         *
631
         * @param newCurrentSelection the currentSelection to set
632
         */
633
        public void setCurrentSelection(Object newCurrentSelection) {
634
                currentSelection = newCurrentSelection;
635
        }
636

    
637
        /**
638
         * Retrieve the fileList.
639
         *
640
         * @return the fileList
641
         */
642
        public FileList getFileList() {
643
                return fileList;
644
        }
645

    
646
        /**
647
         * Retrieve the topPanel.
648
         *
649
         * @return the topPanel
650
         */
651
        TopPanel getTopPanel() {
652
                return topPanel;
653
        }
654

    
655
        /**
656
         * Retrieve the clipboard.
657
         *
658
         * @return the clipboard
659
         */
660
        public Clipboard getClipboard() {
661
                return clipboard;
662
        }
663

    
664
        public StatusPanel getStatusPanel() {
665
                return statusPanel;
666
        }
667

    
668
        /**
669
         * Retrieve the userDetailsPanel.
670
         *
671
         * @return the userDetailsPanel
672
         */
673
        public UserDetailsPanel getUserDetailsPanel() {
674
                return userDetailsPanel;
675
        }
676

    
677
        
678

    
679
        public String getToken() {
680
                return token;
681
        }
682

    
683
        public String getWebDAVPassword() {
684
                return webDAVPassword;
685
        }
686

    
687
        /**
688
         * Retrieve the currentUserResource.
689
         *
690
         * @return the currentUserResource
691
         */
692
        public UserResource getCurrentUserResource() {
693
                return currentUserResource;
694
        }
695

    
696
        /**
697
         * Modify the currentUserResource.
698
         *
699
         * @param newUser the new currentUserResource
700
         */
701
        public void setCurrentUserResource(UserResource newUser) {
702
                currentUserResource = newUser;
703
        }
704

    
705
        public static native void preventIESelection() /*-{
706
                $doc.body.onselectstart = function () { return false; };
707
        }-*/;
708

    
709
        public static native void enableIESelection() /*-{
710
                if ($doc.body.onselectstart != null)
711
                $doc.body.onselectstart = null;
712
        }-*/;
713

    
714
        /**
715
         * @return the absolute path of the API root URL
716
         */
717
        public String getApiPath() {
718
                Configuration conf = (Configuration) GWT.create(Configuration.class);
719
                return conf.apiPath();
720
        }
721

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

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

    
763
        private String handleSpecialFolderNames(String tokenInput){
764
                List<String> pathsToCheck = Arrays.asList("Files/trash", "Files/shared", "Files/others");
765
                if(pathsToCheck.contains(tokenInput))
766
                        return tokenInput + "/";
767
                return tokenInput;
768

    
769
        }
770

    
771
        /**
772
         * Reject illegal resource names, like '.' or '..' or slashes '/'.
773
         */
774
        static boolean isValidResourceName(String name) {
775
                if (".".equals(name) ||        "..".equals(name) || name.contains("/"))
776
                        return false;
777
                return true;
778
        }
779

    
780
        public void putUserToMap(String _userName, String _userFullName){
781
                userFullNameMap.put(_userName, _userFullName);
782
        }
783

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

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

    
836
                @Override
837
                public void onError(Request request, Throwable exception) {
838
                    GSS.get().displayError("System error unable to delete folder: " + exception.getMessage());
839
                }
840
            });
841
        }
842
        catch (RequestException e) {
843
        }
844
    }
845

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

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

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

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

    
925
    public FolderTreeView getFolderTreeView() {
926
        return folderTreeView;
927
    }
928

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

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

    
958
    public void copySubfolders(final Iterator<Folder> iter, final String targetUri, final Command callback) {
959
        if (iter.hasNext()) {
960
            final Folder f = iter.next();
961
            copyFolder(f, targetUri, callback);
962
        }
963
        else  if (callback != null) {
964
            callback.execute();
965
        }
966
    }
967

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

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