Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (58.2 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
    private static final boolean IsLOGEnabled = false;
82
    public static final boolean IsDetailedHTTPLOGEnabled = true;
83
    public static final boolean IsFullResponseBodyLOGEnabled = true;
84

    
85
    public static final Set<String> HTTPHeadersToIgnoreInLOG = new HashSet<String>();
86
    static {
87
        HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_CONNECTION);
88
        HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_DATE);
89
        HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_KEEP_ALIVE);
90
        HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_SERVER);
91
        HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_VARY);
92
        HTTPHeadersToIgnoreInLOG.add(Const.IF_MODIFIED_SINCE);
93
    }
94

    
95
    public static final Configuration config = GWT.create(Configuration.class);
96
    public static final String CONFIG_API_PATH = config.apiPath();
97
    static {
98
        LOG("CONFIG_API_PATH = ", CONFIG_API_PATH);
99
    }
100

    
101
    public static final Dictionary otherProperties = Dictionary.getDictionary(Const.OTHER_PROPERTIES);
102
    public static String getFromOtherPropertiesOrNull(String key) {
103
        try {
104
            return otherProperties.get(key);
105
        }
106
        catch(Exception e) {
107
            LOGError(e);
108
            return null;
109
        }
110
    }
111

    
112
    public static final String OTHERPROPS_STORAGE_API_URL = getFromOtherPropertiesOrNull("STORAGE_API_URL");
113
    public static final String OTHERPROPS_USER_CATALOGS_API_URL = getFromOtherPropertiesOrNull("USER_CATALOGS_API_URL");
114
    static {
115
        LOG("STORAGE_API_URL = ", OTHERPROPS_STORAGE_API_URL);
116
        LOG("USER_CATALOGS_API_URL = ", OTHERPROPS_USER_CATALOGS_API_URL);
117
    }
118

    
119
    public static final String STORAGE_API_URL;
120
    static {
121
        if(OTHERPROPS_STORAGE_API_URL != null) {
122
            STORAGE_API_URL = OTHERPROPS_STORAGE_API_URL;
123
        }
124
        else if(CONFIG_API_PATH != null) {
125
            STORAGE_API_URL = CONFIG_API_PATH;
126
        }
127
        else {
128
            throw new RuntimeException("Unknown STORAGE_API_URL");
129
        }
130

    
131
        LOG("Computed STORAGE_API_URL = ", STORAGE_API_URL);
132
    }
133
    public static final String USER_CATALOGS_API_URL;
134
    static {
135
        if(OTHERPROPS_USER_CATALOGS_API_URL != null) {
136
            USER_CATALOGS_API_URL = OTHERPROPS_USER_CATALOGS_API_URL;
137
        }
138
        else if(OTHERPROPS_STORAGE_API_URL != null) {
139
            throw new RuntimeException("STORAGE_API_URL is defined but USER_CATALOGS_API_URL is not");
140
        }
141
        else {
142
            // https://server.com/v1/ --> https://server.com
143
            String url = CONFIG_API_PATH;
144
            url = Helpers.stripTrailing(url, "/");
145
            url = Helpers.upToIncludingLastPart(url, "/");
146
            url = Helpers.stripTrailing(url, "/");
147
            url = url + "/user_catalogs";
148

    
149
            USER_CATALOGS_API_URL = url;
150

    
151
            LOG("Computed USER_CATALOGS_API_URL = ", USER_CATALOGS_API_URL);
152
        }
153
    }
154

    
155
    public interface Style extends CssResource {
156
        String commandAnchor();
157

    
158
        String statistics();
159

    
160
        @ClassName("gwt-HTML")
161
        String html();
162

    
163
        String uploadAlert();
164

    
165
        String uploadAlertLink();
166

    
167
        String uploadAlertProgress();
168

    
169
        String uploadAlertPercent();
170

    
171
        String uploadAlertClose();
172
    }
173

    
174
    public interface Resources extends ClientBundle {
175
        @Source("Pithos.css")
176
        Style pithosCss();
177

    
178
        @Source("gr/grnet/pithos/resources/close-popup.png")
179
        ImageResource closePopup();
180
    }
181

    
182
    public static Resources resources = GWT.create(Resources.class);
183

    
184
    /**
185
     * Instantiate an application-level image bundle. This object will provide
186
     * programmatic access to all the images needed by widgets.
187
     */
188
    static Images images = (Images) GWT.create(Images.class);
189

    
190
    public String getUserID() {
191
        return userID;
192
    }
193

    
194
    public UserCatalogs getUserCatalogs() {
195
        return userCatalogs;
196
    }
197

    
198
    public String getCurrentUserDisplayNameOrID() {
199
        final String displayName = userCatalogs.getDisplayName(getUserID());
200
        return displayName == null ? getUserID() : displayName;
201
    }
202

    
203
    public boolean hasDisplayNameForUserID(String userID) {
204
        return userCatalogs.getDisplayName(userID) != null;
205
    }
206

    
207
    public boolean hasIDForUserDisplayName(String userDisplayName) {
208
        return userCatalogs.getID(userDisplayName) != null;
209
    }
210

    
211
    public String getDisplayNameForUserID(String userID) {
212
        return userCatalogs.getDisplayName(userID);
213
    }
214

    
215
    public String getIDForUserDisplayName(String userDisplayName) {
216
        return userCatalogs.getID(userDisplayName);
217
    }
218

    
219
    public List<String> getDisplayNamesForUserIDs(List<String> userIDs) {
220
        if(userIDs == null) {
221
            userIDs = new ArrayList<String>();
222
        }
223
        final List<String> userDisplayNames = new ArrayList<String>();
224
        for(String userID : userIDs) {
225
            final String displayName = getDisplayNameForUserID(userID);
226
            userDisplayNames.add(displayName);
227
        }
228

    
229
        return userDisplayNames;
230
    }
231

    
232
    public List<String> filterUserIDsWithUnknownDisplayName(Collection<String> userIDs) {
233
        if(userIDs == null) {
234
            userIDs = new ArrayList<String>();
235
        }
236
        final List<String> filtered = new ArrayList<String>();
237
        for(String userID : userIDs) {
238
            if(!this.userCatalogs.hasID(userID)) {
239
                filtered.add(userID);
240
            }
241
        }
242
        return filtered;
243
    }
244

    
245
    public void setAccount(AccountResource acct) {
246
        account = acct;
247
    }
248

    
249
    public AccountResource getAccount() {
250
        return account;
251
    }
252

    
253
    public void updateFolder(Folder f, boolean showfiles, Command callback, final boolean openParent) {
254
        folderTreeView.updateFolder(f, showfiles, callback, openParent);
255
    }
256

    
257
    public void updateGroupNode(Group group) {
258
        groupTreeView.updateGroupNode(group);
259
    }
