Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (55.3 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
    private static final boolean IsLOGEnabled = true;
83

    
84
    public static final Configuration config = GWT.create(Configuration.class);
85

    
86
    public interface Style extends CssResource {
87
        String commandAnchor();
88

    
89
        String statistics();
90

    
91
        @ClassName("gwt-HTML")
92
        String html();
93

    
94
        String uploadAlert();
95

    
96
        String uploadAlertLink();
97

    
98
        String uploadAlertProgress();
99

    
100
        String uploadAlertPercent();
101

    
102
        String uploadAlertClose();
103
    }
104

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

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

    
113
    public static Resources resources = GWT.create(Resources.class);
114

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

    
121
    public String getUserID() {
122
        return userID;
123
    }
124

    
125
    public UserCatalogs getUserCatalogs() {
126
        return userCatalogs;
127
    }
128

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

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

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

    
142
    public String getDisplayNameForUserID(String userID) {
143
        return userCatalogs.getDisplayName(userID);
144
    }
145

    
146
    public String getIDForUserDisplayName(String userDisplayName) {
147
        return userCatalogs.getID(userDisplayName);
148
    }
149

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

    
160
        return userDisplayNames;
161
    }
162

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

    
176
    public void setAccount(AccountResource acct) {
177
        account = acct;
178
    }
179

    
180
    public AccountResource getAccount() {
181
        return account;
182
    }
183

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

    
188
    public void updateGroupNode(Group group) {
189
        groupTreeView.updateGroupNode(group);
190
    }
191

    
192
    public void updateMySharedRoot() {
193
        mysharedTreeView.updateRoot();
194
    }
195

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

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

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

    
208
    public MysharedTreeView getMySharedTreeView() {
209
        return mysharedTreeView;
210
    }
211

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

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

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

    
226
    private Throwable error;
227

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

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

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

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

    
248
    /**
249
     * The file list widget.
250
     */
251
    private FileList fileList;
252

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

    
258

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

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

    
270
    public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
271

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

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

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

    
288
    VerticalPanel trees;
289

    
290
    SingleSelectionModel<Folder> folderTreeSelectionModel;
291
    FolderTreeViewModel folderTreeViewModel;
292
    FolderTreeView folderTreeView;
293

    
294
    SingleSelectionModel<Folder> mysharedTreeSelectionModel;
295
    MysharedTreeViewModel mysharedTreeViewModel;
296
    MysharedTreeView mysharedTreeView = null;
297

    
298
    protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
299
    OtherSharedTreeViewModel otherSharedTreeViewModel;
300
    OtherSharedTreeView otherSharedTreeView = null;
301

    
302
    GroupTreeViewModel groupTreeViewModel;
303
    GroupTreeView groupTreeView;
304

    
305
    TreeView selectedTree;
306
    protected AccountResource account;
307

    
308
    Folder trash;
309

    
310
    List<Composite> treeViews = new ArrayList<Composite>();
311

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

    
315
    public Button upload;
316

    
317
    private HTML numOfFiles;
318

    
319
    private Toolbar toolbar;
320

    
321
    private FileUploadDialog fileUploadDialog = new FileUploadDialog(this);
322

    
323
    UploadAlert uploadAlert;
324

    
325
    Date lastModified;
326

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

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

    
341
    public static void LOGError(Throwable error, StringBuilder sb) {
342
        if(!IsLOGEnabled) { return; }
343

    
344
        sb.append("\nException: [" + error.toString().replace("\n", "\n  ") + "]");
345
        Throwable cause = error.getCause();
346
        if(cause != null) {
347
            sb.append("\nCauses:\n");
348
            while(cause != null) {
349
                sb.append("  ");
350
                sb.append("[" + cause.toString().replace("\n", "\n  ")  + "]");
351
                sb.append("\n");
352
                cause = cause.getCause();
353
            }
354
        }
355
        else {
356
            sb.append("\n");
357
        }
358

    
359
        StackTraceElement[] stackTrace = error.getStackTrace();
360
        sb.append("Stack trace (" + stackTrace.length + " elements):\n");
361
        for(int i = 0; i < stackTrace.length; i++) {
362
            StackTraceElement errorElem = stackTrace[i];
363
            sb.append("  [" + i + "] ");
364
            sb.append(errorElem.toString());
365
            sb.append("\n");
366
        }
367
    }
368

    
369
    public static void LOGError(Throwable error) {
370
        if(!IsLOGEnabled) { return; }
371

    
372
        final StringBuilder sb = new StringBuilder();
373
        LOGError(error, sb);
374
        if(sb.length() > 0) {
375
            __ConsoleLog(sb.toString());
376
        }
377
    }
378

    
379
    public static boolean isLogEnabled() {
380
        return IsLOGEnabled;
381
    }
382

    
383
    public static void LOG(Object ...args) {
384
        if(!IsLOGEnabled) { return; }
385

    
386
        final StringBuilder sb = new StringBuilder();
387
        for(Object arg : args) {
388
            if(arg instanceof Throwable) {
389
                LOGError((Throwable) arg, sb);
390
            }
391
            else {
392
                sb.append(arg);
393
            }
394
        }
395

    
396
        if(sb.length() > 0) {
397
            __ConsoleLog(sb.toString());
398
        }
399
    }
