Statistics
| Branch: | Tag: | Revision:

root / web_client / src / gr / grnet / pithos / web / client / Pithos.java @ a39e5b47

History | View | Annotate | Download (34.8 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.SelectionChangeEvent.Handler;
52
import com.google.gwt.view.client.SingleSelectionModel;
53
import gr.grnet.pithos.web.client.commands.GetUserCommand;
54
import gr.grnet.pithos.web.client.foldertree.AccountResource;
55
import gr.grnet.pithos.web.client.foldertree.File;
56
import gr.grnet.pithos.web.client.foldertree.Folder;
57
import gr.grnet.pithos.web.client.foldertree.FolderTreeView;
58
import gr.grnet.pithos.web.client.foldertree.FolderTreeViewModel;
59
import gr.grnet.pithos.web.client.foldertree.Resource;
60
import gr.grnet.pithos.web.client.rest.DeleteRequest;
61
import gr.grnet.pithos.web.client.rest.GetRequest;
62
import gr.grnet.pithos.web.client.rest.PutRequest;
63
import gr.grnet.pithos.web.client.rest.RestException;
64
import gr.grnet.pithos.web.client.rest.resource.FileResource;
65
import gr.grnet.pithos.web.client.rest.resource.OtherUserResource;
66
import gr.grnet.pithos.web.client.rest.resource.RestResource;
67
import gr.grnet.pithos.web.client.rest.resource.RestResourceWrapper;
68
import gr.grnet.pithos.web.client.rest.resource.SharedResource;
69
import gr.grnet.pithos.web.client.rest.resource.TrashResource;
70
import gr.grnet.pithos.web.client.rest.resource.UserResource;
71

    
72
import gr.grnet.pithos.web.client.tagtree.Tag;
73
import gr.grnet.pithos.web.client.tagtree.TagTreeView;
74
import gr.grnet.pithos.web.client.tagtree.TagTreeViewModel;
75
import java.util.ArrayList;
76
import java.util.Arrays;
77
import java.util.Collection;
78
import java.util.Date;
79
import java.util.HashMap;
80
import java.util.Iterator;
81
import java.util.List;
82

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

    
106
/**
107
 * Entry point classes define <code>onModuleLoad()</code>.
108
 */
109
public class Pithos implements EntryPoint, ResizeHandler {
110

    
111
        /**
112
         * A constant that denotes the completion of an IncrementalCommand.
113
         */
114
        public static final boolean DONE = false;
115

    
116
        public static final int VISIBLE_FILE_COUNT = 25;
117

    
118
        /**
119
         * Instantiate an application-level image bundle. This object will provide
120
         * programmatic access to all the images needed by widgets.
121
         */
122
        private static Images images = (Images) GWT.create(Images.class);
123

    
124
    public String getUsername() {
125
        return username;
126
    }
127

    
128
    public void setAccount(AccountResource acct) {
129
        account = acct;
130
    }
131

    
132
    public AccountResource getAccount() {
133
        return account;
134
    }
135

    
136
    public void updateFolder(Folder f) {
137
        folderTreeView.updateFolder(f);
138
    }
139

    
140
    public void updateTag(Tag t) {
141
        tagTreeView.updateTag(t);
142
    }
143

    
144
    public void updateTags() {
145
        tagTreeViewModel.initialize(getAllTags());
146
    }
147

    
148
    public List<Tag> getAllTags() {
149
        List<Tag> tagList = new ArrayList<Tag>();
150
        for (Folder f : account.getContainers()) {
151
            for (String t : f.getTags()) {
152
                tagList.add(new Tag(t));
153
            }
154
        }
155
        return tagList;
156
    }
157

    
158
    /**
159
         * An aggregate image bundle that pulls together all the images for this
160
         * application into a single bundle.
161
         */
162
        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 {
163

    
164
                @Source("gr/grnet/pithos/resources/document.png")
165
                ImageResource folders();
166

    
167
                @Source("gr/grnet/pithos/resources/edit_group_22.png")
168
                ImageResource groups();
169

    
170
                @Source("gr/grnet/pithos/resources/search.png")
171
                ImageResource search();
172
        }
173

    
174
        /**
175
         * The single Pithos instance.
176
         */
177
        private static Pithos singleton;
178

    
179
        /**
180
         * Gets the singleton Pithos instance.
181
         *
182
         * @return the Pithos object
183
         */
184
        public static Pithos get() {
185
                if (Pithos.singleton == null)
186
                        Pithos.singleton = new Pithos();
187
                return Pithos.singleton;
188
        }
189

    
190
        /**
191
         * The Application Clipboard implementation;
192
         */
193
        private Clipboard clipboard = new Clipboard();
194

    
195
        private UserResource currentUserResource;
196

    
197
        /**
198
         * The top panel that contains the menu bar.
199
         */
200
        private TopPanel topPanel;
201

    
202
        /**
203
         * The panel that contains the various system messages.
204
         */
205
        private MessagePanel messagePanel = new MessagePanel(Pithos.images);
206

    
207
        /**
208
         * The bottom panel that contains the status bar.
209
         */
210
        private StatusPanel statusPanel = null;
211

    
212
        /**
213
         * The top right panel that displays the logged in user details
214
         */
215
        private UserDetailsPanel userDetailsPanel = new UserDetailsPanel();
216

    
217
        /**
218
         * The file list widget.
219
         */
220
        private FileList fileList;
221

    
222
        /**
223
         * The tab panel that occupies the right side of the screen.
224
         */
225
        private TabPanel inner = new DecoratedTabPanel(){
226
                
227
//                public void onBrowserEvent(com.google.gwt.user.client.Event event) {
228
//                        if (DOM.eventGetType(event) == Event.ONCONTEXTMENU){
229
//                                if(isFileListShowing()){
230
//                                        getFileList().showContextMenu(event);
231
//                                }
232
//                        }
233
//                };
234
        };
235

    
236

    
237
        /**
238
         * The split panel that will contain the left and right panels.
239
         */
240
        private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
241

    
242
        /**
243
         * The widget that displays the tree of folders.
244
         */
245
        
246
        private CellTreeView treeView = null;
247
        /**
248
         * The currently selected item in the application, for use by the Edit menu
249
         * commands. Potential types are Folder, File, User and Group.
250
         */
251
        private Object currentSelection;
252

    
253

    
254
        /**
255
         * The WebDAV password of the current user
256
         */
257
        private String webDAVPassword;
258

    
259
        public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
260

    
261
    private String username = null;
262

    
263
    /**
264
     * The authentication token of the current user.
265
     */
266
    private String token;
267

    
268
    private SingleSelectionModel<Folder> folderTreeSelectionModel;
269
    private FolderTreeViewModel folderTreeViewModel;
270
    private FolderTreeView folderTreeView;
271

    
272
    private SingleSelectionModel<Tag> tagTreeSelectionModel;
273
    private TagTreeViewModel tagTreeViewModel;
274
    private TagTreeView tagTreeView;
275

    
276
    private AccountResource account;
277

    
278
        @Override
279
        public void onModuleLoad() {
280
                // Initialize the singleton before calling the constructors of the
281
                // various widgets that might call Pithos.get().
282
                singleton = this;
283
                if (parseUserCredentials())
284
            initialize();
285
        }
286

    
287
    private void initialize() {
288
        topPanel = new TopPanel(Pithos.images);
289
        topPanel.setWidth("100%");
290

    
291
        messagePanel.setWidth("100%");
292
        messagePanel.setVisible(false);
293

    
294

    
295
        // Inner contains the various lists.
296
        inner.sinkEvents(Event.ONCONTEXTMENU);
297
        inner.setAnimationEnabled(true);
298
        inner.getTabBar().addStyleName("pithos-MainTabBar");
299
        inner.getDeckPanel().addStyleName("pithos-MainTabPanelBottom");
300

    
301
        inner.setWidth("100%");
302

    
303
        inner.addSelectionHandler(new SelectionHandler<Integer>() {
304

    
305
            @Override
306
            public void onSelection(SelectionEvent<Integer> event) {
307
                int tabIndex = event.getSelectedItem();
308
                switch (tabIndex) {
309
                    case 0:
310
                        fileList.updateCurrentlyShowingStats();
311
                        break;
312
                }
313
            }
314
        });
315

    
316
        folderTreeSelectionModel = new SingleSelectionModel<Folder>();
317
        folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
318
            @Override
319
            public void onSelectionChange(SelectionChangeEvent event) {
320
                if (folderTreeSelectionModel.getSelectedObject() != null) {
321
                    tagTreeSelectionModel.setSelected(tagTreeSelectionModel.getSelectedObject(), false);
322
                    Folder f = folderTreeSelectionModel.getSelectedObject();
323
                    updateFolder(f);
324
                }
325
            }
326
        });
327

    
328
        folderTreeViewModel = new FolderTreeViewModel(folderTreeSelectionModel);
329
        folderTreeView = new FolderTreeView(folderTreeViewModel);
330

    
331
        fileList = new FileList(images, folderTreeView);
332
        inner.add(fileList, createHeaderHTML(AbstractImagePrototype.create(images.folders()), "Files"), true);
333

    
334
        tagTreeSelectionModel = new SingleSelectionModel<Tag>();
335
        tagTreeSelectionModel.addSelectionChangeHandler(new Handler() {
336
            @Override
337
            public void onSelectionChange(SelectionChangeEvent event) {
338
                if (tagTreeSelectionModel.getSelectedObject() != null) {
339
                    folderTreeSelectionModel.setSelected(folderTreeSelectionModel.getSelectedObject(), false);
340
                    Tag t = tagTreeSelectionModel.getSelectedObject();
341
                    updateTag(t);
342
                }
343
            }
344
        });
345
        tagTreeViewModel = new TagTreeViewModel(tagTreeSelectionModel);
346
        tagTreeView = new TagTreeView(tagTreeViewModel);
347

    
348
        VerticalPanel trees = new VerticalPanel();
349
        trees.add(folderTreeView);
350
        trees.add(tagTreeView);
351
        // Add the left and right panels to the split panel.
352
        splitPanel.setLeftWidget(trees);
353
        splitPanel.setRightWidget(inner);
354
        splitPanel.setSplitPosition("25%");
355
        splitPanel.setSize("100%", "100%");
356
        splitPanel.addStyleName("pithos-splitPanel");
357

    
358
        // Create a dock panel that will contain the menu bar at the top,
359
        // the shortcuts to the left, the status bar at the bottom and the
360
        // right panel taking the rest.
361
        VerticalPanel outer = new VerticalPanel();
362
        outer.add(topPanel);
363
        outer.add(messagePanel);
364
        outer.add(splitPanel);
365
        statusPanel = new StatusPanel(Pithos.images);
366
        outer.add(statusPanel);
367
        outer.setWidth("100%");
368
        outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
369

    
370
        outer.setSpacing(4);
371

    
372
        // Hook the window resize event, so that we can adjust the UI.
373
        Window.addResizeHandler(this);
374
        // Clear out the window's built-in margin, because we want to take
375
        // advantage of the entire client area.
376
        Window.setMargin("0px");
377
        // Finally, add the outer panel to the RootPanel, so that it will be
378
        // displayed.
379
        RootPanel.get().add(outer);
380
        // Call the window resized handler to get the initial sizes setup. Doing
381
        // this in a deferred command causes it to occur after all widgets'
382
        // sizes have been computed by the browser.
383
        Scheduler.get().scheduleDeferred(new ScheduledCommand() {
384

    
385
            @Override
386
            public void execute() {
387
                onWindowResized(Window.getClientHeight());
388
            }
389
        });
390

    
391
        Scheduler.get().scheduleDeferred(new ScheduledCommand() {
392
            @Override
393
            public void execute() {
394
                fetchAccount();
395
            }
396
        });
397
    }
