Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (54.8 kB)

1
/*
2
 * Copyright 2011-2013 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 com.google.gwt.core.client.EntryPoint;
38
import com.google.gwt.core.client.GWT;
39
import com.google.gwt.core.client.JsArrayString;
40
import com.google.gwt.core.client.Scheduler;
41
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
42
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
43
import com.google.gwt.event.dom.client.ClickEvent;
44
import com.google.gwt.event.dom.client.ClickHandler;
45
import com.google.gwt.event.logical.shared.ResizeEvent;
46
import com.google.gwt.event.logical.shared.ResizeHandler;
47
import com.google.gwt.http.client.Response;
48
import com.google.gwt.http.client.URL;
49
import com.google.gwt.i18n.client.DateTimeFormat;
50
import com.google.gwt.i18n.client.Dictionary;
51
import com.google.gwt.i18n.client.TimeZone;
52
import com.google.gwt.resources.client.ClientBundle;
53
import com.google.gwt.resources.client.CssResource;
54
import com.google.gwt.resources.client.ImageResource;
55
import com.google.gwt.resources.client.ImageResource.ImageOptions;
56
import com.google.gwt.user.client.*;
57
import com.google.gwt.user.client.ui.*;
58
import com.google.gwt.view.client.SelectionChangeEvent;
59
import com.google.gwt.view.client.SelectionChangeEvent.Handler;
60
import com.google.gwt.view.client.SingleSelectionModel;
61
import gr.grnet.pithos.web.client.catalog.UpdateUserCatalogs;
62
import gr.grnet.pithos.web.client.catalog.UserCatalogs;
63
import gr.grnet.pithos.web.client.commands.UploadFileCommand;
64
import gr.grnet.pithos.web.client.foldertree.*;
65
import gr.grnet.pithos.web.client.grouptree.Group;
66
import gr.grnet.pithos.web.client.grouptree.GroupTreeView;
67
import gr.grnet.pithos.web.client.grouptree.GroupTreeViewModel;
68
import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeView;
69
import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeViewModel;
70
import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeView;
71
import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeViewModel;
72
import gr.grnet.pithos.web.client.rest.*;
73
import org.apache.http.HttpStatus;
74

    
75
import java.util.*;
76

    
77
/**
78
 * Entry point classes define <code>onModuleLoad()</code>.
79
 */