260

    
261
    public void updateMySharedRoot() {
262
        mysharedTreeView.updateRoot();
263
    }
264

    
265
    public void updateSharedFolder(Folder f, boolean showfiles, Command callback) {
266
        mysharedTreeView.updateFolder(f, showfiles, callback);
267
    }
268

    
269
    public void updateSharedFolder(Folder f, boolean showfiles) {
270
        updateSharedFolder(f, showfiles, null);
271
    }
272

    
273
    public void updateOtherSharedFolder(Folder f, boolean showfiles, Command callback) {
274
        otherSharedTreeView.updateFolder(f, showfiles, callback);
275
    }
276

    
277
    public MysharedTreeView getMySharedTreeView() {
278
        return mysharedTreeView;
279
    }
280

    
281
    /**
282
     * An aggregate image bundle that pulls together all the images for this
283
     * application into a single bundle.
284
     */
285
    public interface Images extends TopPanel.Images, FileList.Images, ToolsMenu.Images {
286

    
287
        @Source("gr/grnet/pithos/resources/document.png")
288
        ImageResource folders();
289

    
290
        @Source("gr/grnet/pithos/resources/advancedsettings.png")
291
        @ImageOptions(width = 32, height = 32)
292
        ImageResource tools();
293
    }
294

    
295
    private Throwable error;
296

    
297
    /**
298
     * The Application Clipboard implementation;
299
     */
300
    private Clipboard clipboard = new Clipboard();
301

    
302
    /**
303
     * The top panel that contains the menu bar.
304
     */
305
    private TopPanel topPanel;
306

    
307
    /**
308
     * The panel that contains the various system messages.
309
     */
310
    private MessagePanel messagePanel = new MessagePanel(this, Pithos.images);
311

    
312
    /**
313
     * The bottom panel that contains the status bar.
314
     */
315
    StatusPanel statusPanel = null;
316

    
317
    /**
318
     * The file list widget.
319
     */
320
    private FileList fileList;
321

    
322
    /**
323
     * The tab panel that occupies the right side of the screen.
324
     */
325
    private VerticalPanel inner = new VerticalPanel();
326

    
327

    
328
    /**
329
     * The split panel that will contain the left and right panels.
330
     */
331
    private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
332

    
333
    /**
334
     * The currently selected item in the application, for use by the Edit menu
335
     * commands. Potential types are Folder, File, User and Group.
336
     */
337
    private Object currentSelection;
338

    
339
    public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
340

    
341
    /**
342
     * The ID that uniquely identifies the user in Pithos+.
343
     * Currently this is a UUID. It used to be the user's email.
344
     */
345
    private String userID = null;
346

    
347
    /**
348
     * Holds mappings from user UUIDs to emails and vice-versa.
349
     */
350
    private UserCatalogs userCatalogs = new UserCatalogs();
351

    
352
    /**
353
     * The authentication token of the current user.
354
     */
355
    private String userToken;
356

    
357
    VerticalPanel trees;
358

    
359
    SingleSelectionModel<Folder> folderTreeSelectionModel;
360
    FolderTreeViewModel folderTreeViewModel;
361
    FolderTreeView folderTreeView;
362

    
363
    SingleSelectionModel<Folder> mysharedTreeSelectionModel;
364
    MysharedTreeViewModel mysharedTreeViewModel;
365
    MysharedTreeView mysharedTreeView = null;
366

    
367
    protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
368
    OtherSharedTreeViewModel otherSharedTreeViewModel;
369
    OtherSharedTreeView otherSharedTreeView = null;
370

    
371
    GroupTreeViewModel groupTreeViewModel;
372
    GroupTreeView groupTreeView;
373

    
374
    TreeView selectedTree;
375
    protected AccountResource account;
376

    
377
    Folder trash;
378

    
379
    List<Composite> treeViews = new ArrayList<Composite>();
380

    
381
    @SuppressWarnings("rawtypes")
382
    List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
383

    
384
    public Button upload;
385

    
386
    private HTML numOfFiles;
387

    
388
    private Toolbar toolbar;
389

    
390
    private FileUploadDialog fileUploadDialog = new FileUploadDialog(this);
391

    
392
    UploadAlert uploadAlert;
393

    
394
    Date lastModified;
395

    
396
    @Override
397
    public void onModuleLoad() {
398
        if(parseUserCredentials()) {
399
            initialize();
400
        }
401
    }
402

    
403
    static native void __ConsoleLog(String message) /*-{
404
      try { console.log(message); } catch (e) {}
405
    }-*/;
406

    
407
    public static void LOGError(Throwable error, StringBuilder sb) {
408
        if(!isLOGEnabled()) { return; }
409

    
410
        sb.append("\nException: [" + error.toString().replace("\n", "\n  ") + "]");
411
        Throwable cause = error.getCause();
412
        if(cause != null) {
413
            sb.append("\nCauses:\n");
414
            while(cause != null) {
415
                sb.append("  ");
416
                sb.append("[" + cause.toString().replace("\n", "\n  ")  + "]");
417
                sb.append("\n");
418
                cause = cause.getCause();
419
            }
420
        }
421
        else {
422
            sb.append("\n");
423
        }
424

    
425
        StackTraceElement[] stackTrace = error.getStackTrace();
426
        sb.append("Stack trace (" + stackTrace.length + " elements):\n");
427
        for(int i = 0; i < stackTrace.length; i++) {
428
            StackTraceElement errorElem = stackTrace[i];
429
            sb.append("  [" + i + "] ");
430
            sb.append(errorElem.toString());
431
            sb.append("\n");
432
        }
433
    }
434

    
435
    public static void LOGError(Throwable error) {
436
        if(!isLOGEnabled()) { return; }
437

    
438
        final StringBuilder sb = new StringBuilder();
439
        LOGError(error, sb);
440
        if(sb.length() > 0) {
441
            __ConsoleLog(sb.toString());
442
        }
443
    }
444

    
445
    public static boolean isLOGEnabled() {
446
        return IsLOGEnabled;
447
    }
448

    
449
    public static void LOG(Object ...args) {
450
        if(!isLOGEnabled()) { return; }
451

    
452
        final StringBuilder sb = new StringBuilder();
453
        for(Object arg : args) {
454
            if(arg instanceof Throwable) {
455
                LOGError((Throwable) arg, sb);
456
            }
457
            else {
458
                sb.append(arg);
459
            }
460
        }
461

    
462
        if(sb.length() > 0) {
463
            __ConsoleLog(sb.toString());
464
        }
465
    }