400

    
401
    private void initialize() {
402
        userCatalogs.updateWithIDAndName("*", "All Pithos users");
403

    
404
        lastModified = new Date(); //Initialize if-modified-since value with now.
405
        resources.pithosCss().ensureInjected();
406
        boolean bareContent = Window.Location.getParameter("noframe") != null;
407
        String contentWidth = bareContent ? Const.PERCENT_100 : Const.PERCENT_75;
408

    
409
        VerticalPanel outer = new VerticalPanel();
410
        outer.setWidth(Const.PERCENT_100);
411
        if(!bareContent) {
412
            outer.addStyleName("pithos-outer");
413
        }
414

    
415
        if(!bareContent) {
416
            topPanel = new TopPanel(this, Pithos.images);
417
            topPanel.setWidth(Const.PERCENT_100);
418
            outer.add(topPanel);
419
            outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
420
        }
421

    
422
        messagePanel.setVisible(false);
423
        outer.add(messagePanel);
424
        outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
425
        outer.setCellVerticalAlignment(messagePanel, HasVerticalAlignment.ALIGN_MIDDLE);
426

    
427
        HorizontalPanel header = new HorizontalPanel();
428
        header.addStyleName("pithos-header");
429
        header.setWidth(contentWidth);
430
        if(bareContent) {
431
            header.addStyleName("pithos-header-noframe");
432
        }
433
        upload = new Button("Upload", new ClickHandler() {
434
            @Override
435
            public void onClick(ClickEvent event) {
436
                if(getSelection() != null) {
437
                    new UploadFileCommand(Pithos.this, null, getSelection()).execute();
438
                }
439
            }
440
        });
441
        upload.addStyleName("pithos-uploadButton");
442
        header.add(upload);
443
        header.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_LEFT);
444
        header.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
445

    
446
        toolbar = new Toolbar(this);
447
        header.add(toolbar);
448
        header.setCellHorizontalAlignment(toolbar, HasHorizontalAlignment.ALIGN_CENTER);
449
        header.setCellVerticalAlignment(toolbar, HasVerticalAlignment.ALIGN_MIDDLE);
450

    
451
        HorizontalPanel folderStatistics = new HorizontalPanel();
452
        folderStatistics.addStyleName("pithos-folderStatistics");
453
        numOfFiles = new HTML();
454
        folderStatistics.add(numOfFiles);
455
        folderStatistics.setCellVerticalAlignment(numOfFiles, HasVerticalAlignment.ALIGN_MIDDLE);
456
        HTML numOfFilesLabel = new HTML("&nbsp;Files");
457
        folderStatistics.add(numOfFilesLabel);
458
        folderStatistics.setCellVerticalAlignment(numOfFilesLabel, HasVerticalAlignment.ALIGN_MIDDLE);
459
        header.add(folderStatistics);
460
        header.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
461
        header.setCellVerticalAlignment(folderStatistics, HasVerticalAlignment.ALIGN_MIDDLE);
462
        header.setCellWidth(folderStatistics, "40px");
463
        outer.add(header);
464
        outer.setCellHorizontalAlignment(header, HasHorizontalAlignment.ALIGN_CENTER);
465
        // Inner contains the various lists
466
        inner.sinkEvents(Event.ONCONTEXTMENU);
467
        inner.setWidth(Const.PERCENT_100);
468

    
469
        folderTreeSelectionModel = new SingleSelectionModel<Folder>();
470
        folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
471
            @Override
472
            public void onSelectionChange(SelectionChangeEvent event) {
473
                if(folderTreeSelectionModel.getSelectedObject() != null) {
474
                    deselectOthers(folderTreeView, folderTreeSelectionModel);
475
                    applyPermissions(folderTreeSelectionModel.getSelectedObject());
476
                    Folder f = folderTreeSelectionModel.getSelectedObject();
477
                    updateFolder(f, true, new Command() {
478

    
479
                        @Override
480
                        public void execute() {
481
                            updateStatistics();
482
                        }
483
                    }, true);
484
                    showRelevantToolbarButtons();
485
                }
486
                else {
487
                    if(getSelectedTree().equals(folderTreeView)) {
488
                        setSelectedTree(null);
489
                    }
490
                    if(getSelectedTree() == null) {
491
                        showRelevantToolbarButtons();
492
                    }
493
                }
494
            }
495
        });
496
        selectionModels.add(folderTreeSelectionModel);
497

    
498
        folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
499
        folderTreeView = new FolderTreeView(folderTreeViewModel);
500
        treeViews.add(folderTreeView);
501

    
502
        fileList = new FileList(this, images);
503
        inner.add(fileList);
504

    
505
        trees = new VerticalPanel();
506
        trees.setWidth(Const.PERCENT_100);
507

    
508
        // Add the left and right panels to the split panel.
509
        splitPanel.setLeftWidget(trees);
510
        FlowPanel right = new FlowPanel();
511
        right.getElement().setId("rightPanel");
512
        right.add(inner);
513
        splitPanel.setRightWidget(right);
514
        splitPanel.setSplitPosition("219px");
515
        splitPanel.setSize(Const.PERCENT_100, Const.PERCENT_100);
516
        splitPanel.addStyleName("pithos-splitPanel");
517
        splitPanel.setWidth(contentWidth);
518
        outer.add(splitPanel);
519
        outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
520

    
521
        if(!bareContent) {
522
            statusPanel = new StatusPanel();
523
            statusPanel.setWidth(Const.PERCENT_100);
524
            outer.add(statusPanel);
525
            outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
526
        }
527
        else {
528
            splitPanel.addStyleName("pithos-splitPanel-noframe");
529
        }
530

    
531
        // Hook the window resize event, so that we can adjust the UI.
532
        Window.addResizeHandler(this);
533
        // Clear out the window's built-in margin, because we want to take
534
        // advantage of the entire client area.
535
        Window.setMargin("0px");
536
        // Finally, add the outer panel to the RootPanel, so that it will be
537
        // displayed.
538
        RootPanel.get().add(outer);
