Statistics
| Branch: | Tag: | Revision:

root / src / gr / grnet / pithos / web / client / Pithos.java @ 1a0db4f4

History | View | Annotate | Download (42.3 kB)

1
/*
2
 * Copyright 2011-2012 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

    
58
import java.util.ArrayList;
59
import java.util.HashMap;
60
import java.util.Iterator;
61
import java.util.List;
62
import java.util.Set;
63

    
64
import com.google.gwt.core.client.EntryPoint;
65
import com.google.gwt.core.client.GWT;
66
import com.google.gwt.core.client.Scheduler;
67
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
68
import com.google.gwt.event.dom.client.ClickEvent;
69
import com.google.gwt.event.dom.client.ClickHandler;
70
import com.google.gwt.event.logical.shared.ResizeEvent;
71
import com.google.gwt.event.logical.shared.ResizeHandler;
72
import com.google.gwt.http.client.Request;
73
import com.google.gwt.http.client.RequestBuilder;
74
import com.google.gwt.http.client.RequestCallback;
75
import com.google.gwt.http.client.RequestException;
76
import com.google.gwt.http.client.Response;
77
import com.google.gwt.http.client.URL;
78
import com.google.gwt.i18n.client.NumberFormat;
79
import com.google.gwt.json.client.JSONArray;
80
import com.google.gwt.json.client.JSONObject;
81
import com.google.gwt.json.client.JSONParser;
82
import com.google.gwt.json.client.JSONString;
83
import com.google.gwt.json.client.JSONValue;
84
import com.google.gwt.resources.client.ImageResource;
85
import com.google.gwt.resources.client.ImageResource.ImageOptions;
86
import com.google.gwt.user.client.Command;
87
import com.google.gwt.user.client.Cookies;
88
import com.google.gwt.user.client.Event;
89
import com.google.gwt.user.client.History;
90
import com.google.gwt.user.client.Window;
91
import com.google.gwt.user.client.ui.AbstractImagePrototype;
92
import com.google.gwt.user.client.ui.Button;
93
import com.google.gwt.user.client.ui.Composite;
94
import com.google.gwt.user.client.ui.HTML;
95
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
96
import com.google.gwt.user.client.ui.HasVerticalAlignment;
97
import com.google.gwt.user.client.ui.HorizontalPanel;
98
import com.google.gwt.user.client.ui.HorizontalSplitPanel;
99
import com.google.gwt.user.client.ui.RootPanel;
100
import com.google.gwt.user.client.ui.VerticalPanel;
101
import com.google.gwt.view.client.SelectionChangeEvent;
102
import com.google.gwt.view.client.SelectionChangeEvent.Handler;
103
import com.google.gwt.view.client.SingleSelectionModel;
104

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

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

    
112
        public static final String TRASH_CONTAINER = "trash";
113

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

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

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

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

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

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

    
142
    public void updateMySharedRoot() {
143
            mysharedTreeView.updateRoot();
144
    }
145
    
146
    public void updateSharedFolder(Folder f, boolean showfiles) {
147
            mysharedTreeView.updateFolder(f, showfiles);
148
    }
149
    
150
    public void updateOtherSharedFolder(Folder f, boolean showfiles) {
151
            otherSharedTreeView.updateFolder(f, showfiles);
152
    }
153

    
154
    public List<Tag> getAllTags() {
155
        List<Tag> tagList = new ArrayList<Tag>();
156
        for (Folder f : account.getContainers()) {
157
            for (String t : f.getTags()) {
158
                tagList.add(new Tag(t));
159
            }
160
        }
161
        return tagList;
162
    }
163

    
164
    public MysharedTreeView getMySharedTreeView() {
165
        return mysharedTreeView;
166
    }
167

    
168
    /**
169
         * An aggregate image bundle that pulls together all the images for this
170
         * application into a single bundle.
171
         */
172
        public interface Images extends TopPanel.Images, FileList.Images, ToolsMenu.Images {
173

    
174
                @Source("gr/grnet/pithos/resources/document.png")
175
                ImageResource folders();
176

    
177
                @Source("gr/grnet/pithos/resources/advancedsettings.png")
178
                @ImageOptions(width=32, height=32)
179
                ImageResource tools();
180
        }
