Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (54 kB)

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

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

    
75
import java.util.*;
76

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

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

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

    
87
        String statistics();
88

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

    
92
        String uploadAlert();
93

    
94
        String uploadAlertLink();
95

    
96
        String uploadAlertProgress();
97

    
98
        String uploadAlertPercent();
99

    
100
        String uploadAlertClose();
101
    }
102

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

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

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

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

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

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

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

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

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

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

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

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

    
158
        return userDisplayNames;
159
    }
160

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

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

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

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

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

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

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

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

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

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

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

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

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

    
224
    private Throwable error;
225

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

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

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

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

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

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

    
256

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

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

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

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

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

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

    
286
    VerticalPanel trees;
287

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

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

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

    
300
    GroupTreeViewModel groupTreeViewModel;
301
    GroupTreeView groupTreeView;
302

    
303
    TreeView selectedTree;
304
    protected AccountResource account;
305

    
306
    Folder trash;
307

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

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

    
313
    public Button upload;
314

    
315
    private HTML numOfFiles;
316

    
317
    private Toolbar toolbar;
318

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

    
321
    UploadAlert uploadAlert;
322

    
323
    Date lastModified;
324

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

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

    
339
    public static void LOG(Object ...args) {
340
        if(false) {
341
            final StringBuilder sb = new StringBuilder();
342
            for(Object arg : args) {
343
                sb.append(arg);
344
            }
345
            if(sb.length() > 0) {
346
                __ConsoleLog(sb.toString());
347
            }
348
        }
349
    }
350

    
351
    private void initialize() {
352
        lastModified = new Date(); //Initialize if-modified-since value with now.
353
        resources.pithosCss().ensureInjected();
354
        boolean bareContent = Window.Location.getParameter("noframe") != null;
355
        String contentWidth = bareContent ? Const.PERCENT_100 : "75%";
356

    
357
        VerticalPanel outer = new VerticalPanel();
358
        outer.setWidth(Const.PERCENT_100);
359
        if(!bareContent) {
360
            outer.addStyleName("pithos-outer");
361
        }
362

    
363
        if(!bareContent) {
364
            topPanel = new TopPanel(this, Pithos.images);
365
            topPanel.setWidth(Const.PERCENT_100);
366
            outer.add(topPanel);
367
            outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
368
        }
369

    
370
        messagePanel.setVisible(false);
371
        outer.add(messagePanel);
372
        outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
373
        outer.setCellVerticalAlignment(messagePanel, HasVerticalAlignment.ALIGN_MIDDLE);
374

    
375
        HorizontalPanel header = new HorizontalPanel();
376
        header.addStyleName("pithos-header");
377
        header.setWidth(contentWidth);
378
        if(bareContent) {
379
            header.addStyleName("pithos-header-noframe");
380
        }
381
        upload = new Button("Upload", new ClickHandler() {
382
            @Override
383
            public void onClick(ClickEvent event) {
384
                if(getSelection() != null) {
385
                    new UploadFileCommand(Pithos.this, null, getSelection()).execute();
386
                }
387
            }
388
        });
389
        upload.addStyleName("pithos-uploadButton");
390
        header.add(upload);
391
        header.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_LEFT);
392
        header.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
393

    
394
        toolbar = new Toolbar(this);
395
        header.add(toolbar);
396
        header.setCellHorizontalAlignment(toolbar, HasHorizontalAlignment.ALIGN_CENTER);
397
        header.setCellVerticalAlignment(toolbar, HasVerticalAlignment.ALIGN_MIDDLE);
398

    
399
        HorizontalPanel folderStatistics = new HorizontalPanel();
400
        folderStatistics.addStyleName("pithos-folderStatistics");
401
        numOfFiles = new HTML();
402
        folderStatistics.add(numOfFiles);
403
        folderStatistics.setCellVerticalAlignment(numOfFiles, HasVerticalAlignment.ALIGN_MIDDLE);
404
        HTML numOfFilesLabel = new HTML("&nbsp;Files");
405
        folderStatistics.add(numOfFilesLabel);
406
        folderStatistics.setCellVerticalAlignment(numOfFilesLabel, HasVerticalAlignment.ALIGN_MIDDLE);
407
        header.add(folderStatistics);
408
        header.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
409
        header.setCellVerticalAlignment(folderStatistics, HasVerticalAlignment.ALIGN_MIDDLE);
410
        header.setCellWidth(folderStatistics, "40px");
411
        outer.add(header);
412
        outer.setCellHorizontalAlignment(header, HasHorizontalAlignment.ALIGN_CENTER);
413
        // Inner contains the various lists
414
        inner.sinkEvents(Event.ONCONTEXTMENU);
415
        inner.setWidth(Const.PERCENT_100);
416

    
417
        folderTreeSelectionModel = new SingleSelectionModel<Folder>();
418
        folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
419
            @Override
420
            public void onSelectionChange(SelectionChangeEvent event) {
421
                if(folderTreeSelectionModel.getSelectedObject() != null) {
422
                    deselectOthers(folderTreeView, folderTreeSelectionModel);
423
                    applyPermissions(folderTreeSelectionModel.getSelectedObject());
424
                    Folder f = folderTreeSelectionModel.getSelectedObject();
425
                    updateFolder(f, true, new Command() {
426

    
427
                        @Override
428
                        public void execute() {
429
                            updateStatistics();
430
                        }
431
                    }, true);
432
                    showRelevantToolbarButtons();
433
                }
434
                else {
435
                    if(getSelectedTree().equals(folderTreeView)) {
436
                        setSelectedTree(null);
437
                    }
438
                    if(getSelectedTree() == null) {
439
                        showRelevantToolbarButtons();
440
                    }
441
                }
442
            }