539
        // Call the window resized handler to get the initial sizes setup. Doing
540
        // this in a deferred command causes it to occur after all widgets'
541
        // sizes have been computed by the browser.
542
        Scheduler.get().scheduleIncremental(new RepeatingCommand() {
543

    
544
            @Override
545
            public boolean execute() {
546
                if(!isCloudbarReady()) {
547
                    return true;
548
                }
549
                onWindowResized(Window.getClientHeight());
550
                return false;
551
            }
552
        });
553

    
554
        Scheduler.get().scheduleDeferred(new ScheduledCommand() {
555
            @Override
556
            public void execute() {
557
                LOG("Pithos::initialize() Calling Pithos::fetchAccount()");
558
                fetchAccount(new Command() {
559

    
560
                    @Override
561
                    public void execute() {
562
                        if(!account.hasHomeContainer()) {
563
                            createHomeContainer(account, this);
564
                        }
565
                        else if(!account.hasTrashContainer()) {
566
                            createTrashContainer(this);
567
                        }
568
                        else {
569
                            for(Folder f : account.getContainers()) {
570
                                if(f.getName().equals(Const.TRASH_CONTAINER)) {
571
                                    trash = f;
572
                                    break;
573
                                }
574
                            }
575
                            trees.add(folderTreeView);
576
                            folderTreeViewModel.initialize(account, new Command() {
577

    
578
                                @Override
579
                                public void execute() {
580
                                    createMySharedTree();
581
                                }
582
                            });
583

    
584
                            HorizontalPanel separator = new HorizontalPanel();
585
                            separator.addStyleName("pithos-statisticsSeparator");
586
                            separator.add(new HTML(""));
587
                            trees.add(separator);
588

    
589
                            groupTreeViewModel = new GroupTreeViewModel(Pithos.this);
590
                            groupTreeView = new GroupTreeView(groupTreeViewModel);
591
                            treeViews.add(groupTreeView);
592
                            trees.add(groupTreeView);
593
                            folderTreeView.showStatistics(account);
594
                        }
595
                    }
596
                });
597
            }
598
        });
599
    }
600

    
601
    public void scheduleResfresh() {
602
        Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {
603

    
604
            @Override
605
            public boolean execute() {
606
                final Folder f = getSelection();
607
                if(f == null) {
608
                    return true;
609
                }
610

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

    
613
                    @Override
614
                    public void onSuccess(Folder _result) {
615
                        lastModified = new Date();
616
                        if(getSelectedTree().equals(folderTreeView)) {
617
                            updateFolder(f, true, new Command() {
618

    
619
                                @Override
620
                                public void execute() {
621
                                    scheduleResfresh();
622
                                }
623

    
624
                            }, false);
625
                        }
626
                        else if(getSelectedTree().equals(mysharedTreeView)) {
627
                            updateSharedFolder(f, true, new Command() {
628

    
629
                                @Override
630
                                public void execute() {
631
                                    scheduleResfresh();
632
                                }
633
                            });
634
                        }
635
                        else {
636
                            scheduleResfresh();
637
                        }
638
                    }
639

    
640
                    @Override
641
                    public void onError(Throwable t) {
642
                        if(t instanceof RestException && ((RestException) t).getHttpStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
643
                            scheduleResfresh();
644
                        }
645
                        else if(retries >= MAX_RETRIES) {
646
                            LOG("Error heading folder. ", t);
647
                            setError(t);
648
                            if(t instanceof RestException) {
649
                                displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
650
                            }
651
                            else {
652
                                displayError("System error heading folder: " + t.getMessage());
653
                            }
654
                        }
655
                        else {//retry
656
                            LOG("Retry ", retries);
657
                            Scheduler.get().scheduleDeferred(this);
658
                        }
659
                    }
660

    
661
                    @Override
662
                    protected void onUnauthorized(Response response) {
663
                        if(retries >= MAX_RETRIES) {
664
                            sessionExpired();
665
                        }
666
                        else //retry
667
                        {
668
                            Scheduler.get().scheduleDeferred(this);
669
                        }
670
                    }
671
                };
672
                head.setHeader(Const.X_AUTH_TOKEN, getUserToken());
673
                head.setHeader(Const.IF_MODIFIED_SINCE, DateTimeFormat.getFormat(Const.DATE_FORMAT_1).format(lastModified, TimeZone.createTimeZone(0)) + " GMT");
674
                Scheduler.get().scheduleDeferred(head);
675

    
676
                return false;
677
            }
678
        }, 3000);
679
    }
680

    
681
    public void applyPermissions(Folder f) {
682
        if(f != null) {
683
            if(f.isInTrash()) {
684
                upload.setEnabled(false);
685
                disableUploadArea();
686
            }
687
            else {
688
                Boolean[] perms = f.getPermissions().get(userID);
689
                if(f.getOwnerID().equals(userID) || (perms != null && perms[1] != null && perms[1])) {
690
                    upload.setEnabled(true);
691
                    enableUploadArea();
692
                }
693
                else {
694
                    upload.setEnabled(false);
695
                    disableUploadArea();
696
                }
697
            }
698
        }
699
        else {
700
            upload.setEnabled(false);
701
            disableUploadArea();
702
        }
703
    }
704

    
705
    @SuppressWarnings({"rawtypes", "unchecked"})
706
    public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
707
        selectedTree = _selectedTree;
708

    
709
        for(SingleSelectionModel s : selectionModels) {
710
            if(!s.equals(model) && s.getSelectedObject() != null) {
711
                s.setSelected(s.getSelectedObject(), false);
712
            }
713
        }
714
    }
715

    
716
    public void showFiles(final Folder f) {
717
        Set<File> files = f.getFiles();
718
        showFiles(files);
719
    }
