Statistics
| Branch: | Tag: | Revision:

root / src / gr / grnet / pithos / web / client / Pithos.java @ 0549e173

History | View | Annotate | Download (42.1 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 gr.grnet.pithos.web.client.commands.UploadFileCommand;
38
import gr.grnet.pithos.web.client.foldertree.AccountResource;
39
import gr.grnet.pithos.web.client.foldertree.File;
40
import gr.grnet.pithos.web.client.foldertree.Folder;
41
import gr.grnet.pithos.web.client.foldertree.FolderTreeView;
42
import gr.grnet.pithos.web.client.foldertree.FolderTreeViewModel;
43
import gr.grnet.pithos.web.client.foldertree.Resource;
44
import gr.grnet.pithos.web.client.grouptree.Group;
45
import gr.grnet.pithos.web.client.grouptree.GroupTreeView;
46
import gr.grnet.pithos.web.client.grouptree.GroupTreeViewModel;
47
import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeView;
48
import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeViewModel;
49
import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeView;
50
import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeViewModel;
51
import gr.grnet.pithos.web.client.rest.DeleteRequest;
52
import gr.grnet.pithos.web.client.rest.GetRequest;
53
import gr.grnet.pithos.web.client.rest.HeadRequest;
54
import gr.grnet.pithos.web.client.rest.PutRequest;
55
import gr.grnet.pithos.web.client.rest.RestException;
56
import gr.grnet.pithos.web.client.tagtree.Tag;
57
import gr.grnet.pithos.web.client.tagtree.TagTreeView;
58
import gr.grnet.pithos.web.client.tagtree.TagTreeViewModel;
59

    
60
import java.util.ArrayList;
61
import java.util.HashMap;
62
import java.util.Iterator;
63
import java.util.List;
64
import java.util.Set;
65

    
66
import com.google.gwt.core.client.EntryPoint;
67
import com.google.gwt.core.client.GWT;
68
import com.google.gwt.core.client.Scheduler;
69
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
70
import com.google.gwt.event.dom.client.ClickEvent;
71
import com.google.gwt.event.dom.client.ClickHandler;
72
import com.google.gwt.event.logical.shared.ResizeEvent;
73
import com.google.gwt.event.logical.shared.ResizeHandler;
74
import com.google.gwt.http.client.Request;
75
import com.google.gwt.http.client.RequestBuilder;
76
import com.google.gwt.http.client.RequestCallback;
77
import com.google.gwt.http.client.RequestException;
78
import com.google.gwt.http.client.Response;
79
import com.google.gwt.http.client.URL;
80
import com.google.gwt.i18n.client.NumberFormat;
81
import com.google.gwt.json.client.JSONArray;
82
import com.google.gwt.json.client.JSONObject;
83
import com.google.gwt.json.client.JSONParser;
84
import com.google.gwt.json.client.JSONString;
85
import com.google.gwt.json.client.JSONValue;
86
import com.google.gwt.resources.client.ImageResource;
87
import com.google.gwt.user.client.Command;
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.Button;
94
import com.google.gwt.user.client.ui.Composite;
95
import com.google.gwt.user.client.ui.HTML;
96
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
97
import com.google.gwt.user.client.ui.HasVerticalAlignment;
98
import com.google.gwt.user.client.ui.HorizontalPanel;
99
import com.google.gwt.user.client.ui.HorizontalSplitPanel;
100
import com.google.gwt.user.client.ui.RootPanel;
101
import com.google.gwt.user.client.ui.VerticalPanel;
102
import com.google.gwt.view.client.SelectionChangeEvent;
103
import com.google.gwt.view.client.SelectionChangeEvent.Handler;
104
import com.google.gwt.view.client.SingleSelectionModel;
105

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

    
111
        public static final String HOME_CONTAINER = "pithos";
112

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

    
121
    public String getUsername() {
122
        return username;
123
    }
124

    
125
    public void setAccount(AccountResource acct) {
126
        account = acct;
127
    }
128

    
129
    public AccountResource getAccount() {
130
        return account;
131
    }
132

    
133
    public void updateFolder(Folder f, boolean showfiles, Command callback) {
134
        folderTreeView.updateFolder(f, showfiles, callback);
135
    }
136

    
137
    public void updateGroupNode(Group group) {
138
        groupTreeView.updateGroupNode(group);
139
    }
140

    
141
    public void updateSharedFolder(Folder f, boolean showfiles) {
142
            mysharedTreeView.updateFolder(f, showfiles);
143
    }
144
    
145
    public void updateOtherSharedFolder(Folder f, boolean showfiles) {
146
            otherSharedTreeView.updateFolder(f, showfiles);
147
    }
148

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

    
159
    public MysharedTreeView getMySharedTreeView() {
160
        return mysharedTreeView;
161
    }
162

    
163
    /**
164
         * An aggregate image bundle that pulls together all the images for this
165
         * application into a single bundle.
166
         */
167
        public interface Images extends TopPanel.Images, FileList.Images, ToolsMenu.Images {
168

    
169
                @Source("gr/grnet/pithos/resources/document.png")
170
                ImageResource folders();
171

    
172
                @Source("gr/grnet/pithos/resources/advancedsettings.png")
173
                ImageResource tools();
174
        }
175

    
176
        /**
177
         * The Application Clipboard implementation;
178
         */
179
        private Clipboard clipboard = new Clipboard();
180

    
181
        /**
182
         * The top panel that contains the menu bar.
183
         */
184
        private TopPanel topPanel;
185

    
186
        /**
187
         * The panel that contains the various system messages.
188
         */
189
        private MessagePanel messagePanel = new MessagePanel(Pithos.images);
190

    
191
        /**
192
         * The bottom panel that contains the status bar.
193
         */
194
        private StatusPanel statusPanel = null;
195

    
196
        /**
197
         * The file list widget.
198
         */
199
        private FileList fileList;
200

    
201
        /**
202
         * The tab panel that occupies the right side of the screen.
203
         */
204
        private VerticalPanel inner = new VerticalPanel();
205

    
206

    
207
        /**
208
         * The split panel that will contain the left and right panels.
209
         */
210
        private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
211

    
212
        /**
213
         * The currently selected item in the application, for use by the Edit menu
214
         * commands. Potential types are Folder, File, User and Group.
215
         */
216
        private Object currentSelection;
217

    
218
        public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
219

    
220
    private String username = null;
221

    
222
    /**
223
     * The authentication token of the current user.
224
     */
225
    private String token;
226

    
227
    VerticalPanel trees;
228
    
229
    SingleSelectionModel<Folder> folderTreeSelectionModel;
230
    FolderTreeViewModel folderTreeViewModel;
231
    FolderTreeView folderTreeView;
232

    
233
    SingleSelectionModel<Folder> mysharedTreeSelectionModel;
234
    MysharedTreeViewModel mysharedTreeViewModel;
235
    MysharedTreeView mysharedTreeView = null;;
236

    
237
    protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
238
    OtherSharedTreeViewModel otherSharedTreeViewModel;
239
    OtherSharedTreeView otherSharedTreeView = null;
240

    
241
    GroupTreeViewModel groupTreeViewModel;
242
    private GroupTreeView groupTreeView;
243

    
244
    private TreeView selectedTree;
245
    protected AccountResource account;
246
    
247
    Folder trash;
248
    
249
    List<Composite> treeViews = new ArrayList<Composite>();
250

    
251
    @SuppressWarnings("rawtypes") List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
252
    
253
    Button upload;
254
    
255
    private HTML totalFiles;
256
    
257
    private HTML usedBytes;
258
    
259
    private HTML totalBytes;
260
    
261
    private HTML usedPercent;
262
    
263
    private HTML numOfFiles;
264
    
265
    private Button toolsButton;
266

    
267
        @Override
268
        public void onModuleLoad() {
269
                if (parseUserCredentials())
270
            initialize();
271
        }
272

    
273
    private void initialize() {
274
            boolean bareContent = Window.Location.getParameter("noframe") != null;
275
            String contentWidth = bareContent ? "100%" : "75%";
276

    
277
            VerticalPanel outer = new VerticalPanel();
278
        outer.setWidth("100%");
279
            if (!bareContent) {
280
                    outer.addStyleName("pithos-outer");
281
            }
282

    
283
        if (!bareContent) {
284
                topPanel = new TopPanel(this, Pithos.images);
285
                topPanel.setWidth("100%");
286
                outer.add(topPanel);
287
                outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
288
        }
289
        
290
        messagePanel.setWidth(contentWidth);
291
        messagePanel.setVisible(false);
292
        outer.add(messagePanel);
293
        outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
294

    
295
        HorizontalPanel header = new HorizontalPanel();
296
        header.addStyleName("pithos-header");
297
        header.setWidth(contentWidth);
298
        if (bareContent)
299
                header.addStyleName("pithos-header-noframe");
300
        HorizontalPanel leftHeader = new HorizontalPanel();
301
        VerticalPanel uploadButtonPanel = new VerticalPanel();
302
        upload = new Button("Upload File", new ClickHandler() {
303
            @Override
304
            public void onClick(@SuppressWarnings("unused") ClickEvent event) {
305
                new UploadFileCommand(Pithos.this, null, getSelection()).execute();
306
            }
307
        });
308
        upload.addStyleName("pithos-uploadButton");
309
        uploadButtonPanel.add(upload);
310
        uploadButtonPanel.setWidth("100%");
311
        uploadButtonPanel.setHeight("60px");
312
        uploadButtonPanel.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_LEFT);
313
        uploadButtonPanel.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
314
        leftHeader.add(uploadButtonPanel);
315
        header.add(leftHeader);
316
        header.setCellWidth(leftHeader, "35%");
317
        
318
        HorizontalPanel rightHeader = new HorizontalPanel();
319
        rightHeader.addStyleName("pithos-rightSide");
320
        rightHeader.setSpacing(5);
321

    
322
        toolsButton = new Button(AbstractImagePrototype.create(images.tools()).getHTML());
323
        toolsButton.addClickHandler(new ClickHandler() {
324
                        
325
                        @Override
326
                        public void onClick(ClickEvent event) {
327
                ToolsMenu menu = new ToolsMenu(Pithos.this, images, getSelectedTree(), getSelectedTree().getSelection(), getFileList().getSelectedFiles());
328
                if (!menu.isEmpty()) {
329
                            menu.setPopupPosition(event.getClientX(), event.getClientY());
330
                            menu.show();
331
                }
332
                        }
333
                });
334
        rightHeader.add(toolsButton);
335
        rightHeader.setCellHorizontalAlignment(toolsButton, HasHorizontalAlignment.ALIGN_LEFT);
336
        
337
        HorizontalPanel folderStatistics = new HorizontalPanel();
338
        folderStatistics.addStyleName("pithos-folderStatistics");
339
        numOfFiles = new HTML();
340
        folderStatistics.add(numOfFiles);
341
        folderStatistics.setCellVerticalAlignment(numOfFiles, HasVerticalAlignment.ALIGN_MIDDLE);
342
        HTML numOfFilesLabel = new HTML("&nbsp;Files");
343
        folderStatistics.add(numOfFilesLabel);
344
        folderStatistics.setCellVerticalAlignment(numOfFilesLabel, HasVerticalAlignment.ALIGN_MIDDLE);
345
        rightHeader.add(folderStatistics);
346
        rightHeader.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
347
        header.add(rightHeader);
348
        header.setCellVerticalAlignment(rightHeader, HasVerticalAlignment.ALIGN_MIDDLE);
349
        header.setCellHeight(rightHeader, "60px");
350
        outer.add(header);
351
        outer.setCellHorizontalAlignment(header, HasHorizontalAlignment.ALIGN_CENTER);
352
        // Inner contains the various lists.nner
353
        inner.sinkEvents(Event.ONCONTEXTMENU);
354
        inner.setWidth("100%");
355

    
356
        folderTreeSelectionModel = new SingleSelectionModel<Folder>();
357
        folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
358
            @Override
359
            public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
360
                if (folderTreeSelectionModel.getSelectedObject() != null) {
361
                    deselectOthers(folderTreeView, folderTreeSelectionModel);
362
                    applyPermissions(folderTreeSelectionModel.getSelectedObject());
363
                    Folder f = folderTreeSelectionModel.getSelectedObject();
364
                    showFiles(f);
365
                }
366
            }