398

    
399
    public void showFiles(Folder f) {
400
        inner.selectTab(0);
401
        if (f.isTrash()) {
402
            fileList.showTrash();
403
        }
404
        else
405
            fileList.showFiles();
406
        Set<File> files = f.getFiles();
407
        showFiles(files);
408
    }
409

    
410
    public void showFiles(Set<File> files) {
411
        //Iterator<File> iter = files.iterator();
412
        //fetchFile(iter, files);
413
        fileList.setFiles(new ArrayList<File>(files));
414
    }
415

    
416
    private void fetchFile(final Iterator<File> iter, final Set<File> files) {
417
        if (iter.hasNext()) {
418
            File file = iter.next();
419
            String path = getApiPath() + username + "/" + file.getContainer() + "/" + file.getPath() + "?format=json";
420
            GetRequest<File> getFile = new GetRequest<File>(File.class, path, file) {
421
                @Override
422
                public void onSuccess(File result) {
423
                    fetchFile(iter, files);
424
                }
425

    
426
                @Override
427
                public void onError(Throwable t) {
428
                    GWT.log("Error getting file", t);
429
                    if (t instanceof RestException)
430
                        Pithos.get().displayError("Error getting file: " + ((RestException) t).getHttpStatusText());
431
                    else
432
                        Pithos.get().displayError("System error fetching file: " + t.getMessage());
433
                }
434
            };
435
            getFile.setHeader("X-Auth-Token", "0000");
436
            Scheduler.get().scheduleDeferred(getFile);
437
        }
438
        else
439
            fileList.setFiles(new ArrayList<File>(files));
440
    }