720

    
721
    public void showFiles(Set<File> files) {
722
        fileList.setFiles(new ArrayList<File>(files));
723
    }
724

    
725
    /**
726
     * Parse and store the user credentials to the appropriate fields.
727
     */
728
    private boolean parseUserCredentials() {
729
        Configuration conf = (Configuration) GWT.create(Configuration.class);
730
        Dictionary otherProperties = Dictionary.getDictionary(Const.OTHER_PROPERTIES);
731
        String cookie = otherProperties.get(Const.AUTH_COOKIE);
732
        String auth = Cookies.getCookie(cookie);
733
        if(auth == null) {
734
            authenticateUser();
735
            return false;
736
        }
737
        if(auth.startsWith("\"")) {
738
            auth = auth.substring(1);
739
        }
740
        if(auth.endsWith("\"")) {
741
            auth = auth.substring(0, auth.length() - 1);
742
        }
743
        String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
744
        if(authSplit.length != 2) {
745
            authenticateUser();
746
            return false;
747
        }
748
        userID = authSplit[0];
749
        userToken = authSplit[1];
750

    
751
        String gotoUrl = Window.Location.getParameter("goto");
752
        if(gotoUrl != null && gotoUrl.length() > 0) {
753
            Window.Location.assign(gotoUrl);
754
            return false;
755
        }
756
        return true;
757
    }
758

    
759
    /**
760
     * Redirect the user to the login page for authentication.
761
     */
762
    protected void authenticateUser() {
763
        Dictionary otherProperties = Dictionary.getDictionary(Const.OTHER_PROPERTIES);
764
        Window.Location.assign(otherProperties.get(Const.LOGIN_URL) + Window.Location.getHref());
765
    }
766

    
767
    public void fetchAccount(final Command callback) {
768
        String path = "?format=json";
769

    
770
        GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getApiPath(), userID, path) {
771
            @Override
772
            public void onSuccess(AccountResource accountResource) {
773
                account = accountResource;
774
                if(callback != null) {
775
                    callback.execute();
776
                }
777

    
778
                final List<String> memberIDs = new ArrayList<String>();
779
                final List<Group> groups = account.getGroups();
780
                for(Group group : groups) {
781
                    memberIDs.addAll(group.getMemberIDs());
782
                }
783
                memberIDs.add(Pithos.this.getUserID());
784

    
785
                final List<String> theUnknown = Pithos.this.filterUserIDsWithUnknownDisplayName(memberIDs);
786
                // Initialize the user catalog
787
                new UpdateUserCatalogs(Pithos.this, theUnknown).scheduleDeferred();
788
                LOG("Called new UpdateUserCatalogs(Pithos.this, theUnknown).scheduleDeferred();");
789
            }
790

    
791
            @Override
792
            public void onError(Throwable t) {
793
                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
        getAccount.setHeader(Const.X_AUTH_TOKEN, userToken);
809
        Scheduler.get().scheduleDeferred(getAccount);
810
    }
811

    
812
    public void updateStatistics() {
813
        HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getApiPath(), userID, "", account) {
814

    
815
            @Override
816
            public void onSuccess(AccountResource _result) {
817
                folderTreeView.showStatistics(account);
818
            }
819

    
820
            @Override
821
            public void onError(Throwable t) {
822
                LOG("Error getting account", t);
823
                setError(t);
824
                if(t instanceof RestException) {
825
                    displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
826
                }
827
                else {
828
                    displayError("System error fetching user data: " + t.getMessage());
829
                }
830
            }
831

    
832
            @Override
833
            protected void onUnauthorized(Response response) {
834
                sessionExpired();
835
            }
836
        };
837
        headAccount.setHeader(Const.X_AUTH_TOKEN, userToken);
838
        Scheduler.get().scheduleDeferred(headAccount);
839
    }