367
        });
368
        selectionModels.add(folderTreeSelectionModel);
369

    
370
        folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
371
        folderTreeView = new FolderTreeView(folderTreeViewModel);
372
        treeViews.add(folderTreeView);
373
        
374
        fileList = new FileList(this, images, folderTreeView);
375
        inner.add(fileList);
376

    
377
        groupTreeViewModel = new GroupTreeViewModel(this);
378
        groupTreeView = new GroupTreeView(groupTreeViewModel);
379
        treeViews.add(groupTreeView);
380
        
381
        trees = new VerticalPanel();
382
        trees.setWidth("100%");
383

    
384
        
385
        HorizontalPanel treeHeader = new HorizontalPanel();
386
        treeHeader.addStyleName("pithos-treeHeader");
387
        treeHeader.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
388
        treeHeader.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
389
        HorizontalPanel statistics = new HorizontalPanel();
390
        statistics.addStyleName("pithos-statistics");
391
        statistics.add(new HTML("Total Objects:&nbsp;"));
392
        totalFiles = new HTML();
393
        statistics.add(totalFiles);
394
        statistics.add(new HTML("&nbsp;|&nbsp;Used:&nbsp;"));
395
        usedBytes = new HTML();
396
        statistics.add(usedBytes);
397
        statistics.add(new HTML("&nbsp;of&nbsp;"));