80
public class Pithos implements EntryPoint, ResizeHandler {
81

    
82
    public static final Configuration config = GWT.create(Configuration.class);
83

    
84
    public interface Style extends CssResource {
85
        String commandAnchor();
86

    
87
        String statistics();
88

    
89
        @ClassName("gwt-HTML")
90
        String html();
91

    
92
        String uploadAlert();
93

    
94
        String uploadAlertLink();
95

    
96
        String uploadAlertProgress();
97

    
98
        String uploadAlertPercent();
99

    
100
        String uploadAlertClose();
101
    }
102

    
103
    public interface Resources extends ClientBundle {
104
        @Source("Pithos.css")
105
        Style pithosCss();
106

    
107
        @Source("gr/grnet/pithos/resources/close-popup.png")
108
        ImageResource closePopup();
109
    }
110

    
111
    public static Resources resources = GWT.create(Resources.class);
112

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

    
119
    public String getUserID() {
120
        return userID;
121
    }
122

    
123
    public UserCatalogs getUserCatalogs() {
124
        return userCatalogs;
125
    }
126

    
127
    public String getCurrentUserDisplayNameOrID() {
128
        final String displayName = userCatalogs.getDisplayName(getUserID());
129
        return displayName == null ? getUserID() : displayName;
130
    }
131

    
132
    public boolean hasDisplayNameForUserID(String userID) {
133
        return userCatalogs.getDisplayName(userID) != null;
134
    }
135

    
136
    public boolean hasIDForUserDisplayName(String userDisplayName) {
137
        return userCatalogs.getID(userDisplayName) != null;
138
    }
139

    
140
    public String getDisplayNameForUserID(String userID) {
141
        return userCatalogs.getDisplayName(userID);
142
    }
143

    
144
    public String getIDForUserDisplayName(String userDisplayName) {
145
        return userCatalogs.getID(userDisplayName);
146
    }
147

    
148
    public List<String> getDisplayNamesForUserIDs(List<String> userIDs) {
149
        if(userIDs == null) {
150
            userIDs = new ArrayList<String>();
151
        }
152
        final List<String> userDisplayNames = new ArrayList<String>();
153
        for(String userID : userIDs) {
154
            final String displayName = getDisplayNameForUserID(userID);
155
            userDisplayNames.add(displayName);
156
        }
157

    
158
        return userDisplayNames;
159
    }
160

    
161
    public List<String> filterUserIDsWithUnknownDisplayName(Collection<String> userIDs) {
162
        if(userIDs == null) {
163
            userIDs = new ArrayList<String>();
164
        }
165
        final List<String> filtered = new ArrayList<String>();
166
        for(String userID : userIDs) {
167
            if(!this.userCatalogs.hasID(userID)) {
168
                filtered.add(userID);
169
            }
170
        }
171
        return filtered;
172
    }
173

    
174
    public void setAccount(AccountResource acct) {
175
        account = acct;
176
    }
177

    
178
    public AccountResource getAccount() {
179
        return account;
180
    }
181

    
182
    public void updateFolder(Folder f, boolean showfiles, Command callback, final boolean openParent) {
183
        folderTreeView.updateFolder(f, showfiles, callback, openParent);
184
    }
185

    
186
    public void updateGroupNode(Group group) {
187
        groupTreeView.updateGroupNode(group);
188
    }
189

    
190
    public void updateMySharedRoot() {
191
        mysharedTreeView.updateRoot();
192
    }
193

    
194
    public void updateSharedFolder(Folder f, boolean showfiles, Command callback) {
195
        mysharedTreeView.updateFolder(f, showfiles, callback);
196
    }
197

    
198
    public void updateSharedFolder(Folder f, boolean showfiles) {
199
        updateSharedFolder(f, showfiles, null);
200
    }
201

    
202
    public void updateOtherSharedFolder(Folder f, boolean showfiles, Command callback) {
203
        otherSharedTreeView.updateFolder(f, showfiles, callback);
204
    }
205

    
206
    public MysharedTreeView getMySharedTreeView() {
207
        return mysharedTreeView;
208
    }
209

    
210
    /**
211
     * An aggregate image bundle that pulls together all the images for this
212
     * application into a single bundle.
213
     */
214
    public interface Images extends TopPanel.Images, FileList.Images, ToolsMenu.Images {
215

    
216
        @Source("gr/grnet/pithos/resources/document.png")
217
        ImageResource folders();
218

    
219
        @Source("gr/grnet/pithos/resources/advancedsettings.png")
220
        @ImageOptions(width = 32, height = 32)
221
        ImageResource tools();
222
    }
223

    
224
    private Throwable error;
225

    
226
    /**
227
     * The Application Clipboard implementation;
228
     */
229
    private Clipboard clipboard = new Clipboard();
230

    
231
    /**
232
     * The top panel that contains the menu bar.
233
     */
234
    private TopPanel topPanel;
235

    
236
    /**
237
     * The panel that contains the various system messages.
238
     */
239
    private MessagePanel messagePanel = new MessagePanel(this, Pithos.images);
240

    
241
    /**
242
     * The bottom panel that contains the status bar.
243
     */
244
    StatusPanel statusPanel = null;
245

    
246
    /**
247
     * The file list widget.
248
     */
249
    private FileList fileList;
250

    
251
    /**
252
     * The tab panel that occupies the right side of the screen.
253
     */
254
    private VerticalPanel inner = new VerticalPanel();
255

    
256

    
257
    /**
258
     * The split panel that will contain the left and right panels.
259
     */
260
    private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
261

    
262
    /**
263
     * The currently selected item in the application, for use by the Edit menu
264
     * commands. Potential types are Folder, File, User and Group.
265
     */
266
    private Object currentSelection;
267

    
268
    public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
269

    
270
    /**
271
     * The ID that uniquely identifies the user in Pithos+.
272
     * Currently this is a UUID. It used to be the user's email.
273
     */
274
    private String userID = null;
275

    
276
    /**
277
     * Hold mappings from user UUIDs to emails and vice-versa.
278
     */
279
    private UserCatalogs userCatalogs = new UserCatalogs();
280

    
281
    /**
282
     * The authentication token of the current user.
283
     */
284
    private String userToken;
285

    
286
    VerticalPanel trees;
287

    
288
    SingleSelectionModel<Folder> folderTreeSelectionModel;
289
    FolderTreeViewModel folderTreeViewModel;
290
    FolderTreeView folderTreeView;
291

    
292
    SingleSelectionModel<Folder> mysharedTreeSelectionModel;
293
    MysharedTreeViewModel mysharedTreeViewModel;
294
    MysharedTreeView mysharedTreeView = null;
295

    
296
    protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
297
    OtherSharedTreeViewModel otherSharedTreeViewModel;
298
    OtherSharedTreeView otherSharedTreeView = null;
299

    
300
    GroupTreeViewModel groupTreeViewModel;
301
    GroupTreeView groupTreeView;
302

    
303
    TreeView selectedTree;
304
    protected AccountResource account;
305

    
306
    Folder trash;
307

    
308
    List<Composite> treeViews = new ArrayList<Composite>();
309

    
310
    @SuppressWarnings("rawtypes")
311
    List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
312

    
313
    public Button upload;
314

    
315
    private HTML numOfFiles;
316

    
317
    private Toolbar toolbar;
318

    
319
    private FileUploadDialog fileUploadDialog = new FileUploadDialog(this);
320

    
321
    UploadAlert uploadAlert;
322

    
323
    Date lastModified;
324

    
325
    @Override
326
    public void onModuleLoad() {
327
        if(parseUserCredentials()) {
328
            initialize();
329
        }
330
    }
331

    
332
    static native void __ConsoleLog(String message) /*-{
333
      try {
334
        console.log(message);
335
      } catch (e) {
336
      }
337
    }-*/;
338

    
339
    public static void LOG(Object ...args) {
340
        if(false) {
341
            final StringBuilder sb = new StringBuilder();
342
            for(Object arg : args) {
343
                sb.append(arg);
344
                if(arg instanceof Throwable) {
345
                    sb.append("\nCauses (including original):\n");
346
                    final Throwable error = (Throwable) arg;
347
                    Throwable cause = error;
348
                    while(cause != null) {
349
                        sb.append("  ");
350
                        sb.append(cause.toString());
351
                        sb.append("\n");
352
                        cause = cause.getCause();
353
                    }
354

    
355
                    sb.append("Stack trace of original: ");
356
                    sb.append(error.toString());
357
                    sb.append("\n");
358
                    StackTraceElement[] stackTrace = error.getStackTrace();
359
                    for(StackTraceElement errorElem : stackTrace) {
360
                        sb.append("  ");
361
                        sb.append(errorElem.toString());
362
                        sb.append("\n");
363
                    }
364
                }
365
            }
366

    
367

    
368
            if(sb.length() > 0) {
369
                __ConsoleLog(sb.toString());
370
            }
371
        }
372
    }
373

    
374
    private void initialize() {
375
        lastModified = new Date(); //Initialize if-modified-since value with now.
376
        resources.pithosCss().ensureInjected();
377
        boolean bareContent = Window.Location.getParameter("noframe") != null;
378
        String contentWidth = bareContent ? Const.PERCENT_100 : "75%";
379

    
380
        VerticalPanel outer = new VerticalPanel();
381
        outer.setWidth(Const.PERCENT_100);
382
        if(!bareContent) {
383
            outer.addStyleName("pithos-outer");
384
        }
385

    
386
        if(!bareContent) {
387
            topPanel = new TopPanel(this, Pithos.images);
388
            topPanel.setWidth(Const.PERCENT_100);
389
            outer.add(topPanel);
390
            outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
391
        }
392

    
393
        messagePanel.setVisible(false);
394
        outer.add(messagePanel);
395
        outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
396
        outer.setCellVerticalAlignment(messagePanel, HasVerticalAlignment.ALIGN_MIDDLE);
397

    
398
        HorizontalPanel header = new HorizontalPanel();
399
        header.addStyleName("pithos-header");
400
        header.setWidth(contentWidth);
401
        if(bareContent) {
402
            header.addStyleName("pithos-header-noframe");
403
        }
404
        upload = new Button("Upload", new ClickHandler() {
405
            @Override
406
            public void onClick(ClickEvent event) {
407
                if(getSelection() != null) {
408
                    new UploadFileCommand(Pithos.this, null, getSelection()).execute();
409
                }
410
            }
411
        });
412
        upload.addStyleName("pithos-uploadButton");
413
        header.add(upload);
414
        header.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_LEFT);
415
        header.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
416

    
417
        toolbar = new Toolbar(this);
418
        header.add(toolbar);
419
        header.setCellHorizontalAlignment(toolbar, HasHorizontalAlignment.ALIGN_CENTER);
420
        header.setCellVerticalAlignment(toolbar, HasVerticalAlignment.ALIGN_MIDDLE);
421

    
422
        HorizontalPanel folderStatistics = new HorizontalPanel();
423
        folderStatistics.addStyleName("pithos-folderStatistics");
424
        numOfFiles = new HTML();
425
        folderStatistics.add(numOfFiles);
426
        folderStatistics.setCellVerticalAlignment(numOfFiles, HasVerticalAlignment.ALIGN_MIDDLE);
427
        HTML numOfFilesLabel = new HTML("&nbsp;Files");
428
        folderStatistics.add(numOfFilesLabel);
429
        folderStatistics.setCellVerticalAlignment(numOfFilesLabel, HasVerticalAlignment.ALIGN_MIDDLE);
430
        header.add(folderStatistics);
431
        header.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
432
        header.setCellVerticalAlignment(folderStatistics, HasVerticalAlignment.ALIGN_MIDDLE);
433
        header.setCellWidth(folderStatistics, "40px");
434
        outer.add(header);
435
        outer.setCellHorizontalAlignment(header, HasHorizontalAlignment.ALIGN_CENTER);
436
        // Inner contains the various lists
437
        inner.sinkEvents(Event.ONCONTEXTMENU);
438
        inner.setWidth(Const.PERCENT_100);
439

    
440
        folderTreeSelectionModel = new SingleSelectionModel<Folder>();
441
        folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
442
            @Override
443
            public void onSelectionChange(SelectionChangeEvent event) {
444
                if(folderTreeSelectionModel.getSelectedObject() != null) {
445
                    deselectOthers(folderTreeView, folderTreeSelectionModel);
446
                    applyPermissions(folderTreeSelectionModel.getSelectedObject());
447
                    Folder f = folderTreeSelectionModel.getSelectedObject();
448
                    updateFolder(f, true, new Command() {
449

    
450
                        @Override
451
                        public void execute() {
452
                            updateStatistics();
453
                        }
454
                    }, true);
455
                    showRelevantToolbarButtons();
456
                }
457
                else {
458
                    if(getSelectedTree().equals(folderTreeView)) {
459
                        setSelectedTree(null);
460
                    }
461
                    if(getSelectedTree() == null) {
462
                        showRelevantToolbarButtons();
463
                    }
464
                }
465
            }
466
        });