443
        });
444
        selectionModels.add(folderTreeSelectionModel);
445

    
446
        folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
447
        folderTreeView = new FolderTreeView(folderTreeViewModel);
448
        treeViews.add(folderTreeView);
449

    
450
        fileList = new FileList(this, images);
451
        inner.add(fileList);
452

    
453
        trees = new VerticalPanel();
454
        trees.setWidth(Const.PERCENT_100);
455

    
456
        // Add the left and right panels to the split panel.
457
        splitPanel.setLeftWidget(trees);
458
        FlowPanel right = new FlowPanel();
459
        right.getElement().setId("rightPanel");
460
        right.add(inner);
461
        splitPanel.setRightWidget(right);
462
        splitPanel.setSplitPosition("219px");
463
        splitPanel.setSize(Const.PERCENT_100, Const.PERCENT_100);
464
        splitPanel.addStyleName("pithos-splitPanel");
465
        splitPanel.setWidth(contentWidth);
466
        outer.add(splitPanel);
467
        outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
468

    
469
        if(!bareContent) {
470
            statusPanel = new StatusPanel();
471
            statusPanel.setWidth(Const.PERCENT_100);
472
            outer.add(statusPanel);
473
            outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
474
        }
475
        else {
476
            splitPanel.addStyleName("pithos-splitPanel-noframe");
477
        }
478

    
479
        // Hook the window resize event, so that we can adjust the UI.
480
        Window.addResizeHandler(this);
481
        // Clear out the window's built-in margin, because we want to take
482
        // advantage of the entire client area.
483
        Window.setMargin("0px");
484
        // Finally, add the outer panel to the RootPanel, so that it will be
485
        // displayed.
486
        RootPanel.get().add(outer);
487
        // Call the window resized handler to get the initial sizes setup. Doing
488
        // this in a deferred command causes it to occur after all widgets'
489
        // sizes have been computed by the browser.
490
        Scheduler.get().scheduleIncremental(new RepeatingCommand() {
491

    
492
            @Override
493
            public boolean execute() {
494
                if(!isCloudbarReady()) {
495
                    return true;
496
                }
497
                onWindowResized(Window.getClientHeight());
498
                return false;
499
            }
500
        });
501

    
502
        Scheduler.get().scheduleDeferred(new ScheduledCommand() {
503
            @Override
504
            public void execute() {
505
                LOG("Pithos::initialize() Calling Pithos::fetchAccount()");
506
                fetchAccount(new Command() {
507

    
508
                    @Override
509
                    public void execute() {
510
                        if(!account.hasHomeContainer()) {
511
                            createHomeContainer(account, this);
512
                        }
513
                        else if(!account.hasTrashContainer()) {
514
                            createTrashContainer(this);
515
                        }
516
                        else {
517
                            for(Folder f : account.getContainers()) {
518
                                if(f.getName().equals(Const.TRASH_CONTAINER)) {
519
                                    trash = f;
520
                                    break;
521
                                }
522
                            }
523
                            trees.add(folderTreeView);
524
                            folderTreeViewModel.initialize(account, new Command() {
525

    
526
                                @Override
527
                                public void execute() {
528
                                    createMySharedTree();
529
                                }
530
                            });
531

    
532
                            HorizontalPanel separator = new HorizontalPanel();
533
                            separator.addStyleName("pithos-statisticsSeparator");
534
                            separator.add(new HTML(""));
535
                            trees.add(separator);
536

    
537
                            groupTreeViewModel = new GroupTreeViewModel(Pithos.this);
538
                            groupTreeView = new GroupTreeView(groupTreeViewModel);
539
                            treeViews.add(groupTreeView);
540
                            trees.add(groupTreeView);
541
                            folderTreeView.showStatistics(account);
542
                        }
543
                    }
544
                });
545
            }
546
        });
547
    }