398
        totalBytes = new HTML();
399
        statistics.add(totalBytes);
400
        statistics.add(new HTML("&nbsp;("));
401
        usedPercent = new HTML();
402
        statistics.add(usedPercent);
403
        statistics.add(new HTML(")"));
404
        treeHeader.add(statistics);
405
        treeHeader.setCellHorizontalAlignment(statistics, HasHorizontalAlignment.ALIGN_LEFT);
406
        trees.add(treeHeader);
407

    
408
        trees.add(folderTreeView);
409
        trees.add(groupTreeView);
410
        // Add the left and right panels to the split panel.
411
        splitPanel.setLeftWidget(trees);
412
        splitPanel.setRightWidget(inner);
413
        splitPanel.setSplitPosition("35%");
414
        splitPanel.setSize("100%", "100%");
415
        splitPanel.addStyleName("pithos-splitPanel");
416
        splitPanel.setWidth(contentWidth);
417
        outer.add(splitPanel);
418
        outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
419

    
420
        if (!bareContent) {
421
                statusPanel = new StatusPanel();
422
                statusPanel.setWidth("100%");
423
                outer.add(statusPanel);
424
                outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
425
        }
426
        else
427
                splitPanel.addStyleName("pithos-splitPanel-noframe");
428

    
429
        // Hook the window resize event, so that we can adjust the UI.
430
        Window.addResizeHandler(this);
431
        // Clear out the window's built-in margin, because we want to take
432
        // advantage of the entire client area.
433
        Window.setMargin("0px");
434
        // Finally, add the outer panel to the RootPanel, so that it will be
435
        // displayed.
436
        RootPanel.get().add(outer);