467
        selectionModels.add(folderTreeSelectionModel);
468

    
469
        folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
470
        folderTreeView = new FolderTreeView(folderTreeViewModel);
471
        treeViews.add(folderTreeView);
472

    
473
        fileList = new FileList(this, images);
474
        inner.add(fileList);
475

    
476
        trees = new VerticalPanel();
477
        trees.setWidth(Const.PERCENT_100);
478

    
479
        // Add the left and right panels to the split panel.
480
        splitPanel.setLeftWidget(trees);
481
        FlowPanel right = new FlowPanel();
482
        right.getElement().setId("rightPanel");
483
        right.add(inner);
484
        splitPanel.setRightWidget(right);
485
        splitPanel.setSplitPosition("219px");
486
        splitPanel.setSize(Const.PERCENT_100, Const.PERCENT_100);
487
        splitPanel.addStyleName("pithos-splitPanel");
488
        splitPanel.setWidth(contentWidth);
489
        outer.add(splitPanel);
490
        outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
491

    
492
        if(!bareContent) {
493
            statusPanel = new StatusPanel();
494
            statusPanel.setWidth(Const.PERCENT_100);
495
            outer.add(statusPanel);
496
            outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
497
        }
498
        else {
499
            splitPanel.addStyleName("pithos-splitPanel-noframe");
500
        }
501

    
502
        // Hook the window resize event, so that we can adjust the UI.
503
        Window.addResizeHandler(this);
504
        // Clear out the window's built-in margin, because we want to take
505
        // advantage of the entire client area.
506
        Window.setMargin("0px");
507
        // Finally, add the outer panel to the RootPanel, so that it will be
508
        // displayed.
509
        RootPanel.get().add(outer);
510
        // Call the window resized handler to get the initial sizes setup. Doing
511
        // this in a deferred command causes it to occur after all widgets'
512
        // sizes have been computed by the browser.
513
        Scheduler.get().scheduleIncremental(new RepeatingCommand() {
514

    
515
            @Override
516
            public boolean execute() {
517
                if(!isCloudbarReady()) {
518
                    return true;
519
                }
520
                onWindowResized(Window.getClientHeight());
521
                return false;
522
            }
523
        });
524

    
525
        Scheduler.get().scheduleDeferred(new ScheduledCommand() {
526
            @Override
527
            public void execute() {
528
                LOG("Pithos::initialize() Calling Pithos::fetchAccount()");
529
                fetchAccount(new Command() {
530

    
531
                    @Override
532
                    public void execute() {
533
                        if(!account.hasHomeContainer()) {
534
                            createHomeContainer(account, this);
535
                        }
536
                        else if(!account.hasTrashContainer()) {
537
                            createTrashContainer(this);
538
                        }
539
                        else {
540
                            for(Folder f : account.getContainers()) {
541
                                if(f.getName().equals(Const.TRASH_CONTAINER)) {
542
                                    trash = f;
543
                                    break;
544
                                }
545
                            }
546
                            trees.add(folderTreeView);
547
                            folderTreeViewModel.initialize(account, new Command() {
548

    
549
                                @Override
550
                                public void execute() {
551
                                    createMySharedTree();
552
                                }
553
                            });
554

    
555
                            HorizontalPanel separator = new HorizontalPanel();
556
                            separator.addStyleName("pithos-statisticsSeparator");
557
                            separator.add(new HTML(""));
558
                            trees.add(separator);
559

    
560
                            groupTreeViewModel = new GroupTreeViewModel(Pithos.this);
561
                            groupTreeView = new GroupTreeView(groupTreeViewModel);
562
                            treeViews.add(groupTreeView);
563
                            trees.add(groupTreeView);
564
                            folderTreeView.showStatistics(account);
565
                        }
566
                    }
567
                });
568
            }
569
        });
570
    }