466

    
467
    private void initialize() {
468
        userCatalogs.updateWithIDAndName("*", "All Pithos users");
469

    
470
        lastModified = new Date(); //Initialize if-modified-since value with now.
471
        resources.pithosCss().ensureInjected();
472
        boolean bareContent = Window.Location.getParameter("noframe") != null;
473
        String contentWidth = bareContent ? Const.PERCENT_100 : Const.PERCENT_75;
474

    
475
        VerticalPanel outer = new VerticalPanel();
476
        outer.setWidth(Const.PERCENT_100);
477
        if(!bareContent) {
478
            outer.addStyleName("pithos-outer");
479
        }
480

    
481
        if(!bareContent) {
482
            topPanel = new TopPanel(this, Pithos.images);
483
            topPanel.setWidth(Const.PERCENT_100);
484
            outer.add(topPanel);
485
            outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
486
        }
487

    
488
        messagePanel.setVisible(false);
489
        outer.add(messagePanel);
490
        outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
491
        outer.setCellVerticalAlignment(messagePanel, HasVerticalAlignment.ALIGN_MIDDLE);
492

    
493
        HorizontalPanel header = new HorizontalPanel();
494
        header.addStyleName("pithos-header");
495
        header.setWidth(contentWidth);
496
        if(bareContent) {
497
            header.addStyleName("pithos-header-noframe");
498
        }
499
        upload = new Button("Upload", new ClickHandler() {
500
            @Override
501
            public void onClick(ClickEvent event) {
502
                if(getSelection() != null) {
503
                    new UploadFileCommand(Pithos.this, null, getSelection()).execute();
504
                }
505
            }
506
        });
507
        upload.addStyleName("pithos-uploadButton");
508
        header.add(upload);
509
        header.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_LEFT);
510
        header.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
511

    
512
        toolbar = new Toolbar(this);
513
        header.add(toolbar);
514
        header.setCellHorizontalAlignment(toolbar, HasHorizontalAlignment.ALIGN_CENTER);
515
        header.setCellVerticalAlignment(toolbar, HasVerticalAlignment.ALIGN_MIDDLE);
516

    
517
        HorizontalPanel folderStatistics = new HorizontalPanel();
518
        folderStatistics.addStyleName("pithos-folderStatistics");
519
        numOfFiles = new HTML();
520
        folderStatistics.add(numOfFiles);
521
        folderStatistics.setCellVerticalAlignment(numOfFiles, HasVerticalAlignment.ALIGN_MIDDLE);
522
        HTML numOfFilesLabel = new HTML("&nbsp;Files");
523
        folderStatistics.add(numOfFilesLabel);
524
        folderStatistics.setCellVerticalAlignment(numOfFilesLabel, HasVerticalAlignment.ALIGN_MIDDLE);
525
        header.add(folderStatistics);
526
        header.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
527
        header.setCellVerticalAlignment(folderStatistics, HasVerticalAlignment.ALIGN_MIDDLE);
528
        header.setCellWidth(folderStatistics, "40px");
529
        outer.add(header);
530
        outer.setCellHorizontalAlignment(header, HasHorizontalAlignment.ALIGN_CENTER);
531
        // Inner contains the various lists
532
        inner.sinkEvents(Event.ONCONTEXTMENU);
533
        inner.setWidth(Const.PERCENT_100);
534

    
535
        folderTreeSelectionModel = new SingleSelectionModel<Folder>();
536
        folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
537
            @Override
538
            public void onSelectionChange(SelectionChangeEvent event) {
539
                if(folderTreeSelectionModel.getSelectedObject() != null) {
540
                    deselectOthers(folderTreeView, folderTreeSelectionModel);
541
                    applyPermissions(folderTreeSelectionModel.getSelectedObject());
542
                    Folder f = folderTreeSelectionModel.getSelectedObject();
543
                    updateFolder(f, true, new Command() {
544

    
545
                        @Override
546
                        public void execute() {
547
                            updateStatistics();
548
                        }
549
                    }, true);
550
                    showRelevantToolbarButtons();
551
                }
552
                else {
553
                    if(getSelectedTree().equals(folderTreeView)) {
554
                        setSelectedTree(null);
555
                    }
556
                    if(getSelectedTree() == null) {
557
                        showRelevantToolbarButtons();
558
                    }
559
                }
560
            }
561
        });
562
        selectionModels.add(folderTreeSelectionModel);
563

    
564
        folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
565
        folderTreeView = new FolderTreeView(folderTreeViewModel);
566
        treeViews.add(folderTreeView);
567

    
568
        fileList = new FileList(this, images);
569
        inner.add(fileList);
570

    
571
        trees = new VerticalPanel();
572
        trees.setWidth(Const.PERCENT_100);
573

    
574
        // Add the left and right panels to the split panel.
575
        splitPanel.setLeftWidget(trees);
576
        FlowPanel right = new FlowPanel();
577
        right.getElement().setId("rightPanel");
578
        right.add(inner);
579
        splitPanel.setRightWidget(right);
580
        splitPanel.setSplitPosition("219px");
581
        splitPanel.setSize(Const.PERCENT_100, Const.PERCENT_100);
582
        splitPanel.addStyleName("pithos-splitPanel");
583
        splitPanel.setWidth(contentWidth);
584
        outer.add(splitPanel);
585
        outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
586

    
587
        if(!bareContent) {
588
            statusPanel = new StatusPanel();
589
            statusPanel.setWidth(Const.PERCENT_100);
590
            outer.add(statusPanel);
591
            outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
592
        }
593
        else {
594
            splitPanel.addStyleName("pithos-splitPanel-noframe");
595
        }
596

    
597
        // Hook the window resize event, so that we can adjust the UI.
598
        Window.addResizeHandler(this);
599
        // Clear out the window's built-in margin, because we want to take
600
        // advantage of the entire client area.
601
        Window.setMargin("0px");
602
        // Finally, add the outer panel to the RootPanel, so that it will be
603
        // displayed.
604
        RootPanel.get().add(outer);
605
        // Call the window resized handler to get the initial sizes setup. Doing
606
        // this in a deferred command causes it to occur after all widgets'
607
        // sizes have been computed by the browser.
608
        Scheduler.get().scheduleIncremental(new RepeatingCommand() {
609

    
610
            @Override
611
            public boolean execute() {
612
                if(!isCloudbarReady()) {
613
                    return true;
614
                }
615
                onWindowResized(Window.getClientHeight());
616
                return false;
617
            }
618
        });