437
        // Call the window resized handler to get the initial sizes setup. Doing
438
        // this in a deferred command causes it to occur after all widgets'
439
        // sizes have been computed by the browser.
440
        Scheduler.get().scheduleDeferred(new ScheduledCommand() {
441

    
442
            @Override
443
            public void execute() {
444
                onWindowResized(Window.getClientHeight());
445
            }
446
        });
447

    
448
        Scheduler.get().scheduleDeferred(new ScheduledCommand() {
449
            @Override
450
            public void execute() {
451
                fetchAccount(new Command() {
452
                                        
453
                                        @Override
454
                                        public void execute() {
455
                                if (!account.hasHomeContainer())
456
                                    createHomeContainer(account, this);
457
                                else if (!account.hasTrashContainer())
458
                                        createTrashContainer(this);
459
                                else {
460
                                        for (Folder f : account.getContainers())
461
                                                if (f.getName().equals(Pithos.TRASH_CONTAINER)) {
462
                                                        trash = f;
463
                                                        break;
464
                                                }
465
                                    folderTreeViewModel.initialize(account, new Command() {
466
                                                                
467
                                                                @Override
468
                                                                public void execute() {
469
                                                    createMySharedTree();
470
                                                                }
471
                                                        });
472
                                    groupTreeViewModel.initialize();
473
                                    showStatistics();
474
                                }
475
                                        }
476
                                });
477
            }
478
        });
479
    }
480

    
481
    public void applyPermissions(Folder f) {
482
            if (f != null) {
483
                    if (f.isInTrash())
484
                            upload.setEnabled(false);
485
                    else {
486
                            Boolean[] perms = f.getPermissions().get(username);
487
                            if (f.getOwner().equals(username) || (perms != null && perms[1] != null && perms[1])) {
488
                                    upload.setEnabled(true);
489
                            }
490
                            else
491
                                    upload.setEnabled(false);
492
                    }
493
            }
494
            else
495
                    upload.setEnabled(false);
496
        }
497

    
498
        @SuppressWarnings({ "rawtypes", "unchecked" })
499
        public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
500
            selectedTree = _selectedTree;
501
            
502
            for (Composite c : treeViews)
503
                    if (c.equals(selectedTree))
504
                            c.addStyleName("cellTreeWidget-selectedTree");
505
                    else
506
                            c.removeStyleName("cellTreeWidget-selectedTree");
507
            
508
        for (SingleSelectionModel s : selectionModels)
509
            if (!s.equals(model))
510
                s.setSelected(s.getSelectedObject(), false);
511
    }
512

    
513
    public void showFiles(Folder f) {
514
        Set<File> files = f.getFiles();
515
        showFiles(files);
516
    }
517

    
518
    public void showFiles(Set<File> files) {
519
        //Iterator<File> iter = files.iterator();
520
        //fetchFile(iter, files);
521
        fileList.setFiles(new ArrayList<File>(files));
522
    }
523

    
524
    protected void fetchFile(final Iterator<File> iter, final Set<File> files) {
525
        if (iter.hasNext()) {
526
            File file = iter.next();
527
            String path = file.getUri() + "?format=json";
528
            GetRequest<File> getFile = new GetRequest<File>(File.class, getApiPath(), username, path, file) {
529
                @Override
530
                public void onSuccess(@SuppressWarnings("unused") File _result) {
531
                    fetchFile(iter, files);
532
                }
533

    
534
                @Override
535
                public void onError(Throwable t) {
536
                    GWT.log("Error getting file", t);
537
                    if (t instanceof RestException)
538
                        displayError("Error getting file: " + ((RestException) t).getHttpStatusText());
539
                    else
540
                        displayError("System error fetching file: " + t.getMessage());
541
                }
542

    
543
                                @Override
544
                                protected void onUnauthorized(Response response) {
545
                                        sessionExpired();
546
                                }
547
            };
548
            getFile.setHeader("X-Auth-Token", "0000");
549
            Scheduler.get().scheduleDeferred(getFile);
550
        }
551
        else
552
            fileList.setFiles(new ArrayList<File>(files));
553
    }
554

    
555
    /**
556
         * Parse and store the user credentials to the appropriate fields.
557
         */
558
        private boolean parseUserCredentials() {
559
        username = Window.Location.getParameter("user");
560
        token = Window.Location.getParameter("token");
561
        Configuration conf = (Configuration) GWT.create(Configuration.class);
562
        if (username == null || username.length() == 0 || token == null || token.length() == 0) {
563
            String cookie = conf.authCookie();
564
            String auth = Cookies.getCookie(cookie);
565
            if (auth == null) {
566
                authenticateUser();
567
                return false;
568
            }
569
                        String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
570
                        if (authSplit.length != 2) {
571
                            authenticateUser();
572
                            return false;
573
                        }
574
                        username = authSplit[0];
575
                        token = authSplit[1];
576
                        return true;
577
        }
578
                Cookies.setCookie(conf.authCookie(), username + conf.cookieSeparator() + token);
579
                return true;
580
    }
581

    
582
    /**
583
         * Redirect the user to the login page for authentication.
584
         */