548

    
549
    public void scheduleResfresh() {
550
        Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {
551

    
552
            @Override
553
            public boolean execute() {
554
                final Folder f = getSelection();
555
                if(f == null) {
556
                    return true;
557
                }
558

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

    
561
                    @Override
562
                    public void onSuccess(Folder _result) {
563
                        lastModified = new Date();
564
                        if(getSelectedTree().equals(folderTreeView)) {
565
                            updateFolder(f, true, new Command() {
566

    
567
                                @Override
568
                                public void execute() {
569
                                    scheduleResfresh();
570
                                }
571

    
572
                            }, false);
573
                        }
574
                        else if(getSelectedTree().equals(mysharedTreeView)) {
575
                            updateSharedFolder(f, true, new Command() {
576

    
577
                                @Override
578
                                public void execute() {
579
                                    scheduleResfresh();
580
                                }
581
                            });
582
                        }
583
                        else {
584
                            scheduleResfresh();
585
                        }
586
                    }
587

    
588
                    @Override
589
                    public void onError(Throwable t) {
590
                        if(t instanceof RestException && ((RestException) t).getHttpStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
591
                            scheduleResfresh();
592
                        }
593
                        else if(retries >= MAX_RETRIES) {
594
                            GWT.log("Error heading folder", t);
595
                            setError(t);
596
                            if(t instanceof RestException) {
597
                                displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
598
                            }
599
                            else {
600
                                displayError("System error heading folder: " + t.getMessage());
601
                            }
602
                        }
603
                        else {//retry
604
                            GWT.log("Retry " + retries);
605
                            Scheduler.get().scheduleDeferred(this);
606
                        }
607
                    }
608

    
609
                    @Override
610
                    protected void onUnauthorized(Response response) {
611
                        if(retries >= MAX_RETRIES) {
612
                            sessionExpired();
613
                        }
614
                        else //retry
615
                        {
616
                            Scheduler.get().scheduleDeferred(this);
617
                        }
618
                    }
619
                };
620
                head.setHeader(Const.X_AUTH_TOKEN, getUserToken());
621
                head.setHeader(Const.IF_MODIFIED_SINCE, DateTimeFormat.getFormat(Const.DATE_FORMAT_1).format(lastModified, TimeZone.createTimeZone(0)) + " GMT");
622
                Scheduler.get().scheduleDeferred(head);
623

    
624
                return false;
625
            }
626
        }, 3000);
627
    }
628

    
629
    public void applyPermissions(Folder f) {
630
        if(f != null) {
631
            if(f.isInTrash()) {
632
                upload.setEnabled(false);
633
                disableUploadArea();
634
            }
635
            else {
636
                Boolean[] perms = f.getPermissions().get(userID);
637
                if(f.getOwnerID().equals(userID) || (perms != null && perms[1] != null && perms[1])) {
638
                    upload.setEnabled(true);
639
                    enableUploadArea();
640
                }
641
                else {
642
                    upload.setEnabled(false);
643
                    disableUploadArea();
644
                }
645
            }
646
        }
647
        else {
648
            upload.setEnabled(false);
649
            disableUploadArea();
650
        }
651
    }
652

    
653
    @SuppressWarnings({"rawtypes", "unchecked"})
654
    public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
655
        selectedTree = _selectedTree;
656

    
657
        for(SingleSelectionModel s : selectionModels) {
658
            if(!s.equals(model) && s.getSelectedObject() != null) {
659
                s.setSelected(s.getSelectedObject(), false);
660
            }
661
        }
662
    }
663

    
664
    public void showFiles(final Folder f) {
665
        Set<File> files = f.getFiles();
666
        showFiles(files);
667
    }
668

    
669
    public void showFiles(Set<File> files) {
670
        fileList.setFiles(new ArrayList<File>(files));
671
    }
672

    
673
    /**
674
     * Parse and store the user credentials to the appropriate fields.
675
     */
676
    private boolean parseUserCredentials() {
677
        Configuration conf = (Configuration) GWT.create(Configuration.class);
678
        Dictionary otherProperties = Dictionary.getDictionary(Const.OTHER_PROPERTIES);
679
        String cookie = otherProperties.get(Const.AUTH_COOKIE);
680
        String auth = Cookies.getCookie(cookie);
681
        if(auth == null) {
682
            authenticateUser();
683
            return false;
684
        }
685
        if(auth.startsWith("\"")) {
686
            auth = auth.substring(1);
687
        }
688
        if(auth.endsWith("\"")) {
689
            auth = auth.substring(0, auth.length() - 1);
690
        }
691
        String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
692
        if(authSplit.length != 2) {
693
            authenticateUser();
694
            return false;
695
        }
696
        userID = authSplit[0];
697
        userToken = authSplit[1];
698

    
699
        String gotoUrl = Window.Location.getParameter("goto");
700
        if(gotoUrl != null && gotoUrl.length() > 0) {
701
            Window.Location.assign(gotoUrl);
702
            return false;
703
        }
704
        return true;
705
    }
706

    
707
    /**
708
     * Redirect the user to the login page for authentication.
709
     */
710
    protected void authenticateUser() {
711
        Dictionary otherProperties = Dictionary.getDictionary(Const.OTHER_PROPERTIES);
712
        Window.Location.assign(otherProperties.get(Const.LOGIN_URL) + Window.Location.getHref());
713
    }
714

    
715
    public void fetchAccount(final Command callback) {
716
        String path = "?format=json";
717

    
718
        GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getApiPath(), userID, path) {
719
            @Override
720
            public void onSuccess(AccountResource accountResource) {
721
                account = accountResource;
722
                if(callback != null) {
723
                    callback.execute();
724
                }
725

    
726
                final List<String> memberIDs = new ArrayList<String>();
727
                final List<Group> groups = account.getGroups();
728
                for(Group group : groups) {
729
//                    LOG("Group ", group);
730
                    for(String member: group.getMemberIDs()) {
731
//                        LOG("      ", member);
732
                        memberIDs.add(member);
733
                    }
734
                }
735

    
736
                final List<String> theUnknown = Pithos.this.filterUserIDsWithUnknownDisplayName(memberIDs);
737
                // Initialize the user catalog
738
                new UpdateUserCatalogs(Pithos.this, theUnknown).scheduleEntry();
739
                LOG("Called new UpdateUserCatalogs(Pithos.this, theUnknown).scheduleDeferred();");
740
            }
741

    
742
            @Override
743
            public void onError(Throwable t) {
744
                GWT.log("Error getting account", t);
745
                setError(t);
746
                if(t instanceof RestException) {
747
                    displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
748
                }
749
                else {
750
                    displayError("System error fetching user data: " + t.getMessage());
751
                }
752
            }
753

    
754
            @Override
755
            protected void onUnauthorized(Response response) {
756
                sessionExpired();
757
            }
758
        };