571

    
572
    public void scheduleResfresh() {
573
        Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {
574

    
575
            @Override
576
            public boolean execute() {
577
                final Folder f = getSelection();
578
                if(f == null) {
579
                    return true;
580
                }
581

    
582
                HeadRequest<Folder> head = new HeadRequest<Folder>(Folder.class, getApiPath(), f.getOwnerID(), "/" + f.getContainer()) {
583

    
584
                    @Override
585
                    public void onSuccess(Folder _result) {
586
                        lastModified = new Date();
587
                        if(getSelectedTree().equals(folderTreeView)) {
588
                            updateFolder(f, true, new Command() {
589

    
590
                                @Override
591
                                public void execute() {
592
                                    scheduleResfresh();
593
                                }
594

    
595
                            }, false);
596
                        }
597
                        else if(getSelectedTree().equals(mysharedTreeView)) {
598
                            updateSharedFolder(f, true, new Command() {
599

    
600
                                @Override
601
                                public void execute() {
602
                                    scheduleResfresh();
603
                                }
604
                            });
605
                        }
606
                        else {
607
                            scheduleResfresh();
608
                        }
609
                    }
610

    
611
                    @Override
612
                    public void onError(Throwable t) {
613
                        if(t instanceof RestException && ((RestException) t).getHttpStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
614
                            scheduleResfresh();
615
                        }
616
                        else if(retries >= MAX_RETRIES) {
617
                            GWT.log("Error heading folder", t);
618
                            setError(t);
619
                            if(t instanceof RestException) {
620
                                displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
621
                            }
622
                            else {
623
                                displayError("System error heading folder: " + t.getMessage());
624
                            }
625
                        }
626
                        else {//retry
627
                            GWT.log("Retry " + retries);
628
                            Scheduler.get().scheduleDeferred(this);
629
                        }
630
                    }
631

    
632
                    @Override
633
                    protected void onUnauthorized(Response response) {
634
                        if(retries >= MAX_RETRIES) {
635
                            sessionExpired();
636
                        }
637
                        else //retry
638
                        {
639
                            Scheduler.get().scheduleDeferred(this);
640
                        }
641
                    }
642
                };
643
                head.setHeader(Const.X_AUTH_TOKEN, getUserToken());
644
                head.setHeader(Const.IF_MODIFIED_SINCE, DateTimeFormat.getFormat(Const.DATE_FORMAT_1).format(lastModified, TimeZone.createTimeZone(0)) + " GMT");
645
                Scheduler.get().scheduleDeferred(head);
646

    
647
                return false;
648
            }
649
        }, 3000);
650
    }
651

    
652
    public void applyPermissions(Folder f) {
653
        if(f != null) {
654
            if(f.isInTrash()) {
655
                upload.setEnabled(false);
656
                disableUploadArea();
657
            }
658
            else {
659
                Boolean[] perms = f.getPermissions().get(userID);
660
                if(f.getOwnerID().equals(userID) || (perms != null && perms[1] != null && perms[1])) {
661
                    upload.setEnabled(true);
662
                    enableUploadArea();
663
                }
664
                else {
665
                    upload.setEnabled(false);
666
                    disableUploadArea();
667
                }
668
            }
669
        }
670
        else {
671
            upload.setEnabled(false);
672
            disableUploadArea();
673
        }
674
    }
675

    
676
    @SuppressWarnings({"rawtypes", "unchecked"})
677
    public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
678
        selectedTree = _selectedTree;
679

    
680
        for(SingleSelectionModel s : selectionModels) {
681
            if(!s.equals(model) && s.getSelectedObject() != null) {
682
                s.setSelected(s.getSelectedObject(), false);
683
            }
684
        }
685
    }
686

    
687
    public void showFiles(final Folder f) {
688
        Set<File> files = f.getFiles();
689
        showFiles(files);
690
    }
691

    
692
    public void showFiles(Set<File> files) {
693
        fileList.setFiles(new ArrayList<File>(files));
694
    }
695

    
696
    /**
697
     * Parse and store the user credentials to the appropriate fields.
698
     */
699
    private boolean parseUserCredentials() {
700
        Configuration conf = (Configuration) GWT.create(Configuration.class);
701
        Dictionary otherProperties = Dictionary.getDictionary(Const.OTHER_PROPERTIES);
702
        String cookie = otherProperties.get(Const.AUTH_COOKIE);
703
        String auth = Cookies.getCookie(cookie);
704
        if(auth == null) {
705
            authenticateUser();
706
            return false;
707
        }
708
        if(auth.startsWith("\"")) {
709
            auth = auth.substring(1);
710
        }
711
        if(auth.endsWith("\"")) {
712
            auth = auth.substring(0, auth.length() - 1);
713
        }
714
        String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
715
        if(authSplit.length != 2) {
716
            authenticateUser();
717
            return false;
718
        }
719
        userID = authSplit[0];
720
        userToken = authSplit[1];
721

    
722
        String gotoUrl = Window.Location.getParameter("goto");
723
        if(gotoUrl != null && gotoUrl.length() > 0) {
724
            Window.Location.assign(gotoUrl);
725
            return false;
726
        }
727
        return true;
728
    }
729

    
730
    /**
731
     * Redirect the user to the login page for authentication.
732
     */
733
    protected void authenticateUser() {
734
        Dictionary otherProperties = Dictionary.getDictionary(Const.OTHER_PROPERTIES);
735
        Window.Location.assign(otherProperties.get(Const.LOGIN_URL) + Window.Location.getHref());
736
    }
737

    
738
    public void fetchAccount(final Command callback) {
739
        String path = "?format=json";
740

    
741
        GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getApiPath(), userID, path) {
742
            @Override
743
            public void onSuccess(AccountResource accountResource) {
744
                account = accountResource;
745
                if(callback != null) {
746
                    callback.execute();
747
                }
748

    
749
                final List<String> memberIDs = new ArrayList<String>();
750
                final List<Group> groups = account.getGroups();
751
                for(Group group : groups) {
752
                    memberIDs.addAll(group.getMemberIDs());
753
                }
754
                memberIDs.add(Pithos.this.getUserID());
755

    
756
                final List<String> theUnknown = Pithos.this.filterUserIDsWithUnknownDisplayName(memberIDs);
757
                // Initialize the user catalog
758
                new UpdateUserCatalogs(Pithos.this, theUnknown).scheduleDeferred();
759
                LOG("Called new UpdateUserCatalogs(Pithos.this, theUnknown).scheduleDeferred();");
760
            }
761

    
762
            @Override
763
            public void onError(Throwable t) {
764
                GWT.log("Error getting account", t);
765
                setError(t);
766
                if(t instanceof RestException) {
767
                    displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
768
                }
769
                else {
770
                    displayError("System error fetching user data: " + t.getMessage());
771
                }
772
            }
773

    
774
            @Override
775
            protected void onUnauthorized(Response response) {
776
                sessionExpired();
777
            }
778
        };