585
        protected void authenticateUser() {
586
                Configuration conf = (Configuration) GWT.create(Configuration.class);
587
        Window.Location.assign(conf.loginUrl() + "?next=" + Window.Location.getHref());
588
        }
589

    
590
        protected void fetchAccount(final Command callback) {
591
        String path = "?format=json";
592

    
593
        GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getApiPath(), username, path) {
594
            @Override
595
            public void onSuccess(AccountResource _result) {
596
                account = _result;
597
                if (callback != null)
598
                        callback.execute();
599
            }
600

    
601
            @Override
602
            public void onError(Throwable t) {
603
                GWT.log("Error getting account", t);
604
                if (t instanceof RestException)
605
                    displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
606
                else
607
                    displayError("System error fetching user data: " + t.getMessage());
608
            }
609

    
610
                        @Override
611
                        protected void onUnauthorized(Response response) {
612
                                sessionExpired();
613
                        }
614
        };
615
        getAccount.setHeader("X-Auth-Token", token);
616
        Scheduler.get().scheduleDeferred(getAccount);
617
    }
618

    
619
    public void updateStatistics() {
620
            HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getApiPath(), username, "", account) {
621

    
622
                        @Override
623
                        public void onSuccess(@SuppressWarnings("unused") AccountResource _result) {
624
                                showStatistics();
625
                        }
626

    
627
                        @Override
628
                        public void onError(Throwable t) {
629
                GWT.log("Error getting account", t);
630
                if (t instanceof RestException)
631
                    displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
632
                else
633
                    displayError("System error fetching user data: " + t.getMessage());
634
                        }
635

    
636
                        @Override
637
                        protected void onUnauthorized(Response response) {
638
                                sessionExpired();
639
                        }
640
                };
641
                headAccount.setHeader("X-Auth-Token", token);
642
                Scheduler.get().scheduleDeferred(headAccount);
643
        }
644

    
645
        protected void showStatistics() {
646
            totalFiles.setHTML(String.valueOf(account.getNumberOfObjects()));
647
            usedBytes.setHTML(String.valueOf(account.getFileSizeAsString()));
648
            totalBytes.setHTML(String.valueOf(account.getQuotaAsString()));
649
            NumberFormat nf = NumberFormat.getPercentFormat();
650
            usedPercent.setHTML(nf.format(account.getUsedPercentage()));
651
        }
652

    
653
        protected void createHomeContainer(final AccountResource _account, final Command callback) {
654
        String path = "/" + Pithos.HOME_CONTAINER;
655
        PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
656
            @Override
657
            public void onSuccess(@SuppressWarnings("unused") Resource result) {
658
                    if (!_account.hasTrashContainer())
659
                            createTrashContainer(callback);
660
                    else
661
                            fetchAccount(callback);
662
            }
663

    
664
            @Override
665
            public void onError(Throwable t) {
666
                GWT.log("Error creating pithos", t);
667
                if (t instanceof RestException)
668
                    displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
669
                else
670
                    displayError("System error Error creating pithos: " + t.getMessage());
671
            }
672

    
673
                        @Override
674
                        protected void onUnauthorized(Response response) {
675
                                sessionExpired();
676
                        }
677
        };
678
        createPithos.setHeader("X-Auth-Token", getToken());
679
        Scheduler.get().scheduleDeferred(createPithos);
680
    }
681

    
682
    protected void createTrashContainer(final Command callback) {
683
        String path = "/" + Pithos.TRASH_CONTAINER;
684
        PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
685
            @Override
686
            public void onSuccess(@SuppressWarnings("unused") Resource result) {
687
                           fetchAccount(callback);
688
            }
689

    
690
            @Override
691
            public void onError(Throwable t) {
692
                GWT.log("Error creating pithos", t);
693
                if (t instanceof RestException)
694
                    displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
695
                else
696
                    displayError("System error Error creating pithos: " + t.getMessage());
697
            }
698

    
699
                        @Override
700
                        protected void onUnauthorized(Response response) {
701
                                sessionExpired();
702
                        }
703
        };
704
        createPithos.setHeader("X-Auth-Token", getToken());
705
        Scheduler.get().scheduleDeferred(createPithos);
706
    }
707

    
708
    /**
709
         * Creates an HTML fragment that places an image & caption together, for use
710
         * in a group header.
711
         *
712
         * @param imageProto an image prototype for an image
713
         * @param caption the group caption
714
         * @return the header HTML fragment
715
         */
716
        private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
717
                String captionHTML = "<table class='caption' cellpadding='0' " 
718
                + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML() 
719
                + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'>&nbsp;" 
720
                + caption + "</b></td></tr></table>";
721
                return captionHTML;
722
        }
723

    
724
        protected void onWindowResized(int height) {
725
                // Adjust the split panel to take up the available room in the window.
726
                int newHeight = height - splitPanel.getAbsoluteTop();
727
                if (newHeight < 1)
728
                        newHeight = 1;
729
                splitPanel.setHeight("" + newHeight);
730
                inner.setHeight("" + newHeight);
731
        }
732

    
733
        @Override
734
        public void onResize(ResizeEvent event) {
735
                int height = event.getHeight();
736
                onWindowResized(height);
737
        }