441

    
442
    /**
443
         * Parse and store the user credentials to the appropriate fields.
444
         */
445
        private boolean parseUserCredentials() {
446
                Configuration conf = (Configuration) GWT.create(Configuration.class);
447
                String cookie = conf.authCookie();
448
                String auth = Cookies.getCookie(cookie);
449
                if (auth == null) {
450
                        authenticateUser();
451
            return false;
452
        }
453
        else {
454
            String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
455
            if (authSplit.length != 2) {
456
                authenticateUser();
457
                return false;
458
            }
459
            else {
460
                username = authSplit[0];
461
                token = authSplit[1];
462
                return true;
463
            }
464
        }
465
        }
466

    
467
    /**
468
         * Redirect the user to the login page for authentication.
469
         */
470
        protected void authenticateUser() {
471
                Configuration conf = (Configuration) GWT.create(Configuration.class);
472

    
473
//        Window.Location.assign(GWT.getModuleBaseURL() + conf.loginUrl() + "?next=" + Window.Location.getHref());
474
        Cookies.setCookie(conf.authCookie(), "test" + conf.cookieSeparator() + "0000");
475
        Window.Location.assign(GWT.getModuleBaseURL() + "pithos.html");
476
        }
477

    
478
    private void fetchAccount() {
479
        String path = getApiPath() + username + "?format=json";
480

    
481
        GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, path) {
482
            @Override
483
            public void onSuccess(AccountResource result) {
484
                account = result;
485
                statusPanel.displayStats(account);
486
                folderTreeViewModel.initialize(account);
487
                inner.selectTab(0);
488
            }
489

    
490
            @Override
491
            public void onError(Throwable t) {
492
                GWT.log("Error getting account", t);
493
                if (t instanceof RestException)
494
                    Pithos.get().displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
495
                else
496
                    Pithos.get().displayError("System error fetching user data: " + t.getMessage());
497
            }
498
        };
