Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (43.2 kB)

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

    
37
import gr.grnet.pithos.web.client.commands.UploadFileCommand;
38
import gr.grnet.pithos.web.client.foldertree.AccountResource;
39
import gr.grnet.pithos.web.client.foldertree.File;
40
import gr.grnet.pithos.web.client.foldertree.Folder;
41
import gr.grnet.pithos.web.client.foldertree.FolderTreeView;
42
import gr.grnet.pithos.web.client.foldertree.FolderTreeViewModel;
43
import gr.grnet.pithos.web.client.foldertree.Resource;
44
import gr.grnet.pithos.web.client.grouptree.Group;
45
import gr.grnet.pithos.web.client.grouptree.GroupTreeView;
46
import gr.grnet.pithos.web.client.grouptree.GroupTreeViewModel;
47
import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeView;
48
import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeViewModel;
49
import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeView;
50
import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeViewModel;
51
import gr.grnet.pithos.web.client.rest.DeleteRequest;
52
import gr.grnet.pithos.web.client.rest.GetRequest;
53
import gr.grnet.pithos.web.client.rest.HeadRequest;
54
import gr.grnet.pithos.web.client.rest.PutRequest;
55
import gr.grnet.pithos.web.client.rest.RestException;
56
import gr.grnet.pithos.web.client.tagtree.Tag;
57
import gr.grnet.pithos.web.client.tagtree.TagTreeView;
58
import gr.grnet.pithos.web.client.tagtree.TagTreeViewModel;
59

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

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

    
109
/**
110
 * Entry point classes define <code>onModuleLoad()</code>.
111
 */