181

    
182
        private Throwable error;
183
        
184
        /**
185
         * The Application Clipboard implementation;
186
         */
187
        private Clipboard clipboard = new Clipboard();
188

    
189
        /**
190
         * The top panel that contains the menu bar.
191
         */
192
        private TopPanel topPanel;
193

    
194
        /**
195
         * The panel that contains the various system messages.
196
         */
197
        private MessagePanel messagePanel = new MessagePanel(this, Pithos.images);
198

    
199
        /**
200
         * The bottom panel that contains the status bar.
201
         */
202
        private StatusPanel statusPanel = null;
203

    
204
        /**
205
         * The file list widget.
206
         */
207
        private FileList fileList;
208

    
209
        /**
210
         * The tab panel that occupies the right side of the screen.
211
         */
212
        private VerticalPanel inner = new VerticalPanel();
213

    
214

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

    
220
        /**
221
         * The currently selected item in the application, for use by the Edit menu
222
         * commands. Potential types are Folder, File, User and Group.
223
         */
224
        private Object currentSelection;
225

    
226
        public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
227

    
228
    private String username = null;
229

    
230
    /**
231
     * The authentication token of the current user.
232
     */
233
    private String token;
234

    
235
    VerticalPanel trees;
236
    
237
    SingleSelectionModel<Folder> folderTreeSelectionModel;
238
    FolderTreeViewModel folderTreeViewModel;
239
    FolderTreeView folderTreeView;
240

    
241
    SingleSelectionModel<Folder> mysharedTreeSelectionModel;
242
    MysharedTreeViewModel mysharedTreeViewModel;
243
    MysharedTreeView mysharedTreeView = null;;
244

    
245
    protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
246
    OtherSharedTreeViewModel otherSharedTreeViewModel;
247
    OtherSharedTreeView otherSharedTreeView = null;
248

    
249
    GroupTreeViewModel groupTreeViewModel;
250
    private GroupTreeView groupTreeView;
251

    
252
    TreeView selectedTree;
253
    protected AccountResource account;
254
    
255
    Folder trash;
256
    
257
    List<Composite> treeViews = new ArrayList<Composite>();
258

    
259
    @SuppressWarnings("rawtypes") List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
260
    
261
    Button upload;
262
    
263
    private HTML usedBytes;
264
    
265
    private HTML totalBytes;
266
    
267
    private HTML usedPercent;
268
    
269
    private HTML numOfFiles;
270
    
271
    private Toolbar toolbar;
272
    
273
    private FileUploadDialog fileUploadDialog;
274
    
275
        @Override
276
        public void onModuleLoad() {
277
                if (parseUserCredentials())
278
            initialize();
279
        }
280

    
281
    private void initialize() {
282
            boolean bareContent = Window.Location.getParameter("noframe") != null;
283
            String contentWidth = bareContent ? "100%" : "75%";
284

    
285
            VerticalPanel outer = new VerticalPanel();
286
        outer.setWidth("100%");
287
            if (!bareContent) {
288
                    outer.addStyleName("pithos-outer");
289
            }
290

    
291
        if (!bareContent) {
292
                topPanel = new TopPanel(this, Pithos.images);
293
                topPanel.setWidth("100%");
294
                outer.add(topPanel);
295
                outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
296
        }
297
        
298
        messagePanel.setVisible(false);
299
        outer.add(messagePanel);
300
        outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
301
        outer.setCellVerticalAlignment(messagePanel, HasVerticalAlignment.ALIGN_MIDDLE);
302

    
303
        HorizontalPanel header = new HorizontalPanel();
304
        header.addStyleName("pithos-header");
305
        header.setWidth(contentWidth);
306
        if (bareContent)
307
                header.addStyleName("pithos-header-noframe");
308
        upload = new Button("Upload", new ClickHandler() {
309
            @Override
310
            public void onClick(ClickEvent event) {
311
                    if (getSelection() != null)
312
                            new UploadFileCommand(Pithos.this, null, getSelection()).execute();
313
            }
314
        });
315
        upload.addStyleName("pithos-uploadButton");
316
        header.add(upload);
317
        header.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_LEFT);