779
        getAccount.setHeader(Const.X_AUTH_TOKEN, userToken);
780
        Scheduler.get().scheduleDeferred(getAccount);
781
    }
782

    
783
    public void updateStatistics() {
784
        HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getApiPath(), userID, "", account) {
785

    
786
            @Override
787
            public void onSuccess(AccountResource _result) {
788
                folderTreeView.showStatistics(account);
789
            }
790

    
791
            @Override
792
            public void onError(Throwable t) {
793
                GWT.log("Error getting account", t);
794
                setError(t);
795
                if(t instanceof RestException) {
796
                    displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
797
                }
798
                else {
799
                    displayError("System error fetching user data: " + t.getMessage());
800
                }
801
            }
802

    
803
            @Override
804
            protected void onUnauthorized(Response response) {
805
                sessionExpired();
806
            }
807
        };
808
        headAccount.setHeader(Const.X_AUTH_TOKEN, userToken);
809
        Scheduler.get().scheduleDeferred(headAccount);
810
    }
811

    
812
    protected void createHomeContainer(final AccountResource _account, final Command callback) {
813
        String path = "/" + Const.HOME_CONTAINER;
814
        PutRequest createPithos = new PutRequest(getApiPath(), getUserID(), path) {
815
            @Override
816
            public void onSuccess(Resource result) {
817
                if(!_account.hasTrashContainer()) {
818
                    createTrashContainer(callback);
819
                }
820
                else {
821
                    fetchAccount(callback);
822
                }
823
            }
824

    
825
            @Override
826
            public void onError(Throwable t) {
827
                GWT.log("Error creating pithos", t);
828
                setError(t);
829
                if(t instanceof RestException) {
830
                    displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
831
                }
832
                else {
833
                    displayError("System error Error creating pithos: " + t.getMessage());
834
                }
835
            }
836

    
837
            @Override
838
            protected void onUnauthorized(Response response) {
839
                sessionExpired();
840
            }
841
        };
842
        createPithos.setHeader(Const.X_AUTH_TOKEN, getUserToken());
843
        Scheduler.get().scheduleDeferred(createPithos);
844
    }
845

    
846
    protected void createTrashContainer(final Command callback) {
847
        String path = "/" + Const.TRASH_CONTAINER;
848
        PutRequest createPithos = new PutRequest(getApiPath(), getUserID(), path) {
849
            @Override
850
            public void onSuccess(Resource result) {
851
                fetchAccount(callback);
852
            }
853

    
854
            @Override
855
            public void onError(Throwable t) {
856
                GWT.log("Error creating pithos", t);
857
                setError(t);
858
                if(t instanceof RestException) {
859
                    displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
860
                }
861
                else {
862
                    displayError("System error Error creating pithos: " + t.getMessage());
863
                }
864
            }
865

    
866
            @Override
867
            protected void onUnauthorized(Response response) {
868
                sessionExpired();
869
            }
870
        };
871
        createPithos.setHeader(Const.X_AUTH_TOKEN, getUserToken());
872
        Scheduler.get().scheduleDeferred(createPithos);
873
    }
874

    
875
    /**
876
     * Creates an HTML fragment that places an image & caption together, for use
877
     * in a group header.
878
     *
879
     * @param imageProto an image prototype for an image
880
     * @param caption    the group caption
881
     * @return the header HTML fragment
882
     */
883
    private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
884
        String captionHTML = "<table class='caption' cellpadding='0' "
885
            + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
886
            + "</td><td id =" + caption + " class='rcaption'><b style='white-space:nowrap'>&nbsp;"
887
            + caption + "</b></td></tr></table>";
888
        return captionHTML;
889
    }
890

    
891
    protected void onWindowResized(int height) {
892
        // Adjust the split panel to take up the available room in the window.
893
        int newHeight = height - splitPanel.getAbsoluteTop() - 153;
894
        if(newHeight < 1) {
895
            newHeight = 1;
896
        }
897
        splitPanel.setHeight("" + newHeight);
898
        inner.setHeight("" + newHeight);
899
    }
900

    
901
    native boolean isCloudbarReady()/*-{
902
      if ($wnd.$("div.cloudbar") && $wnd.$("div.cloudbar").height() > 0)
903
        return true;
904
      return false;
905
    }-*/;
906

    
907
    @Override
908
    public void onResize(ResizeEvent event) {
909
        int height = event.getHeight();
910
        onWindowResized(height);
911
    }
912

    
913
    /**
914
     * Display an error message.
915
     *
916
     * @param msg the message to display
917
     */
918
    public void displayError(String msg) {
919
        messagePanel.displayError(msg);
920
        onWindowResized(Window.getClientHeight());
921
    }
922

    
923
    /**
924
     * Display a warning message.
925
     *
926
     * @param msg the message to display
927
     */
928
    public void displayWarning(String msg) {
929
        messagePanel.displayWarning(msg);
930
        onWindowResized(Window.getClientHeight());
931
    }
932

    
933
    /**
934
     * Display an informational message.
935
     *
936
     * @param msg the message to display
937
     */
938
    public void displayInformation(String msg) {
939
        messagePanel.displayInformation(msg);
940
        onWindowResized(Window.getClientHeight());
941
    }
942

    
943
    /**
944
     * Retrieve the fileList.
945
     *
946
     * @return the fileList
947
     */
948
    public FileList getFileList() {
949
        return fileList;
950
    }
951

    
952
    /**
953
     * Retrieve the topPanel.
954
     *
955
     * @return the topPanel
956
     */
957
    TopPanel getTopPanel() {
958
        return topPanel;
959
    }
960

    
961
    /**
962
     * Retrieve the clipboard.
963
     *
964
     * @return the clipboard
965
     */
966
    public Clipboard getClipboard() {
967
        return clipboard;
968
    }
969

    
970
    public StatusPanel getStatusPanel() {
971
        return statusPanel;
972
    }
973

    
974
    public String getUserToken() {
975
        return userToken;
976
    }
977

    
978
    public static native void preventIESelection() /*-{
979
      $doc.body.onselectstart = function () {
980
        return false;
981
      };
982
    }-*/;
983

    
984
    public static native void enableIESelection() /*-{
985
      if ($doc.body.onselectstart != null)
986
        $doc.body.onselectstart = null;
987
    }-*/;
988

    
989
    /**
990
     * @return the absolute path of the API root URL
991
     */
992
    public String getApiPath() {
993
        Configuration conf = (Configuration) GWT.create(Configuration.class);
994
        return conf.apiPath();
995
    }