112
public class Pithos implements EntryPoint, ResizeHandler {
113

    
114
        public static final String HOME_CONTAINER = "pithos";
115

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

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

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

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

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

    
140
    public void updateGroupNode(Group group) {
141
        groupTreeView.updateGroupNode(group);
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
        /**
181
         * The Application Clipboard implementation;
182
         */
183
        private Clipboard clipboard = new Clipboard();
184

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

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

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

    
200
        /**
201
         * The file list widget.
202
         */
203
        private FileList fileList;
204

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

    
210

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

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

    
222
        public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
223

    
224
    private String username = null;
225

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

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

    
237
    SingleSelectionModel<Folder> mysharedTreeSelectionModel;
238
    MysharedTreeViewModel mysharedTreeViewModel;
239
    MysharedTreeView mysharedTreeView = null;;
240

    
241
    protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
242
    OtherSharedTreeViewModel otherSharedTreeViewModel;
243
    OtherSharedTreeView otherSharedTreeView = null;
244

    
245
    GroupTreeViewModel groupTreeViewModel;
246
    private GroupTreeView groupTreeView;
247

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

    
255
    @SuppressWarnings("rawtypes") List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
256
    
257
    Button upload;
258
    
259
    private HTML usedBytes;
260
    
261
    private HTML totalBytes;
262
    
263
    private HTML usedPercent;
264
    
265
    private HTML numOfFiles;
266
    
267
    private Image refreshButton;
268

    
269
    private Image toolsButton;
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
        HorizontalPanel header = new HorizontalPanel();
295
        header.addStyleName("pithos-header");
296
        header.setWidth(contentWidth);
297
        if (bareContent)
298
                header.addStyleName("pithos-header-noframe");
299
        upload = new Button("Upload File", new ClickHandler() {
300
            @Override
301
            public void onClick(@SuppressWarnings("unused") ClickEvent event) {
302
                new UploadFileCommand(Pithos.this, null, getSelection()).execute();
303
            }
304
        });
305
        upload.addStyleName("pithos-uploadButton");
306
        header.add(upload);
307
        header.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_LEFT);
308
        header.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
309
//        header.setCellWidth(upload, "146px");
310

    
311
        messagePanel.setVisible(false);
312
        header.add(messagePanel);
313
        header.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
314
        header.setCellVerticalAlignment(messagePanel, HasVerticalAlignment.ALIGN_MIDDLE);
315
        
316
        refreshButton = new Image(images.refresh());
317
        refreshButton.addStyleName("pithos-toolsButton");
318
        refreshButton.setWidth("32px");
319
        refreshButton.setHeight("32px");
320
        refreshButton.addClickHandler(new ClickHandler() {
321
                        
322
                        @Override
323
                        public void onClick(@SuppressWarnings("unused") ClickEvent event) {
324
                            boolean isFolderTreeSelected = selectedTree.equals(getFolderTreeView());
325
                            boolean otherSharedTreeSelected = selectedTree.equals(getOtherSharedTreeView());
326
                            Folder folder = getSelectedTree().getSelection();
327
                            
328
                            if (folder != null && (isFolderTreeSelected || otherSharedTreeSelected))
329
                                    updateFolder(folder, true, null);
330
                        }
331
                });
332
        header.add(refreshButton);
333
        header.setCellHorizontalAlignment(refreshButton, HasHorizontalAlignment.ALIGN_CENTER);
334
        header.setCellVerticalAlignment(refreshButton, HasVerticalAlignment.ALIGN_MIDDLE);
335
        header.setCellWidth(refreshButton, "40px");
336

    
337
        toolsButton = new Image(images.tools());
338
        toolsButton.addStyleName("pithos-toolsButton");
339
        toolsButton.addClickHandler(new ClickHandler() {
340
                        
341
                        @Override
342
                        public void onClick(ClickEvent event) {
343
                ToolsMenu menu = new ToolsMenu(Pithos.this, images, getSelectedTree(), getSelectedTree().getSelection(), getFileList().getSelectedFiles());
344
                if (!menu.isEmpty()) {
345
                            menu.setPopupPosition(event.getClientX(), event.getClientY());
346
                            menu.show();
347
                }
348
                        }
349
                });
350
        header.add(toolsButton);
351
        header.setCellHorizontalAlignment(toolsButton, HasHorizontalAlignment.ALIGN_CENTER);
352
        header.setCellVerticalAlignment(toolsButton, HasVerticalAlignment.ALIGN_MIDDLE);
353
        header.setCellWidth(toolsButton, "40px");
354
       
355
        HorizontalPanel folderStatistics = new HorizontalPanel();
356
        folderStatistics.addStyleName("pithos-folderStatistics");
357
        numOfFiles = new HTML();
358
        folderStatistics.add(numOfFiles);
359
        folderStatistics.setCellVerticalAlignment(numOfFiles, HasVerticalAlignment.ALIGN_MIDDLE);
360
        HTML numOfFilesLabel = new HTML("&nbsp;Files");
361
        folderStatistics.add(numOfFilesLabel);
362
        folderStatistics.setCellVerticalAlignment(numOfFilesLabel, HasVerticalAlignment.ALIGN_MIDDLE);
363
        header.add(folderStatistics);
364
        header.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
365
        header.setCellVerticalAlignment(folderStatistics, HasVerticalAlignment.ALIGN_MIDDLE);
366
        header.setCellWidth(folderStatistics, "40px");
367
        outer.add(header);
368
        outer.setCellHorizontalAlignment(header, HasHorizontalAlignment.ALIGN_CENTER);
369
        // Inner contains the various lists.nner
370
        inner.sinkEvents(Event.ONCONTEXTMENU);
371
        inner.setWidth("100%");
372

    
373
        folderTreeSelectionModel = new SingleSelectionModel<Folder>();
374
        folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
375
            @Override
376
            public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
377
                if (folderTreeSelectionModel.getSelectedObject() != null) {
378
                    deselectOthers(folderTreeView, folderTreeSelectionModel);
379
                    applyPermissions(folderTreeSelectionModel.getSelectedObject());
380
                    Folder f = folderTreeSelectionModel.getSelectedObject();
381
                    showFiles(f);
382
                }
383
            }
384
        });
385
        selectionModels.add(folderTreeSelectionModel);
386

    
387
        folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
388
        folderTreeView = new FolderTreeView(folderTreeViewModel);
389
        treeViews.add(folderTreeView);
390
        
391
        fileList = new FileList(this, images, folderTreeView);
392
        inner.add(fileList);
393

    
394
        groupTreeViewModel = new GroupTreeViewModel(this);
395
        groupTreeView = new GroupTreeView(groupTreeViewModel);
396
        treeViews.add(groupTreeView);
397
        
398
        trees = new VerticalPanel();
399
        trees.setWidth("100%");
400

    
401
        
402
        HorizontalPanel treeHeader = new HorizontalPanel();
403
        treeHeader.addStyleName("pithos-treeHeader");
404
        treeHeader.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
405
        treeHeader.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
406
        HorizontalPanel statistics = new HorizontalPanel();
407
        statistics.addStyleName("pithos-statistics");
408
        statistics.add(new HTML("Used:&nbsp;"));
409
        usedBytes = new HTML();
410
        statistics.add(usedBytes);
411
        statistics.add(new HTML("&nbsp;of&nbsp;"));