759
        getAccount.setHeader(Const.X_AUTH_TOKEN, userToken);
760
        Scheduler.get().scheduleDeferred(getAccount);
761
    }
762

    
763
    public void updateStatistics() {
764
        HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getApiPath(), userID, "", account) {
765

    
766
            @Override
767
            public void onSuccess(AccountResource _result) {
768
                folderTreeView.showStatistics(account);
769
            }
770

    
771
            @Override
772
            public void onError(Throwable t) {
773
                GWT.log("Error getting account", t);
774
                setError(t);
775
                if(t instanceof RestException) {
776
                    displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
777
                }
778
                else {
779
                    displayError("System error fetching user data: " + t.getMessage());
780
                }
781
            }
782

    
783
            @Override
784
            protected void onUnauthorized(Response response) {
785
                sessionExpired();
786
            }
787
        };
788
        headAccount.setHeader(Const.X_AUTH_TOKEN, userToken);
789
        Scheduler.get().scheduleDeferred(headAccount);
790
    }
791

    
792
    protected void createHomeContainer(final AccountResource _account, final Command callback) {
793
        String path = "/" + Const.HOME_CONTAINER;
794
        PutRequest createPithos = new PutRequest(getApiPath(), getUserID(), path) {
795
            @Override
796
            public void onSuccess(Resource result) {
797
                if(!_account.hasTrashContainer()) {
798
                    createTrashContainer(callback);
799
                }
800
                else {
801
                    fetchAccount(callback);
802
                }
803
            }
804

    
805
            @Override
806
            public void onError(Throwable t) {
807
                GWT.log("Error creating pithos", t);
808
                setError(t);
809
                if(t instanceof RestException) {
810
                    displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
811
                }
812
                else {
813
                    displayError("System error Error creating pithos: " + t.getMessage());
814
                }
815
            }
816

    
817
            @Override
818
            protected void onUnauthorized(Response response) {
819
                sessionExpired();
820
            }
821
        };
822
        createPithos.setHeader(Const.X_AUTH_TOKEN, getUserToken());
823
        Scheduler.get().scheduleDeferred(createPithos);
824
    }
825

    
826
    protected void createTrashContainer(final Command callback) {
827
        String path = "/" + Const.TRASH_CONTAINER;
828
        PutRequest createPithos = new PutRequest(getApiPath(), getUserID(), path) {
829
            @Override
830
            public void onSuccess(Resource result) {
831
                fetchAccount(callback);
832
            }
833

    
834
            @Override
835
            public void onError(Throwable t) {
836
                GWT.log("Error creating pithos", t);
837
                setError(t);
838
                if(t instanceof RestException) {
839
                    displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
840
                }
841
                else {
842
                    displayError("System error Error creating pithos: " + t.getMessage());
843
                }
844
            }
845

    
846
            @Override
847
            protected void onUnauthorized(Response response) {
848
                sessionExpired();
849
            }
850
        };
851
        createPithos.setHeader(Const.X_AUTH_TOKEN, getUserToken());
852
        Scheduler.get().scheduleDeferred(createPithos);
853
    }
854

    
855
    /**
856
     * Creates an HTML fragment that places an image & caption together, for use
857
     * in a group header.
858
     *
859
     * @param imageProto an image prototype for an image
860
     * @param caption    the group caption
861
     * @return the header HTML fragment
862
     */
863
    private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
864
        String captionHTML = "<table class='caption' cellpadding='0' "
865
            + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
866
            + "</td><td id =" + caption + " class='rcaption'><b style='white-space:nowrap'>&nbsp;"
867
            + caption + "</b></td></tr></table>";
868
        return captionHTML;
869
    }
870

    
871
    protected void onWindowResized(int height) {
872
        // Adjust the split panel to take up the available room in the window.
873
        int newHeight = height - splitPanel.getAbsoluteTop() - 153;
874
        if(newHeight < 1) {
875
            newHeight = 1;
876
        }
877
        splitPanel.setHeight("" + newHeight);
878
        inner.setHeight("" + newHeight);
879
    }
880

    
881
    native boolean isCloudbarReady()/*-{
882
      if ($wnd.$("div.cloudbar") && $wnd.$("div.cloudbar").height() > 0)
883
        return true;
884
      return false;
885
    }-*/;
886

    
887
    @Override
888
    public void onResize(ResizeEvent event) {
889
        int height = event.getHeight();
890
        onWindowResized(height);
891
    }
892

    
893
    /**
894
     * Display an error message.
895
     *
896
     * @param msg the message to display
897
     */
898
    public void displayError(String msg) {
899
        messagePanel.displayError(msg);
900
        onWindowResized(Window.getClientHeight());
901
    }
902

    
903
    /**
904
     * Display a warning message.
905
     *
906
     * @param msg the message to display
907
     */