318
        header.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
319

    
320
        toolbar = new Toolbar(this);
321
        header.add(toolbar);
322
        header.setCellHorizontalAlignment(toolbar, HasHorizontalAlignment.ALIGN_CENTER);
323
        header.setCellVerticalAlignment(toolbar, HasVerticalAlignment.ALIGN_MIDDLE);
324
        
325
        HorizontalPanel folderStatistics = new HorizontalPanel();
326
        folderStatistics.addStyleName("pithos-folderStatistics");
327
        numOfFiles = new HTML();
328
        folderStatistics.add(numOfFiles);
329
        folderStatistics.setCellVerticalAlignment(numOfFiles, HasVerticalAlignment.ALIGN_MIDDLE);
330
        HTML numOfFilesLabel = new HTML("&nbsp;Files");
331
        folderStatistics.add(numOfFilesLabel);
332
        folderStatistics.setCellVerticalAlignment(numOfFilesLabel, HasVerticalAlignment.ALIGN_MIDDLE);
333
        header.add(folderStatistics);
334
        header.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
335
        header.setCellVerticalAlignment(folderStatistics, HasVerticalAlignment.ALIGN_MIDDLE);
336
        header.setCellWidth(folderStatistics, "40px");
337
        outer.add(header);
338
        outer.setCellHorizontalAlignment(header, HasHorizontalAlignment.ALIGN_CENTER);
339
        // Inner contains the various lists.nner
340
        inner.sinkEvents(Event.ONCONTEXTMENU);
341
        inner.setWidth("100%");
342

    
343
        folderTreeSelectionModel = new SingleSelectionModel<Folder>();
344
        folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
345
            @Override
346
            public void onSelectionChange(SelectionChangeEvent event) {
347
                if (folderTreeSelectionModel.getSelectedObject() != null) {
348
                    deselectOthers(folderTreeView, folderTreeSelectionModel);
349
                    applyPermissions(folderTreeSelectionModel.getSelectedObject());
350
                    Folder f = folderTreeSelectionModel.getSelectedObject();
351
                            updateFolder(f, true, new Command() {
352
                                    
353
                                    @Override
354
                                    public void execute() {
355
                                            updateStatistics();
356
                                    }
357
                            });
358
                }
359
                showRelevantToolbarButtons();
360
            }
361
        });
362
        selectionModels.add(folderTreeSelectionModel);
363

    
364
        folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
365
        folderTreeView = new FolderTreeView(folderTreeViewModel);
366
        treeViews.add(folderTreeView);
367
        
368
        fileList = new FileList(this, images, folderTreeView);
369
        inner.add(fileList);
370

    
371
        groupTreeViewModel = new GroupTreeViewModel(this);
372
        groupTreeView = new GroupTreeView(groupTreeViewModel);
373
        treeViews.add(groupTreeView);
374
        
375
        trees = new VerticalPanel();
376
        trees.setWidth("100%");
377

    
378
        
379
        HorizontalPanel treeHeader = new HorizontalPanel();
380
        treeHeader.addStyleName("pithos-treeHeader");
381
        treeHeader.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
382
        treeHeader.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
383
        HorizontalPanel statistics = new HorizontalPanel();
384
        statistics.addStyleName("pithos-statistics");
385
        statistics.add(new HTML("Used:&nbsp;"));
386
        usedBytes = new HTML();
387
        statistics.add(usedBytes);
388
        statistics.add(new HTML("&nbsp;of&nbsp;"));
389
        totalBytes = new HTML();
390
        statistics.add(totalBytes);
391
        statistics.add(new HTML("&nbsp;("));
392
        usedPercent = new HTML();
393
        statistics.add(usedPercent);
394
        statistics.add(new HTML(")"));
395
        treeHeader.add(statistics);