619

    
620
        Scheduler.get().scheduleDeferred(new ScheduledCommand() {
621
            @Override
622
            public void execute() {
623
                LOG("Pithos::initialize() Calling Pithos::fetchAccount()");
624
                fetchAccount(new Command() {
625

    
626
                    @Override
627
                    public void execute() {
628
                        if(!account.hasHomeContainer()) {
629
                            createHomeContainer(account, this);
630
                        }
631
                        else if(!account.hasTrashContainer()) {
632
                            createTrashContainer(this);
633
                        }
634
                        else {
635
                            for(Folder f : account.getContainers()) {
636
                                if(f.getName().equals(Const.TRASH_CONTAINER)) {
637
                                    trash = f;
638
                                    break;
639
                                }
640
                            }
641
                            trees.add(folderTreeView);
642
                            folderTreeViewModel.initialize(account, new Command() {
643

    
644
                                @Override
645
                                public void execute() {
646
                                    createMySharedTree();
647
                                }
648
                            });
649

    
650
                            HorizontalPanel separator = new HorizontalPanel();
651
                            separator.addStyleName("pithos-statisticsSeparator");
652
                            separator.add(new HTML(""));
653
                            trees.add(separator);
654

    
655
                            groupTreeViewModel = new GroupTreeViewModel(Pithos.this);
656
                            groupTreeView = new GroupTreeView(groupTreeViewModel);
657
                            treeViews.add(groupTreeView);
658
                            trees.add(groupTreeView);
659
                            folderTreeView.showStatistics(account);
660
                        }
661
                    }
662
                });
663
            }
664
        });
665
    }
666

    
667
    public void scheduleResfresh() {
668
        Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {
669

    
670
            @Override
671
            public boolean execute() {
672
                final Folder f = getSelection();
673
                if(f == null) {
674
                    return true;
675
                }
676

    
677
                HeadRequest<Folder> head = new HeadRequest<Folder>(Folder.class, getStorageAPIURL(), f.getOwnerID(), "/" + f.getContainer()) {
678

    
679
                    @Override
680
                    public void onSuccess(Folder _result) {
681
                        lastModified = new Date();
682
                        if(getSelectedTree().equals(folderTreeView)) {
683
                            updateFolder(f, true, new Command() {
684

    
685
                                @Override
686
                                public void execute() {
687
                                    scheduleResfresh();
688
                                }
689

    
690
                            }, false);
691
                        }
692
                        else if(getSelectedTree().equals(mysharedTreeView)) {
693
                            updateSharedFolder(f, true, new Command() {
694

    
695
                                @Override
696
                                public void execute() {
697
                                    scheduleResfresh();
698
                                }
699
                            });
700
                        }
701
                        else {
702
                            scheduleResfresh();
703
                        }
704
                    }
705

    
706
                    @Override
707
                    public void onError(Throwable t) {
708
                        if(t instanceof RestException && ((RestException) t).getHttpStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
709
                            scheduleResfresh();
710
                        }
711
                        else if(retries >= MAX_RETRIES) {
712
                            LOG("Error heading folder. ", t);
713
                            setError(t);
714
                            if(t instanceof RestException) {
715
                                displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
716
                            }
717
                            else {
718
                                displayError("System error heading folder: " + t.getMessage());
719
                            }
720
                        }
721
                        else {//retry
722
                            LOG("Retry ", retries);
723
                            Scheduler.get().scheduleDeferred(this);
724
                        }
725
                    }
726

    
727
                    @Override
728
                    protected void onUnauthorized(Response response) {
729
                        if(retries >= MAX_RETRIES) {
730
                            sessionExpired();
731
                        }
732
                        else //retry
733
                        {
734
                            Scheduler.get().scheduleDeferred(this);
735
                        }
736
                    }
737
                };
738
                head.setHeader(Const.X_AUTH_TOKEN, getUserToken());
739
                head.setHeader(Const.IF_MODIFIED_SINCE, DateTimeFormat.getFormat(Const.DATE_FORMAT_1).format(lastModified, TimeZone.createTimeZone(0)) + " GMT");
740
                Scheduler.get().scheduleDeferred(head);
741

    
742
                return false;
743
            }
744
        }, 3000);
745
    }
746

    
747
    public void applyPermissions(Folder f) {
748
        if(f != null) {
749
            if(f.isInTrash()) {
750
                upload.setEnabled(false);
751
                disableUploadArea();
752
            }
753
            else {
754
                Boolean[] perms = f.getPermissions().get(userID);
755
                if(f.getOwnerID().equals(userID) || (perms != null && perms[1] != null && perms[1])) {
756
                    upload.setEnabled(true);
757
                    enableUploadArea();
758
                }
759
                else {
760
                    upload.setEnabled(false);
761
                    disableUploadArea();
762
                }
763
            }
764
        }
765
        else {
766
            upload.setEnabled(false);
767
            disableUploadArea();
768
        }
769
    }
770

    
771
    @SuppressWarnings({"rawtypes", "unchecked"})
772
    public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
773
        selectedTree = _selectedTree;
774

    
775
        for(SingleSelectionModel s : selectionModels) {
776
            if(!s.equals(model) && s.getSelectedObject() != null) {
777
                s.setSelected(s.getSelectedObject(), false);
778
            }
779
        }
780
    }
781

    
782
    public void showFiles(final Folder f) {
783
        Set<File> files = f.getFiles();
784
        showFiles(files);
785
    }
786

    
787
    public void showFiles(Set<File> files) {
788
        fileList.setFiles(new ArrayList<File>(files));
789
    }
790

    
791
    /**
792
     * Parse and store the user credentials to the appropriate fields.
793
     */
794
    private boolean parseUserCredentials() {
795
        final String cookie = otherProperties.get(Const.AUTH_COOKIE);
796
        String auth = Cookies.getCookie(cookie);
797
        if(auth == null) {
798
            authenticateUser();
799
            return false;
800
        }
801
        if(auth.startsWith("\"")) {
802
            auth = auth.substring(1);
803
        }
804
        if(auth.endsWith("\"")) {
805
            auth = auth.substring(0, auth.length() - 1);
806
        }
807
        String[] authSplit = auth.split("\\" + config.cookieSeparator(), 2);
808
        if(authSplit.length != 2) {
809
            authenticateUser();
810
            return false;
811
        }
812
        this.userID = authSplit[0];
813
        this.userToken = authSplit[1];
814

    
815
        String gotoUrl = Window.Location.getParameter("goto");
816
        if(gotoUrl != null && gotoUrl.length() > 0) {
817
            Window.Location.assign(gotoUrl);
818
            return false;
819
        }
820
        return true;
821
    }
822

    
823
    /**
824
     * Redirect the user to the login page for authentication.
825
     */
826
    protected void authenticateUser() {
827
        Dictionary otherProperties = Dictionary.getDictionary(Const.OTHER_PROPERTIES);
828
        Window.Location.assign(otherProperties.get(Const.LOGIN_URL) + Window.Location.getHref());
829
    }
