Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (41.7 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
        Window.Location.assign("/im/login");
587
        }
588

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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