396
        treeHeader.setCellHorizontalAlignment(statistics, HasHorizontalAlignment.ALIGN_LEFT);
397
        trees.add(treeHeader);
398

    
399
        trees.add(folderTreeView);
400
        trees.add(groupTreeView);
401
        // Add the left and right panels to the split panel.
402
        splitPanel.setLeftWidget(trees);
403
        splitPanel.setRightWidget(inner);
404
        splitPanel.setSplitPosition("35%");
405
        splitPanel.setSize("100%", "100%");
406
        splitPanel.addStyleName("pithos-splitPanel");
407
        splitPanel.setWidth(contentWidth);
408
        outer.add(splitPanel);
409
        outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
410

    
411
        if (!bareContent) {
412
                statusPanel = new StatusPanel();
413
                statusPanel.setWidth("100%");
414
                outer.add(statusPanel);
415
                outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
416
        }
417
        else
418
                splitPanel.addStyleName("pithos-splitPanel-noframe");
419

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

    
433
            @Override
434
            public void execute() {
435
                onWindowResized(Window.getClientHeight());
436
            }
437
        });
438

    
439
        Scheduler.get().scheduleDeferred(new ScheduledCommand() {
440
            @Override
441
            public void execute() {
442
                fetchAccount(new Command() {
443
                                        
444
                                        @Override
445
                                        public void execute() {
446
                                if (!account.hasHomeContainer())
447
                                    createHomeContainer(account, this);
448
                                else if (!account.hasTrashContainer())
449
                                        createTrashContainer(this);
450
                                else {
451
                                        for (Folder f : account.getContainers())
452
                                                if (f.getName().equals(Pithos.TRASH_CONTAINER)) {
453
                                                        trash = f;
454
                                                        break;
455
                                                }
456
                                    folderTreeViewModel.initialize(account, new Command() {
457
                                                                
458
                                                                @Override
459
                                                                public void execute() {
460
                                                    createMySharedTree();
461
                                                                }
462
                                                        });
463
                                    groupTreeViewModel.initialize();
464
                                    showStatistics();
465
                                }
466
                                        }
467
                                });
468
            }
469
        });
470
        
471
//        Scheduler.get().scheduleDeferred(new Command() {
472
//                        
473
//                        @Override
474
//                        public void execute() {
475
//                                displayError("lalala");
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(final Folder f) {
514
        Set<File> files = f.getFiles();
515
        showFiles(files);
516
    }
517

    
518
    public void showFiles(Set<File> files) {
519
        fileList.setFiles(new ArrayList<File>(files));
520
    }
521

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

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

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

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

    
586
    /**
587
         * Redirect the user to the login page for authentication.
588
         */
589
        protected void authenticateUser() {
590
        Window.Location.assign(config.loginUrl());
591
        }
592

    
593
        protected void fetchAccount(final Command callback) {
594
        String path = "?format=json";
595

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

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

    
614
                        @Override
615
                        protected void onUnauthorized(Response response) {
616
                                sessionExpired();
617
                        }
618
        };
619
        getAccount.setHeader("X-Auth-Token", token);
620
        Scheduler.get().scheduleDeferred(getAccount);
621
    }
622

    
623
    public void updateStatistics() {
624
            HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getApiPath(), username, "", account) {
625

    
626
                        @Override
627
                        public void onSuccess(AccountResource _result) {
628
                                showStatistics();
629
                        }
630

    
631
                        @Override
632
                        public void onError(Throwable t) {
633
                GWT.log("Error getting account", t);
634
                                setError(t);
635
                if (t instanceof RestException)
636
                    displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
637
                else
638
                    displayError("System error fetching user data: " + t.getMessage());
639
                        }
640

    
641
                        @Override
642
                        protected void onUnauthorized(Response response) {
643
                                sessionExpired();
644
                        }
645
                };
646
                headAccount.setHeader("X-Auth-Token", token);
647
                Scheduler.get().scheduleDeferred(headAccount);
648
        }