738

    
739
        /**
740
         * Display an error message.
741
         *
742
         * @param msg the message to display
743
         */
744
        public void displayError(String msg) {
745
                messagePanel.displayError(msg);
746
        }
747

    
748
        /**
749
         * Display a warning message.
750
         *
751
         * @param msg the message to display
752
         */
753
        public void displayWarning(String msg) {
754
                messagePanel.displayWarning(msg);
755
        }
756

    
757
        /**
758
         * Display an informational message.
759
         *
760
         * @param msg the message to display
761
         */
762
        public void displayInformation(String msg) {
763
                messagePanel.displayInformation(msg);
764
        }
765

    
766
        /**
767
         * Retrieve the fileList.
768
         *
769
         * @return the fileList
770
         */
771
        public FileList getFileList() {
772
                return fileList;
773
        }
774

    
775
        /**
776
         * Retrieve the topPanel.
777
         *
778
         * @return the topPanel
779
         */
780
        TopPanel getTopPanel() {
781
                return topPanel;
782
        }
783

    
784
        /**
785
         * Retrieve the clipboard.
786
         *
787
         * @return the clipboard
788
         */
789
        public Clipboard getClipboard() {
790
                return clipboard;
791
        }
792

    
793
        public StatusPanel getStatusPanel() {
794
                return statusPanel;
795
        }
796

    
797
        public String getToken() {
798
                return token;
799
        }
800

    
801
        public static native void preventIESelection() /*-{
802
                $doc.body.onselectstart = function () { return false; };
803
        }-*/;
804

    
805
        public static native void enableIESelection() /*-{
806
                if ($doc.body.onselectstart != null)
807
                $doc.body.onselectstart = null;
808
        }-*/;
809

    
810
        /**
811
         * @return the absolute path of the API root URL
812
         */
813
        public String getApiPath() {
814
                Configuration conf = (Configuration) GWT.create(Configuration.class);
815
                return conf.apiPath();
816
        }
817

    
818
        /**
819
         * History support for folder navigation
820
         * adds a new browser history entry
821
         *
822
         * @param key
823
         */
824
        public void updateHistory(String key){
825
//                Replace any whitespace of the initial string to "+"
826
//                String result = key.replaceAll("\\s","+");
827
//                Add a new browser history entry.
828
//                History.newItem(result);
829
                History.newItem(key);
830
        }
831

    
832
    public void deleteFolder(final Folder folder) {
833
        String path = getApiPath() + folder.getOwner() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(folder.getPrefix()) + "&t=" + System.currentTimeMillis();
834
        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
835
        builder.setHeader("X-Auth-Token", getToken());
836
        try {
837
            builder.sendRequest("", new RequestCallback() {
838
                @Override
839
                public void onResponseReceived(@SuppressWarnings("unused") Request request, Response response) {
840
                    if (response.getStatusCode() == Response.SC_OK) {
841
                        JSONValue json = JSONParser.parseStrict(response.getText());
842
                        JSONArray array = json.isArray();
843
                        int i = 0;
844
                        if (array != null) {
845
                            deleteObject(folder, i, array);
846
                        }
847
                    }
848
                }
849

    
850
                @Override
851
                public void onError(@SuppressWarnings("unused") Request request, Throwable exception) {
852
                    displayError("System error unable to delete folder: " + exception.getMessage());
853
                }
854
            });
855
        }
856
        catch (RequestException e) {
857
        }
858
    }