840

    
841
    protected void createHomeContainer(final AccountResource _account, final Command callback) {
842
        String path = "/" + Const.HOME_CONTAINER;
843
        PutRequest createPithos = new PutRequest(getApiPath(), getUserID(), path) {
844
            @Override
845
            public void onSuccess(Resource result) {
846
                if(!_account.hasTrashContainer()) {
847
                    createTrashContainer(callback);
848
                }
849
                else {
850
                    fetchAccount(callback);
851
                }
852
            }
853

    
854
            @Override
855
            public void onError(Throwable t) {
856
                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
    protected void createTrashContainer(final Command callback) {
876
        String path = "/" + Const.TRASH_CONTAINER;
877
        PutRequest createPithos = new PutRequest(getApiPath(), getUserID(), path) {
878
            @Override
879
            public void onSuccess(Resource result) {
880
                fetchAccount(callback);
881
            }
882

    
883
            @Override
884
            public void onError(Throwable t) {
885
                LOG("Error creating pithos", t);
886
                setError(t);
887
                if(t instanceof RestException) {
888
                    displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
889
                }
890
                else {
891
                    displayError("System error Error creating pithos: " + t.getMessage());
892
                }
893
            }
894

    
895
            @Override
896
            protected void onUnauthorized(Response response) {
897
                sessionExpired();
898
            }
899
        };
900
        createPithos.setHeader(Const.X_AUTH_TOKEN, getUserToken());
901
        Scheduler.get().scheduleDeferred(createPithos);
902
    }
903

    
904
    /**
905
     * Creates an HTML fragment that places an image & caption together, for use
906
     * in a group header.
907
     *
908
     * @param imageProto an image prototype for an image
909
     * @param caption    the group caption
910
     * @return the header HTML fragment
911
     */
912
    private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
913
        String captionHTML = "<table class='caption' cellpadding='0' "
914
            + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
915
            + "</td><td id =" + caption + " class='rcaption'><b style='white-space:nowrap'>&nbsp;"
916
            + caption + "</b></td></tr></table>";
917
        return captionHTML;
918
    }
919

    
920
    protected void onWindowResized(int height) {
921
        // Adjust the split panel to take up the available room in the window.
922
        int newHeight = height - splitPanel.getAbsoluteTop() - 153;
923
        if(newHeight < 1) {
924
            newHeight = 1;
925
        }
926
        splitPanel.setHeight("" + newHeight);
927
        inner.setHeight("" + newHeight);
928
    }
929

    
930
    native boolean isCloudbarReady()/*-{
931
      if ($wnd.$("div.cloudbar") && $wnd.$("div.cloudbar").height() > 0)
932
        return true;
933
      return false;
934
    }-*/;
935

    
936
    @Override
937
    public void onResize(ResizeEvent event) {
938
        int height = event.getHeight();
939
        onWindowResized(height);
940
    }
941

    
942
    /**
943
     * Display an error message.
944
     *
945
     * @param msg the message to display
946
     */
947
    public void displayError(String msg) {
948
        messagePanel.displayError(msg);
949
        onWindowResized(Window.getClientHeight());
950
    }
951

    
952
    /**
953
     * Display a warning message.
954
     *
955
     * @param msg the message to display
956
     */
957
    public void displayWarning(String msg) {
958
        messagePanel.displayWarning(msg);
959
        onWindowResized(Window.getClientHeight());
960
    }
961

    
962
    /**
963
     * Display an informational message.
964
     *
965
     * @param msg the message to display
966
     */
967
    public void displayInformation(String msg) {
968
        messagePanel.displayInformation(msg);
969
        onWindowResized(Window.getClientHeight());
970
    }
971

    
972
    /**
973
     * Retrieve the fileList.
974
     *
975
     * @return the fileList
976
     */
977
    public FileList getFileList() {
978
        return fileList;
979
    }
980

    
981
    /**
982
     * Retrieve the topPanel.
983
     *
984
     * @return the topPanel
985
     */
986
    TopPanel getTopPanel() {
987
        return topPanel;
988
    }
989

    
990
    /**
991
     * Retrieve the clipboard.
992
     *
993
     * @return the clipboard
994
     */
995
    public Clipboard getClipboard() {
996
        return clipboard;
997
    }
998

    
999
    public StatusPanel getStatusPanel() {
1000
        return statusPanel;
1001
    }
1002

    
1003
    public String getUserToken() {
1004
        return userToken;
1005
    }
1006

    
1007
    public static native void preventIESelection() /*-{
1008
      $doc.body.onselectstart = function () {
1009
        return false;
1010
      };
1011
    }-*/;
1012

    
1013
    public static native void enableIESelection() /*-{
1014
      if ($doc.body.onselectstart != null)
1015
        $doc.body.onselectstart = null;
1016
    }-*/;
1017

    
1018
    /**
1019
     * @return the absolute path of the API root URL
1020
     */
1021
    public String getApiPath() {
1022
        Configuration conf = (Configuration) GWT.create(Configuration.class);
1023
        return conf.apiPath();
1024
    }
1025

    
1026
    /**
1027
     * History support for folder navigation
1028
     * adds a new browser history entry
1029
     *
1030
     * @param key
1031
     */
1032
    public void updateHistory(String key) {
1033
//                Replace any whitespace of the initial string to "+"
1034
//                String result = key.replaceAll("\\s","+");
1035
//                Add a new browser history entry.
1036
//                History.newItem(result);
1037
        History.newItem(key);
1038
    }
1039

    
1040
    public void deleteFolder(final Folder folder, final Command callback) {
1041
        final PleaseWaitPopup pwp = new PleaseWaitPopup();
1042
        pwp.center();
1043
        String path = "/" + folder.getContainer() + "/" + folder.getPrefix() + "?delimiter=/" + "&t=" + System.currentTimeMillis();
1044
        DeleteRequest deleteFolder = new DeleteRequest(getApiPath(), folder.getOwnerID(), path) {
1045

    
1046
            @Override
1047
            protected void onUnauthorized(Response response) {
1048
                pwp.hide();
1049
                sessionExpired();
1050
            }
1051

    
1052
            @Override
1053
            public void onSuccess(Resource result) {
1054
                updateFolder(folder.getParent(), true, new Command() {
1055

    
1056
                    @Override
1057
                    public void execute() {
1058
                        folderTreeSelectionModel.setSelected(folder.getParent(), true);
1059
                        updateStatistics();
1060
                        if(callback != null) {
1061
                            callback.execute();
1062
                        }
1063
                        pwp.hide();
1064
                    }
1065
                }, true);
1066
            }
1067

    
1068
            @Override
1069
            public void onError(Throwable t) {
1070
                LOG(t);
1071
                setError(t);
1072
                if(t instanceof RestException) {
1073
                    if(((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND) {
1074
                        displayError("Unable to delete folder: " + ((RestException) t).getHttpStatusText());
1075
                    }
1076
                    else {
1077
                        onSuccess(null);
1078
                    }
1079
                }
1080
                else {
1081
                    displayError("System error unable to delete folder: " + t.getMessage());
1082
                }
1083
                pwp.hide();
1084
            }
1085
        };
1086
        deleteFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1087
        Scheduler.get().scheduleDeferred(deleteFolder);
1088
    }
1089

    
1090
    public FolderTreeView getFolderTreeView() {
1091
        return folderTreeView;
1092
    }
1093

    
1094
    public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
1095
        if(iter.hasNext()) {
1096
            File file = iter.next();
1097
            String path = targetUri + "/" + file.getName();
1098
            PutRequest copyFile = new PutRequest(getApiPath(), targetUsername, path) {
1099
                @Override
1100
                public void onSuccess(Resource result) {
1101
                    copyFiles(iter, targetUsername, targetUri, callback);
1102
                }
1103

    
1104
                @Override
1105
                public void onError(Throwable t) {
1106
                    LOG(t);
1107
                    setError(t);
1108
                    if(t instanceof RestException) {
1109
                        displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
1110
                    }
1111
                    else {
1112
                        displayError("System error unable to copy file: " + t.getMessage());
1113
                    }
1114
                }
1115

    
1116
                @Override
1117
                protected void onUnauthorized(Response response) {
1118
                    sessionExpired();
1119
                }
1120
            };
1121
            copyFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1122
            copyFile.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(file.getUri()));
1123
            if(!file.getOwnerID().equals(targetUsername)) {
1124
                copyFile.setHeader(Const.X_SOURCE_ACCOUNT, URL.encodePathSegment(file.getOwnerID()));
1125
            }
1126
            copyFile.setHeader(Const.CONTENT_TYPE, file.getContentType());
1127
            Scheduler.get().scheduleDeferred(copyFile);
1128
        }
1129
        else if(callback != null) {
1130
            callback.execute();
1131
        }
1132
    }
1133

    
1134
    public void copyFolder(final Folder f, final String targetUsername, final String targetUri, boolean move, final Command callback) {
1135
        String path = targetUri + "?delimiter=/";
1136
        PutRequest copyFolder = new PutRequest(getApiPath(), targetUsername, path) {
1137
            @Override
1138
            public void onSuccess(Resource result) {
1139
                if(callback != null) {
1140
                    callback.execute();
1141
                }
1142
            }
1143

    
1144
            @Override
1145
            public void onError(Throwable t) {
1146
                LOG(t);
1147
                setError(t);
1148
                if(t instanceof RestException) {
1149
                    displayError("Unable to copy folder: " + ((RestException) t).getHttpStatusText());
1150
                }
1151
                else {
1152
                    displayError("System error copying folder: " + t.getMessage());
1153
                }
1154
            }
1155

    
1156
            @Override
1157
            protected void onUnauthorized(Response response) {
1158
                sessionExpired();
1159
            }
1160
        };
1161
        copyFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1162
        copyFolder.setHeader(Const.ACCEPT, "*/*");
1163
        copyFolder.setHeader(Const.CONTENT_LENGTH, "0");
1164
        copyFolder.setHeader(Const.CONTENT_TYPE, "application/directory");
1165
        if(!f.getOwnerID().equals(targetUsername)) {
1166
            copyFolder.setHeader(Const.X_SOURCE_ACCOUNT, f.getOwnerID());
1167
        }
1168
        if(move) {
1169
            copyFolder.setHeader(Const.X_MOVE_FROM, URL.encodePathSegment(f.getUri()));
1170
        }
1171
        else {
1172
            copyFolder.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(f.getUri()));
1173
        }
1174
        Scheduler.get().scheduleDeferred(copyFolder);
1175
    }
1176

    
1177
    public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1178
        selectionModels.add(model);
1179
    }
