Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (19.8 kB)

1
/*
2
 * Copyright (c) 2011 Greek Research and Technology Network
3
 */
4
package gr.grnet.pithos.web.client;
5

    
6
import com.google.gwt.core.client.Scheduler;
7
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
8
import com.google.gwt.user.client.ui.DockPanel;
9
import com.google.gwt.user.client.ui.HasVerticalAlignment;
10
import gr.grnet.pithos.web.client.clipboard.Clipboard;
11
import gr.grnet.pithos.web.client.commands.GetUserCommand;
12
import gr.grnet.pithos.web.client.foldertree.AccountResource;
13
import gr.grnet.pithos.web.client.foldertree.FolderTreeView;
14
import gr.grnet.pithos.web.client.rest.GetRequest;
15
import gr.grnet.pithos.web.client.rest.RestException;
16
import gr.grnet.pithos.web.client.rest.resource.FileResource;
17
import gr.grnet.pithos.web.client.rest.resource.OtherUserResource;
18
import gr.grnet.pithos.web.client.rest.resource.RestResource;
19
import gr.grnet.pithos.web.client.rest.resource.RestResourceWrapper;
20
import gr.grnet.pithos.web.client.rest.resource.SharedResource;
21
import gr.grnet.pithos.web.client.rest.resource.TrashResource;
22
import gr.grnet.pithos.web.client.rest.resource.UserResource;
23

    
24
import java.util.ArrayList;
25
import java.util.Arrays;
26
import java.util.Date;
27
import java.util.HashMap;
28
import java.util.List;
29

    
30
import com.google.gwt.core.client.EntryPoint;
31
import com.google.gwt.core.client.GWT;
32
import com.google.gwt.event.logical.shared.ResizeEvent;
33
import com.google.gwt.event.logical.shared.ResizeHandler;
34
import com.google.gwt.event.logical.shared.SelectionEvent;
35
import com.google.gwt.event.logical.shared.SelectionHandler;
36
import com.google.gwt.http.client.URL;
37
import com.google.gwt.i18n.client.DateTimeFormat;
38
import com.google.gwt.resources.client.ClientBundle;
39
import com.google.gwt.resources.client.ImageResource;
40
import com.google.gwt.user.client.Command;
41
import com.google.gwt.user.client.Cookies;
42
import com.google.gwt.user.client.DOM;
43
import com.google.gwt.user.client.DeferredCommand;
44
import com.google.gwt.user.client.Event;
45
import com.google.gwt.user.client.History;
46
import com.google.gwt.user.client.Window;
47
import com.google.gwt.user.client.ui.AbstractImagePrototype;
48
import com.google.gwt.user.client.ui.DecoratedTabPanel;
49
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
50
import com.google.gwt.user.client.ui.HorizontalSplitPanel;
51
import com.google.gwt.user.client.ui.RootPanel;
52
import com.google.gwt.user.client.ui.TabPanel;
53
import com.google.gwt.user.client.ui.VerticalPanel;
54

    
55
/**
56
 * Entry point classes define <code>onModuleLoad()</code>.
57
 */