908
    public void displayWarning(String msg) {
909
        messagePanel.displayWarning(msg);
910
        onWindowResized(Window.getClientHeight());
911
    }
912

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

    
923
    /**
924
     * Retrieve the fileList.
925
     *
926
     * @return the fileList
927
     */
928
    public FileList getFileList() {
929
        return fileList;
930
    }
931

    
932
    /**
933
     * Retrieve the topPanel.
934
     *
935
     * @return the topPanel
936
     */
937
    TopPanel getTopPanel() {
938
        return topPanel;
939
    }
940

    
941
    /**
942
     * Retrieve the clipboard.
943
     *
944
     * @return the clipboard
945
     */
946
    public Clipboard getClipboard() {
947
        return clipboard;
948
    }
949

    
950
    public StatusPanel getStatusPanel() {
951
        return statusPanel;
952
    }
953

    
954
    public String getUserToken() {
955
        return userToken;
956
    }
957

    
958
    public static native void preventIESelection() /*-{
959
      $doc.body.onselectstart = function () {
960
        return false;
961
      };
962
    }-*/;
963

    
964
    public static native void enableIESelection() /*-{
965
      if ($doc.body.onselectstart != null)
966
        $doc.body.onselectstart = null;
967
    }-*/;
968

    
969
    /**
970
     * @return the absolute path of the API root URL
971
     */
972
    public String getApiPath() {
973
        Configuration conf = (Configuration) GWT.create(Configuration.class);
974
        return conf.apiPath();
975
    }
976

    
977
    /**
978
     * History support for folder navigation
979
     * adds a new browser history entry
980
     *
981
     * @param key
982
     */
983
    public void updateHistory(String key) {
984
//                Replace any whitespace of the initial string to "+"
985
//                String result = key.replaceAll("\\s","+");
986
//                Add a new browser history entry.
987
//                History.newItem(result);
988
        History.newItem(key);
989
    }
990

    
991
    public void deleteFolder(final Folder folder, final Command callback) {
992
        final PleaseWaitPopup pwp = new PleaseWaitPopup();
993
        pwp.center();
994
        String path = "/" + folder.getContainer() + "/" + folder.getPrefix() + "?delimiter=/" + "&t=" + System.currentTimeMillis();
995
        DeleteRequest deleteFolder = new DeleteRequest(getApiPath(), folder.getOwnerID(), path) {
996

    
997
            @Override
998
            protected void onUnauthorized(Response response) {
999
                pwp.hide();
1000
                sessionExpired();
1001
            }
1002

    
1003
            @Override
1004
            public void onSuccess(Resource result) {
1005
                updateFolder(folder.getParent(), true, new Command() {
1006

    
1007
                    @Override
1008
                    public void execute() {
1009
                        folderTreeSelectionModel.setSelected(folder.getParent(), true);
1010
                        updateStatistics();
1011
                        if(callback != null) {
1012
                            callback.execute();
1013
                        }
1014
                        pwp.hide();
1015
                    }
1016
                }, true);
1017
            }
1018

    
1019
            @Override
1020
            public void onError(Throwable t) {
1021
                GWT.log("", t);
1022
                setError(t);
1023
                if(t instanceof RestException) {
1024
                    if(((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND) {
1025
                        displayError("Unable to delete folder: " + ((RestException) t).getHttpStatusText());
1026
                    }
1027
                    else {
1028
                        onSuccess(null);
1029
                    }
1030
                }
1031
                else {
1032
                    displayError("System error unable to delete folder: " + t.getMessage());
1033
                }
1034
                pwp.hide();
1035
            }
1036
        };
1037
        deleteFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1038
        Scheduler.get().scheduleDeferred(deleteFolder);
1039
    }
1040

    
1041
    public FolderTreeView getFolderTreeView() {
1042
        return folderTreeView;
1043
    }
1044

    
1045
    public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
1046
        if(iter.hasNext()) {
1047
            File file = iter.next();
1048
            String path = targetUri + "/" + file.getName();
1049
            PutRequest copyFile = new PutRequest(getApiPath(), targetUsername, path) {
1050
                @Override
1051
                public void onSuccess(Resource result) {
1052
                    copyFiles(iter, targetUsername, targetUri, callback);
1053
                }
1054

    
1055
                @Override
1056
                public void onError(Throwable t) {
1057
                    GWT.log("", t);
1058
                    setError(t);
1059
                    if(t instanceof RestException) {
1060
                        displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
1061
                    }
1062
                    else {
1063
                        displayError("System error unable to copy file: " + t.getMessage());
1064
                    }
1065
                }
1066

    
1067
                @Override
1068
                protected void onUnauthorized(Response response) {
1069
                    sessionExpired();
1070
                }
1071
            };
1072
            copyFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1073
            copyFile.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(file.getUri()));
1074
            if(!file.getOwnerID().equals(targetUsername)) {
1075
                copyFile.setHeader(Const.X_SOURCE_ACCOUNT, URL.encodePathSegment(file.getOwnerID()));
1076
            }
1077
            copyFile.setHeader(Const.CONTENT_TYPE, file.getContentType());
1078
            Scheduler.get().scheduleDeferred(copyFile);
1079
        }
1080
        else if(callback != null) {
1081
            callback.execute();
1082
        }
1083
    }