412
        totalBytes = new HTML();
413
        statistics.add(totalBytes);
414
        statistics.add(new HTML("&nbsp;("));
415
        usedPercent = new HTML();
416
        statistics.add(usedPercent);
417
        statistics.add(new HTML(")"));
418
        treeHeader.add(statistics);
419
        treeHeader.setCellHorizontalAlignment(statistics, HasHorizontalAlignment.ALIGN_LEFT);
420
        trees.add(treeHeader);
421

    
422
        trees.add(folderTreeView);
423
        trees.add(groupTreeView);
424
        // Add the left and right panels to the split panel.
425
        splitPanel.setLeftWidget(trees);
426
        splitPanel.setRightWidget(inner);
427
        splitPanel.setSplitPosition("35%");
428
        splitPanel.setSize("100%", "100%");
429
        splitPanel.addStyleName("pithos-splitPanel");
430
        splitPanel.setWidth(contentWidth);
431
        outer.add(splitPanel);
432
        outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
433

    
434
        if (!bareContent) {
435
                statusPanel = new StatusPanel();
436
                statusPanel.setWidth("100%");
437
                outer.add(statusPanel);
438
                outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
439
        }
440
        else
441
                splitPanel.addStyleName("pithos-splitPanel-noframe");
442

    
443
        // Hook the window resize event, so that we can adjust the UI.
444
        Window.addResizeHandler(this);
445
        // Clear out the window's built-in margin, because we want to take
446
        // advantage of the entire client area.
447
        Window.setMargin("0px");
448
        // Finally, add the outer panel to the RootPanel, so that it will be
449
        // displayed.
450
        RootPanel.get().add(outer);
451
        // Call the window resized handler to get the initial sizes setup. Doing
452
        // this in a deferred command causes it to occur after all widgets'
453
        // sizes have been computed by the browser.
454
        Scheduler.get().scheduleDeferred(new ScheduledCommand() {
455

    
456
            @Override
457
            public void execute() {
458
                onWindowResized(Window.getClientHeight());
459
            }
460
        });
461

    
462
        Scheduler.get().scheduleDeferred(new ScheduledCommand() {
463
            @Override
464
            public void execute() {
465
                fetchAccount(new Command() {
466
                                        
467
                                        @Override
468
                                        public void execute() {
469
                                if (!account.hasHomeContainer())
470
                                    createHomeContainer(account, this);
471
                                else if (!account.hasTrashContainer())
472
                                        createTrashContainer(this);
473
                                else {
474
                                        for (Folder f : account.getContainers())
475
                                                if (f.getName().equals(Pithos.TRASH_CONTAINER)) {
476
                                                        trash = f;
477
                                                        break;
478
                                                }
479
                                    folderTreeViewModel.initialize(account, new Command() {
480
                                                                
481
                                                                @Override
482
                                                                public void execute() {
483
                                                    createMySharedTree();
484
                                                                }
485
                                                        });
486
                                    groupTreeViewModel.initialize();
487
                                    showStatistics();
488
                                }
489
                                        }
490
                                });
491
            }
492
        });
493
        
494
//        Scheduler.get().scheduleDeferred(new Command() {
495
//                        
496
//                        @Override
497
//                        public void execute() {
498
//                                displayError("lalala");
499
//                                
500
//                        }
501
//                });
502
    }
503

    
504
    public void applyPermissions(Folder f) {
505
            if (f != null) {
506
                    if (f.isInTrash())
507
                            upload.setEnabled(false);
508
                    else {
509
                            Boolean[] perms = f.getPermissions().get(username);
510
                            if (f.getOwner().equals(username) || (perms != null && perms[1] != null && perms[1])) {
511
                                    upload.setEnabled(true);
512
                            }
513
                            else
514
                                    upload.setEnabled(false);
515
                    }
516
            }
517
            else
518
                    upload.setEnabled(false);
519
        }
520

    
521
        @SuppressWarnings({ "rawtypes", "unchecked" })
522
        public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
523
            selectedTree = _selectedTree;
524
            
525
            for (Composite c : treeViews)
526
                    if (c.equals(selectedTree))
527
                            c.addStyleName("cellTreeWidget-selectedTree");
528
                    else
529
                            c.removeStyleName("cellTreeWidget-selectedTree");
530
            
531
        for (SingleSelectionModel s : selectionModels)
532
            if (!s.equals(model))
533
                s.setSelected(s.getSelectedObject(), false);
534
    }