649

    
650
        protected void showStatistics() {
651
            usedBytes.setHTML(String.valueOf(account.getFileSizeAsString()));
652
            totalBytes.setHTML(String.valueOf(account.getQuotaAsString()));
653
            NumberFormat nf = NumberFormat.getPercentFormat();
654
            usedPercent.setHTML(nf.format(account.getUsedPercentage()));
655
        }
656

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

    
668
            @Override
669
            public void onError(Throwable t) {
670
                GWT.log("Error creating pithos", t);
671
                                setError(t);
672
                if (t instanceof RestException)
673
                    displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
674
                else
675
                    displayError("System error Error creating pithos: " + t.getMessage());
676
            }
677

    
678
                        @Override
679
                        protected void onUnauthorized(Response response) {
680
                                sessionExpired();
681
                        }
682
        };
683
        createPithos.setHeader("X-Auth-Token", getToken());
684
        Scheduler.get().scheduleDeferred(createPithos);
685
    }
686

    
687
    protected void createTrashContainer(final Command callback) {
688
        String path = "/" + Pithos.TRASH_CONTAINER;
689
        PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
690
            @Override
691
            public void onSuccess(Resource result) {
692
                           fetchAccount(callback);
693
            }
694

    
695
            @Override
696
            public void onError(Throwable t) {
697
                GWT.log("Error creating pithos", t);
698
                                setError(t);
699
                if (t instanceof RestException)
700
                    displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
701
                else
702
                    displayError("System error Error creating pithos: " + t.getMessage());
703
            }
704

    
705
                        @Override
706
                        protected void onUnauthorized(Response response) {
707
                                sessionExpired();
708
                        }
709
        };
710
        createPithos.setHeader("X-Auth-Token", getToken());
711
        Scheduler.get().scheduleDeferred(createPithos);
712
    }
713

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

    
730
        protected void onWindowResized(int height) {
731
                // Adjust the split panel to take up the available room in the window.
732
                int newHeight = height - splitPanel.getAbsoluteTop();
733
                if (newHeight < 1)
734
                        newHeight = 1;
735
                splitPanel.setHeight("" + newHeight);
736
                inner.setHeight("" + newHeight);
737
        }
738

    
739
        @Override
740
        public void onResize(ResizeEvent event) {
741
                int height = event.getHeight();
742
                onWindowResized(height);
743
        }
744

    
745
        /**
746
         * Display an error message.
747
         *
748
         * @param msg the message to display
749
         */
750
        public void displayError(String msg) {
751
                messagePanel.displayError(msg);
752
        }
753

    
754
        /**
755
         * Display a warning message.
756
         *
757
         * @param msg the message to display
758
         */
759
        public void displayWarning(String msg) {
760
                messagePanel.displayWarning(msg);
761
        }
762

    
763
        /**
764
         * Display an informational message.
765
         *
766
         * @param msg the message to display
767
         */
768
        public void displayInformation(String msg) {
769
                messagePanel.displayInformation(msg);
770
        }
771

    
772
        /**
773
         * Retrieve the fileList.
774
         *
775
         * @return the fileList
776
         */
777
        public FileList getFileList() {
778
                return fileList;
779
        }
780

    
781
        /**
782
         * Retrieve the topPanel.
783
         *
784
         * @return the topPanel
785
         */
786
        TopPanel getTopPanel() {
787
                return topPanel;
788
        }
789

    
790
        /**
791
         * Retrieve the clipboard.
792
         *
793
         * @return the clipboard
794
         */
795
        public Clipboard getClipboard() {
796
                return clipboard;
797
        }
798

    
799
        public StatusPanel getStatusPanel() {
800
                return statusPanel;
801
        }
802

    
803
        public String getToken() {
804
                return token;
805
        }
806

    
807
        public static native void preventIESelection() /*-{
808
                $doc.body.onselectstart = function () { return false; };
809
        }-*/;
810

    
811
        public static native void enableIESelection() /*-{
812
                if ($doc.body.onselectstart != null)
813
                $doc.body.onselectstart = null;
814
        }-*/;
815

    
816
        /**
817
         * @return the absolute path of the API root URL
818
         */