1084

    
1085
    public void copyFolder(final Folder f, final String targetUsername, final String targetUri, boolean move, final Command callback) {
1086
        String path = targetUri + "?delimiter=/";
1087
        PutRequest copyFolder = new PutRequest(getApiPath(), targetUsername, path) {
1088
            @Override
1089
            public void onSuccess(Resource result) {
1090
                if(callback != null) {
1091
                    callback.execute();
1092
                }
1093
            }
1094

    
1095
            @Override
1096
            public void onError(Throwable t) {
1097
                GWT.log("", t);
1098
                setError(t);
1099
                if(t instanceof RestException) {
1100
                    displayError("Unable to copy folder: " + ((RestException) t).getHttpStatusText());
1101
                }
1102
                else {
1103
                    displayError("System error copying folder: " + t.getMessage());
1104
                }
1105
            }
1106

    
1107
            @Override
1108
            protected void onUnauthorized(Response response) {
1109
                sessionExpired();
1110
            }
1111
        };
1112
        copyFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1113
        copyFolder.setHeader(Const.ACCEPT, "*/*");
1114
        copyFolder.setHeader(Const.CONTENT_LENGTH, "0");
1115
        copyFolder.setHeader(Const.CONTENT_TYPE, "application/directory");
1116
        if(!f.getOwnerID().equals(targetUsername)) {
1117
            copyFolder.setHeader(Const.X_SOURCE_ACCOUNT, f.getOwnerID());
1118
        }
1119
        if(move) {
1120
            copyFolder.setHeader(Const.X_MOVE_FROM, URL.encodePathSegment(f.getUri()));
1121
        }
1122
        else {
1123
            copyFolder.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(f.getUri()));
1124
        }
1125
        Scheduler.get().scheduleDeferred(copyFolder);
1126
    }
1127

    
1128
    public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1129
        selectionModels.add(model);
1130
    }
1131

    
1132
    public OtherSharedTreeView getOtherSharedTreeView() {
1133
        return otherSharedTreeView;
1134
    }
1135

    
1136
    public void updateTrash(boolean showFiles, Command callback) {
1137
        updateFolder(trash, showFiles, callback, true);
1138
    }
1139

    
1140
    public void updateGroupsNode() {
1141
        groupTreeView.updateGroupNode(null);
1142
    }
1143

    
1144
    public Group addGroup(String groupname) {
1145
        Group newGroup = new Group(groupname);
1146
        account.addGroup(newGroup);
1147
        groupTreeView.updateGroupNode(null);
1148
        return newGroup;
1149
    }
1150

    
1151
    public void removeGroup(Group group) {
1152
        account.removeGroup(group);
1153
        updateGroupsNode();
1154
    }
1155

    
1156
    public TreeView getSelectedTree() {
1157
        return selectedTree;
1158
    }
1159

    
1160
    public void setSelectedTree(TreeView selected) {
1161
        selectedTree = selected;
1162
    }
1163

    
1164
    public Folder getSelection() {
1165
        if(selectedTree != null) {
1166
            return selectedTree.getSelection();
1167
        }
1168
        return null;
1169
    }
1170

    
1171
    public void showFolderStatistics(int folderFileCount) {
1172
        numOfFiles.setHTML(String.valueOf(folderFileCount));
1173
    }
1174

    
1175
    public GroupTreeView getGroupTreeView() {
1176
        return groupTreeView;
1177
    }
1178

    
1179
    public void sessionExpired() {
1180
        new SessionExpiredDialog(this).center();
1181
    }
1182

    
1183
    public void updateRootFolder(Command callback) {
1184
        updateFolder(account.getPithos(), false, callback, true);
1185
    }
1186

    
1187
    void createMySharedTree() {
1188
        LOG("Pithos::createMySharedTree()");
1189
        mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1190
        mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1191
            @Override
1192
            public void onSelectionChange(SelectionChangeEvent event) {
1193
                if(mysharedTreeSelectionModel.getSelectedObject() != null) {
1194
                    deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1195
                    upload.setEnabled(false);
1196
                    disableUploadArea();
1197
                    updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1198
                    showRelevantToolbarButtons();
1199
                }
1200
                else {
1201
                    if(getSelectedTree().equals(mysharedTreeView)) {
1202
                        setSelectedTree(null);
1203
                    }
1204
                    if(getSelectedTree() == null) {
1205
                        showRelevantToolbarButtons();
1206
                    }
1207
                }
1208
            }
1209
        });
1210
        selectionModels.add(mysharedTreeSelectionModel);
1211
        mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1212
        mysharedTreeViewModel.initialize(new Command() {
1213

    
1214
            @Override
1215
            public void execute() {
1216
                mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1217
                trees.insert(mysharedTreeView, 2);
1218
                treeViews.add(mysharedTreeView);
1219
                createOtherSharedTree();
1220
            }
1221
        });
1222
    }
1223

    
1224
    void createOtherSharedTree() {
1225
        LOG("Pithos::createOtherSharedTree()");
1226
        otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1227
        otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1228
            @Override
1229
            public void onSelectionChange(SelectionChangeEvent event) {
1230
                if(otherSharedTreeSelectionModel.getSelectedObject() != null) {
1231
                    deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1232
                    applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1233
                    updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true, null);
1234
                    showRelevantToolbarButtons();
1235
                }
1236
                else {
1237
                    if(getSelectedTree().equals(otherSharedTreeView)) {
1238
                        setSelectedTree(null);
1239
                    }
1240
                    if(getSelectedTree() == null) {
1241
                        showRelevantToolbarButtons();
1242
                    }
1243
                }
1244
            }
