Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (41.8 kB)

1
/*
2
 * Copyright 2011 GRNET S.A. All rights reserved.
3
 *
4
 * Redistribution and use in source and binary forms, with or
5
 * without modification, are permitted provided that the following
6
 * conditions are met:
7
 *
8
 *   1. Redistributions of source code must retain the above
9
 *      copyright notice, this list of conditions and the following
10
 *      disclaimer.
11
 *
12
 *   2. Redistributions in binary form must reproduce the above
13
 *      copyright notice, this list of conditions and the following
14
 *      disclaimer in the documentation and/or other materials
15
 *      provided with the distribution.
16
 *
17
 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
18
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
21
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
24
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28
 * POSSIBILITY OF SUCH DAMAGE.
29
 *
30
 * The views and conclusions contained in the software and
31
 * documentation are those of the authors and should not be
32
 * interpreted as representing official policies, either expressed
33
 * or implied, of GRNET S.A.
34
 */
35
package gr.grnet.pithos.web.client;
36

    
37
import 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
        /**
115
         * Instantiate an application-level image bundle. This object will provide
116
         * programmatic access to all the images needed by widgets.
117
         */
118
        static Images images = (Images) GWT.create(Images.class);
119

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

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

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

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

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

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

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

    
162
    public MysharedTreeView getMySharedTreeView() {
163
        return mysharedTreeView;
164
    }
165

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

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

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

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

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

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

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

    
202
        /**
203
         * The file list widget.
204
         */
205
        private FileList fileList;
206

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

    
212

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

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

    
224
        public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
225

    
226
    private String username = null;
227

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

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

    
239
    SingleSelectionModel<Folder> mysharedTreeSelectionModel;
240
    MysharedTreeViewModel mysharedTreeViewModel;
241
    MysharedTreeView mysharedTreeView = null;;
242

    
243
    protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
244
    OtherSharedTreeViewModel otherSharedTreeViewModel;
245
    OtherSharedTreeView otherSharedTreeView = null;
246

    
247
    GroupTreeViewModel groupTreeViewModel;
248
    private GroupTreeView groupTreeView;
249

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

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

    
277
    private void initialize() {
278
            boolean bareContent = Window.Location.getParameter("noframe") != null;
279
            String contentWidth = bareContent ? "100%" : "75%";
280

    
281
            VerticalPanel outer = new VerticalPanel();
282
        outer.setWidth("100%");
283
            if (!bareContent) {
284
                    outer.addStyleName("pithos-outer");
285
            }
286

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

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

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

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

    
360
        folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
361
        folderTreeView = new FolderTreeView(folderTreeViewModel);
362
        treeViews.add(folderTreeView);
363
        
364
        fileList = new FileList(this, images, folderTreeView);
365
        inner.add(fileList);
366

    
367
        groupTreeViewModel = new GroupTreeViewModel(this);
368
        groupTreeView = new GroupTreeView(groupTreeViewModel);
369
        treeViews.add(groupTreeView);
370
        
371
        trees = new VerticalPanel();
372
        trees.setWidth("100%");
373

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

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

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

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

    
429
            @Override
430
            public void execute() {
431
                onWindowResized(Window.getClientHeight());
432
            }
433
        });
434

    
435
        Scheduler.get().scheduleDeferred(new ScheduledCommand() {
436
            @Override
437
            public void execute() {
438
                fetchAccount(new Command() {
439
                                        
440
                                        @Override
441
                                        public void execute() {
442
                                if (!account.hasHomeContainer())
443
                                    createHomeContainer(account, this);
444
                                else if (!account.hasTrashContainer())
445
                                        createTrashContainer(this);
446
                                else {
447
                                        for (Folder f : account.getContainers())
448
                                                if (f.getName().equals(Pithos.TRASH_CONTAINER)) {
449
                                                        trash = f;
450
                                                        break;
451
                                                }
452
                                    folderTreeViewModel.initialize(account, new Command() {
453
                                                                
454
                                                                @Override
455
                                                                public void execute() {
456
                                                    createMySharedTree();
457
                                                                }
458
                                                        });
459
                                    groupTreeViewModel.initialize();
460
                                    showStatistics();
461
                                }
462
                                        }
463
                                });
464
            }
465
        });
466
        
467
//        Scheduler.get().scheduleDeferred(new Command() {
468
//                        
469
//                        @Override
470
//                        public void execute() {
471
//                                displayError("lalala");
472
//                                
473
//                        }
474
//                });
475
    }
476

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

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

    
509
    public void showFiles(final Folder f) {
510
        Set<File> files = f.getFiles();
511
        showFiles(files);
512
    }
513

    
514
    public void showFiles(Set<File> files) {
515
        fileList.setFiles(new ArrayList<File>(files));
516
    }
517

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

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

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

    
550
    /**
551
         * Parse and store the user credentials to the appropriate fields.
552
         */