819
        public String getApiPath() {
820
                Configuration conf = (Configuration) GWT.create(Configuration.class);
821
                return conf.apiPath();
822
        }
823

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

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

    
856
                @Override
857
                public void onError(Request request, Throwable exception) {
858
                        setError(exception);
859
                    displayError("System error unable to delete folder: " + exception.getMessage());
860
                }
861
            });
862
        }
863
        catch (RequestException e) {
864
        }
865
    }
866

    
867
    void deleteObject(final Folder folder, final int i, final JSONArray array) {
868
        if (i < array.size()) {
869
            JSONObject o = array.get(i).isObject();
870
            if (o != null && !o.containsKey("subdir")) {
871
                JSONString name = o.get("name").isString();
872
                String path = "/" + folder.getContainer() + "/" + name.stringValue();
873
                DeleteRequest delete = new DeleteRequest(getApiPath(), folder.getOwner(), URL.encode(path)) {
874
                    @Override
875
                    public void onSuccess(Resource result) {
876
                        deleteObject(folder, i + 1, array);
877
                    }
878

    
879
                    @Override
880
                    public void onError(Throwable t) {
881
                        GWT.log("", t);
882
                                                setError(t);
883
                        displayError("System error unable to delete folder: " + t.getMessage());
884
                    }
885

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

    
917
                        @Override
918
                        public void onError(Request request, Throwable exception) {
919
                                setError(exception);
920
                            displayError("System error unable to delete folder: " + exception.getMessage());
921
                        }
922
                    });
923
                }
924
                catch (RequestException e) {
925
                }
926
            }
927
        }
928
        else {
929
            String path = folder.getUri();
930
            DeleteRequest deleteFolder = new DeleteRequest(getApiPath(), getUsername(), URL.encode(path)) {
931
                @Override
932
                public void onSuccess(Resource result) {
933
                    updateFolder(folder.getParent(), true, new Command() {
934
                                                
935
                                                @Override
936
                                                public void execute() {
937
                                                        updateStatistics();
938
                                                }
939
                                        });
940
                }
941

    
942
                @Override
943
                public void onError(Throwable t) {
944
                    GWT.log("", t);
945
                                        setError(t);
946
                    if (t instanceof RestException) {
947
                            if (((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND)
948
                                    displayError("Unable to delete folder: "+((RestException) t).getHttpStatusText());
949
                            else
950
                                    onSuccess(null);
951
                    }
952
                    else
953
                        displayError("System error unable to delete folder: " + t.getMessage());
954
                }
955

    
956
                                @Override
957
                                protected void onUnauthorized(Response response) {
958
                                        sessionExpired();
959
                                }
960
            };
961
            deleteFolder.setHeader("X-Auth-Token", getToken());
962
            Scheduler.get().scheduleDeferred(deleteFolder);
963
        }
964
    }
965

    
966
    public FolderTreeView getFolderTreeView() {
967
        return folderTreeView;
968
    }
969

    
970
    public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
971
        if (iter.hasNext()) {
972
            File file = iter.next();
973
            String path = targetUri + "/" + file.getName();
974
            PutRequest copyFile = new PutRequest(getApiPath(), targetUsername, path) {
975
                @Override
976
                public void onSuccess(Resource result) {
977
                    copyFiles(iter, targetUsername, targetUri, callback);
978
                }
979

    
980
                @Override
981
                public void onError(Throwable t) {
982
                    GWT.log("", t);
983
                                        setError(t);
984
                    if (t instanceof RestException) {
985
                        displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
986
                    }
987
                    else
988
                        displayError("System error unable to copy file: "+t.getMessage());
989
                }
990

    
991
                                @Override
992
                                protected void onUnauthorized(Response response) {
993
                                        sessionExpired();
994
                                }
995
            };
996
            copyFile.setHeader("X-Auth-Token", getToken());
997
            copyFile.setHeader("X-Copy-From", URL.encodePathSegment(file.getUri()));
998
            if (!file.getOwner().equals(targetUsername))
999
                    copyFile.setHeader("X-Source-Account", URL.encodePathSegment(file.getOwner()));
1000
            copyFile.setHeader("Content-Type", file.getContentType());
1001
            Scheduler.get().scheduleDeferred(copyFile);
1002
        }
1003
        else  if (callback != null) {
1004
            callback.execute();
1005
        }
1006
    }