535

    
536
    public void showFiles(Folder f) {
537
        Set<File> files = f.getFiles();
538
        showFiles(files);
539
    }
540

    
541
    public void showFiles(Set<File> files) {
542
        //Iterator<File> iter = files.iterator();
543
        //fetchFile(iter, files);
544
        fileList.setFiles(new ArrayList<File>(files));
545
    }
546

    
547
    protected void fetchFile(final Iterator<File> iter, final Set<File> files) {
548
        if (iter.hasNext()) {
549
            File file = iter.next();
550
            String path = file.getUri() + "?format=json";
551
            GetRequest<File> getFile = new GetRequest<File>(File.class, getApiPath(), username, path, file) {
552
                @Override
553
                public void onSuccess(@SuppressWarnings("unused") File _result) {
554
                    fetchFile(iter, files);
555
                }
556

    
557
                @Override
558
                public void onError(Throwable t) {
559
                    GWT.log("Error getting file", t);
560
                    if (t instanceof RestException)
561
                        displayError("Error getting file: " + ((RestException) t).getHttpStatusText());
562
                    else
563
                        displayError("System error fetching file: " + t.getMessage());
564
                }
565

    
566
                                @Override
567
                                protected void onUnauthorized(Response response) {
568
                                        sessionExpired();
569
                                }
570
            };
571
            getFile.setHeader("X-Auth-Token", "0000");
572
            Scheduler.get().scheduleDeferred(getFile);
573
        }
574
        else
575
            fileList.setFiles(new ArrayList<File>(files));
576
    }
577

    
578
    /**
579
         * Parse and store the user credentials to the appropriate fields.
580
         */
581
        private boolean parseUserCredentials() {
582
        username = Window.Location.getParameter("user");
583
        token = Window.Location.getParameter("token");
584
        Configuration conf = (Configuration) GWT.create(Configuration.class);
585
        if (username == null || username.length() == 0 || token == null || token.length() == 0) {
586
            String cookie = conf.authCookie();
587
            String auth = Cookies.getCookie(cookie);
588
            if (auth == null) {
589
                authenticateUser();
590
                return false;
591
            }
592
            if (auth.startsWith("\""))
593
                    auth = auth.substring(1);
594
            if (auth.endsWith("\""))
595
                    auth = auth.substring(0, auth.length() - 1);
596
                        String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
597
                        if (authSplit.length != 2) {
598
                            authenticateUser();
599
                            return false;
600
                        }
601
                        username = authSplit[0];
602
                        token = authSplit[1];
603
                        return true;
604
        }
605
        
606
                Cookies.setCookie(conf.authCookie(), username + conf.cookieSeparator() + token, null, "", "/", false);
607
                return true;
608
    }
609

    
610
    /**
611
         * Redirect the user to the login page for authentication.
612
         */
613
        protected void authenticateUser() {
614
                Configuration conf = (Configuration) GWT.create(Configuration.class);
615
        Window.Location.assign(conf.loginUrl() + "?next=" + Window.Location.getHref());
616
        }