859

    
860
    void deleteObject(final Folder folder, final int i, final JSONArray array) {
861
        if (i < array.size()) {
862
            JSONObject o = array.get(i).isObject();
863
            if (o != null && !o.containsKey("subdir")) {
864
                JSONString name = o.get("name").isString();
865
                String path = "/" + folder.getContainer() + "/" + name.stringValue();
866
                DeleteRequest delete = new DeleteRequest(getApiPath(), folder.getOwner(), path) {
867
                    @Override
868
                    public void onSuccess(@SuppressWarnings("unused") Resource result) {
869
                        deleteObject(folder, i + 1, array);
870
                    }
871

    
872
                    @Override
873
                    public void onError(Throwable t) {
874
                        GWT.log("", t);
875
                        displayError("System error unable to delete folder: " + t.getMessage());
876
                    }
877

    
878
                                    @Override
879
                                    protected void onUnauthorized(Response response) {
880
                                            sessionExpired();
881
                                    }
882
                };
883
                delete.setHeader("X-Auth-Token", getToken());
884
                Scheduler.get().scheduleDeferred(delete);
885
            }
886
            else if (o != null) {
887
                String subdir = o.get("subdir").isString().stringValue();
888
                subdir = subdir.substring(0, subdir.length() - 1);
889
                String path = getApiPath() + getUsername() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(subdir) + "&t=" + System.currentTimeMillis();
890
                RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
891
                builder.setHeader("X-Auth-Token", getToken());
892
                try {
893
                    builder.sendRequest("", new RequestCallback() {
894
                        @Override
895
                        public void onResponseReceived(@SuppressWarnings("unused") Request request, Response response) {
896
                            if (response.getStatusCode() == Response.SC_OK) {
897
                                JSONValue json = JSONParser.parseStrict(response.getText());
898
                                JSONArray array2 = json.isArray();
899
                                if (array2 != null) {
900
                                    int l = array.size();
901
                                    for (int j=0; j<array2.size(); j++) {
902
                                        array.set(l++, array2.get(j));
903
                                    }
904
                                }
905
                                deleteObject(folder, i + 1, array);
906
                            }
907
                        }
908

    
909
                        @Override
910
                        public void onError(@SuppressWarnings("unused") Request request, Throwable exception) {
911
                            displayError("System error unable to delete folder: " + exception.getMessage());
912
                        }
913
                    });
914
                }
915
                catch (RequestException e) {
916
                }
917
            }
918
        }
919
        else {
920
            String path = folder.getUri();
921
            DeleteRequest deleteFolder = new DeleteRequest(getApiPath(), getUsername(), path) {
922
                @Override
923
                public void onSuccess(@SuppressWarnings("unused") Resource result) {
924
                    updateFolder(folder.getParent(), true, new Command() {
925
                                                
926
                                                @Override
927
                                                public void execute() {
928
                                                        updateStatistics();
929
                                                }
930
                                        });
931
                }
932

    
933
                @Override
934
                public void onError(Throwable t) {
935
                    GWT.log("", t);
936
                    if (t instanceof RestException) {
937
                            if (((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND)
938
                                    displayError("Unable to delete folder: "+((RestException) t).getHttpStatusText());
939
                            else
940
                                    onSuccess(null);
941
                    }
942
                    else
943
                        displayError("System error unable to delete folder: " + t.getMessage());
944
                }
945

    
946
                                @Override
947
                                protected void onUnauthorized(Response response) {
948
                                        sessionExpired();
949
                                }
950
            };
951
            deleteFolder.setHeader("X-Auth-Token", getToken());
952
            Scheduler.get().scheduleDeferred(deleteFolder);
953
        }
954
    }
955

    
956
    public FolderTreeView getFolderTreeView() {
957
        return folderTreeView;
958
    }
959

    
960
    public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
961
        if (iter.hasNext()) {
962
            File file = iter.next();
963
            String path = targetUri + "/" + file.getName();
964
            PutRequest copyFile = new PutRequest(getApiPath(), targetUsername, path) {
965
                @Override
966
                public void onSuccess(@SuppressWarnings("unused") Resource result) {
967
                    copyFiles(iter, targetUsername, targetUri, callback);
968
                }
969

    
970
                @Override
971
                public void onError(Throwable t) {
972
                    GWT.log("", t);
973
                    if (t instanceof RestException) {
974
                        displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
975
                    }
976
                    else
977
                        displayError("System error unable to copy file: "+t.getMessage());
978
                }
979

    
980
                                @Override
981
                                protected void onUnauthorized(Response response) {
982
                                        sessionExpired();
983
                                }
984
            };
985
            copyFile.setHeader("X-Auth-Token", getToken());
986
            copyFile.setHeader("X-Copy-From", file.getUri());
987
            if (!file.getOwner().equals(targetUsername))
988
                    copyFile.setHeader("X-Source-Account", file.getOwner());
989
            Scheduler.get().scheduleDeferred(copyFile);
990
        }
991
        else  if (callback != null) {
992
            callback.execute();
993
        }
994
    }
995

    
996
    public void copySubfolders(final Iterator<Folder> iter, final String targetUsername, final String targetUri, final Command callback) {
997
        if (iter.hasNext()) {
998
            final Folder f = iter.next();
999
            copyFolder(f, targetUsername, targetUri, new Command() {
1000
                                
1001
                                @Override
1002
                                public void execute() {
1003
                                        copySubfolders(iter, targetUsername, targetUri, callback);
1004
                                }
1005
                        });
1006
        }
1007
        else  if (callback != null) {
1008
            callback.execute();
1009
        }
1010
    }
1011

    
1012
    public void copyFolder(final Folder f, final String targetUsername, final String targetUri, final Command callback) {
1013
        String path = targetUri + "/" + f.getName();
1014
        PutRequest createFolder = new PutRequest(getApiPath(), targetUsername, path) {
1015
            @Override
1016
            public void onSuccess(@SuppressWarnings("unused") Resource result) {
1017
                    GetRequest<Folder> getFolder = new GetRequest<Folder>(Folder.class, getApiPath(), f.getOwner(), "/" + f.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(f.getPrefix()), f) {
1018

    
1019
                                        @Override
1020
                                        public void onSuccess(final Folder _f) {
1021
                                Iterator<File> iter = _f.getFiles().iterator();
1022
                                copyFiles(iter, targetUsername, targetUri + "/" + _f.getName(), new Command() {
1023
                                    @Override
1024
                                    public void execute() {
1025
                                        Iterator<Folder> iterf = _f.getSubfolders().iterator();
1026
                                        copySubfolders(iterf, targetUsername, targetUri + "/" + _f.getName(), callback);
1027
                                    }
1028
                                });
1029
                                        }
1030

    
1031
                                        @Override
1032
                                        public void onError(Throwable t) {
1033
                                GWT.log("", t);
1034
                                if (t instanceof RestException) {
1035
                                    displayError("Unable to get folder: " + ((RestException) t).getHttpStatusText());
1036
                                }
1037
                                else
1038
                                    displayError("System error getting folder: " + t.getMessage());
1039
                                        }
1040

    
1041
                                        @Override
1042
                                        protected void onUnauthorized(Response response) {
1043
                                                sessionExpired();
1044
                                        }
1045
                                };
1046
                                getFolder.setHeader("X-Auth-Token", getToken());
1047
                                Scheduler.get().scheduleDeferred(getFolder);
1048
            }
1049

    
1050
            @Override
1051
            public void onError(Throwable t) {
1052
                GWT.log("", t);
1053
                if (t instanceof RestException) {
1054
                    displayError("Unable to create folder: " + ((RestException) t).getHttpStatusText());
1055
                }
1056
                else
1057
                    displayError("System error creating folder: " + t.getMessage());
1058
            }
1059

    
1060
                        @Override
1061
                        protected void onUnauthorized(Response response) {
1062
                                sessionExpired();
1063
                        }
1064
        };
1065
        createFolder.setHeader("X-Auth-Token", getToken());
1066
        createFolder.setHeader("Accept", "*/*");
1067
        createFolder.setHeader("Content-Length", "0");
1068
        createFolder.setHeader("Content-Type", "application/folder");
1069
        Scheduler.get().scheduleDeferred(createFolder);
1070
    }
1071
    
1072
    public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1073
            selectionModels.add(model);
1074
    }