1245
        });
1246
        selectionModels.add(otherSharedTreeSelectionModel);
1247
        otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1248
        LOG("Pithos::createOtherSharedTree(), initializing otherSharedTreeViewModel with a callback");
1249
        otherSharedTreeViewModel.initialize(new Command() {
1250
            @Override
1251
            public void execute() {
1252
                otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel);
1253
                trees.insert(otherSharedTreeView, 1);
1254
                treeViews.add(otherSharedTreeView);
1255
                scheduleResfresh();
1256
            }
1257
        });
1258
    }
1259

    
1260
    public String getErrorData() {
1261
        final StringBuilder sb = new StringBuilder();
1262
        final String NL = Const.NL;
1263
        Throwable t = this.error;
1264
        while(t != null) {
1265
            sb.append(t.toString());
1266
            sb.append(NL);
1267
            StackTraceElement[] traces = t.getStackTrace();
1268
            for(StackTraceElement trace : traces) {
1269
                sb.append("  [");
1270
                sb.append(trace.getClassName());
1271
                sb.append("::");
1272
                sb.append(trace.getMethodName());
1273
                sb.append("() at ");
1274
                sb.append(trace.getFileName());
1275
                sb.append(":");
1276
                sb.append(trace.getLineNumber());
1277
                sb.append("]");
1278
                sb.append(NL);
1279
            }
1280
            t = t.getCause();
1281
        }
1282

    
1283
        return sb.toString();
1284
    }
1285

    
1286
    public void setError(Throwable t) {
1287
        error = t;
1288
    }
1289

    
1290
    public void showRelevantToolbarButtons() {
1291
        toolbar.showRelevantButtons();
1292
    }
1293

    
1294
    public FileUploadDialog getFileUploadDialog() {
1295
        if(fileUploadDialog == null) {
1296
            fileUploadDialog = new FileUploadDialog(this);
1297
        }
1298
        return fileUploadDialog;
1299
    }
1300

    
1301
    public void hideUploadIndicator() {
1302
        upload.removeStyleName("pithos-uploadButton-loading");
1303
        upload.setTitle("");
1304
    }
1305

    
1306
    public void showUploadIndicator() {
1307
        upload.addStyleName("pithos-uploadButton-loading");
1308
        upload.setTitle("Upload in progress. Click for details.");
1309
    }
1310

    
1311
    public void scheduleFolderHeadCommand(final Folder folder, final Command callback) {
1312
        if(folder == null) {
1313
            if(callback != null) {
1314
                callback.execute();
1315
            }
1316
        }
1317
        else {
1318
            HeadRequest<Folder> headFolder = new HeadRequest<Folder>(Folder.class, getApiPath(), folder.getOwnerID(), folder.getUri(), folder) {
1319

    
1320
                @Override
1321
                public void onSuccess(Folder _result) {
1322
                    if(callback != null) {
1323
                        callback.execute();
1324
                    }
1325
                }
1326

    
1327
                @Override
1328
                public void onError(Throwable t) {
1329
                    if(t instanceof RestException) {
1330
                        if(((RestException) t).getHttpStatusCode() == Response.SC_NOT_FOUND) {
1331
                            final String path = folder.getUri();
1332
                            PutRequest newFolder = new PutRequest(getApiPath(), folder.getOwnerID(), path) {
1333
                                @Override
1334
                                public void onSuccess(Resource _result) {
1335
                                    scheduleFolderHeadCommand(folder, callback);
1336
                                }
1337

    
1338
                                @Override
1339
                                public void onError(Throwable _t) {
1340
                                    GWT.log("", _t);
1341
                                    setError(_t);
1342
                                    if(_t instanceof RestException) {
1343
                                        displayError("Unable to create folder: " + ((RestException) _t).getHttpStatusText());
1344
                                    }
1345
                                    else {
1346
                                        displayError("System error creating folder: " + _t.getMessage());
1347
                                    }
1348
                                }
1349

    
1350
                                @Override
1351
                                protected void onUnauthorized(Response response) {
1352
                                    sessionExpired();
1353
                                }
1354
                            };
1355
                            newFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1356
                            newFolder.setHeader(Const.CONTENT_TYPE, "application/folder");
1357
                            newFolder.setHeader(Const.ACCEPT, "*/*");
1358
                            newFolder.setHeader(Const.CONTENT_LENGTH, "0");
1359
                            Scheduler.get().scheduleDeferred(newFolder);
1360
                        }
1361
                        else if(((RestException) t).getHttpStatusCode() == Response.SC_FORBIDDEN) {
1362
                            onSuccess(folder);
1363
                        }
1364
                        else {
1365
                            displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
1366
                        }
1367
                    }
1368
                    else {
1369
                        displayError("System error heading folder: " + t.getMessage());
1370
                    }
1371

    
1372
                    GWT.log("Error heading folder", t);
1373
                    setError(t);
1374
                }
1375

    
1376
                @Override
1377
                protected void onUnauthorized(Response response) {
1378
                    sessionExpired();
1379
                }
1380
            };
1381
            headFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1382
            Scheduler.get().scheduleDeferred(headFolder);
1383
        }
1384
    }