830

    
831
    public void fetchAccount(final Command callback) {
832
        String path = "?format=json";
833

    
834
        GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getStorageAPIURL(), userID, path) {
835
            @Override
836
            public void onSuccess(AccountResource accountResource) {
837
                account = accountResource;
838
                if(callback != null) {
839
                    callback.execute();
840
                }
841

    
842
                final List<String> memberIDs = new ArrayList<String>();
843
                final List<Group> groups = account.getGroups();
844
                for(Group group : groups) {
845
                    memberIDs.addAll(group.getMemberIDs());
846
                }
847
                memberIDs.add(Pithos.this.getUserID());
848

    
849
                final List<String> theUnknown = Pithos.this.filterUserIDsWithUnknownDisplayName(memberIDs);
850
                // Initialize the user catalog
851
                new UpdateUserCatalogs(Pithos.this, theUnknown).scheduleDeferred();
852
                LOG("Called new UpdateUserCatalogs(Pithos.this, theUnknown).scheduleDeferred();");
853
            }
854

    
855
            @Override
856
            public void onError(Throwable t) {
857
                LOG("Error getting account", t);
858
                setError(t);
859
                if(t instanceof RestException) {
860
                    displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
861
                }
862
                else {
863
                    displayError("System error fetching user data: " + t.getMessage());
864
                }
865
            }
866

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

    
876
    public void updateStatistics() {
877
        HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getStorageAPIURL(), userID, "", account) {
878

    
879
            @Override
880
            public void onSuccess(AccountResource _result) {
881
                folderTreeView.showStatistics(account);
882
            }
883

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

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

    
905
    protected void createHomeContainer(final AccountResource _account, final Command callback) {
906
        String path = "/" + Const.HOME_CONTAINER;
907
        PutRequest createPithos = new PutRequest(getStorageAPIURL(), getUserID(), path) {
908
            @Override
909
            public void onSuccess(Resource result) {
910
                if(!_account.hasTrashContainer()) {
911
                    createTrashContainer(callback);
912
                }
913
                else {
914
                    fetchAccount(callback);
915
                }
916
            }
917

    
918
            @Override
919
            public void onError(Throwable t) {
920
                LOG("Error creating pithos", t);
921
                setError(t);
922
                if(t instanceof RestException) {
923
                    displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
924
                }
925
                else {
926
                    displayError("System error Error creating pithos: " + t.getMessage());
927
                }
928
            }
929

    
930
            @Override
931
            protected void onUnauthorized(Response response) {
932
                sessionExpired();
933
            }
934
        };
935
        createPithos.setHeader(Const.X_AUTH_TOKEN, getUserToken());
936
        Scheduler.get().scheduleDeferred(createPithos);
937
    }
938

    
939
    protected void createTrashContainer(final Command callback) {
940
        String path = "/" + Const.TRASH_CONTAINER;
941
        PutRequest createPithos = new PutRequest(getStorageAPIURL(), getUserID(), path) {
942
            @Override
943
            public void onSuccess(Resource result) {
944
                fetchAccount(callback);
945
            }
946

    
947
            @Override
948
            public void onError(Throwable t) {
949
                LOG("Error creating pithos", t);
950
                setError(t);
951
                if(t instanceof RestException) {
952
                    displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
953
                }
954
                else {
955
                    displayError("System error Error creating pithos: " + t.getMessage());
956
                }
957
            }
958

    
959
            @Override
960
            protected void onUnauthorized(Response response) {
961
                sessionExpired();
962
            }
963
        };
964
        createPithos.setHeader(Const.X_AUTH_TOKEN, getUserToken());
965
        Scheduler.get().scheduleDeferred(createPithos);
966
    }
967

    
968
    /**
969
     * Creates an HTML fragment that places an image & caption together, for use
970
     * in a group header.
971
     *
972
     * @param imageProto an image prototype for an image
973
     * @param caption    the group caption
974
     * @return the header HTML fragment
975
     */
976
    private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
977
        String captionHTML = "<table class='caption' cellpadding='0' "
978
            + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
979
            + "</td><td id =" + caption + " class='rcaption'><b style='white-space:nowrap'>&nbsp;"
980
            + caption + "</b></td></tr></table>";
981
        return captionHTML;
982
    }
983

    
984
    protected void onWindowResized(int height) {
985
        // Adjust the split panel to take up the available room in the window.
986
        int newHeight = height - splitPanel.getAbsoluteTop() - 153;
987
        if(newHeight < 1) {
988
            newHeight = 1;
989
        }
990
        splitPanel.setHeight("" + newHeight);
991
        inner.setHeight("" + newHeight);
992
    }
993

    
994
    native boolean isCloudbarReady()/*-{
995
      if ($wnd.$("div.cloudbar") && $wnd.$("div.cloudbar").height() > 0)
996
        return true;
997
      return false;
998
    }-*/;
999

    
1000
    @Override
1001
    public void onResize(ResizeEvent event) {
1002
        int height = event.getHeight();
1003
        onWindowResized(height);
1004
    }
1005

    
1006
    /**
1007
     * Display an error message.
1008
     *
1009
     * @param msg the message to display
1010
     */
1011
    public void displayError(String msg) {
1012
        messagePanel.displayError(msg);
1013
        onWindowResized(Window.getClientHeight());
1014
    }
1015

    
1016
    /**
1017
     * Display a warning message.
1018
     *
1019
     * @param msg the message to display
1020
     */
1021
    public void displayWarning(String msg) {
1022
        messagePanel.displayWarning(msg);
1023
        onWindowResized(Window.getClientHeight());
1024
    }
1025

    
1026
    /**
1027
     * Display an informational message.
1028
     *
1029
     * @param msg the message to display
1030
     */
1031
    public void displayInformation(String msg) {
1032
        messagePanel.displayInformation(msg);
1033
        onWindowResized(Window.getClientHeight());
1034
    }
1035

    
1036
    /**
1037
     * Retrieve the fileList.
1038
     *
1039
     * @return the fileList
1040
     */
1041
    public FileList getFileList() {
1042
        return fileList;
1043
    }
1044

    
1045
    /**
1046
     * Retrieve the topPanel.
1047
     *
1048
     * @return the topPanel
1049
     */
1050
    TopPanel getTopPanel() {
1051
        return topPanel;
1052
    }
1053

    
1054
    /**
1055
     * Retrieve the clipboard.
1056
     *
1057
     * @return the clipboard
1058
     */
1059
    public Clipboard getClipboard() {
1060
        return clipboard;
1061
    }
1062

    
1063
    public StatusPanel getStatusPanel() {
1064
        return statusPanel;
1065
    }
1066

    
1067
    public String getUserToken() {
1068
        return userToken;
1069
    }
1070

    
1071
    public static native void preventIESelection() /*-{
1072
      $doc.body.onselectstart = function () {
1073
        return false;
1074
      };
1075
    }-*/;
1076

    
1077
    public static native void enableIESelection() /*-{
1078
      if ($doc.body.onselectstart != null)
1079
        $doc.body.onselectstart = null;
1080
    }-*/;
1081

    
1082
    public static String getStorageAPIURL() {
1083
        return STORAGE_API_URL;
1084
    }
1085

    
1086
    public static String getUserCatalogsURL() {
1087
        return USER_CATALOGS_API_URL;
1088
    }
1089

    
1090
    /**
1091
     * History support for folder navigation
1092
     * adds a new browser history entry
1093
     *
1094
     * @param key
1095
     */
1096
    public void updateHistory(String key) {
1097
//                Replace any whitespace of the initial string to "+"
1098
//                String result = key.replaceAll("\\s","+");
1099
//                Add a new browser history entry.
1100
//                History.newItem(result);
1101
        History.newItem(key);
1102
    }
1103

    
1104
    public void deleteFolder(final Folder folder, final Command callback) {
1105
        final PleaseWaitPopup pwp = new PleaseWaitPopup();
1106
        pwp.center();
1107
        String path = "/" + folder.getContainer() + "/" + folder.getPrefix() + "?delimiter=/" + "&t=" + System.currentTimeMillis();
1108
        DeleteRequest deleteFolder = new DeleteRequest(getStorageAPIURL(), folder.getOwnerID(), path) {
1109

    
1110
            @Override
1111
            protected void onUnauthorized(Response response) {
1112
                pwp.hide();
1113
                sessionExpired();
1114
            }
1115

    
1116
            @Override
1117
            public void onSuccess(Resource result) {
1118
                updateFolder(folder.getParent(), true, new Command() {
1119

    
1120
                    @Override
1121
                    public void execute() {
1122
                        folderTreeSelectionModel.setSelected(folder.getParent(), true);
1123
                        updateStatistics();
1124
                        if(callback != null) {
1125
                            callback.execute();
1126
                        }
1127
                        pwp.hide();
1128
                    }
1129
                }, true);
1130
            }
1131

    
1132
            @Override
1133
            public void onError(Throwable t) {
1134
                LOG(t);
1135
                setError(t);
1136
                if(t instanceof RestException) {
1137
                    if(((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND) {
1138
                        displayError("Unable to delete folder: " + ((RestException) t).getHttpStatusText());
1139
                    }
1140
                    else {
1141
                        onSuccess(null);
1142
                    }
1143
                }
1144
                else {
1145
                    displayError("System error unable to delete folder: " + t.getMessage());
1146
                }
1147
                pwp.hide();
1148
            }
1149
        };
1150
        deleteFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1151
        Scheduler.get().scheduleDeferred(deleteFolder);
1152
    }
1153

    
1154
    public FolderTreeView getFolderTreeView() {
1155
        return folderTreeView;
1156
    }
1157

    
1158
    public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
1159
        if(iter.hasNext()) {
1160
            File file = iter.next();
1161
            String path = targetUri + "/" + file.getName();
1162
            PutRequest copyFile = new PutRequest(getStorageAPIURL(), targetUsername, path) {
1163
                @Override
1164
                public void onSuccess(Resource result) {
1165
                    copyFiles(iter, targetUsername, targetUri, callback);
1166
                }
1167

    
1168
                @Override
1169
                public void onError(Throwable t) {
1170
                    LOG(t);
1171
                    setError(t);
1172
                    if(t instanceof RestException) {
1173
                        displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
1174
                    }
1175
                    else {
1176
                        displayError("System error unable to copy file: " + t.getMessage());
1177
                    }
1178
                }
1179

    
1180
                @Override
1181
                protected void onUnauthorized(Response response) {
1182
                    sessionExpired();
1183
                }
1184
            };
1185
            copyFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1186
            copyFile.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(file.getUri()));
1187
            if(!file.getOwnerID().equals(targetUsername)) {
1188
                copyFile.setHeader(Const.X_SOURCE_ACCOUNT, URL.encodePathSegment(file.getOwnerID()));
1189
            }
1190
            copyFile.setHeader(Const.CONTENT_TYPE, file.getContentType());
1191
            Scheduler.get().scheduleDeferred(copyFile);
1192
        }
1193
        else if(callback != null) {
1194
            callback.execute();
1195
        }
1196
    }
1197

    
1198
    public void copyFolder(final Folder f, final String targetUsername, final String targetUri, boolean move, final Command callback) {
1199
        String path = targetUri + "?delimiter=/";
1200
        PutRequest copyFolder = new PutRequest(getStorageAPIURL(), targetUsername, path) {
1201
            @Override
1202
            public void onSuccess(Resource result) {
1203
                if(callback != null) {
1204
                    callback.execute();
1205
                }
1206
            }
1207

    
1208
            @Override
1209
            public void onError(Throwable t) {
1210
                LOG(t);
1211
                setError(t);
1212
                if(t instanceof RestException) {
1213
                    displayError("Unable to copy folder: " + ((RestException) t).getHttpStatusText());
1214
                }
1215
                else {
1216
                    displayError("System error copying folder: " + t.getMessage());
1217
                }
1218
            }
1219

    
1220
            @Override
1221
            protected void onUnauthorized(Response response) {
1222
                sessionExpired();
1223
            }
1224
        };
1225
        copyFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1226
        copyFolder.setHeader(Const.ACCEPT, "*/*");
1227
        copyFolder.setHeader(Const.CONTENT_LENGTH, "0");
1228
        copyFolder.setHeader(Const.CONTENT_TYPE, "application/directory");
1229
        if(!f.getOwnerID().equals(targetUsername)) {
1230
            copyFolder.setHeader(Const.X_SOURCE_ACCOUNT, f.getOwnerID());
1231
        }
1232
        if(move) {
1233
            copyFolder.setHeader(Const.X_MOVE_FROM, URL.encodePathSegment(f.getUri()));
1234
        }
1235
        else {
1236
            copyFolder.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(f.getUri()));
1237
        }
1238
        Scheduler.get().scheduleDeferred(copyFolder);
1239
    }