58
public class GSS implements EntryPoint, ResizeHandler {
59

    
60
        /**
61
         * A constant that denotes the completion of an IncrementalCommand.
62
         */
63
        public static final boolean DONE = false;
64

    
65
        public static final int VISIBLE_FILE_COUNT = 25;
66

    
67
        /**
68
         * Instantiate an application-level image bundle. This object will provide
69
         * programmatic access to all the images needed by widgets.
70
         */
71
        private static Images images = (Images) GWT.create(Images.class);
72

    
73
    public String getUsername() {
74
        return username;
75
    }
76

    
77
    public void setAccount(AccountResource acct) {
78
        account = acct;
79
    }
80

    
81
    public AccountResource getAccount() {
82
        return account;
83
    }
84

    
85
    /**
86
         * An aggregate image bundle that pulls together all the images for this
87
         * application into a single bundle.
88
         */
89
        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 {
90

    
91
                @Source("gr/grnet/pithos/resources/document.png")
92
                ImageResource folders();
93

    
94
                @Source("gr/grnet/pithos/resources/edit_group_22.png")
95
                ImageResource groups();
96

    
97
                @Source("gr/grnet/pithos/resources/search.png")
98
                ImageResource search();
99
        }
100

    
101
        /**
102
         * The single GSS instance.
103
         */
104
        private static GSS singleton;
105

    
106
        /**
107
         * Gets the singleton GSS instance.
108
         *
109
         * @return the GSS object
110
         */
111
        public static GSS get() {
112
                if (GSS.singleton == null)
113
                        GSS.singleton = new GSS();
114
                return GSS.singleton;
115
        }
116

    
117
        /**
118
         * The Application Clipboard implementation;
119
         */
120
        private Clipboard clipboard = new Clipboard();
121

    
122
        private UserResource currentUserResource;
123

    
124
        /**
125
         * The top panel that contains the menu bar.
126
         */
127
        private TopPanel topPanel;
128

    
129
        /**
130
         * The panel that contains the various system messages.
131
         */
132
        private MessagePanel messagePanel = new MessagePanel(GSS.images);
133

    
134
        /**
135
         * The bottom panel that contains the status bar.
136
         */
137
        private StatusPanel statusPanel = null;
138

    
139
        /**
140
         * The top right panel that displays the logged in user details
141
         */
142
        private UserDetailsPanel userDetailsPanel = new UserDetailsPanel();
143

    
144
        /**
145
         * The file list widget.
146
         */
147
        private FileList fileList;
148

    
149
        /**
150
         * The tab panel that occupies the right side of the screen.
151
         */
152
        private TabPanel inner = new DecoratedTabPanel(){
153
                
154
                public void onBrowserEvent(com.google.gwt.user.client.Event event) {
155
                        if (DOM.eventGetType(event) == Event.ONCONTEXTMENU){
156
                                if(isFileListShowing()){
157
                                        getFileList().showContextMenu(event);
158
                                }
159
                        }
160
                };
161
        };
162

    
163
        /**
164
         * The split panel that will contain the left and right panels.
165
         */
166
        private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
167

    
168
        /**
169
         * The widget that displays the tree of folders.
170
         */
171
        
172
        private CellTreeView treeView = null;
173
        /**
174
         * The currently selected item in the application, for use by the Edit menu
175
         * commands. Potential types are Folder, File, User and Group.
176
         */
177
        private Object currentSelection;
178

    
179

    
180
        /**
181
         * The WebDAV password of the current user
182
         */
183
        private String webDAVPassword;
184

    
185
        public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
186

    
187
    private String username = null;
188

    
189
    /**
190
     * The authentication token of the current user.
191
     */
192
    private String token;
193

    
194
    private FolderTreeView folderTreeView = new FolderTreeView();
195

    
196
    private AccountResource account;
197

    
198
        @Override
199
        public void onModuleLoad() {
200
                // Initialize the singleton before calling the constructors of the
201
                // various widgets that might call GSS.get().
202
                singleton = this;
203
                if (parseUserCredentials())
204
            initialize();
205
        }
206

    
207
    private void initialize() {
208
        topPanel = new TopPanel(GSS.images);
209
        topPanel.setWidth("100%");
210

    
211
        messagePanel.setWidth("100%");
212
        messagePanel.setVisible(false);
213

    
214
        fileList = new FileList(images);
215

    
216
        // Inner contains the various lists.
217
        inner.sinkEvents(Event.ONCONTEXTMENU);
218
        inner.setAnimationEnabled(true);
219
        inner.getTabBar().addStyleName("pithos-MainTabBar");
220
        inner.getDeckPanel().addStyleName("pithos-MainTabPanelBottom");
221
        inner.add(fileList, createHeaderHTML(AbstractImagePrototype.create(images.folders()), "Files"), true);
222

    
223
        inner.setWidth("100%");
224
        inner.selectTab(0);
225

    
226
        inner.addSelectionHandler(new SelectionHandler<Integer>() {
227

    
228
            @Override
229
            public void onSelection(SelectionEvent<Integer> event) {
230
                int tabIndex = event.getSelectedItem();
231
                switch (tabIndex) {
232
                    case 0:
233
                        fileList.updateCurrentlyShowingStats();
234
                        break;
235
                }
236
            }
237
        });
238

    
239
        // Add the left and right panels to the split panel.
240
        splitPanel.setLeftWidget(folderTreeView);
241
        splitPanel.setRightWidget(inner);
242
        splitPanel.setSplitPosition("25%");
243
        splitPanel.setSize("100%", "100%");
244
        splitPanel.addStyleName("pithos-splitPanel");
245

    
246
        // Create a dock panel that will contain the menu bar at the top,
247
        // the shortcuts to the left, the status bar at the bottom and the
248
        // right panel taking the rest.
249
        VerticalPanel outer = new VerticalPanel();
250
        outer.add(topPanel);
251
        outer.add(messagePanel);
252
        outer.add(splitPanel);
253
        statusPanel = new StatusPanel(GSS.images);
254
        outer.add(statusPanel);
255
        outer.setWidth("100%");
256
        outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
257

    
258
        outer.setSpacing(4);
259

    
260
        // Hook the window resize event, so that we can adjust the UI.
261
        Window.addResizeHandler(this);
262
        // Clear out the window's built-in margin, because we want to take
263
        // advantage of the entire client area.
264
        Window.setMargin("0px");
265
        // Finally, add the outer panel to the RootPanel, so that it will be
266
        // displayed.
267
        RootPanel.get().add(outer);
268
        // Call the window resized handler to get the initial sizes setup. Doing
269
        // this in a deferred command causes it to occur after all widgets'
270
        // sizes have been computed by the browser.
271
        DeferredCommand.addCommand(new Command() {
272

    
273
            @Override
274
            public void execute() {
275
                onWindowResized(Window.getClientHeight());
276
            }
277
        });
278
    }
279

    
280
        /**
281
         * Parse and store the user credentials to the appropriate fields.
282
         */
283
        private boolean parseUserCredentials() {
284
                Configuration conf = (Configuration) GWT.create(Configuration.class);
285
                String cookie = conf.authCookie();
286
                String auth = Cookies.getCookie(cookie);
287
                if (auth == null) {
288
                        authenticateUser();
289
            return false;
290
        }
291
        else {
292
            String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
293
            if (authSplit.length != 2) {
294
                authenticateUser();
295
                return false;
296
            }
297
            else {
298
                username = authSplit[0];
299
                token = authSplit[1];
300
                return true;
301
            }
302
        }
303
        }
304

    
305
    /**
306
         * Redirect the user to the login page for authentication.
307
         */
308
        protected void authenticateUser() {
309
                Configuration conf = (Configuration) GWT.create(Configuration.class);
310

    
311
//        Window.Location.assign(GWT.getModuleBaseURL() + conf.loginUrl() + "?next=" + Window.Location.getHref());
312
        Cookies.setCookie(conf.authCookie(), "demo" + conf.cookieSeparator() + "0000");
313
        Window.Location.assign(GWT.getModuleBaseURL() + "GSS.html");
314
        }
315

    
316
        /**
317
         * Clear the cookie and redirect the user to the logout page.
318
         */
319
        void logout() {
320
                Configuration conf = (Configuration) GWT.create(Configuration.class);
321
                String cookie = conf.authCookie();
322
                String domain = Window.Location.getHostName();
323
                String path = Window.Location.getPath();
324
                Cookies.setCookie(cookie, "", null, domain, path, false);
325
        String baseUrl = GWT.getModuleBaseURL();
326
        String homeUrl = baseUrl.substring(0, baseUrl.indexOf(path));
327
                Window.Location.assign(homeUrl + conf.logoutUrl());
328
        }
329

    
330
        /**
331
         * Creates an HTML fragment that places an image & caption together, for use
332
         * in a group header.
333
         *
334
         * @param imageProto an image prototype for an image
335
         * @param caption the group caption
336
         * @return the header HTML fragment
337
         */
338
        private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
339
                String captionHTML = "<table class='caption' cellpadding='0' " 
340
                + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML() 
341
                + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'>&nbsp;" 
342
                + caption + "</b></td></tr></table>";
343
                return captionHTML;
344
        }