1180

    
1181
    public OtherSharedTreeView getOtherSharedTreeView() {
1182
        return otherSharedTreeView;
1183
    }
1184

    
1185
    public void updateTrash(boolean showFiles, Command callback) {
1186
        updateFolder(trash, showFiles, callback, true);
1187
    }
1188

    
1189
    public void updateGroupsNode() {
1190
        groupTreeView.updateGroupNode(null);
1191
    }
1192

    
1193
    public Group addGroup(String groupname) {
1194
        Group newGroup = new Group(groupname);
1195
        account.addGroup(newGroup);
1196
        groupTreeView.updateGroupNode(null);
1197
        return newGroup;
1198
    }
1199

    
1200
    public void removeGroup(Group group) {
1201
        account.removeGroup(group);
1202
        updateGroupsNode();
1203
    }
1204

    
1205
    public TreeView getSelectedTree() {
1206
        return selectedTree;
1207
    }
1208

    
1209
    public void setSelectedTree(TreeView selected) {
1210
        selectedTree = selected;
1211
    }
1212

    
1213
    public Folder getSelection() {
1214
        if(selectedTree != null) {
1215
            return selectedTree.getSelection();
1216
        }
1217
        return null;
1218
    }
1219

    
1220
    public void showFolderStatistics(int folderFileCount) {
1221
        numOfFiles.setHTML(String.valueOf(folderFileCount));
1222
    }
1223

    
1224
    public GroupTreeView getGroupTreeView() {
1225
        return groupTreeView;
1226
    }
1227

    
1228
    public void sessionExpired() {
1229
        new SessionExpiredDialog(this).center();
1230
    }
1231

    
1232
    public void updateRootFolder(Command callback) {
1233
        updateFolder(account.getPithos(), false, callback, true);
1234
    }
1235

    
1236
    void createMySharedTree() {
1237
        LOG("Pithos::createMySharedTree()");
1238
        mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1239
        mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1240
            @Override
1241
            public void onSelectionChange(SelectionChangeEvent event) {
1242
                if(mysharedTreeSelectionModel.getSelectedObject() != null) {
1243
                    deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1244
                    upload.setEnabled(false);
1245
                    disableUploadArea();
1246
                    updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1247
                    showRelevantToolbarButtons();
1248
                }
1249
                else {
1250
                    if(getSelectedTree().equals(mysharedTreeView)) {
1251
                        setSelectedTree(null);
1252
                    }
1253
                    if(getSelectedTree() == null) {
1254
                        showRelevantToolbarButtons();
1255
                    }
1256
                }
1257
            }
1258
        });