1075

    
1076
        public OtherSharedTreeView getOtherSharedTreeView() {
1077
                return otherSharedTreeView;
1078
        }
1079

    
1080
        public void updateTrash(boolean showFiles, Command callback) {
1081
                updateFolder(trash, showFiles, callback);
1082
        }
1083

    
1084
        public void updateGroupsNode() {
1085
                groupTreeView.updateGroupNode(null);
1086
        }
1087

    
1088
        public void addGroup(String groupname) {
1089
                Group newGroup = new Group(groupname);
1090
                account.addGroup(newGroup);
1091
                groupTreeView.updateGroupNode(null);
1092
        }
1093

    
1094
        public void removeGroup(Group group) {
1095
                account.removeGroup(group);
1096
                updateGroupsNode();
1097
        }
1098

    
1099
        public TreeView getSelectedTree() {
1100
                return selectedTree;
1101
        }
1102
        
1103
        public Folder getSelection() {
1104
                return selectedTree.getSelection();
1105
        }
1106

    
1107
        public void showFolderStatistics(int folderFileCount) {
1108
                numOfFiles.setHTML(String.valueOf(folderFileCount));
1109
        }
1110

    
1111
        public GroupTreeView getGroupTreeView() {
1112
                return groupTreeView;
1113
        }
1114

    
1115
        public void sessionExpired() {
1116
                new SessionExpiredDialog(this).center();
1117
        }
1118

    
1119
        public void updateRootFolder(Command callback) {
1120
                updateFolder(account.getPithos(), false, callback);
1121
        }
1122

    
1123
        void createMySharedTree() {
1124
                mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1125
                mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1126
                    @Override
1127
                    public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
1128
                        if (mysharedTreeSelectionModel.getSelectedObject() != null) {
1129
                            deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1130
                            upload.setEnabled(false);
1131
                            updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1132
                        }
1133
                     }
1134
                });
1135
                selectionModels.add(mysharedTreeSelectionModel);
1136
                mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1137
                mysharedTreeViewModel.initialize(new Command() {
1138
                        
1139
                        @Override
1140
                        public void execute() {
1141
                            mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1142
                                trees.insert(mysharedTreeView, 2);
1143
                                treeViews.add(mysharedTreeView);
1144
                                createOtherSharedTree();
1145
                        }
1146
                });
1147
        }
1148

    
1149
        void createOtherSharedTree() {
1150
                otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1151
                otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1152
                    @Override
1153
                    public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
1154
                        if (otherSharedTreeSelectionModel.getSelectedObject() != null) {
1155
                            deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1156
                            otherSharedTreeView.addStyleName("cellTreeWidget-selectedTree");
1157
                            applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1158
                            updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true);
1159
                        }
1160
                     }
1161
                });
1162
                selectionModels.add(otherSharedTreeSelectionModel);
1163
                otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1164
                otherSharedTreeViewModel.initialize(new Command() {
1165
                        
1166
                        @Override
1167
                        public void execute() {
1168
                            otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel);
1169
                                trees.insert(otherSharedTreeView, 3);
1170
                                treeViews.add(otherSharedTreeView);
1171
                        }
1172
                });
1173
        }
1174

    
1175
        public void logoff() {
1176
        Configuration conf = (Configuration) GWT.create(Configuration.class);
1177
                Cookies.removeCookie(conf.authCookie());
1178
                Cookies.removeCookie(conf.authTokenCookie(), "/");
1179
                for (String s: Cookies.getCookieNames())
1180
                        if (s.startsWith(conf.shibSessionCookiePrefix()))
1181
                                Cookies.removeCookie(s, "/");
1182
                Window.Location.assign(Window.Location.getPath());
1183
        }
1184
}