345

    
346
        private void onWindowResized(int height) {
347
                // Adjust the split panel to take up the available room in the window.
348
                int newHeight = height - splitPanel.getAbsoluteTop() - 44;
349
                if (newHeight < 1)
350
                        newHeight = 1;
351
                splitPanel.setHeight("" + newHeight);
352
                inner.setHeight("" + newHeight);
353
        }
354

    
355
        @Override
356
        public void onResize(ResizeEvent event) {
357
                int height = event.getHeight();
358
                onWindowResized(height);
359
        }
360

    
361
        public boolean isFileListShowing() {
362
                int tab = inner.getTabBar().getSelectedTab();
363
                if (tab == 0)
364
                        return true;
365
                return false;
366
        }
367

    
368
        public boolean isSearchResultsShowing() {
369
                int tab = inner.getTabBar().getSelectedTab();
370
                if (tab == 2)
371
                        return true;
372
                return false;
373
        }
374

    
375
        /**
376
         * Make the user list visible.
377
         */
378
        public void showUserList() {
379
                inner.selectTab(1);
380
        }
381

    
382
        /**
383
         * Make the file list visible.
384
         */
385
        public void showFileList() {
386
                fileList.updateFileCache(true /*clear selection*/);
387
                inner.selectTab(0);
388
        }