617

    
618
        protected void fetchAccount(final Command callback) {
619
        String path = "?format=json";
620

    
621
        GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getApiPath(), username, path) {
622
            @Override
623
            public void onSuccess(AccountResource _result) {
624
                account = _result;
625
                if (callback != null)
626
                        callback.execute();
627
            }
628

    
629
            @Override
630
            public void onError(Throwable t) {
631
                GWT.log("Error getting account", 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
        getAccount.setHeader("X-Auth-Token", token);
644
        Scheduler.get().scheduleDeferred(getAccount);
645
    }
646

    
647
    public void updateStatistics() {
648
            HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getApiPath(), username, "", account) {
649

    
650
                        @Override
651
                        public void onSuccess(@SuppressWarnings("unused") AccountResource _result) {
652
                                showStatistics();
653
                        }
654

    
655
                        @Override
656
                        public void onError(Throwable t) {
657
                GWT.log("Error getting account", t);
658
                if (t instanceof RestException)
659
                    displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
660
                else
661
                    displayError("System error fetching user data: " + t.getMessage());
662
                        }
663

    
664
                        @Override
665
                        protected void onUnauthorized(Response response) {
666
                                sessionExpired();
667
                        }
668
                };
669
                headAccount.setHeader("X-Auth-Token", token);
670
                Scheduler.get().scheduleDeferred(headAccount);
671
        }
672

    
673
        protected void showStatistics() {
674
            usedBytes.setHTML(String.valueOf(account.getFileSizeAsString()));
675
            totalBytes.setHTML(String.valueOf(account.getQuotaAsString()));
676
            NumberFormat nf = NumberFormat.getPercentFormat();
677
            usedPercent.setHTML(nf.format(account.getUsedPercentage()));
678
        }
679

    
680
        protected void createHomeContainer(final AccountResource _account, final Command callback) {
681
        String path = "/" + Pithos.HOME_CONTAINER;
682
        PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
683
            @Override
684
            public void onSuccess(@SuppressWarnings("unused") Resource result) {
685
                    if (!_account.hasTrashContainer())
686
                            createTrashContainer(callback);
687
                    else
688
                            fetchAccount(callback);
689
            }
690

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

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

    
709
    protected void createTrashContainer(final Command callback) {
710
        String path = "/" + Pithos.TRASH_CONTAINER;
711
        PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
712
            @Override
713
            public void onSuccess(@SuppressWarnings("unused") Resource result) {
714
                           fetchAccount(callback);
715
            }
716

    
717
            @Override
718
            public void onError(Throwable t) {
719
                GWT.log("Error creating pithos", t);
720
                if (t instanceof RestException)
721
                    displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
722
                else
723
                    displayError("System error Error creating pithos: " + t.getMessage());
724
            }
725

    
726
                        @Override
727
                        protected void onUnauthorized(Response response) {
728
                                sessionExpired();
729
                        }
730
        };
731
        createPithos.setHeader("X-Auth-Token", getToken());
732
        Scheduler.get().scheduleDeferred(createPithos);
733
    }
734

    
735
    /**
736
         * Creates an HTML fragment that places an image & caption together, for use
737
         * in a group header.
738
         *
739
         * @param imageProto an image prototype for an image
740
         * @param caption the group caption
741
         * @return the header HTML fragment
742
         */
743
        private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
744
                String captionHTML = "<table class='caption' cellpadding='0' " 
745
                + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML() 
746
                + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'>&nbsp;" 
747
                + caption + "</b></td></tr></table>";
748
                return captionHTML;
749
        }
750

    
751
        protected void onWindowResized(int height) {
752
                // Adjust the split panel to take up the available room in the window.
753
                int newHeight = height - splitPanel.getAbsoluteTop();
754
                if (newHeight < 1)
755
                        newHeight = 1;
756
                splitPanel.setHeight("" + newHeight);
757
                inner.setHeight("" + newHeight);
758
        }
759

    
760
        @Override
761
        public void onResize(ResizeEvent event) {
762
                int height = event.getHeight();
763
                onWindowResized(height);
764
        }
765

    
766
        /**
767
         * Display an error message.
768
         *
769
         * @param msg the message to display
770
         */
771
        public void displayError(String msg) {
772
                messagePanel.displayError(msg);
773
        }
774

    
775
        /**
776
         * Display a warning message.
777
         *
778
         * @param msg the message to display
779
         */
780
        public void displayWarning(String msg) {
781
                messagePanel.displayWarning(msg);
782
        }
783

    
784
        /**
785
         * Display an informational message.
786
         *
787
         * @param msg the message to display
788
         */
789
        public void displayInformation(String msg) {
790
                messagePanel.displayInformation(msg);
791
        }
792

    
793
        /**
794
         * Retrieve the fileList.
795
         *
796
         * @return the fileList
797
         */
798
        public FileList getFileList() {
799
                return fileList;
800
        }
801

    
802
        /**
803
         * Retrieve the topPanel.
804
         *
805
         * @return the topPanel
806
         */
807
        TopPanel getTopPanel() {
808
                return topPanel;
809
        }
810

    
811
        /**
812
         * Retrieve the clipboard.
813
         *
814
         * @return the clipboard
815
         */
816
        public Clipboard getClipboard() {
817
                return clipboard;
818
        }
819

    
820
        public StatusPanel getStatusPanel() {
821
                return statusPanel;
822
        }
823

    
824
        public String getToken() {
825
                return token;
826
        }
827

    
828
        public static native void preventIESelection() /*-{
829
                $doc.body.onselectstart = function () { return false; };
830
        }-*/;
831

    
832
        public static native void enableIESelection() /*-{
833
                if ($doc.body.onselectstart != null)
834
                $doc.body.onselectstart = null;
835
        }-*/;
836

    
837
        /**
838
         * @return the absolute path of the API root URL
839
         */
840
        public String getApiPath() {
841
                Configuration conf = (Configuration) GWT.create(Configuration.class);
842
                return conf.apiPath();
843
        }