1240

    
1241
    public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1242
        selectionModels.add(model);
1243
    }
1244

    
1245
    public OtherSharedTreeView getOtherSharedTreeView() {
1246
        return otherSharedTreeView;
1247
    }
1248

    
1249
    public void updateTrash(boolean showFiles, Command callback) {
1250
        updateFolder(trash, showFiles, callback, true);
1251
    }
1252

    
1253
    public void updateGroupsNode() {
1254
        groupTreeView.updateGroupNode(null);
1255
    }
1256

    
1257
    public Group addGroup(String groupname) {
1258
        Group newGroup = new Group(groupname);
1259
        account.addGroup(newGroup);
1260
        groupTreeView.updateGroupNode(null);
1261
        return newGroup;
1262
    }
1263

    
1264
    public void removeGroup(Group group) {
1265
        account.removeGroup(group);
1266
        updateGroupsNode();
1267
    }
1268

    
1269
    public TreeView getSelectedTree() {
1270
        return selectedTree;
1271
    }
1272

    
1273
    public void setSelectedTree(TreeView selected) {
1274
        selectedTree = selected;
1275
    }
1276

    
1277
    public Folder getSelection() {
1278
        if(selectedTree != null) {
1279
            return selectedTree.getSelection();
1280
        }
1281
        return null;
1282
    }