389

    
390
        /**
391
         * Make the file list visible.
392
         *
393
         * @param update
394
         */
395
        public void showFileList(boolean update) {
396
                if(update){
397
                        getTreeView().refreshCurrentNode(true);
398
                }
399
                else{
400
                        RestResource currentFolder = getTreeView().getSelection();
401
                        if(currentFolder!=null){
402
                                showFileList(currentFolder);
403
                }
404
                }
405

    
406
        }
407
        
408
        public void showFileList(RestResource r) {
409
                showFileList(r,true);
410
        }
411
        
412
        public void showFileList(RestResource r, boolean clearSelection) {
413
                RestResource currentFolder = r;
414
                if(currentFolder!=null){
415
                        List<FileResource> files = null;
416
                        if (currentFolder instanceof RestResourceWrapper) {
417
                                RestResourceWrapper folder = (RestResourceWrapper) currentFolder;
418
                                files = folder.getResource().getFiles();
419
                        } else if (currentFolder instanceof TrashResource) {
420
                                TrashResource folder = (TrashResource) currentFolder;
421
                                files = folder.getFiles();
422
                        }
423
                        else if (currentFolder instanceof SharedResource) {
424
                                SharedResource folder = (SharedResource) currentFolder;
425
                                files = folder.getFiles();
426
                        }
427
                        else if (currentFolder instanceof OtherUserResource) {
428
                                OtherUserResource folder = (OtherUserResource) currentFolder;
429
                                files = folder.getFiles();
430
                        }
431
                        if (files != null)
432
                                getFileList().setFiles(files);
433
                        else
434
                                getFileList().setFiles(new ArrayList<FileResource>());
435
                }
436
                fileList.updateFileCache(clearSelection /*clear selection*/);
437
                inner.selectTab(0);
438
        }
439

    
440
        /**
441
         * Display the 'loading' indicator.
442
         */
443
        public void showLoadingIndicator(String message, String path) {
444
                if(path!=null){
445
                        String[] split = path.split("/");
446
                        message = message +" "+URL.decode(split[split.length-1]);
447
                }
448
                topPanel.getLoading().show(message);
449
        }
450

    
451
        /**
452
         * Hide the 'loading' indicator.
453
         */