844

    
845
        /**
846
         * History support for folder navigation
847
         * adds a new browser history entry
848
         *
849
         * @param key
850
         */
851
        public void updateHistory(String key){
852
//                Replace any whitespace of the initial string to "+"
853
//                String result = key.replaceAll("\\s","+");
854
//                Add a new browser history entry.
855
//                History.newItem(result);
856
                History.newItem(key);
857
        }
858

    
859
    public void deleteFolder(final Folder folder) {
860
        String path = getApiPath() + folder.getOwner() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(folder.getPrefix()) + "&t=" + System.currentTimeMillis();
861
        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
862
        builder.setHeader("X-Auth-Token", getToken());
863
        try {
864
            builder.sendRequest("", new RequestCallback() {
865
                @Override
866
                public void onResponseReceived(@SuppressWarnings("unused") Request request, Response response) {
867
                    if (response.getStatusCode() == Response.SC_OK) {
868
                        JSONValue json = JSONParser.parseStrict(response.getText());
869
                        JSONArray array = json.isArray();
870
                        int i = 0;
871
                        if (array != null) {
872
                            deleteObject(folder, i, array);
873
                        }
874
                    }
875
                }
876

    
877
                @Override
878
                public void onError(@SuppressWarnings("unused") Request request, Throwable exception) {
879
                    displayError("System error unable to delete folder: " + exception.getMessage());
880
                }
881
            });
882
        }
883
        catch (RequestException e) {
884
        }
885
    }