1259
        selectionModels.add(mysharedTreeSelectionModel);
1260
        mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1261
        mysharedTreeViewModel.initialize(new Command() {
1262

    
1263
            @Override
1264
            public void execute() {
1265
                mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1266
                trees.insert(mysharedTreeView, 2);
1267
                treeViews.add(mysharedTreeView);
1268
                createOtherSharedTree();
1269
            }
1270
        });
1271
    }
1272

    
1273
    void createOtherSharedTree() {
1274
        LOG("Pithos::createOtherSharedTree()");
1275
        otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1276
        otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1277
            @Override
1278
            public void onSelectionChange(SelectionChangeEvent event) {
1279
                if(otherSharedTreeSelectionModel.getSelectedObject() != null) {
1280
                    deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1281
                    applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1282
                    updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true, null);
1283
                    showRelevantToolbarButtons();
1284
                }
1285
                else {
1286
                    if(getSelectedTree().equals(otherSharedTreeView)) {
1287
                        setSelectedTree(null);
1288
                    }
1289
                    if(getSelectedTree() == null) {
1290
                        showRelevantToolbarButtons();
1291
                    }
1292
                }
1293
            }
1294
        });
1295
        selectionModels.add(otherSharedTreeSelectionModel);
1296
        otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1297
        LOG("Pithos::createOtherSharedTree(), initializing otherSharedTreeViewModel with a callback");
1298
        otherSharedTreeViewModel.initialize(new Command() {
1299
            @Override
1300
            public void execute() {
1301
                otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel);
1302
                trees.insert(otherSharedTreeView, 1);
1303
                treeViews.add(otherSharedTreeView);
1304
                scheduleResfresh();
1305
            }
1306
        });
1307
    }
1308

    
1309
    public String getErrorData() {
1310
        final StringBuilder sb = new StringBuilder();
1311
        final String NL = Const.NL;
1312
        Throwable t = this.error;
1313
        while(t != null) {
1314
            sb.append(t.toString());
1315
            sb.append(NL);
1316
            StackTraceElement[] traces = t.getStackTrace();
1317
            for(StackTraceElement trace : traces) {
1318
                sb.append("  [");
1319
                sb.append(trace.getClassName());
1320
                sb.append("::");
1321
                sb.append(trace.getMethodName());
1322
                sb.append("() at ");
1323
                sb.append(trace.getFileName());
1324
                sb.append(":");
1325
                sb.append(trace.getLineNumber());
1326
                sb.append("]");
1327
                sb.append(NL);
1328
            }
1329
            t = t.getCause();
1330
        }
1331

    
1332
        return sb.toString();
1333
    }
1334

    
1335
    public void setError(Throwable t) {
1336
        error = t;
1337
        LOG(t);
1338
    }
1339

    
1340
    public void showRelevantToolbarButtons() {
1341
        toolbar.showRelevantButtons();
1342
    }
1343

    
1344
    public FileUploadDialog getFileUploadDialog() {
1345
        if(fileUploadDialog == null) {
1346
            fileUploadDialog = new FileUploadDialog(this);
1347
        }
1348
        return fileUploadDialog;
1349
    }
1350

    
1351
    public void hideUploadIndicator() {
1352
        upload.removeStyleName("pithos-uploadButton-loading");
1353
        upload.setTitle("");
1354
    }
1355

    
1356
    public void showUploadIndicator() {
1357
        upload.addStyleName("pithos-uploadButton-loading");
1358
        upload.setTitle("Upload in progress. Click for details.");
1359
    }