499
        getAccount.setHeader("X-Auth-Token", token);
500
        Scheduler.get().scheduleDeferred(getAccount);
501
    }
502

    
503
        /**
504
         * Clear the cookie and redirect the user to the logout page.
505
         */
506
        void logout() {
507
                Configuration conf = (Configuration) GWT.create(Configuration.class);
508
                String cookie = conf.authCookie();
509
                String domain = Window.Location.getHostName();
510
                String path = Window.Location.getPath();
511
                Cookies.setCookie(cookie, "", null, domain, path, false);
512
        String baseUrl = GWT.getModuleBaseURL();
513
        String homeUrl = baseUrl.substring(0, baseUrl.indexOf(path));
514
                Window.Location.assign(homeUrl + conf.logoutUrl());
515
        }
516

    
517
        /**
518
         * Creates an HTML fragment that places an image & caption together, for use
519
         * in a group header.
520
         *
521
         * @param imageProto an image prototype for an image
522
         * @param caption the group caption
523
         * @return the header HTML fragment
524
         */
525
        private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
526
                String captionHTML = "<table class='caption' cellpadding='0' " 
527
                + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML() 
528
                + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'>&nbsp;" 
529
                + caption + "</b></td></tr></table>";
530
                return captionHTML;
531
        }
532

    
533
        private void onWindowResized(int height) {
534
                // Adjust the split panel to take up the available room in the window.
535
                int newHeight = height - splitPanel.getAbsoluteTop() - 44;
536
                if (newHeight < 1)
537
                        newHeight = 1;
538
                splitPanel.setHeight("" + newHeight);
539
                inner.setHeight("" + newHeight);
540
        }