553
        private boolean parseUserCredentials() {
554
        username = Window.Location.getParameter("user");
555
        token = Window.Location.getParameter("token");
556
        Configuration conf = (Configuration) GWT.create(Configuration.class);
557
        if (username == null || username.length() == 0 || token == null || token.length() == 0) {
558
            String cookie = conf.authCookie();
559
            String auth = Cookies.getCookie(cookie);
560
            if (auth == null) {
561
                authenticateUser();
562
                return false;
563
            }
564
            if (auth.startsWith("\""))
565
                    auth = auth.substring(1);
566
            if (auth.endsWith("\""))
567
                    auth = auth.substring(0, auth.length() - 1);
568
                        String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
569
                        if (authSplit.length != 2) {
570
                            authenticateUser();
571
                            return false;
572
                        }
573
                        username = authSplit[0];
574
                        token = authSplit[1];
575
                        return true;
576
        }
577
        
578
                Cookies.setCookie(conf.authCookie(), username + conf.cookieSeparator() + token, null, "", "/", false);
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
                                setError(t);
605
                if (t instanceof RestException)
606
                    displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
607
                else
608
                    displayError("System error fetching user data: " + t.getMessage());
609
            }
610

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

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

    
623
                        @Override
624
                        public void onSuccess(AccountResource _result) {
625
                                showStatistics();
626
                        }
627

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

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

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

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

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

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

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

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

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

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

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

    
736
        @Override
737
        public void onResize(ResizeEvent event) {
738
                int height = event.getHeight();
739
                onWindowResized(height);
740
        }
741

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

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

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

    
769
        /**
770
         * Retrieve the fileList.
771
         *
772
         * @return the fileList
773
         */
774
        public FileList getFileList() {
775
                return fileList;
776
        }
777

    
778
        /**
779
         * Retrieve the topPanel.
780
         *
781
         * @return the topPanel
782
         */
783
        TopPanel getTopPanel() {
784
                return topPanel;
785
        }
786

    
787
        /**
788
         * Retrieve the clipboard.
789
         *
790
         * @return the clipboard
791
         */
792
        public Clipboard getClipboard() {
793
                return clipboard;
794
        }
795

    
796
        public StatusPanel getStatusPanel() {
797
                return statusPanel;
798
        }
799

    
800
        public String getToken() {
801
                return token;
802
        }
803

    
804
        public static native void preventIESelection() /*-{
805
                $doc.body.onselectstart = function () { return false; };
806
        }-*/;
807

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

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

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

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

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

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

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

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

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

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

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

    
963
    public FolderTreeView getFolderTreeView() {
964
        return folderTreeView;
965
    }
966

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

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

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

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

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

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

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

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

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

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

    
1087
        public OtherSharedTreeView getOtherSharedTreeView() {
1088
                return otherSharedTreeView;
1089
        }
1090

    
1091
        public void updateTrash(boolean showFiles, Command callback) {
1092
                updateFolder(trash, showFiles, callback);
1093
        }
1094

    
1095
        public void updateGroupsNode() {
1096
                groupTreeView.updateGroupNode(null);
1097
        }
1098

    
1099
        public void addGroup(String groupname) {
1100
                Group newGroup = new Group(groupname);
1101
                account.addGroup(newGroup);
1102
                groupTreeView.updateGroupNode(null);
1103
        }
1104

    
1105
        public void removeGroup(Group group) {
1106
                account.removeGroup(group);
1107
                updateGroupsNode();
1108
        }
1109

    
1110
        public TreeView getSelectedTree() {
1111
                return selectedTree;
1112
        }
1113
        
1114
        public Folder getSelection() {
1115
                return selectedTree.getSelection();
1116
        }
1117

    
1118
        public void showFolderStatistics(int folderFileCount) {
1119
                numOfFiles.setHTML(String.valueOf(folderFileCount));
1120
        }
1121

    
1122
        public GroupTreeView getGroupTreeView() {
1123
                return groupTreeView;
1124
        }
1125

    
1126
        public void sessionExpired() {
1127
                new SessionExpiredDialog(this).center();
1128
        }
1129

    
1130
        public void updateRootFolder(Command callback) {
1131
                updateFolder(account.getPithos(), false, callback);
1132
        }
1133

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

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

    
1188
        public void logoff() {
1189
        Configuration conf = (Configuration) GWT.create(Configuration.class);
1190
                Cookies.removeCookie(conf.authCookie(), "/");
1191
                Cookies.removeCookie(conf.authTokenCookie(), "/");
1192
                for (String s: Cookies.getCookieNames())
1193
                        if (s.startsWith(conf.shibSessionCookiePrefix()))
1194
                                Cookies.removeCookie(s, "/");
1195
                Window.Location.assign("/im/logout");
1196
        }
1197

    
1198
        public String getErrorData() {
1199
                if (error != null)
1200
                        return error.toString();
1201
                return "";
1202
        }
1203
        
1204
        public void setError(Throwable t) {
1205
                error = t;
1206
        }
1207
        
1208
        public void showRelevantToolbarButtons() {
1209
                toolbar.showRelevantButtons();
1210
        }
1211
}