886

    
887
    void deleteObject(final Folder folder, final int i, final JSONArray array) {
888
        if (i < array.size()) {
889
            JSONObject o = array.get(i).isObject();
890
            if (o != null && !o.containsKey("subdir")) {
891
                JSONString name = o.get("name").isString();
892
                String path = "/" + folder.getContainer() + "/" + name.stringValue();
893
                DeleteRequest delete = new DeleteRequest(getApiPath(), folder.getOwner(), path) {
894
                    @Override
895
                    public void onSuccess(@SuppressWarnings("unused") Resource result) {
896
                        deleteObject(folder, i + 1, array);
897
                    }
898

    
899
                    @Override
900
                    public void onError(Throwable t) {
901
                        GWT.log("", t);
902
                        displayError("System error unable to delete folder: " + t.getMessage());
903
                    }
904

    
905
                                    @Override
906
                                    protected void onUnauthorized(Response response) {
907
                                            sessionExpired();
908
                                    }
909
                };
910
                delete.setHeader("X-Auth-Token", getToken());
911
                Scheduler.get().scheduleDeferred(delete);
912
            }
913
            else if (o != null) {
914
                String subdir = o.get("subdir").isString().stringValue();
915
                subdir = subdir.substring(0, subdir.length() - 1);
916
                String path = getApiPath() + getUsername() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(subdir) + "&t=" + System.currentTimeMillis();
917
                RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
918
                builder.setHeader("X-Auth-Token", getToken());
919
                try {
920
                    builder.sendRequest("", new RequestCallback() {
921
                        @Override
922
                        public void onResponseReceived(@SuppressWarnings("unused") Request request, Response response) {
923
                            if (response.getStatusCode() == Response.SC_OK) {
924
                                JSONValue json = JSONParser.parseStrict(response.getText());
925
                                JSONArray array2 = json.isArray();
926
                                if (array2 != null) {
927
                                    int l = array.size();
928
                                    for (int j=0; j<array2.size(); j++) {
929
                                        array.set(l++, array2.get(j));
930
                                    }
931
                                }
932
                                deleteObject(folder, i + 1, array);
933
                            }
934
                        }
935

    
936
                        @Override
937
                        public void onError(@SuppressWarnings("unused") Request request, Throwable exception) {
938
                            displayError("System error unable to delete folder: " + exception.getMessage());
939
                        }
940
                    });
941
                }
942
                catch (RequestException e) {
943
                }
944
            }
945
        }
946
        else {
947
            String path = folder.getUri();
948
            DeleteRequest deleteFolder = new DeleteRequest(getApiPath(), getUsername(), path) {
949
                @Override
950
                public void onSuccess(@SuppressWarnings("unused") Resource result) {
951
                    updateFolder(folder.getParent(), true, new Command() {
952
                                                
953
                                                @Override
954
                                                public void execute() {
955
                                                        updateStatistics();
956
                                                }
957
                                        });
958
                }
959

    
960
                @Override
961
                public void onError(Throwable t) {
962
                    GWT.log("", t);
963
                    if (t instanceof RestException) {
964
                            if (((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND)
965
                                    displayError("Unable to delete folder: "+((RestException) t).getHttpStatusText());
966
                            else
967
                                    onSuccess(null);
968
                    }
969
                    else
970
                        displayError("System error unable to delete folder: " + t.getMessage());
971
                }
972

    
973
                                @Override
974
                                protected void onUnauthorized(Response response) {
975
                                        sessionExpired();
976
                                }
977
            };
978
            deleteFolder.setHeader("X-Auth-Token", getToken());
979
            Scheduler.get().scheduleDeferred(deleteFolder);
980
        }
981
    }
982

    
983
    public FolderTreeView getFolderTreeView() {
984
        return folderTreeView;
985
    }
986

    
987
    public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
988
        if (iter.hasNext()) {
989
            File file = iter.next();
990
            String path = targetUri + "/" + file.getName();
991
            PutRequest copyFile = new PutRequest(getApiPath(), targetUsername, path) {
992
                @Override
993
                public void onSuccess(@SuppressWarnings("unused") Resource result) {
994
                    copyFiles(iter, targetUsername, targetUri, callback);
995
                }
996

    
997
                @Override
998
                public void onError(Throwable t) {
999
                    GWT.log("", t);
1000
                    if (t instanceof RestException) {
1001
                        displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
1002
                    }
1003
                    else
1004
                        displayError("System error unable to copy file: "+t.getMessage());
1005
                }
1006

    
1007
                                @Override
1008
                                protected void onUnauthorized(Response response) {
1009
                                        sessionExpired();
1010
                                }
1011
            };
1012
            copyFile.setHeader("X-Auth-Token", getToken());
1013
            copyFile.setHeader("X-Copy-From", URL.encodePathSegment(file.getUri()));
1014
            if (!file.getOwner().equals(targetUsername))
1015
                    copyFile.setHeader("X-Source-Account", URL.encodePathSegment(file.getOwner()));
1016
            copyFile.setHeader("Content-Type", file.getContentType());
1017
            Scheduler.get().scheduleDeferred(copyFile);
1018
        }
1019
        else  if (callback != null) {
1020
            callback.execute();
1021
        }
1022
    }
1023

    
1024
    public void copySubfolders(final Iterator<Folder> iter, final String targetUsername, final String targetUri, final Command callback) {
1025
        if (iter.hasNext()) {
1026
            final Folder f = iter.next();
1027
            copyFolder(f, targetUsername, targetUri, new Command() {
1028
                                
1029
                                @Override
1030
                                public void execute() {
1031
                                        copySubfolders(iter, targetUsername, targetUri, callback);
1032
                                }
1033
                        });
1034
        }
1035
        else  if (callback != null) {
1036
            callback.execute();
1037
        }
1038
    }
1039

    
1040
    public void copyFolder(final Folder f, final String targetUsername, final String targetUri, final Command callback) {
1041
        String path = targetUri + "/" + f.getName();
1042
        PutRequest createFolder = new PutRequest(getApiPath(), targetUsername, path) {
1043
            @Override
1044
            public void onSuccess(@SuppressWarnings("unused") Resource result) {
1045
                    GetRequest<Folder> getFolder = new GetRequest<Folder>(Folder.class, getApiPath(), f.getOwner(), "/" + f.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(f.getPrefix()), f) {
1046

    
1047
                                        @Override
1048
                                        public void onSuccess(final Folder _f) {
1049
                                Iterator<File> iter = _f.getFiles().iterator();
1050
                                copyFiles(iter, targetUsername, targetUri + "/" + _f.getName(), new Command() {
1051
                                    @Override
1052
                                    public void execute() {
1053
                                        Iterator<Folder> iterf = _f.getSubfolders().iterator();
1054
                                        copySubfolders(iterf, targetUsername, targetUri + "/" + _f.getName(), callback);
1055
                                    }
1056
                                });
1057
                                        }
1058

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

    
1069
                                        @Override
1070
                                        protected void onUnauthorized(Response response) {
1071
                                                sessionExpired();
1072
                                        }
1073
                                };
1074
                                getFolder.setHeader("X-Auth-Token", getToken());
1075
                                Scheduler.get().scheduleDeferred(getFolder);
1076
            }
1077

    
1078
            @Override
1079
            public void onError(Throwable t) {
1080
                GWT.log("", t);
1081
                if (t instanceof RestException) {
1082
                    displayError("Unable to create folder: " + ((RestException) t).getHttpStatusText());
1083
                }
1084
                else
1085
                    displayError("System error creating folder: " + t.getMessage());
1086
            }
1087

    
1088
                        @Override
1089
                        protected void onUnauthorized(Response response) {
1090
                                sessionExpired();
1091
                        }
1092
        };
1093
        createFolder.setHeader("X-Auth-Token", getToken());
1094
        createFolder.setHeader("Accept", "*/*");
1095
        createFolder.setHeader("Content-Length", "0");
1096
        createFolder.setHeader("Content-Type", "application/folder");
1097
        Scheduler.get().scheduleDeferred(createFolder);
1098
    }
1099
    
1100
    public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1101
            selectionModels.add(model);
1102
    }