1283

    
1284
    public void showFolderStatistics(int folderFileCount) {
1285
        numOfFiles.setHTML(String.valueOf(folderFileCount));
1286
    }
1287

    
1288
    public GroupTreeView getGroupTreeView() {
1289
        return groupTreeView;
1290
    }
1291

    
1292
    public void sessionExpired() {
1293
        new SessionExpiredDialog(this).center();
1294
    }
1295

    
1296
    public void updateRootFolder(Command callback) {
1297
        updateFolder(account.getPithos(), false, callback, true);
1298
    }
1299

    
1300
    void createMySharedTree() {
1301
        LOG("Pithos::createMySharedTree()");
1302
        mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1303
        mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1304
            @Override
1305
            public void onSelectionChange(SelectionChangeEvent event) {
1306
                if(mysharedTreeSelectionModel.getSelectedObject() != null) {
1307
                    deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1308
                    upload.setEnabled(false);
1309
                    disableUploadArea();
1310
                    updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1311
                    showRelevantToolbarButtons();
1312
                }
1313
                else {
1314
                    if(getSelectedTree().equals(mysharedTreeView)) {
1315
                        setSelectedTree(null);
1316
                    }
1317
                    if(getSelectedTree() == null) {
1318
                        showRelevantToolbarButtons();
1319
                    }
1320
                }
1321
            }
1322
        });
1323
        selectionModels.add(mysharedTreeSelectionModel);
1324
        mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1325
        mysharedTreeViewModel.initialize(new Command() {
1326

    
1327
            @Override
1328
            public void execute() {
1329
                mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1330
                trees.insert(mysharedTreeView, 2);
1331
                treeViews.add(mysharedTreeView);
1332
                createOtherSharedTree();
1333
            }
1334
        });
1335
    }
1336

    
1337
    void createOtherSharedTree() {
1338
        LOG("Pithos::createOtherSharedTree()");
1339
        otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1340
        otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1341
            @Override
1342
            public void onSelectionChange(SelectionChangeEvent event) {
1343
                if(otherSharedTreeSelectionModel.getSelectedObject() != null) {
1344
                    deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1345
                    applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1346
                    updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true, null);
1347
                    showRelevantToolbarButtons();
1348
                }
1349
                else {
1350
                    if(getSelectedTree().equals(otherSharedTreeView)) {
1351
                        setSelectedTree(null);
1352
                    }
1353
                    if(getSelectedTree() == null) {
1354
                        showRelevantToolbarButtons();
1355
                    }
1356
                }
1357
            }
1358
        });
1359
        selectionModels.add(otherSharedTreeSelectionModel);
1360
        otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1361
        // #3784 We show it empty...
1362
        otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel, true);
1363
        trees.insert(otherSharedTreeView, 1);
1364

    
1365
        LOG("Pithos::createOtherSharedTree(), initializing otherSharedTreeViewModel with a callback");
1366
        otherSharedTreeViewModel.initialize(new Command() {
1367
            @Override
1368
            public void execute() {
1369
                // #3784 ... then remove the empty stuff and add a new view with the populated model
1370
                trees.remove(otherSharedTreeView);
1371

    
1372
                otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel, false);
1373
                trees.insert(otherSharedTreeView, 1);
1374
                treeViews.add(otherSharedTreeView);
1375
                scheduleResfresh();
1376
            }
1377
        });
1378
    }
1379

    
1380
    public String getErrorData() {
1381
        final StringBuilder sb = new StringBuilder();
1382
        final String NL = Const.NL;
1383
        Throwable t = this.error;
1384
        while(t != null) {
1385
            sb.append(t.toString());
1386
            sb.append(NL);
1387
            StackTraceElement[] traces = t.getStackTrace();
1388
            for(StackTraceElement trace : traces) {
1389
                sb.append("  [");
1390
                sb.append(trace.getClassName());
1391
                sb.append("::");
1392
                sb.append(trace.getMethodName());
1393
                sb.append("() at ");
1394
                sb.append(trace.getFileName());
1395
                sb.append(":");
1396
                sb.append(trace.getLineNumber());
1397
                sb.append("]");
1398
                sb.append(NL);
1399
            }
1400
            t = t.getCause();
1401
        }
1402

    
1403
        return sb.toString();
1404
    }
1405

    
1406
    public void setError(Throwable t) {
1407
        error = t;
1408
        LOG(t);
1409
    }
1410

    
1411
    public void showRelevantToolbarButtons() {
1412
        toolbar.showRelevantButtons();
1413
    }
1414

    
1415
    public FileUploadDialog getFileUploadDialog() {
1416
        if(fileUploadDialog == null) {
1417
            fileUploadDialog = new FileUploadDialog(this);
1418
        }
1419
        return fileUploadDialog;
1420
    }
1421

    
1422
    public void hideUploadIndicator() {
1423
        upload.removeStyleName("pithos-uploadButton-loading");
1424
        upload.setTitle("");
1425
    }
1426

    
1427
    public void showUploadIndicator() {
1428
        upload.addStyleName("pithos-uploadButton-loading");
1429
        upload.setTitle("Upload in progress. Click for details.");
1430
    }