996

    
997
    /**
998
     * History support for folder navigation
999
     * adds a new browser history entry
1000
     *
1001
     * @param key
1002
     */
1003
    public void updateHistory(String key) {
1004
//                Replace any whitespace of the initial string to "+"
1005
//                String result = key.replaceAll("\\s","+");
1006
//                Add a new browser history entry.
1007
//                History.newItem(result);
1008
        History.newItem(key);
1009
    }
1010

    
1011
    public void deleteFolder(final Folder folder, final Command callback) {
1012
        final PleaseWaitPopup pwp = new PleaseWaitPopup();
1013
        pwp.center();
1014
        String path = "/" + folder.getContainer() + "/" + folder.getPrefix() + "?delimiter=/" + "&t=" + System.currentTimeMillis();
1015
        DeleteRequest deleteFolder = new DeleteRequest(getApiPath(), folder.getOwnerID(), path) {
1016

    
1017
            @Override
1018
            protected void onUnauthorized(Response response) {
1019
                pwp.hide();
1020
                sessionExpired();
1021
            }
1022

    
1023
            @Override
1024
            public void onSuccess(Resource result) {
1025
                updateFolder(folder.getParent(), true, new Command() {
1026

    
1027
                    @Override
1028
                    public void execute() {
1029
                        folderTreeSelectionModel.setSelected(folder.getParent(), true);
1030
                        updateStatistics();
1031
                        if(callback != null) {
1032
                            callback.execute();
1033
                        }
1034
                        pwp.hide();
1035
                    }
1036
                }, true);
1037
            }
1038

    
1039
            @Override
1040
            public void onError(Throwable t) {
1041
                GWT.log("", t);
1042
                setError(t);
1043
                if(t instanceof RestException) {
1044
                    if(((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND) {
1045
                        displayError("Unable to delete folder: " + ((RestException) t).getHttpStatusText());
1046
                    }
1047
                    else {
1048
                        onSuccess(null);
1049
                    }
1050
                }
1051
                else {
1052
                    displayError("System error unable to delete folder: " + t.getMessage());
1053
                }
1054
                pwp.hide();
1055
            }
1056
        };
1057
        deleteFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1058
        Scheduler.get().scheduleDeferred(deleteFolder);
1059
    }
1060

    
1061
    public FolderTreeView getFolderTreeView() {
1062
        return folderTreeView;
1063
    }
1064

    
1065
    public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
1066
        if(iter.hasNext()) {
1067
            File file = iter.next();
1068
            String path = targetUri + "/" + file.getName();
1069
            PutRequest copyFile = new PutRequest(getApiPath(), targetUsername, path) {
1070
                @Override
1071
                public void onSuccess(Resource result) {
1072
                    copyFiles(iter, targetUsername, targetUri, callback);
1073
                }
1074

    
1075
                @Override
1076
                public void onError(Throwable t) {
1077
                    GWT.log("", t);
1078
                    setError(t);
1079
                    if(t instanceof RestException) {
1080
                        displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
1081
                    }
1082
                    else {
1083
                        displayError("System error unable to copy file: " + t.getMessage());
1084
                    }
1085
                }
1086

    
1087
                @Override
1088
                protected void onUnauthorized(Response response) {
1089
                    sessionExpired();
1090
                }
1091
            };
1092
            copyFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1093
            copyFile.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(file.getUri()));
1094
            if(!file.getOwnerID().equals(targetUsername)) {
1095
                copyFile.setHeader(Const.X_SOURCE_ACCOUNT, URL.encodePathSegment(file.getOwnerID()));
1096
            }
1097
            copyFile.setHeader(Const.CONTENT_TYPE, file.getContentType());
1098
            Scheduler.get().scheduleDeferred(copyFile);
1099
        }
1100
        else if(callback != null) {
1101
            callback.execute();
1102
        }
1103
    }
1104

    
1105
    public void copyFolder(final Folder f, final String targetUsername, final String targetUri, boolean move, final Command callback) {
1106
        String path = targetUri + "?delimiter=/";
1107
        PutRequest copyFolder = new PutRequest(getApiPath(), targetUsername, path) {
1108
            @Override
1109
            public void onSuccess(Resource result) {
1110
                if(callback != null) {
1111
                    callback.execute();
1112
                }
1113
            }
1114

    
1115
            @Override
1116
            public void onError(Throwable t) {
1117
                GWT.log("", t);
1118
                setError(t);
1119
                if(t instanceof RestException) {
1120
                    displayError("Unable to copy folder: " + ((RestException) t).getHttpStatusText());
1121
                }
1122
                else {
1123
                    displayError("System error copying folder: " + t.getMessage());
1124
                }
1125
            }
1126

    
1127
            @Override
1128
            protected void onUnauthorized(Response response) {
1129
                sessionExpired();
1130
            }
1131
        };
1132
        copyFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1133
        copyFolder.setHeader(Const.ACCEPT, "*/*");
1134
        copyFolder.setHeader(Const.CONTENT_LENGTH, "0");
1135
        copyFolder.setHeader(Const.CONTENT_TYPE, "application/directory");
1136
        if(!f.getOwnerID().equals(targetUsername)) {
1137
            copyFolder.setHeader(Const.X_SOURCE_ACCOUNT, f.getOwnerID());
1138
        }
1139
        if(move) {
1140
            copyFolder.setHeader(Const.X_MOVE_FROM, URL.encodePathSegment(f.getUri()));
1141
        }
1142
        else {
1143
            copyFolder.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(f.getUri()));
1144
        }
1145
        Scheduler.get().scheduleDeferred(copyFolder);
1146
    }
1147

    
1148
    public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1149
        selectionModels.add(model);
1150
    }
1151

    
1152
    public OtherSharedTreeView getOtherSharedTreeView() {
1153
        return otherSharedTreeView;
1154
    }
1155

    
1156
    public void updateTrash(boolean showFiles, Command callback) {
1157
        updateFolder(trash, showFiles, callback, true);
1158
    }
1159

    
1160
    public void updateGroupsNode() {
1161
        groupTreeView.updateGroupNode(null);
1162
    }
1163

    
1164
    public Group addGroup(String groupname) {
1165
        Group newGroup = new Group(groupname);
1166
        account.addGroup(newGroup);
1167
        groupTreeView.updateGroupNode(null);
1168
        return newGroup;
1169
    }
1170

    
1171
    public void removeGroup(Group group) {
1172
        account.removeGroup(group);
1173
        updateGroupsNode();
1174
    }