454
        public void hideLoadingIndicator() {
455
                topPanel.getLoading().hide();
456
        }
457

    
458
        /**
459
         * A native JavaScript method to reach out to the browser's window and
460
         * invoke its resizeTo() method.
461
         *
462
         * @param x the new width
463
         * @param y the new height
464
         */
465
        public static native void resizeTo(int x, int y) /*-{
466
                $wnd.resizeTo(x,y);
467
        }-*/;
468

    
469
        /**
470
         * A helper method that returns true if the user's list is currently visible
471
         * and false if it is hidden.
472
         *
473
         * @return true if the user list is visible
474
         */
475
        public boolean isUserListVisible() {
476
                return inner.getTabBar().getSelectedTab() == 1;
477
        }
478

    
479
        /**
480
         * Display an error message.
481
         *
482
         * @param msg the message to display
483
         */
484
        public void displayError(String msg) {
485
                messagePanel.displayError(msg);
486
        }
487

    
488
        /**
489
         * Display a warning message.
490
         *
491
         * @param msg the message to display
492
         */
493
        public void displayWarning(String msg) {
494
                messagePanel.displayWarning(msg);
495
        }
496

    
497
        /**
498
         * Display an informational message.
499
         *
500
         * @param msg the message to display
501
         */
502
        public void displayInformation(String msg) {
503
                messagePanel.displayInformation(msg);
504
        }
505

    
506
        /**
507
         * Retrieve the folders.
508
         *
509
         * @return the folders
510
         
511
        public Folders getFolders() {
512
                return folders;
513
        }*/
514

    
515
        /**
516
         * Retrieve the currentSelection.
517
         *
518
         * @return the currentSelection
519
         */
520
        public Object getCurrentSelection() {
521
                return currentSelection;
522
        }
523

    
524
        /**
525
         * Modify the currentSelection.
526
         *
527
         * @param newCurrentSelection the currentSelection to set
528
         */
529
        public void setCurrentSelection(Object newCurrentSelection) {
530
                currentSelection = newCurrentSelection;
531
        }
532

    
533
        /**
534
         * Retrieve the fileList.
535
         *
536
         * @return the fileList
537
         */
538
        public FileList getFileList() {
539
                return fileList;
540
        }
541

    
542
        /**
543
         * Retrieve the topPanel.
544
         *
545
         * @return the topPanel
546
         */
547
        TopPanel getTopPanel() {
548
                return topPanel;
549
        }
550

    
551
        /**
552
         * Retrieve the clipboard.
553
         *
554
         * @return the clipboard
555
         */
556
        public Clipboard getClipboard() {
557
                return clipboard;
558
        }
559

    
560
        public StatusPanel getStatusPanel() {
561
                return statusPanel;
562
        }
563

    
564
        /**
565
         * Retrieve the userDetailsPanel.
566
         *
567
         * @return the userDetailsPanel
568
         */
569
        public UserDetailsPanel getUserDetailsPanel() {
570
                return userDetailsPanel;
571
        }
572

    
573
        
574

    
575
        public String getToken() {
576
                return token;
577
        }
578

    
579
        public String getWebDAVPassword() {
580
                return webDAVPassword;
581
        }
582

    
583
        /**
584
         * Retrieve the currentUserResource.
585
         *
586
         * @return the currentUserResource
587
         */
588
        public UserResource getCurrentUserResource() {
589
                return currentUserResource;
590
        }
591

    
592
        /**
593
         * Modify the currentUserResource.
594
         *
595
         * @param newUser the new currentUserResource
596
         */
597
        public void setCurrentUserResource(UserResource newUser) {
598
                currentUserResource = newUser;
599
        }
600

    
601
        public static native void preventIESelection() /*-{
602
                $doc.body.onselectstart = function () { return false; };
603
        }-*/;
604

    
605
        public static native void enableIESelection() /*-{
606
                if ($doc.body.onselectstart != null)
607
                $doc.body.onselectstart = null;
608
        }-*/;