541

    
542
        @Override
543
        public void onResize(ResizeEvent event) {
544
                int height = event.getHeight();
545
                onWindowResized(height);
546
        }
547

    
548
        public boolean isFileListShowing() {
549
                int tab = inner.getTabBar().getSelectedTab();
550
                if (tab == 0)
551
                        return true;
552
                return false;
553
        }
554

    
555
        public boolean isSearchResultsShowing() {
556
                int tab = inner.getTabBar().getSelectedTab();
557
                if (tab == 2)
558
                        return true;
559
                return false;
560
        }
561

    
562
        /**
563
         * Make the file list visible.
564
         *
565
         * @param update
566
         */
567
        public void showFileList(boolean update) {
568
                if(update){
569
                        getTreeView().refreshCurrentNode(true);
570
                }
571
                else{
572
                        RestResource currentFolder = getTreeView().getSelection();
573
                        if(currentFolder!=null){
574
                                showFileList(currentFolder);
575
                }
576
                }
577

    
578
        }
579
        
580
        public void showFileList(RestResource r) {
581
                showFileList(r,true);
582
        }
583
        
584
        public void showFileList(RestResource r, boolean clearSelection) {
585
                RestResource currentFolder = r;
586
                if(currentFolder!=null){
587
                        List<FileResource> files = null;
588
                        if (currentFolder instanceof RestResourceWrapper) {
589
                                RestResourceWrapper folder = (RestResourceWrapper) currentFolder;
590
                                files = folder.getResource().getFiles();
591
                        }
592
                }
593
                inner.selectTab(0);
594
        }
595

    
596
        /**
597
         * Display the 'loading' indicator.
598
         */
599
        public void showLoadingIndicator(String message, String path) {
600
                if(path!=null){
601
                        String[] split = path.split("/");
602
                        message = message +" "+URL.decode(split[split.length-1]);
603
                }
604
                topPanel.getLoading().show(message);
605
        }
606

    
607
        /**
608
         * Hide the 'loading' indicator.
609
         */
610
        public void hideLoadingIndicator() {
611
                topPanel.getLoading().hide();
612
        }
613

    
614
        /**
615
         * A native JavaScript method to reach out to the browser's window and
616
         * invoke its resizeTo() method.
617
         *
618
         * @param x the new width
619
         * @param y the new height
620
         */
621
        public static native void resizeTo(int x, int y) /*-{
622
                $wnd.resizeTo(x,y);
623
        }-*/;
624

    
625
        /**
626
         * A helper method that returns true if the user's list is currently visible
627
         * and false if it is hidden.
628
         *
629
         * @return true if the user list is visible
630
         */
631
        public boolean isUserListVisible() {
632
                return inner.getTabBar().getSelectedTab() == 1;
633
        }
634

    
635
        /**
636
         * Display an error message.
637
         *
638
         * @param msg the message to display
639
         */
640
        public void displayError(String msg) {
641
                messagePanel.displayError(msg);
642
        }
643

    
644
        /**
645
         * Display a warning message.
646
         *
647
         * @param msg the message to display
648
         */
649
        public void displayWarning(String msg) {
650
                messagePanel.displayWarning(msg);
651
        }
652

    
653
        /**
654
         * Display an informational message.
655
         *
656
         * @param msg the message to display
657
         */
658
        public void displayInformation(String msg) {
659
                messagePanel.displayInformation(msg);
660
        }
661

    
662
        /**
663
         * Retrieve the folders.
664
         *
665
         * @return the folders
666
         
667
        public Folders getFolders() {
668
                return folders;
669
        }*/
670

    
671
        /**
672
         * Retrieve the currentSelection.
673
         *
674
         * @return the currentSelection
675
         */
676
        public Object getCurrentSelection() {
677
                return currentSelection;
678
        }
679

    
680
        /**
681
         * Modify the currentSelection.
682
         *
683
         * @param newCurrentSelection the currentSelection to set
684
         */
685
        public void setCurrentSelection(Object newCurrentSelection) {
686
                currentSelection = newCurrentSelection;
687
        }