1431

    
1432
    public void scheduleFolderHeadCommand(final Folder folder, final Command callback) {
1433
        if(folder == null) {
1434
            if(callback != null) {
1435
                callback.execute();
1436
            }
1437
        }
1438
        else {
1439
            HeadRequest<Folder> headFolder = new HeadRequest<Folder>(Folder.class, getStorageAPIURL(), folder.getOwnerID(), folder.getUri(), folder) {
1440

    
1441
                @Override
1442
                public void onSuccess(Folder _result) {
1443
                    if(callback != null) {
1444
                        callback.execute();
1445
                    }
1446
                }
1447

    
1448
                @Override
1449
                public void onError(Throwable t) {
1450
                    if(t instanceof RestException) {
1451
                        if(((RestException) t).getHttpStatusCode() == Response.SC_NOT_FOUND) {
1452
                            final String path = folder.getUri();
1453
                            PutRequest newFolder = new PutRequest(getStorageAPIURL(), folder.getOwnerID(), path) {
1454
                                @Override
1455
                                public void onSuccess(Resource _result) {
1456
                                    scheduleFolderHeadCommand(folder, callback);
1457
                                }
1458

    
1459
                                @Override
1460
                                public void onError(Throwable _t) {
1461
                                    setError(_t);
1462
                                    if(_t instanceof RestException) {
1463
                                        displayError("Unable to create folder: " + ((RestException) _t).getHttpStatusText());
1464
                                    }
1465
                                    else {
1466
                                        displayError("System error creating folder: " + _t.getMessage());
1467
                                    }
1468
                                }
1469

    
1470
                                @Override
1471
                                protected void onUnauthorized(Response response) {
1472
                                    sessionExpired();
1473
                                }
1474
                            };
1475
                            newFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1476
                            newFolder.setHeader(Const.CONTENT_TYPE, "application/folder");
1477
                            newFolder.setHeader(Const.ACCEPT, "*/*");
1478
                            newFolder.setHeader(Const.CONTENT_LENGTH, "0");
1479
                            Scheduler.get().scheduleDeferred(newFolder);
1480
                        }
1481
                        else if(((RestException) t).getHttpStatusCode() == Response.SC_FORBIDDEN) {
1482
                            onSuccess(folder);
1483
                        }
1484
                        else {
1485
                            displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
1486
                        }
1487
                    }
1488
                    else {
1489
                        displayError("System error heading folder: " + t.getMessage());
1490
                    }
1491

    
1492
                    LOG("Error heading folder", t);
1493
                    setError(t);
1494
                }
1495

    
1496
                @Override
1497
                protected void onUnauthorized(Response response) {
1498
                    sessionExpired();
1499
                }
1500
            };
1501
            headFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1502
            Scheduler.get().scheduleDeferred(headFolder);
1503
        }
1504
    }
1505

    
1506
    public void scheduleFileHeadCommand(File f, final Command callback) {
1507
        HeadRequest<File> headFile = new HeadRequest<File>(File.class, getStorageAPIURL(), f.getOwnerID(), f.getUri(), f) {
1508

    
1509
            @Override
1510
            public void onSuccess(File _result) {
1511
                if(callback != null) {
1512
                    callback.execute();
1513
                }
1514
            }
1515

    
1516
            @Override
1517
            public void onError(Throwable t) {
1518
                LOG("Error heading file", t);
1519
                setError(t);
1520
                if(t instanceof RestException) {
1521
                    displayError("Error heading file: " + ((RestException) t).getHttpStatusText());
1522
                }
1523
                else {
1524
                    displayError("System error heading file: " + t.getMessage());
1525
                }
1526
            }
1527

    
1528
            @Override
1529
            protected void onUnauthorized(Response response) {
1530
                sessionExpired();
1531
            }
1532
        };
1533
        headFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1534
        Scheduler.get().scheduleDeferred(headFile);
1535
    }
1536

    
1537
    public boolean isMySharedSelected() {
1538
        return getSelectedTree().equals(getMySharedTreeView());
1539
    }
1540

    
1541
    private Folder getUploadFolder() {
1542
        if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1543
            return getSelection();
1544
        }
1545
        return null;
1546
    }
1547

    
1548
    private void updateUploadFolder() {
1549
        updateUploadFolder(null);
1550
    }
1551

    
1552
    private void updateUploadFolder(final JsArrayString urls) {
1553
        if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1554
            Folder f = getSelection();
1555
            if(getSelectedTree().equals(getFolderTreeView())) {
1556
                updateFolder(f, true, new Command() {
1557

    
1558
                    @Override
1559
                    public void execute() {
1560
                        updateStatistics();
1561
                        if(urls != null) {
1562
                            selectUploadedFiles(urls);
1563
                        }
1564
                    }
1565
                }, false);
1566
            }
1567
            else {
1568
                updateOtherSharedFolder(f, true, null);
1569
            }
1570
        }
1571
    }
1572

    
1573
    public native void disableUploadArea() /*-{
1574
      var uploader = $wnd.$("#uploader").pluploadQueue();
1575
      var dropElm = $wnd.document.getElementById('rightPanel');
1576
      $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1577
    }-*/;
1578

    
1579
    public native void enableUploadArea() /*-{
1580
      var uploader = $wnd.$("#uploader").pluploadQueue();
1581
      var dropElm = $wnd.document.getElementById('rightPanel');
1582
      $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1583
      if (uploader.runtime == 'html5') {
1584
        uploader.settings.drop_element = 'rightPanel';
1585
        uploader.trigger('PostInit');
1586
      }
1587
    }-*/;
1588

    
1589
    public void showUploadAlert(int nOfFiles) {
1590
        if(uploadAlert == null) {
1591
            uploadAlert = new UploadAlert(this, nOfFiles);
1592
        }
1593
        if(!uploadAlert.isShowing()) {
1594
            uploadAlert.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
1595

    
1596
                @Override
1597
                public void setPosition(int offsetWidth, int offsetHeight) {
1598
                    uploadAlert.setPopupPosition((Window.getClientWidth() - offsetWidth) / 2, statusPanel.getAbsoluteTop() - offsetHeight);
1599
                }
1600
            });
1601
        }
1602
        uploadAlert.setNumOfFiles(nOfFiles);
1603
    }
1604

    
1605
    public void hideUploadAlert() {
1606
        if(uploadAlert != null && uploadAlert.isShowing()) {
1607
            uploadAlert.hide();
1608
        }
1609
    }
1610

    
1611
    public void selectUploadedFiles(JsArrayString urls) {
1612
        List<String> selectedUrls = new ArrayList<String>();
1613
        for(int i = 0; i < urls.length(); i++) {
1614
            selectedUrls.add(urls.get(i));
1615
        }
1616
        fileList.selectByUrl(selectedUrls);
1617
    }
1618

    
1619
    public void purgeContainer(final Folder container) {
1620
        String path = "/" + container.getName() + "?delimiter=/";
1621
        DeleteRequest delete = new DeleteRequest(getStorageAPIURL(), getUserID(), path) {
1622

    
1623
            @Override
1624
            protected void onUnauthorized(Response response) {
1625
                sessionExpired();
1626
            }
1627

    
1628
            @Override
1629
            public void onSuccess(Resource result) {
1630
                updateFolder(container, true, null, true);
1631
            }
1632

    
1633
            @Override
1634
            public void onError(Throwable t) {
1635
                LOG("Error deleting trash", t);
1636
                setError(t);
1637
                if(t instanceof RestException) {
1638
                    displayError("Error deleting trash: " + ((RestException) t).getHttpStatusText());
1639
                }
1640
                else {
1641
                    displayError("System error deleting trash: " + t.getMessage());
1642
                }
1643
            }
1644
        };
1645
        delete.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1646
        Scheduler.get().scheduleDeferred(delete);
1647
    }
1648
}