1385

    
1386
    public void scheduleFileHeadCommand(File f, final Command callback) {
1387
        HeadRequest<File> headFile = new HeadRequest<File>(File.class, getApiPath(), f.getOwnerID(), f.getUri(), f) {
1388

    
1389
            @Override
1390
            public void onSuccess(File _result) {
1391
                if(callback != null) {
1392
                    callback.execute();
1393
                }
1394
            }
1395

    
1396
            @Override
1397
            public void onError(Throwable t) {
1398
                GWT.log("Error heading file", t);
1399
                setError(t);
1400
                if(t instanceof RestException) {
1401
                    displayError("Error heading file: " + ((RestException) t).getHttpStatusText());
1402
                }
1403
                else {
1404
                    displayError("System error heading file: " + t.getMessage());
1405
                }
1406
            }
1407

    
1408
            @Override
1409
            protected void onUnauthorized(Response response) {
1410
                sessionExpired();
1411
            }
1412
        };
1413
        headFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1414
        Scheduler.get().scheduleDeferred(headFile);
1415
    }
1416

    
1417
    public boolean isMySharedSelected() {
1418
        return getSelectedTree().equals(getMySharedTreeView());
1419
    }
1420

    
1421
    private Folder getUploadFolder() {
1422
        if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1423
            return getSelection();
1424
        }
1425
        return null;
1426
    }
1427

    
1428
    private void updateUploadFolder() {
1429
        updateUploadFolder(null);
1430
    }
1431

    
1432
    private void updateUploadFolder(final JsArrayString urls) {
1433
        if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1434
            Folder f = getSelection();
1435
            if(getSelectedTree().equals(getFolderTreeView())) {
1436
                updateFolder(f, true, new Command() {
1437

    
1438
                    @Override
1439
                    public void execute() {
1440
                        updateStatistics();
1441
                        if(urls != null) {
1442
                            selectUploadedFiles(urls);
1443
                        }
1444
                    }
1445
                }, false);
1446
            }
1447
            else {
1448
                updateOtherSharedFolder(f, true, null);
1449
            }
1450
        }
1451
    }
1452

    
1453
    public native void disableUploadArea() /*-{
1454
      var uploader = $wnd.$("#uploader").pluploadQueue();
1455
      var dropElm = $wnd.document.getElementById('rightPanel');
1456
      $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1457
    }-*/;
1458

    
1459
    public native void enableUploadArea() /*-{
1460
      var uploader = $wnd.$("#uploader").pluploadQueue();
1461
      var dropElm = $wnd.document.getElementById('rightPanel');
1462
      $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1463
      if (uploader.runtime == 'html5') {
1464
        uploader.settings.drop_element = 'rightPanel';
1465
        uploader.trigger('PostInit');
1466
      }
1467
    }-*/;
1468

    
1469
    public void showUploadAlert(int nOfFiles) {
1470
        if(uploadAlert == null) {
1471
            uploadAlert = new UploadAlert(this, nOfFiles);
1472
        }
1473
        if(!uploadAlert.isShowing()) {
1474
            uploadAlert.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
1475

    
1476
                @Override
1477
                public void setPosition(int offsetWidth, int offsetHeight) {
1478
                    uploadAlert.setPopupPosition((Window.getClientWidth() - offsetWidth) / 2, statusPanel.getAbsoluteTop() - offsetHeight);
1479
                }
1480
            });
1481
        }
1482
        uploadAlert.setNumOfFiles(nOfFiles);
1483
    }
1484

    
1485
    public void hideUploadAlert() {
1486
        if(uploadAlert != null && uploadAlert.isShowing()) {
1487
            uploadAlert.hide();
1488
        }
1489
    }
1490

    
1491
    public void selectUploadedFiles(JsArrayString urls) {
1492
        List<String> selectedUrls = new ArrayList<String>();
1493
        for(int i = 0; i < urls.length(); i++) {
1494
            selectedUrls.add(urls.get(i));
1495
        }
1496
        fileList.selectByUrl(selectedUrls);
1497
    }
1498

    
1499
    public void emptyContainer(final Folder container) {
1500
        String path = "/" + container.getName() + "?delimiter=/";
1501
        DeleteRequest delete = new DeleteRequest(getApiPath(), getUserID(), path) {
1502

    
1503
            @Override
1504
            protected void onUnauthorized(Response response) {
1505
                sessionExpired();
1506
            }
1507

    
1508
            @Override
1509
            public void onSuccess(Resource result) {
1510
                updateFolder(container, true, null, true);
1511
            }
1512

    
1513
            @Override
1514
            public void onError(Throwable t) {
1515
                GWT.log("Error deleting trash", t);
1516
                setError(t);
1517
                if(t instanceof RestException) {
1518
                    displayError("Error deleting trash: " + ((RestException) t).getHttpStatusText());
1519
                }
1520
                else {
1521
                    displayError("System error deleting trash: " + t.getMessage());
1522
                }
1523
            }
1524
        };
1525
        delete.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1526
        Scheduler.get().scheduleDeferred(delete);
1527
    }
1528
}