609

    
610
        /**
611
         * @return the absolute path of the API root URL
612
         */
613
        public String getApiPath() {
614
                Configuration conf = (Configuration) GWT.create(Configuration.class);
615
                return conf.apiPath();
616
        }
617

    
618
        /**
619
         * Convert server date to local time according to browser timezone
620
         * and format it according to localized pattern.
621
         * Time is always formatted to 24hr format.
622
         * NB: This assumes that server runs in UTC timezone. Otherwise
623
         * we would need to adjust for server time offset as well.
624
         *
625
         * @param date
626
         * @return String
627
         */
628
        public static String formatLocalDateTime(Date date) {
629
                Date convertedDate = new Date(date.getTime() - date.getTimezoneOffset());
630
                final DateTimeFormat dateFormatter = DateTimeFormat.getShortDateFormat();
631
                final DateTimeFormat timeFormatter = DateTimeFormat.getFormat("HH:mm");
632
                String datePart = dateFormatter.format(convertedDate);
633
                String timePart = timeFormatter.format(convertedDate);
634
                return datePart + " " + timePart;
635
        }
636
        
637
        /**
638
         * History support for folder navigation
639
         * adds a new browser history entry
640
         *
641
         * @param key
642
         */
643
        public void updateHistory(String key){
644
//                Replace any whitespace of the initial string to "+"
645
//                String result = key.replaceAll("\\s","+");
646
//                Add a new browser history entry.
647
//                History.newItem(result);
648
                History.newItem(key);
649
        }
650

    
651
        /**
652
         * This method examines the token input and add a "/" at the end in case it's omitted.
653
         * This happens only in Files/trash/, Files/shared/, Files/others.
654
         *
655
         * @param tokenInput
656
         * @return the formated token with a "/" at the end or the same tokenInput parameter
657
         */
658

    
659
        private String handleSpecialFolderNames(String tokenInput){
660
                List<String> pathsToCheck = Arrays.asList("Files/trash", "Files/shared", "Files/others");
661
                if(pathsToCheck.contains(tokenInput))
662
                        return tokenInput + "/";
663
                return tokenInput;
664

    
665
        }
666

    
667
        /**
668
         * Reject illegal resource names, like '.' or '..' or slashes '/'.
669
         */
670
        static boolean isValidResourceName(String name) {
671
                if (".".equals(name) ||        "..".equals(name) || name.contains("/"))
672
                        return false;
673
                return true;
674
        }
675

    
676
        public void putUserToMap(String _userName, String _userFullName){
677
                userFullNameMap.put(_userName, _userFullName);
678
        }
679

    
680
        public String findUserFullName(String _userName){
681
                return userFullNameMap.get(_userName);
682
        }
683
        public String getUserFullName(String _userName) {
684
                
685
        if (GSS.get().findUserFullName(_userName) == null)
686
                //if there is no userFullName found then the map fills with the given _userName,
687
                //so userFullName = _userName
688
                GSS.get().putUserToMap(_userName, _userName);
689
        else if(GSS.get().findUserFullName(_userName).indexOf('@') != -1){
690
                //if the userFullName = _userName the GetUserCommand updates the userFullName in the map
691
                GetUserCommand guc = new GetUserCommand(_userName);
692
                guc.execute();
693
        }
694
        return GSS.get().findUserFullName(_userName);
695
        }
696
        /**
697
         * Retrieve the treeView.
698
         *
699
         * @return the treeView
700
         */
701
        public CellTreeView getTreeView() {
702
                return treeView;
703
        }
704
        
705
        public void onResourceUpdate(RestResource resource,boolean clearSelection){
706
                if(resource instanceof RestResourceWrapper || resource instanceof OtherUserResource || resource instanceof TrashResource || resource instanceof SharedResource){
707
                        if(getTreeView().getSelection()!=null&&getTreeView().getSelection().getUri().equals(resource.getUri()))
708
                                showFileList(resource,clearSelection);
709
                }
710
                
711
        }
712
}