1007

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

    
1024
    public void copyFolder(final Folder f, final String targetUsername, final String targetUri, final Command callback) {
1025
        String path = targetUri + "/" + f.getName();
1026
        PutRequest createFolder = new PutRequest(getApiPath(), targetUsername, path) {
1027
            @Override
1028
            public void onSuccess(Resource result) {
1029
                    GetRequest<Folder> getFolder = new GetRequest<Folder>(Folder.class, getApiPath(), f.getOwner(), "/" + f.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(f.getPrefix()), f) {
1030

    
1031
                                        @Override
1032
                                        public void onSuccess(final Folder _f) {
1033
                                Iterator<File> iter = _f.getFiles().iterator();
1034
                                copyFiles(iter, targetUsername, targetUri + "/" + _f.getName(), new Command() {
1035
                                    @Override
1036
                                    public void execute() {
1037
                                        Iterator<Folder> iterf = _f.getSubfolders().iterator();
1038
                                        copySubfolders(iterf, targetUsername, targetUri + "/" + _f.getName(), callback);
1039
                                    }
1040
                                });
1041
                                        }
1042

    
1043
                                        @Override
1044
                                        public void onError(Throwable t) {
1045
                                GWT.log("", t);
1046
                                                setError(t);
1047
                                if (t instanceof RestException) {
1048
                                    displayError("Unable to get folder: " + ((RestException) t).getHttpStatusText());
1049
                                }
1050
                                else
1051
                                    displayError("System error getting folder: " + t.getMessage());
1052
                                        }
1053

    
1054
                                        @Override
1055
                                        protected void onUnauthorized(Response response) {
1056
                                                sessionExpired();
1057
                                        }
1058
                                };
1059
                                getFolder.setHeader("X-Auth-Token", getToken());
1060
                                Scheduler.get().scheduleDeferred(getFolder);
1061
            }
1062

    
1063
            @Override
1064
            public void onError(Throwable t) {
1065
                GWT.log("", t);
1066
                                setError(t);
1067
               if (t instanceof RestException) {
1068
                    displayError("Unable to create folder: " + ((RestException) t).getHttpStatusText());
1069
                }
1070
                else
1071
                    displayError("System error creating folder: " + t.getMessage());
1072
            }
1073

    
1074
                        @Override
1075
                        protected void onUnauthorized(Response response) {
1076
                                sessionExpired();
1077
                        }
1078
        };
1079
        createFolder.setHeader("X-Auth-Token", getToken());
1080
        createFolder.setHeader("Accept", "*/*");
1081
        createFolder.setHeader("Content-Length", "0");
1082
        createFolder.setHeader("Content-Type", "application/folder");
1083
        Scheduler.get().scheduleDeferred(createFolder);
1084
    }
1085
    
1086
    public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1087
            selectionModels.add(model);
1088
    }
1089

    
1090
        public OtherSharedTreeView getOtherSharedTreeView() {
1091
                return otherSharedTreeView;
1092
        }
1093

    
1094
        public void updateTrash(boolean showFiles, Command callback) {
1095
                updateFolder(trash, showFiles, callback);
1096
        }
1097

    
1098
        public void updateGroupsNode() {
1099
                groupTreeView.updateGroupNode(null);
1100
        }
1101

    
1102
        public void addGroup(String groupname) {
1103
                Group newGroup = new Group(groupname);
1104
                account.addGroup(newGroup);
1105
                groupTreeView.updateGroupNode(null);
1106
        }
1107

    
1108
        public void removeGroup(Group group) {
1109
                account.removeGroup(group);
1110
                updateGroupsNode();
1111
        }
1112

    
1113
        public TreeView getSelectedTree() {
1114
                return selectedTree;
1115
        }
1116
        