688

    
689
        /**
690
         * Retrieve the fileList.
691
         *
692
         * @return the fileList
693
         */
694
        public FileList getFileList() {
695
                return fileList;
696
        }
697

    
698
        /**
699
         * Retrieve the topPanel.
700
         *
701
         * @return the topPanel
702
         */
703
        TopPanel getTopPanel() {
704
                return topPanel;
705
        }
706

    
707
        /**
708
         * Retrieve the clipboard.
709
         *
710
         * @return the clipboard
711
         */
712
        public Clipboard getClipboard() {
713
                return clipboard;
714
        }
715

    
716
        public StatusPanel getStatusPanel() {
717
                return statusPanel;
718
        }
719

    
720
        /**
721
         * Retrieve the userDetailsPanel.
722
         *
723
         * @return the userDetailsPanel
724
         */
725
        public UserDetailsPanel getUserDetailsPanel() {
726
                return userDetailsPanel;
727
        }
728

    
729
        
730

    
731
        public String getToken() {
732
                return token;
733
        }
734

    
735
        public String getWebDAVPassword() {
736
                return webDAVPassword;
737
        }
738

    
739
        /**
740
         * Retrieve the currentUserResource.
741
         *
742
         * @return the currentUserResource
743
         */
744
        public UserResource getCurrentUserResource() {
745
                return currentUserResource;
746
        }
747

    
748
        /**
749
         * Modify the currentUserResource.
750
         *
751
         * @param newUser the new currentUserResource
752
         */
753
        public void setCurrentUserResource(UserResource newUser) {
754
                currentUserResource = newUser;
755
        }
756

    
757
        public static native void preventIESelection() /*-{
758
                $doc.body.onselectstart = function () { return false; };
759
        }-*/;
760

    
761
        public static native void enableIESelection() /*-{
762
                if ($doc.body.onselectstart != null)
763
                $doc.body.onselectstart = null;
764
        }-*/;
765

    
766
        /**
767
         * @return the absolute path of the API root URL
768
         */
769
        public String getApiPath() {
770
                Configuration conf = (Configuration) GWT.create(Configuration.class);
771
                return conf.apiPath();
772
        }
773

    
774
        /**
775
         * Convert server date to local time according to browser timezone
776
         * and format it according to localized pattern.
777
         * Time is always formatted to 24hr format.
778
         * NB: This assumes that server runs in UTC timezone. Otherwise
779
         * we would need to adjust for server time offset as well.
780
         *
781
         * @param date
782
         * @return String
783
         */
784
        public static String formatLocalDateTime(Date date) {
785
                Date convertedDate = new Date(date.getTime() - date.getTimezoneOffset());
786
                final DateTimeFormat dateFormatter = DateTimeFormat.getShortDateFormat();
787
                final DateTimeFormat timeFormatter = DateTimeFormat.getFormat("HH:mm");
788
                String datePart = dateFormatter.format(convertedDate);
789
                String timePart = timeFormatter.format(convertedDate);
790
                return datePart + " " + timePart;
791
        }
792
        
793
        /**
794
         * History support for folder navigation
795
         * adds a new browser history entry
796
         *
797
         * @param key
798
         */
799
        public void updateHistory(String key){
800
//                Replace any whitespace of the initial string to "+"
801
//                String result = key.replaceAll("\\s","+");
802
//                Add a new browser history entry.
803
//                History.newItem(result);
804
                History.newItem(key);
805
        }
806

    
807
        /**
808
         * This method examines the token input and add a "/" at the end in case it's omitted.
809
         * This happens only in Files/trash/, Files/shared/, Files/others.
810
         *
811
         * @param tokenInput
812
         * @return the formated token with a "/" at the end or the same tokenInput parameter
813
         */
814

    
815
        private String handleSpecialFolderNames(String tokenInput){
816
                List<String> pathsToCheck = Arrays.asList("Files/trash", "Files/shared", "Files/others");
817
                if(pathsToCheck.contains(tokenInput))
818
                        return tokenInput + "/";
819
                return tokenInput;
820

    
821
        }
822

    
823
        /**
824
         * Reject illegal resource names, like '.' or '..' or slashes '/'.
825
         */
826
        static boolean isValidResourceName(String name) {
827
                if (".".equals(name) ||        "..".equals(name) || name.contains("/"))
828
                        return false;
829
                return true;
830
        }