1175

    
1176
    public TreeView getSelectedTree() {
1177
        return selectedTree;
1178
    }
1179

    
1180
    public void setSelectedTree(TreeView selected) {
1181
        selectedTree = selected;
1182
    }
1183

    
1184
    public Folder getSelection() {
1185
        if(selectedTree != null) {
1186
            return selectedTree.getSelection();
1187
        }
1188
        return null;
1189
    }
1190

    
1191
    public void showFolderStatistics(int folderFileCount) {
1192
        numOfFiles.setHTML(String.valueOf(folderFileCount));
1193
    }
1194

    
1195
    public GroupTreeView getGroupTreeView() {
1196
        return groupTreeView;
1197
    }
1198

    
1199
    public void sessionExpired() {
1200
        new SessionExpiredDialog(this).center();
1201
    }
1202

    
1203
    public void updateRootFolder(Command callback) {
1204
        updateFolder(account.getPithos(), false, callback, true);
1205
    }
1206

    
1207
    void createMySharedTree() {
1208
        LOG("Pithos::createMySharedTree()");
1209
        mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1210
        mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1211
            @Override
1212
            public void onSelectionChange(SelectionChangeEvent event) {
1213
                if(mysharedTreeSelectionModel.getSelectedObject() != null) {
1214
                    deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1215
                    upload.setEnabled(false);
1216
                    disableUploadArea();
1217
                    updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1218
                    showRelevantToolbarButtons();
1219
                }
1220
                else {
1221
                    if(getSelectedTree().equals(mysharedTreeView)) {
1222
                        setSelectedTree(null);
1223
                    }
1224
                    if(getSelectedTree() == null) {
1225
                        showRelevantToolbarButtons();
1226
                    }
1227
                }
1228
            }
1229
        });
1230
        selectionModels.add(mysharedTreeSelectionModel);
1231
        mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1232
        mysharedTreeViewModel.initialize(new Command() {
1233

    
1234
            @Override
1235
            public void execute() {
1236
                mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1237
                trees.insert(mysharedTreeView, 2);
1238
                treeViews.add(mysharedTreeView);
1239
                createOtherSharedTree();
1240
            }
1241
        });
1242
    }
1243

    
1244
    void createOtherSharedTree() {
1245
        LOG("Pithos::createOtherSharedTree()");
1246
        otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1247
        otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1248
            @Override
1249
            public void onSelectionChange(SelectionChangeEvent event) {
1250
                if(otherSharedTreeSelectionModel.getSelectedObject() != null) {
1251
                    deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1252
                    applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1253
                    updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true, null);
1254
                    showRelevantToolbarButtons();
1255
                }
1256
                else {
1257
                    if(getSelectedTree().equals(otherSharedTreeView)) {
1258
                        setSelectedTree(null);
1259
                    }
1260
                    if(getSelectedTree() == null) {
1261
                        showRelevantToolbarButtons();
1262
                    }
1263
                }
1264
            }
1265
        });
1266
        selectionModels.add(otherSharedTreeSelectionModel);
1267
        otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1268
        LOG("Pithos::createOtherSharedTree(), initializing otherSharedTreeViewModel with a callback");
1269
        otherSharedTreeViewModel.initialize(new Command() {
1270
            @Override
1271
            public void execute() {
1272
                otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel);
1273
                trees.insert(otherSharedTreeView, 1);
1274
                treeViews.add(otherSharedTreeView);
1275
                scheduleResfresh();
1276
            }
1277
        });
1278
    }
1279

    
1280
    public String getErrorData() {
1281
        final StringBuilder sb = new StringBuilder();
1282
        final String NL = Const.NL;
1283
        Throwable t = this.error;
1284
        while(t != null) {
1285
            sb.append(t.toString());
1286
            sb.append(NL);
1287
            StackTraceElement[] traces = t.getStackTrace();
1288
            for(StackTraceElement trace : traces) {
1289
                sb.append("  [");
1290
                sb.append(trace.getClassName());
1291
                sb.append("::");
1292
                sb.append(trace.getMethodName());
1293
                sb.append("() at ");
1294
                sb.append(trace.getFileName());
1295
                sb.append(":");
1296
                sb.append(trace.getLineNumber());
1297
                sb.append("]");
1298
                sb.append(NL);
1299
            }
1300
            t = t.getCause();
1301
        }
1302

    
1303
        return sb.toString();
1304
    }
1305

    
1306
    public void setError(Throwable t) {
1307
        error = t;
1308
    }
1309

    
1310
    public void showRelevantToolbarButtons() {
1311
        toolbar.showRelevantButtons();
1312
    }
1313

    
1314
    public FileUploadDialog getFileUploadDialog() {
1315
        if(fileUploadDialog == null) {
1316
            fileUploadDialog = new FileUploadDialog(this);
1317
        }
1318
        return fileUploadDialog;
1319
    }
1320

    
1321
    public void hideUploadIndicator() {
1322
        upload.removeStyleName("pithos-uploadButton-loading");
1323
        upload.setTitle("");
1324
    }
1325

    
1326
    public void showUploadIndicator() {
1327
        upload.addStyleName("pithos-uploadButton-loading");
1328
        upload.setTitle("Upload in progress. Click for details.");
1329
    }