1117
        public Folder getSelection() {
1118
                return selectedTree.getSelection();
1119
        }
1120

    
1121
        public void showFolderStatistics(int folderFileCount) {
1122
                numOfFiles.setHTML(String.valueOf(folderFileCount));
1123
        }
1124

    
1125
        public GroupTreeView getGroupTreeView() {
1126
                return groupTreeView;
1127
        }
1128

    
1129
        public void sessionExpired() {
1130
                new SessionExpiredDialog(this).center();
1131
        }
1132

    
1133
        public void updateRootFolder(Command callback) {
1134
                updateFolder(account.getPithos(), false, callback);
1135
        }
1136

    
1137
        void createMySharedTree() {
1138
                mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1139
                mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1140
                    @Override
1141
                    public void onSelectionChange(SelectionChangeEvent event) {
1142
                        if (mysharedTreeSelectionModel.getSelectedObject() != null) {
1143
                            deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1144
                            upload.setEnabled(false);
1145
                            updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1146
                        }
1147
                        showRelevantToolbarButtons();
1148
                     }
1149
                });
1150
                selectionModels.add(mysharedTreeSelectionModel);
1151
                mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1152
                mysharedTreeViewModel.initialize(new Command() {
1153
                        
1154
                        @Override
1155
                        public void execute() {
1156
                            mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1157
                                trees.insert(mysharedTreeView, 2);
1158
                                treeViews.add(mysharedTreeView);
1159
                                createOtherSharedTree();
1160
                        }
1161
                });
1162
        }
1163

    
1164
        void createOtherSharedTree() {
1165
                otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1166
                otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1167
                    @Override
1168
                    public void onSelectionChange(SelectionChangeEvent event) {
1169
                        if (otherSharedTreeSelectionModel.getSelectedObject() != null) {
1170
                            deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1171
                            otherSharedTreeView.addStyleName("cellTreeWidget-selectedTree");
1172
                            applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1173
                            updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true);
1174
                        }
1175
                        showRelevantToolbarButtons();
1176
                     }
1177
                });
1178
                selectionModels.add(otherSharedTreeSelectionModel);
1179
                otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1180
                otherSharedTreeViewModel.initialize(new Command() {
1181
                        
1182
                        @Override
1183
                        public void execute() {
1184
                            otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel);
1185
                                trees.insert(otherSharedTreeView, 3);
1186
                                treeViews.add(otherSharedTreeView);
1187
                        }
1188
                });
1189
        }
1190

    
1191
        public void logoff() {
1192
                Cookies.removeCookie(config.authCookie(), "/");
1193
                Cookies.removeCookie(config.authTokenCookie(), "/");
1194
                for (String s: Cookies.getCookieNames())
1195
                        if (s.startsWith(config.shibSessionCookiePrefix()))
1196
                                Cookies.removeCookie(s, "/");
1197
                Window.Location.assign(config.logoutUrl());
1198
        }
1199
        
1200
        public native void log1(String message)/*-{
1201
                $wnd.console.log(message);
1202
        }-*/;
1203

    
1204
        public String getErrorData() {
1205
                if (error != null)
1206
                        return error.toString();
1207
                return "";
1208
        }
1209
        
1210
        public void setError(Throwable t) {
1211
                error = t;
1212
        }
1213
        
1214
        public void showRelevantToolbarButtons() {
1215
                toolbar.showRelevantButtons();
1216
        }
1217

    
1218
        public FileUploadDialog getFileUploadDialog() {
1219
                if (fileUploadDialog == null)
1220
                        fileUploadDialog = new FileUploadDialog(this);
1221
                return fileUploadDialog;
1222
        }
1223

    
1224
        public void hideUploadIndicator() {
1225
                upload.removeStyleName("pithos-uploadButton-loading");
1226
                upload.setTitle("");
1227
        }
1228
        
1229
        public void showUploadIndicator() {
1230
                upload.addStyleName("pithos-uploadButton-loading");
1231
                upload.setTitle("Upload in progress. Click for details.");
1232
        }
1233
}