831

    
832
        public void putUserToMap(String _userName, String _userFullName){
833
                userFullNameMap.put(_userName, _userFullName);
834
        }
835

    
836
        public String findUserFullName(String _userName){
837
                return userFullNameMap.get(_userName);
838
        }
839
        public String getUserFullName(String _userName) {
840
                
841
        if (Pithos.get().findUserFullName(_userName) == null)
842
                //if there is no userFullName found then the map fills with the given _userName,
843
                //so userFullName = _userName
844
                Pithos.get().putUserToMap(_userName, _userName);
845
        else if(Pithos.get().findUserFullName(_userName).indexOf('@') != -1){
846
                //if the userFullName = _userName the GetUserCommand updates the userFullName in the map
847
                GetUserCommand guc = new GetUserCommand(_userName);
848
                guc.execute();
849
        }
850
        return Pithos.get().findUserFullName(_userName);
851
        }
852
        /**
853
         * Retrieve the treeView.
854
         *
855
         * @return the treeView
856
         */
857
        public CellTreeView getTreeView() {
858
                return treeView;
859
        }
860
        
861
        public void onResourceUpdate(RestResource resource,boolean clearSelection){
862
                if(resource instanceof RestResourceWrapper || resource instanceof OtherUserResource || resource instanceof TrashResource || resource instanceof SharedResource){
863
                        if(getTreeView().getSelection()!=null&&getTreeView().getSelection().getUri().equals(resource.getUri()))
864
                                showFileList(resource,clearSelection);
865
                }
866
                
867
        }
868

    
869
    public void deleteFolder(final Folder folder) {
870
        String path = getApiPath() + getUsername() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + folder.getPrefix();
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 array = json.isArray();
881
                        int i = 0;
882
                        if (array != null) {
883
                            deleteObject(folder, i, array);
884
                        }
885
                    }
886
                }
887

    
888
                @Override
889
                public void onError(Request request, Throwable exception) {
890
                    Pithos.get().displayError("System error unable to delete folder: " + exception.getMessage());
891
                }
892
            });
893
        }
894
        catch (RequestException e) {
895
        }
896
    }
897

    
898
    public void deleteObject(final Folder folder, final int i, final JSONArray array) {
899
        if (i < array.size()) {
900
            JSONObject o = array.get(i).isObject();
901
            if (o != null && !o.containsKey("subdir")) {
902
                JSONString name = o.get("name").isString();
903
                String path = getApiPath() + getUsername() + "/" + folder.getContainer() + "/" + name.stringValue();
904
                DeleteRequest delete = new DeleteRequest(path) {
905
                    @Override
906
                    public void onSuccess(Resource result) {
907
                        deleteObject(folder, i + 1, array);
908
                    }
909

    
910
                    @Override
911
                    public void onError(Throwable t) {
912
                        GWT.log("", t);
913
                        Pithos.get().displayError("System error unable to delete folder: " + t.getMessage());
914
                    }
915
                };
916
                delete.setHeader("X-Auth-Token", getToken());
917
                Scheduler.get().scheduleDeferred(delete);
918
            }
919
            else {
920
                String subdir = o.get("subdir").isString().stringValue();
921
                subdir = subdir.substring(0, subdir.length() - 1);
922
                String path = getApiPath() + getUsername() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + subdir;
923
                RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
924
                builder.setHeader("If-Modified-Since", "0");
925
                builder.setHeader("X-Auth-Token", getToken());
926
                try {
927
                    builder.sendRequest("", new RequestCallback() {
928
                        @Override
929
                        public void onResponseReceived(Request request, Response response) {
930
                            if (response.getStatusCode() == Response.SC_OK) {
931
                                JSONValue json = JSONParser.parseStrict(response.getText());
932
                                JSONArray array2 = json.isArray();
933
                                if (array2 != null) {
934
                                    int l = array.size();
935
                                    for (int j=0; j<array2.size(); j++) {
936
                                        array.set(l++, array2.get(j));
937
                                    }
938
                                }
939
                                deleteObject(folder, i + 1, array);
940
                            }
941
                        }
942

    
943
                        @Override
944
                        public void onError(Request request, Throwable exception) {
945
                            Pithos.get().displayError("System error unable to delete folder: " + exception.getMessage());
946
                        }
947
                    });
948
                }
949
                catch (RequestException e) {
950
                }
951
            }
952
        }
953
        else {
954
            String prefix = folder.getPrefix();
955
            String path = getApiPath() + getUsername() + "/" + folder.getContainer() + (prefix.length() == 0 ? "" : "/" + prefix);
956
            DeleteRequest deleteFolder = new DeleteRequest(path) {
957
                @Override
958
                public void onSuccess(Resource result) {
959
                    updateFolder(folder.getParent());
960
                }
961

    
962
                @Override
963
                public void onError(Throwable t) {
964
                    GWT.log("", t);
965
                    if (t instanceof RestException) {
966
                        displayError("Unable to delete folder: "+((RestException) t).getHttpStatusText());
967
                    }
968
                    else
969
                        Pithos.get().displayError("System error unable to delete folder: " + t.getMessage());
970
                }
971
            };
972
            deleteFolder.setHeader("X-Auth-Token", getToken());
973
            Scheduler.get().scheduleDeferred(deleteFolder);
974
        }
975
    }