1360

    
1361
    public void scheduleFolderHeadCommand(final Folder folder, final Command callback) {
1362
        if(folder == null) {
1363
            if(callback != null) {
1364
                callback.execute();
1365
            }
1366
        }
1367
        else {
1368
            HeadRequest<Folder> headFolder = new HeadRequest<Folder>(Folder.class, getApiPath(), folder.getOwnerID(), folder.getUri(), folder) {
1369

    
1370
                @Override
1371
                public void onSuccess(Folder _result) {
1372
                    if(callback != null) {
1373
                        callback.execute();
1374
                    }
1375
                }
1376

    
1377
                @Override
1378
                public void onError(Throwable t) {
1379
                    if(t instanceof RestException) {
1380
                        if(((RestException) t).getHttpStatusCode() == Response.SC_NOT_FOUND) {
1381
                            final String path = folder.getUri();
1382
                            PutRequest newFolder = new PutRequest(getApiPath(), folder.getOwnerID(), path) {
1383
                                @Override
1384
                                public void onSuccess(Resource _result) {
1385
                                    scheduleFolderHeadCommand(folder, callback);
1386
                                }
1387

    
1388
                                @Override
1389
                                public void onError(Throwable _t) {
1390
                                    setError(_t);
1391
                                    if(_t instanceof RestException) {
1392
                                        displayError("Unable to create folder: " + ((RestException) _t).getHttpStatusText());
1393
                                    }
1394
                                    else {
1395
                                        displayError("System error creating folder: " + _t.getMessage());
1396
                                    }
1397
                                }
1398

    
1399
                                @Override
1400
                                protected void onUnauthorized(Response response) {
1401
                                    sessionExpired();
1402
                                }
1403
                            };
1404
                            newFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1405
                            newFolder.setHeader(Const.CONTENT_TYPE, "application/folder");
1406
                            newFolder.setHeader(Const.ACCEPT, "*/*");
1407
                            newFolder.setHeader(Const.CONTENT_LENGTH, "0");
1408
                            Scheduler.get().scheduleDeferred(newFolder);
1409
                        }
1410
                        else if(((RestException) t).getHttpStatusCode() == Response.SC_FORBIDDEN) {
1411
                            onSuccess(folder);
1412
                        }
1413
                        else {
1414
                            displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
1415
                        }
1416
                    }
1417
                    else {
1418
                        displayError("System error heading folder: " + t.getMessage());
1419
                    }
1420

    
1421
                    LOG("Error heading folder", t);
1422
                    setError(t);
1423
                }
1424

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

    
1435
    public void scheduleFileHeadCommand(File f, final Command callback) {
1436
        HeadRequest<File> headFile = new HeadRequest<File>(File.class, getApiPath(), f.getOwnerID(), f.getUri(), f) {
1437

    
1438
            @Override
1439
            public void onSuccess(File _result) {
1440
                if(callback != null) {
1441
                    callback.execute();
1442
                }
1443
            }
1444

    
1445
            @Override
1446
            public void onError(Throwable t) {
1447
                LOG("Error heading file", t);
1448
                setError(t);
1449
                if(t instanceof RestException) {
1450
                    displayError("Error heading file: " + ((RestException) t).getHttpStatusText());
1451
                }
1452
                else {
1453
                    displayError("System error heading file: " + t.getMessage());
1454
                }
1455
            }
1456

    
1457
            @Override
1458
            protected void onUnauthorized(Response response) {
1459
                sessionExpired();
1460
            }
1461
        };
1462
        headFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1463
        Scheduler.get().scheduleDeferred(headFile);
1464
    }
1465

    
1466
    public boolean isMySharedSelected() {
1467
        return getSelectedTree().equals(getMySharedTreeView());
1468
    }
1469

    
1470
    private Folder getUploadFolder() {
1471
        if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1472
            return getSelection();
1473
        }
1474
        return null;
1475
    }
1476

    
1477
    private void updateUploadFolder() {
1478
        updateUploadFolder(null);
1479
    }
1480

    
1481
    private void updateUploadFolder(final JsArrayString urls) {
1482
        if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1483
            Folder f = getSelection();
1484
            if(getSelectedTree().equals(getFolderTreeView())) {
1485
                updateFolder(f, true, new Command() {
1486

    
1487
                    @Override
1488
                    public void execute() {
1489
                        updateStatistics();
1490
                        if(urls != null) {
1491
                            selectUploadedFiles(urls);
1492
                        }
1493
                    }
1494
                }, false);
1495
            }
1496
            else {
1497
                updateOtherSharedFolder(f, true, null);
1498
            }
1499
        }
1500
    }
1501

    
1502
    public native void disableUploadArea() /*-{
1503
      var uploader = $wnd.$("#uploader").pluploadQueue();
1504
      var dropElm = $wnd.document.getElementById('rightPanel');
1505
      $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1506
    }-*/;
1507

    
1508
    public native void enableUploadArea() /*-{
1509
      var uploader = $wnd.$("#uploader").pluploadQueue();
1510
      var dropElm = $wnd.document.getElementById('rightPanel');
1511
      $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1512
      if (uploader.runtime == 'html5') {
1513
        uploader.settings.drop_element = 'rightPanel';
1514
        uploader.trigger('PostInit');
1515
      }
1516
    }-*/;
1517

    
1518
    public void showUploadAlert(int nOfFiles) {
1519
        if(uploadAlert == null) {
1520
            uploadAlert = new UploadAlert(this, nOfFiles);
1521
        }
1522
        if(!uploadAlert.isShowing()) {
1523
            uploadAlert.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
1524

    
1525
                @Override
1526
                public void setPosition(int offsetWidth, int offsetHeight) {
1527
                    uploadAlert.setPopupPosition((Window.getClientWidth() - offsetWidth) / 2, statusPanel.getAbsoluteTop() - offsetHeight);
1528
                }
1529
            });
1530
        }
1531
        uploadAlert.setNumOfFiles(nOfFiles);
1532
    }
1533

    
1534
    public void hideUploadAlert() {
1535
        if(uploadAlert != null && uploadAlert.isShowing()) {
1536
            uploadAlert.hide();
1537
        }
1538
    }
1539

    
1540
    public void selectUploadedFiles(JsArrayString urls) {
1541
        List<String> selectedUrls = new ArrayList<String>();
1542
        for(int i = 0; i < urls.length(); i++) {
1543
            selectedUrls.add(urls.get(i));
1544
        }
1545
        fileList.selectByUrl(selectedUrls);
1546
    }
1547

    
1548
    public void purgeContainer(final Folder container) {
1549
        String path = "/" + container.getName() + "?delimiter=/";
1550
        DeleteRequest delete = new DeleteRequest(getApiPath(), getUserID(), path) {
1551

    
1552
            @Override
1553
            protected void onUnauthorized(Response response) {
1554
                sessionExpired();
1555
            }
1556

    
1557
            @Override
1558
            public void onSuccess(Resource result) {
1559
                updateFolder(container, true, null, true);
1560
            }
1561

    
1562
            @Override
1563
            public void onError(Throwable t) {
1564
                LOG("Error deleting trash", t);
1565
                setError(t);
1566
                if(t instanceof RestException) {
1567
                    displayError("Error deleting trash: " + ((RestException) t).getHttpStatusText());
1568
                }
1569
                else {
1570
                    displayError("System error deleting trash: " + t.getMessage());
1571
                }
1572
            }
1573
        };
1574
        delete.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1575
        Scheduler.get().scheduleDeferred(delete);
1576
    }
1577
}