1103

    
1104
        public OtherSharedTreeView getOtherSharedTreeView() {
1105
                return otherSharedTreeView;
1106
        }
1107

    
1108
        public void updateTrash(boolean showFiles, Command callback) {
1109
                updateFolder(trash, showFiles, callback);
1110
        }
1111

    
1112
        public void updateGroupsNode() {
1113
                groupTreeView.updateGroupNode(null);
1114
        }
1115

    
1116
        public void addGroup(String groupname) {
1117
                Group newGroup = new Group(groupname);
1118
                account.addGroup(newGroup);
1119
                groupTreeView.updateGroupNode(null);
1120
        }
1121

    
1122
        public void removeGroup(Group group) {
1123
                account.removeGroup(group);
1124
                updateGroupsNode();
1125
        }
1126

    
1127
        public TreeView getSelectedTree() {
1128
                return selectedTree;
1129
        }
1130
        
1131
        public Folder getSelection() {
1132
                return selectedTree.getSelection();
1133
        }
1134

    
1135
        public void showFolderStatistics(int folderFileCount) {
1136
                numOfFiles.setHTML(String.valueOf(folderFileCount));
1137
        }
1138

    
1139
        public GroupTreeView getGroupTreeView() {
1140
                return groupTreeView;
1141
        }
1142

    
1143
        public void sessionExpired() {
1144
                new SessionExpiredDialog(this).center();
1145
        }
1146

    
1147
        public void updateRootFolder(Command callback) {
1148
                updateFolder(account.getPithos(), false, callback);
1149
        }
1150

    
1151
        void createMySharedTree() {
1152
                mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1153
                mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1154
                    @Override
1155
                    public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
1156
                        if (mysharedTreeSelectionModel.getSelectedObject() != null) {
1157
                            deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1158
                            upload.setEnabled(false);
1159
                            updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1160
                        }
1161
                     }
1162
                });
1163
                selectionModels.add(mysharedTreeSelectionModel);
1164
                mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1165
                mysharedTreeViewModel.initialize(new Command() {
1166
                        
1167
                        @Override
1168
                        public void execute() {
1169
                            mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1170
                                trees.insert(mysharedTreeView, 2);
1171
                                treeViews.add(mysharedTreeView);
1172
                                createOtherSharedTree();
1173
                        }
1174
                });
1175
        }
1176

    
1177
        void createOtherSharedTree() {
1178
                otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1179
                otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1180
                    @Override
1181
                    public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
1182
                        if (otherSharedTreeSelectionModel.getSelectedObject() != null) {
1183
                            deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1184
                            otherSharedTreeView.addStyleName("cellTreeWidget-selectedTree");
1185
                            applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1186
                            updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true);
1187
                        }
1188
                     }
1189
                });
1190
                selectionModels.add(otherSharedTreeSelectionModel);
1191
                otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1192
                otherSharedTreeViewModel.initialize(new Command() {
1193
                        
1194
                        @Override
1195
                        public void execute() {
1196
                            otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel);
1197
                                trees.insert(otherSharedTreeView, 3);
1198
                                treeViews.add(otherSharedTreeView);
1199
                        }
1200
                });
1201
        }
1202

    
1203
        public void logoff() {
1204
        Configuration conf = (Configuration) GWT.create(Configuration.class);
1205
                Cookies.removeCookie(conf.authCookie(), "/");
1206
                Cookies.removeCookie(conf.authTokenCookie(), "/");
1207
                for (String s: Cookies.getCookieNames())
1208
                        if (s.startsWith(conf.shibSessionCookiePrefix()))
1209
                                Cookies.removeCookie(s, "/");
1210
                Window.Location.assign(Window.Location.getPath());
1211
        }
1212
}