976

    
977
    public FolderTreeView getFolderTreeView() {
978
        return folderTreeView;
979
    }
980

    
981
    public void copyFiles(final Iterator<File> iter, final String targetUri, final Command callback) {
982
        if (iter.hasNext()) {
983
            File file = iter.next();
984
            String path = getApiPath() + getUsername() + targetUri + "/" + file.getName();
985
            PutRequest copyFile = new PutRequest(path) {
986
                @Override
987
                public void onSuccess(Resource result) {
988
                    copyFiles(iter, targetUri, callback);
989
                }
990

    
991
                @Override
992
                public void onError(Throwable t) {
993
                    GWT.log("", t);
994
                    if (t instanceof RestException) {
995
                        Pithos.get().displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
996
                    }
997
                    else
998
                        Pithos.get().displayError("System error unable to copy file: "+t.getMessage());
999
                }
1000
            };
1001
            copyFile.setHeader("X-Auth-Token", getToken());
1002
            copyFile.setHeader("X-Copy-From", file.getUri());
1003
            Scheduler.get().scheduleDeferred(copyFile);
1004
        }
1005
        else  if (callback != null) {
1006
            callback.execute();
1007
        }
1008
    }
1009

    
1010
    public void copySubfolders(final Iterator<Folder> iter, final String targetUri, final Command callback) {
1011
        if (iter.hasNext()) {
1012
            final Folder f = iter.next();
1013
            copyFolder(f, targetUri, callback);
1014
        }
1015
        else  if (callback != null) {
1016
            callback.execute();
1017
        }
1018
    }
1019

    
1020
    public void copyFolder(final Folder f, final String targetUri, final Command callback) {
1021
        String path = getApiPath() + getUsername() + targetUri + "/" + f.getName();
1022
        PutRequest createFolder = new PutRequest(path) {
1023
            @Override
1024
            public void onSuccess(Resource result) {
1025
                Iterator<File> iter = f.getFiles().iterator();
1026
                copyFiles(iter, targetUri + "/" + f.getName(), new Command() {
1027
                    @Override
1028
                    public void execute() {
1029
                        Iterator<Folder> iterf = f.getSubfolders().iterator();
1030
                        copySubfolders(iterf, targetUri + "/" + f.getName(), new Command() {
1031
                            @Override
1032
                            public void execute() {
1033
                                callback.execute();
1034
                            }
1035
                        });
1036
                    }
1037
                });
1038
            }
1039

    
1040
            @Override
1041
            public void onError(Throwable t) {
1042
                GWT.log("", t);
1043
                if (t instanceof RestException) {
1044
                    displayError("Unable to create folder:" + ((RestException) t).getHttpStatusText());
1045
                }
1046
                else
1047
                    displayError("System error creating folder:" + t.getMessage());
1048
            }
1049
        };
1050
        createFolder.setHeader("X-Auth-Token", getToken());
1051
        createFolder.setHeader("Accept", "*/*");
1052
        createFolder.setHeader("Content-Length", "0");
1053
        createFolder.setHeader("Content-Type", "application/folder");
1054
        Scheduler.get().scheduleDeferred(createFolder);
1055
    }
1056
}