1330

    
1331
    public void scheduleFolderHeadCommand(final Folder folder, final Command callback) {
1332
        if(folder == null) {
1333
            if(callback != null) {
1334
                callback.execute();
1335
            }
1336
        }
1337
        else {
1338
            HeadRequest<Folder> headFolder = new HeadRequest<Folder>(Folder.class, getApiPath(), folder.getOwnerID(), folder.getUri(), folder) {
1339

    
1340
                @Override
1341
                public void onSuccess(Folder _result) {
1342
                    if(callback != null) {
1343
                        callback.execute();
1344
                    }
1345
                }
1346

    
1347
                @Override
1348
                public void onError(Throwable t) {
1349
                    if(t instanceof RestException) {
1350
                        if(((RestException) t).getHttpStatusCode() == Response.SC_NOT_FOUND) {
1351
                            final String path = folder.getUri();
1352
                            PutRequest newFolder = new PutRequest(getApiPath(), folder.getOwnerID(), path) {
1353
                                @Override
1354
                                public void onSuccess(Resource _result) {
1355
                                    scheduleFolderHeadCommand(folder, callback);
1356
                                }
1357

    
1358
                                @Override
1359
                                public void onError(Throwable _t) {
1360
                                    GWT.log("", _t);
1361
                                    setError(_t);
1362
                                    if(_t instanceof RestException) {
1363
                                        displayError("Unable to create folder: " + ((RestException) _t).getHttpStatusText());
1364
                                    }
1365
                                    else {
1366
                                        displayError("System error creating folder: " + _t.getMessage());
1367
                                    }
1368
                                }
1369

    
1370
                                @Override
1371
                                protected void onUnauthorized(Response response) {
1372
                                    sessionExpired();
1373
                                }
1374
                            };
1375
                            newFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1376
                            newFolder.setHeader(Const.CONTENT_TYPE, "application/folder");
1377
                            newFolder.setHeader(Const.ACCEPT, "*/*");
1378
                            newFolder.setHeader(Const.CONTENT_LENGTH, "0");
1379
                            Scheduler.get().scheduleDeferred(newFolder);
1380
                        }
1381
                        else if(((RestException) t).getHttpStatusCode() == Response.SC_FORBIDDEN) {
1382
                            onSuccess(folder);
1383
                        }
1384
                        else {
1385
                            displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
1386
                        }
1387
                    }
1388
                    else {
1389
                        displayError("System error heading folder: " + t.getMessage());
1390
                    }
1391

    
1392
                    GWT.log("Error heading folder", t);
1393
                    setError(t);
1394
                }
1395

    
1396
                @Override
1397
                protected void onUnauthorized(Response response) {
1398
                    sessionExpired();
1399
                }
1400
            };
1401
            headFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1402
            Scheduler.get().scheduleDeferred(headFolder);
1403
        }
1404
    }
1405

    
1406
    public void scheduleFileHeadCommand(File f, final Command callback) {
1407
        HeadRequest<File> headFile = new HeadRequest<File>(File.class, getApiPath(), f.getOwnerID(), f.getUri(), f) {
1408

    
1409
            @Override
1410
            public void onSuccess(File _result) {
1411
                if(callback != null) {
1412
                    callback.execute();
1413
                }
1414
            }
1415

    
1416
            @Override
1417
            public void onError(Throwable t) {
1418
                GWT.log("Error heading file", t);
1419
                setError(t);
1420
                if(t instanceof RestException) {
1421
                    displayError("Error heading file: " + ((RestException) t).getHttpStatusText());
1422
                }
1423
                else {
1424
                    displayError("System error heading file: " + t.getMessage());
1425
                }
1426
            }
1427

    
1428
            @Override
1429
            protected void onUnauthorized(Response response) {
1430
                sessionExpired();
1431
            }
1432
        };
1433
        headFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1434
        Scheduler.get().scheduleDeferred(headFile);
1435
    }
1436

    
1437
    public boolean isMySharedSelected() {
1438
        return getSelectedTree().equals(getMySharedTreeView());
1439
    }
1440

    
1441
    private Folder getUploadFolder() {
1442
        if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1443
            return getSelection();
1444
        }
1445
        return null;
1446
    }
1447

    
1448
    private void updateUploadFolder() {
1449
        updateUploadFolder(null);
1450
    }
1451

    
1452
    private void updateUploadFolder(final JsArrayString urls) {
1453
        if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1454
            Folder f = getSelection();
1455
            if(getSelectedTree().equals(getFolderTreeView())) {
1456
                updateFolder(f, true, new Command() {
1457

    
1458
                    @Override
1459
                    public void execute() {
1460
                        updateStatistics();
1461
                        if(urls != null) {
1462
                            selectUploadedFiles(urls);
1463
                        }
1464
                    }
1465
                }, false);
1466
            }
1467
            else {
1468
                updateOtherSharedFolder(f, true, null);
1469
            }
1470
        }
1471
    }
1472

    
1473
    public native void disableUploadArea() /*-{
1474
      var uploader = $wnd.$("#uploader").pluploadQueue();
1475
      var dropElm = $wnd.document.getElementById('rightPanel');
1476
      $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1477
    }-*/;
1478

    
1479
    public native void enableUploadArea() /*-{
1480
      var uploader = $wnd.$("#uploader").pluploadQueue();
1481
      var dropElm = $wnd.document.getElementById('rightPanel');
1482
      $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1483
      if (uploader.runtime == 'html5') {
1484
        uploader.settings.drop_element = 'rightPanel';
1485
        uploader.trigger('PostInit');
1486
      }
1487
    }-*/;
1488

    
1489
    public void showUploadAlert(int nOfFiles) {
1490
        if(uploadAlert == null) {
1491
            uploadAlert = new UploadAlert(this, nOfFiles);
1492
        }
1493
        if(!uploadAlert.isShowing()) {
1494
            uploadAlert.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
1495

    
1496
                @Override
1497
                public void setPosition(int offsetWidth, int offsetHeight) {
1498
                    uploadAlert.setPopupPosition((Window.getClientWidth() - offsetWidth) / 2, statusPanel.getAbsoluteTop() - offsetHeight);
1499
                }
1500
            });
1501
        }
1502
        uploadAlert.setNumOfFiles(nOfFiles);
1503
    }
1504

    
1505
    public void hideUploadAlert() {
1506
        if(uploadAlert != null && uploadAlert.isShowing()) {
1507
            uploadAlert.hide();
1508
        }
1509
    }
1510

    
1511
    public void selectUploadedFiles(JsArrayString urls) {
1512
        List<String> selectedUrls = new ArrayList<String>();
1513
        for(int i = 0; i < urls.length(); i++) {
1514
            selectedUrls.add(urls.get(i));
1515
        }
1516
        fileList.selectByUrl(selectedUrls);
1517
    }
1518

    
1519
    public void emptyContainer(final Folder container) {
1520
        String path = "/" + container.getName() + "?delimiter=/";
1521
        DeleteRequest delete = new DeleteRequest(getApiPath(), getUserID(), path) {
1522

    
1523
            @Override
1524
            protected void onUnauthorized(Response response) {
1525
                sessionExpired();
1526
            }
1527

    
1528
            @Override
1529
            public void onSuccess(Resource result) {
1530
                updateFolder(container, true, null, true);
1531
            }
1532

    
1533
            @Override
1534
            public void onError(Throwable t) {
1535
                GWT.log("Error deleting trash", t);
1536
                setError(t);
1537
                if(t instanceof RestException) {
1538
                    displayError("Error deleting trash: " + ((RestException) t).getHttpStatusText());
1539
                }
1540
                else {
1541
                    displayError("System error deleting trash: " + t.getMessage());
1542
                }
1543
            }
1544
        };
1545
        delete.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1546
        Scheduler.get().scheduleDeferred(delete);
1547
    }
1548
}