Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (51 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 gr.grnet.pithos.web.client.commands.UploadFileCommand;
38
import gr.grnet.pithos.web.client.foldertree.AccountResource;
39
import gr.grnet.pithos.web.client.foldertree.File;
40
import gr.grnet.pithos.web.client.foldertree.Folder;
41
import gr.grnet.pithos.web.client.foldertree.FolderTreeView;
42
import gr.grnet.pithos.web.client.foldertree.FolderTreeViewModel;
43
import gr.grnet.pithos.web.client.foldertree.Resource;
44
import gr.grnet.pithos.web.client.grouptree.Group;
45
import gr.grnet.pithos.web.client.grouptree.GroupTreeView;
46
import gr.grnet.pithos.web.client.grouptree.GroupTreeViewModel;
47
import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeView;
48
import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeViewModel;
49
import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeView;
50
import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeViewModel;
51
import gr.grnet.pithos.web.client.rest.DeleteRequest;
52
import gr.grnet.pithos.web.client.rest.GetRequest;
53
import gr.grnet.pithos.web.client.rest.HeadRequest;
54
import gr.grnet.pithos.web.client.rest.PutRequest;
55
import gr.grnet.pithos.web.client.rest.RestException;
56

    
57
import java.util.ArrayList;
58
import java.util.Date;
59
import java.util.HashMap;
60
import java.util.Iterator;
61
import java.util.List;
62
import java.util.Set;
63

    
64
import org.apache.http.HttpStatus;
65

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

    
118
/**
119
 * Entry point classes define <code>onModuleLoad()</code>.
120
 */
121
public class Pithos implements EntryPoint, ResizeHandler {
122

    
123
        public static final String HOME_CONTAINER = "pithos";
124

    
125
        public static final String TRASH_CONTAINER = "trash";
126

    
127
        public static final Configuration config = GWT.create(Configuration.class);
128
        
129
        public interface Style extends CssResource {
130
                String commandAnchor();
131
                
132
                String statistics();
133
                
134
                @ClassName("gwt-HTML")
135
                String html();
136
                
137
                String uploadAlert();
138

    
139
                String uploadAlertLink();
140

    
141
                String uploadAlertProgress();
142
                
143
                String uploadAlertPercent();
144
                
145
                String uploadAlertClose();
146
        }
147
        
148
        public interface Resources extends ClientBundle {
149
                @Source("Pithos.css")
150
                Style pithosCss();
151
                
152
                @Source("gr/grnet/pithos/resources/close-popup.png")
153
                ImageResource closePopup();
154
        }
155

    
156
        public static Resources resources = GWT.create(Resources.class);
157
        
158
        /**
159
         * Instantiate an application-level image bundle. This object will provide
160
         * programmatic access to all the images needed by widgets.
161
         */
162
        static Images images = (Images) GWT.create(Images.class);
163

    
164
    public String getUsername() {
165
        return username;
166
    }
167

    
168
    public void setAccount(AccountResource acct) {
169
        account = acct;
170
    }
171

    
172
    public AccountResource getAccount() {
173
        return account;
174
    }
175

    
176
    public void updateFolder(Folder f, boolean showfiles, Command callback, final boolean openParent) {
177
        folderTreeView.updateFolder(f, showfiles, callback, openParent);
178
    }
179

    
180
    public void updateGroupNode(Group group) {
181
        groupTreeView.updateGroupNode(group);
182
    }
183

    
184
    public void updateMySharedRoot() {
185
            mysharedTreeView.updateRoot();
186
    }
187
    
188
    public void updateSharedFolder(Folder f, boolean showfiles, Command callback) {
189
            mysharedTreeView.updateFolder(f, showfiles, callback);
190
    }
191
    
192
    public void updateSharedFolder(Folder f, boolean showfiles) {
193
            updateSharedFolder(f, showfiles, null);
194
    }
195

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

    
200
    public MysharedTreeView getMySharedTreeView() {
201
        return mysharedTreeView;
202
    }
203

    
204
    /**
205
         * An aggregate image bundle that pulls together all the images for this
206
         * application into a single bundle.
207
         */
208
        public interface Images extends TopPanel.Images, FileList.Images, ToolsMenu.Images {
209

    
210
                @Source("gr/grnet/pithos/resources/document.png")
211
                ImageResource folders();
212

    
213
                @Source("gr/grnet/pithos/resources/advancedsettings.png")
214
                @ImageOptions(width=32, height=32)
215
                ImageResource tools();
216
        }
217

    
218
        private Throwable error;
219
        
220
        /**
221
         * The Application Clipboard implementation;
222
         */
223
        private Clipboard clipboard = new Clipboard();
224

    
225
        /**
226
         * The top panel that contains the menu bar.
227
         */
228
        private TopPanel topPanel;
229

    
230
        /**
231
         * The panel that contains the various system messages.
232
         */
233
        private MessagePanel messagePanel = new MessagePanel(this, Pithos.images);
234

    
235
        /**
236
         * The bottom panel that contains the status bar.
237
         */
238
        StatusPanel statusPanel = null;
239

    
240
        /**
241
         * The file list widget.
242
         */
243
        private FileList fileList;
244

    
245
        /**
246
         * The tab panel that occupies the right side of the screen.
247
         */
248
        private VerticalPanel inner = new VerticalPanel();
249

    
250

    
251
        /**
252
         * The split panel that will contain the left and right panels.
253
         */
254
        private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
255

    
256
        /**
257
         * The currently selected item in the application, for use by the Edit menu
258
         * commands. Potential types are Folder, File, User and Group.
259
         */
260
        private Object currentSelection;
261

    
262
        public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
263

    
264
    private String username = null;
265

    
266
    /**
267
     * The authentication token of the current user.
268
     */
269
    private String token;
270

    
271
    VerticalPanel trees;
272
    
273
    SingleSelectionModel<Folder> folderTreeSelectionModel;
274
    FolderTreeViewModel folderTreeViewModel;
275
    FolderTreeView folderTreeView;
276

    
277
    SingleSelectionModel<Folder> mysharedTreeSelectionModel;
278
    MysharedTreeViewModel mysharedTreeViewModel;
279
    MysharedTreeView mysharedTreeView = null;;
280

    
281
    protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
282
    OtherSharedTreeViewModel otherSharedTreeViewModel;
283
    OtherSharedTreeView otherSharedTreeView = null;
284

    
285
    GroupTreeViewModel groupTreeViewModel;
286
    GroupTreeView groupTreeView;
287

    
288
    TreeView selectedTree;
289
    protected AccountResource account;
290
    
291
    Folder trash;
292
    
293
    List<Composite> treeViews = new ArrayList<Composite>();
294

    
295
    @SuppressWarnings("rawtypes") List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
296
    
297
    public Button upload;
298
    
299
    private HTML numOfFiles;
300
    
301
    private Toolbar toolbar;
302
    
303
    private FileUploadDialog fileUploadDialog = new FileUploadDialog(this);
304

    
305
        UploadAlert uploadAlert;
306
        
307
        Date lastModified;
308

    
309
        @Override
310
        public void onModuleLoad() {
311
                if (parseUserCredentials())
312
            initialize();
313
        }
314

    
315
    private void initialize() {
316
            lastModified = new Date(); //Initialize if-modified-since value with now.
317
            resources.pithosCss().ensureInjected();
318
            boolean bareContent = Window.Location.getParameter("noframe") != null;
319
            String contentWidth = bareContent ? "100%" : "75%";
320

    
321
            VerticalPanel outer = new VerticalPanel();
322
        outer.setWidth("100%");
323
            if (!bareContent) {
324
                    outer.addStyleName("pithos-outer");
325
            }
326

    
327
        if (!bareContent) {
328
                topPanel = new TopPanel(this, Pithos.images);
329
                topPanel.setWidth("100%");
330
                outer.add(topPanel);
331
                outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
332
        }
333
        
334
        messagePanel.setVisible(false);
335
        outer.add(messagePanel);
336
        outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
337
        outer.setCellVerticalAlignment(messagePanel, HasVerticalAlignment.ALIGN_MIDDLE);
338

    
339
        HorizontalPanel header = new HorizontalPanel();
340
        header.addStyleName("pithos-header");
341
        header.setWidth(contentWidth);
342
        if (bareContent)
343
                header.addStyleName("pithos-header-noframe");
344
        upload = new Button("Upload", new ClickHandler() {
345
            @Override
346
            public void onClick(ClickEvent event) {
347
                    if (getSelection() != null)
348
                            new UploadFileCommand(Pithos.this, null, getSelection()).execute();
349
            }
350
        });
351
        upload.addStyleName("pithos-uploadButton");
352
        header.add(upload);
353
        header.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_LEFT);
354
        header.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
355

    
356
        toolbar = new Toolbar(this);
357
        header.add(toolbar);
358
        header.setCellHorizontalAlignment(toolbar, HasHorizontalAlignment.ALIGN_CENTER);
359
        header.setCellVerticalAlignment(toolbar, HasVerticalAlignment.ALIGN_MIDDLE);
360
        
361
        HorizontalPanel folderStatistics = new HorizontalPanel();
362
        folderStatistics.addStyleName("pithos-folderStatistics");
363
        numOfFiles = new HTML();
364
        folderStatistics.add(numOfFiles);
365
        folderStatistics.setCellVerticalAlignment(numOfFiles, HasVerticalAlignment.ALIGN_MIDDLE);
366
        HTML numOfFilesLabel = new HTML("&nbsp;Files");
367
        folderStatistics.add(numOfFilesLabel);
368
        folderStatistics.setCellVerticalAlignment(numOfFilesLabel, HasVerticalAlignment.ALIGN_MIDDLE);
369
        header.add(folderStatistics);
370
        header.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
371
        header.setCellVerticalAlignment(folderStatistics, HasVerticalAlignment.ALIGN_MIDDLE);
372
        header.setCellWidth(folderStatistics, "40px");
373
        outer.add(header);
374
        outer.setCellHorizontalAlignment(header, HasHorizontalAlignment.ALIGN_CENTER);
375
        // Inner contains the various lists
376
        inner.sinkEvents(Event.ONCONTEXTMENU);
377
        inner.setWidth("100%");
378

    
379
        folderTreeSelectionModel = new SingleSelectionModel<Folder>();
380
        folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
381
            @Override
382
            public void onSelectionChange(SelectionChangeEvent event) {
383
                if (folderTreeSelectionModel.getSelectedObject() != null) {
384
                    deselectOthers(folderTreeView, folderTreeSelectionModel);
385
                    applyPermissions(folderTreeSelectionModel.getSelectedObject());
386
                    Folder f = folderTreeSelectionModel.getSelectedObject();
387
                            updateFolder(f, true, new Command() {
388
                                    
389
                                    @Override
390
                                    public void execute() {
391
                                            updateStatistics();
392
                                    }
393
                            }, true);
394
                            showRelevantToolbarButtons();
395
                }
396
                                else {
397
                                        if (getSelectedTree().equals(folderTreeView))
398
                                                setSelectedTree(null);
399
                                        if (getSelectedTree() == null)
400
                                                showRelevantToolbarButtons();
401
                                }
402
            }
403
        });
404
        selectionModels.add(folderTreeSelectionModel);
405

    
406
        folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
407
        folderTreeView = new FolderTreeView(folderTreeViewModel);
408
        treeViews.add(folderTreeView);
409
        
410
        fileList = new FileList(this, images);
411
        inner.add(fileList);
412

    
413
        trees = new VerticalPanel();
414
        trees.setWidth("100%");
415
        
416
        // Add the left and right panels to the split panel.
417
        splitPanel.setLeftWidget(trees);
418
        FlowPanel right = new FlowPanel();
419
        right.getElement().setId("rightPanel");
420
        right.add(inner);
421
        splitPanel.setRightWidget(right);
422
        splitPanel.setSplitPosition("219px");
423
        splitPanel.setSize("100%", "100%");
424
        splitPanel.addStyleName("pithos-splitPanel");
425
        splitPanel.setWidth(contentWidth);
426
        outer.add(splitPanel);
427
        outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
428

    
429
        if (!bareContent) {
430
                statusPanel = new StatusPanel();
431
                statusPanel.setWidth("100%");
432
                outer.add(statusPanel);
433
                outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
434
        }
435
        else
436
                splitPanel.addStyleName("pithos-splitPanel-noframe");
437

    
438
        // Hook the window resize event, so that we can adjust the UI.
439
        Window.addResizeHandler(this);
440
        // Clear out the window's built-in margin, because we want to take
441
        // advantage of the entire client area.
442
        Window.setMargin("0px");
443
        // Finally, add the outer panel to the RootPanel, so that it will be
444
        // displayed.
445
        RootPanel.get().add(outer);
446
        // Call the window resized handler to get the initial sizes setup. Doing
447
        // this in a deferred command causes it to occur after all widgets'
448
        // sizes have been computed by the browser.
449
        Scheduler.get().scheduleIncremental(new RepeatingCommand() {
450
                        
451
                        @Override
452
                        public boolean execute() {
453
                                if (!isCloudbarReady())
454
                                        return true;
455
                onWindowResized(Window.getClientHeight());
456
                                return false;
457
                        }
458
                });
459
        
460
        Scheduler.get().scheduleDeferred(new ScheduledCommand() {
461
            @Override
462
            public void execute() {
463
                fetchAccount(new Command() {
464
                                        
465
                                        @Override
466
                                        public void execute() {
467
                                if (!account.hasHomeContainer())
468
                                    createHomeContainer(account, this);
469
                                else if (!account.hasTrashContainer())
470
                                        createTrashContainer(this);
471
                                else {
472
                                        for (Folder f : account.getContainers())
473
                                                if (f.getName().equals(Pithos.TRASH_CONTAINER)) {
474
                                                        trash = f;
475
                                                        break;
476
                                                }
477
                                    trees.add(folderTreeView);
478
                                    folderTreeViewModel.initialize(account, new Command() {
479
                                                                
480
                                                                @Override
481
                                                                public void execute() {
482
                                                    createMySharedTree();
483
                                                                }
484
                                                        });
485

    
486
                                    HorizontalPanel separator = new HorizontalPanel();
487
                                    separator.addStyleName("pithos-statisticsSeparator");
488
                                    separator.add(new HTML(""));
489
                                    trees.add(separator);
490

    
491
                                    groupTreeViewModel = new GroupTreeViewModel(Pithos.this);
492
                                    groupTreeView = new GroupTreeView(groupTreeViewModel);
493
                                    treeViews.add(groupTreeView);
494
                                    trees.add(groupTreeView);
495
                                    folderTreeView.showStatistics(account);
496
                                }
497
                                        }
498
                                });
499
            }
500
        });
501
    }
502
    
503
    public void scheduleResfresh() {
504
                Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {
505
                        
506
                        @Override
507
                        public boolean execute() {
508
                                final Folder f = getSelection();
509
                                if (f == null)
510
                                        return true;
511
                                
512
                            HeadRequest<Folder> head = new HeadRequest<Folder>(Folder.class, getApiPath(), getUsername(), "/" + f.getContainer()) {
513

    
514
                                        @Override
515
                                        public void onSuccess(Folder _result) {
516
                                                lastModified = new Date();
517
                                                if (getSelectedTree().equals(folderTreeView))
518
                                                        updateFolder(f, true, new Command() {
519
        
520
                                                                @Override
521
                                                                public void execute() {
522
                                                                        scheduleResfresh();
523
                                                                }
524
                                                                
525
                                                        }, false);
526
                                                else if (getSelectedTree().equals(mysharedTreeView))
527
                                                        updateSharedFolder(f, true, new Command() {
528
        
529
                                                                @Override
530
                                                                public void execute() {
531
                                                                        scheduleResfresh();
532
                                                                }
533
                                                        });
534
                                        }
535

    
536
                                        @Override
537
                                        public void onError(Throwable t) {
538
                                                if (t instanceof RestException && ((RestException) t).getHttpStatusCode() == HttpStatus.SC_NOT_MODIFIED)
539
                                                        scheduleResfresh();
540
                                                else if (retries >= MAX_RETRIES) {
541
                                        GWT.log("Error heading folder", t);
542
                                                        setError(t);
543
                                        if (t instanceof RestException)
544
                                            displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
545
                                        else
546
                                            displayError("System error heading folder: " + t.getMessage());
547
                                    }
548
                                    else {//retry
549
                                            GWT.log("Retry " + retries);
550
                                            Scheduler.get().scheduleDeferred(this);
551
                                    }
552
                                        }
553

    
554
                                        @Override
555
                                        protected void onUnauthorized(Response response) {
556
                                                if (retries >= MAX_RETRIES)
557
                                                        sessionExpired();
558
                                    else //retry
559
                                            Scheduler.get().scheduleDeferred(this);
560
                                        }
561
                                };
562
                                head.setHeader("X-Auth-Token", getToken());
563
                                head.setHeader("If-Modified-Since", DateTimeFormat.getFormat("EEE, dd MMM yyyy HH:mm:ss").format(lastModified, TimeZone.createTimeZone(0)) + " GMT");
564
                                Scheduler.get().scheduleDeferred(head);
565
                                
566
                                return false;
567
                        }
568
                }, 3000);
569
    }
570

    
571
    public void applyPermissions(Folder f) {
572
            if (f != null) {
573
                    if (f.isInTrash()) {
574
                            upload.setEnabled(false);
575
                            disableUploadArea();
576
                    }
577
                    else {
578
                            Boolean[] perms = f.getPermissions().get(username);
579
                            if (f.getOwner().equals(username) || (perms != null && perms[1] != null && perms[1])) {
580
                                    upload.setEnabled(true);
581
                                    enableUploadArea();
582
                            }
583
                            else {
584
                                    upload.setEnabled(false);
585
                                    disableUploadArea();
586
                            }
587
                    }
588
            }
589
            else {
590
                    upload.setEnabled(false);
591
                    disableUploadArea();
592
            }
593
        }
594

    
595
        @SuppressWarnings({ "rawtypes", "unchecked" })
596
        public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
597
            selectedTree = _selectedTree;
598
            
599
        for (SingleSelectionModel s : selectionModels)
600
            if (!s.equals(model) && s.getSelectedObject() != null)
601
                s.setSelected(s.getSelectedObject(), false);
602
    }
603

    
604
    public void showFiles(final Folder f) {
605
        Set<File> files = f.getFiles();
606
        showFiles(files);
607
    }
608

    
609
    public void showFiles(Set<File> files) {
610
        fileList.setFiles(new ArrayList<File>(files));
611
    }
612

    
613
    /**
614
         * Parse and store the user credentials to the appropriate fields.
615
         */
616
        private boolean parseUserCredentials() {
617
        Configuration conf = (Configuration) GWT.create(Configuration.class);
618
                Dictionary otherProperties = Dictionary.getDictionary("otherProperties");
619
        String cookie = otherProperties.get("authCookie");
620
        String auth = Cookies.getCookie(cookie);
621
        if (auth == null) {
622
            authenticateUser();
623
            return false;
624
        }
625
        if (auth.startsWith("\""))
626
                auth = auth.substring(1);
627
        if (auth.endsWith("\""))
628
                auth = auth.substring(0, auth.length() - 1);
629
                String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
630
                if (authSplit.length != 2) {
631
                    authenticateUser();
632
                    return false;
633
                }
634
                username = authSplit[0];
635
                token = authSplit[1];
636

    
637
        String gotoUrl = Window.Location.getParameter("goto");
638
                if (gotoUrl != null && gotoUrl.length() > 0) {
639
                        Window.Location.assign(gotoUrl);
640
                        return false;
641
                }
642
                return true;
643
    }
644

    
645
    /**
646
         * Redirect the user to the login page for authentication.
647
         */
648
        protected void authenticateUser() {
649
                Dictionary otherProperties = Dictionary.getDictionary("otherProperties");
650
        Window.Location.assign(otherProperties.get("loginUrl") + Window.Location.getHref());
651
        }
652

    
653
        public void fetchAccount(final Command callback) {
654
        String path = "?format=json";
655

    
656
        GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getApiPath(), username, path) {
657
            @Override
658
            public void onSuccess(AccountResource _result) {
659
                account = _result;
660
                if (callback != null)
661
                        callback.execute();
662
            }
663

    
664
            @Override
665
            public void onError(Throwable t) {
666
                GWT.log("Error getting account", t);
667
                                setError(t);
668
                if (t instanceof RestException)
669
                    displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
670
                else
671
                    displayError("System error fetching user data: " + t.getMessage());
672
            }
673

    
674
                        @Override
675
                        protected void onUnauthorized(Response response) {
676
                                sessionExpired();
677
                        }
678
        };
679
        getAccount.setHeader("X-Auth-Token", token);
680
        Scheduler.get().scheduleDeferred(getAccount);
681
    }
682

    
683
    public void updateStatistics() {
684
            HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getApiPath(), username, "", account) {
685

    
686
                        @Override
687
                        public void onSuccess(AccountResource _result) {
688
                                folderTreeView.showStatistics(account);
689
                        }
690

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

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

    
710
        protected void createHomeContainer(final AccountResource _account, final Command callback) {
711
        String path = "/" + Pithos.HOME_CONTAINER;
712
        PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
713
            @Override
714
            public void onSuccess(Resource result) {
715
                    if (!_account.hasTrashContainer())
716
                            createTrashContainer(callback);
717
                    else
718
                            fetchAccount(callback);
719
            }
720

    
721
            @Override
722
            public void onError(Throwable t) {
723
                GWT.log("Error creating pithos", t);
724
                                setError(t);
725
                if (t instanceof RestException)
726
                    displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
727
                else
728
                    displayError("System error Error creating pithos: " + t.getMessage());
729
            }
730

    
731
                        @Override
732
                        protected void onUnauthorized(Response response) {
733
                                sessionExpired();
734
                        }
735
        };
736
        createPithos.setHeader("X-Auth-Token", getToken());
737
        Scheduler.get().scheduleDeferred(createPithos);
738
    }
739

    
740
    protected void createTrashContainer(final Command callback) {
741
        String path = "/" + Pithos.TRASH_CONTAINER;
742
        PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
743
            @Override
744
            public void onSuccess(Resource result) {
745
                           fetchAccount(callback);
746
            }
747

    
748
            @Override
749
            public void onError(Throwable t) {
750
                GWT.log("Error creating pithos", t);
751
                                setError(t);
752
                if (t instanceof RestException)
753
                    displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
754
                else
755
                    displayError("System error Error creating pithos: " + t.getMessage());
756
            }
757

    
758
                        @Override
759
                        protected void onUnauthorized(Response response) {
760
                                sessionExpired();
761
                        }
762
        };
763
        createPithos.setHeader("X-Auth-Token", getToken());
764
        Scheduler.get().scheduleDeferred(createPithos);
765
    }
766

    
767
    /**
768
         * Creates an HTML fragment that places an image & caption together, for use
769
         * in a group header.
770
         *
771
         * @param imageProto an image prototype for an image
772
         * @param caption the group caption
773
         * @return the header HTML fragment
774
         */
775
        private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
776
                String captionHTML = "<table class='caption' cellpadding='0' " 
777
                + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML() 
778
                + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'>&nbsp;" 
779
                + caption + "</b></td></tr></table>";
780
                return captionHTML;
781
        }
782

    
783
        protected void onWindowResized(int height) {
784
                // Adjust the split panel to take up the available room in the window.
785
                int newHeight = height - splitPanel.getAbsoluteTop() - 153;
786
                if (newHeight < 1)
787
                        newHeight = 1;
788
                splitPanel.setHeight("" + newHeight);
789
                inner.setHeight("" + newHeight);
790
        }
791
        
792
        native boolean isCloudbarReady()/*-{
793
                if ($wnd.$("div.servicesbar") && $wnd.$("div.servicesbar").height() > 0)
794
                        return true;
795
                return false;
796
        }-*/;
797
        
798
        @Override
799
        public void onResize(ResizeEvent event) {
800
                int height = event.getHeight();
801
                onWindowResized(height);
802
        }
803

    
804
        /**
805
         * Display an error message.
806
         *
807
         * @param msg the message to display
808
         */
809
        public void displayError(String msg) {
810
                messagePanel.displayError(msg);
811
                onWindowResized(Window.getClientHeight());
812
        }
813

    
814
        /**
815
         * Display a warning message.
816
         *
817
         * @param msg the message to display
818
         */
819
        public void displayWarning(String msg) {
820
                messagePanel.displayWarning(msg);
821
                onWindowResized(Window.getClientHeight());
822
        }
823

    
824
        /**
825
         * Display an informational message.
826
         *
827
         * @param msg the message to display
828
         */
829
        public void displayInformation(String msg) {
830
                messagePanel.displayInformation(msg);
831
                onWindowResized(Window.getClientHeight());
832
        }
833

    
834
        /**
835
         * Retrieve the fileList.
836
         *
837
         * @return the fileList
838
         */
839
        public FileList getFileList() {
840
                return fileList;
841
        }
842

    
843
        /**
844
         * Retrieve the topPanel.
845
         *
846
         * @return the topPanel
847
         */
848
        TopPanel getTopPanel() {
849
                return topPanel;
850
        }
851

    
852
        /**
853
         * Retrieve the clipboard.
854
         *
855
         * @return the clipboard
856
         */
857
        public Clipboard getClipboard() {
858
                return clipboard;
859
        }
860

    
861
        public StatusPanel getStatusPanel() {
862
                return statusPanel;
863
        }
864

    
865
        public String getToken() {
866
                return token;
867
        }
868

    
869
        public static native void preventIESelection() /*-{
870
                $doc.body.onselectstart = function() {
871
                        return false;
872
                };
873
        }-*/;
874

    
875
        public static native void enableIESelection() /*-{
876
                if ($doc.body.onselectstart != null)
877
                        $doc.body.onselectstart = null;
878
        }-*/;
879

    
880
        /**
881
         * @return the absolute path of the API root URL
882
         */
883
        public String getApiPath() {
884
                Configuration conf = (Configuration) GWT.create(Configuration.class);
885
                return conf.apiPath();
886
        }
887

    
888
        /**
889
         * History support for folder navigation
890
         * adds a new browser history entry
891
         *
892
         * @param key
893
         */
894
        public void updateHistory(String key){
895
//                Replace any whitespace of the initial string to "+"
896
//                String result = key.replaceAll("\\s","+");
897
//                Add a new browser history entry.
898
//                History.newItem(result);
899
                History.newItem(key);
900
        }
901

    
902
    public void deleteFolder(final Folder folder, final Command callback) {
903
        String path = getApiPath() + folder.getOwner() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(folder.getPrefix()) + "&t=" + System.currentTimeMillis();
904
        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
905
        builder.setHeader("X-Auth-Token", getToken());
906
        try {
907
            builder.sendRequest("", new RequestCallback() {
908
                @Override
909
                public void onResponseReceived(Request request, Response response) {
910
                    if (response.getStatusCode() == Response.SC_OK) {
911
                        JSONValue json = JSONParser.parseStrict(response.getText());
912
                        JSONArray array = json.isArray();
913
                        int i = 0;
914
                        if (array != null) {
915
                            deleteObject(folder, i, array, callback);
916
                        }
917
                    }
918
                }
919

    
920
                @Override
921
                public void onError(Request request, Throwable exception) {
922
                        setError(exception);
923
                    displayError("System error unable to delete folder: " + exception.getMessage());
924
                }
925
            });
926
        }
927
        catch (RequestException e) {
928
        }
929
    }
930

    
931
    void deleteObject(final Folder folder, final int i, final JSONArray array, final Command callback) {
932
        if (i < array.size()) {
933
            JSONObject o = array.get(i).isObject();
934
            if (o != null && !o.containsKey("subdir")) {
935
                JSONString name = o.get("name").isString();
936
                String path = "/" + folder.getContainer() + "/" + name.stringValue();
937
                DeleteRequest delete = new DeleteRequest(getApiPath(), folder.getOwner(), URL.encode(path)) {
938
                    @Override
939
                    public void onSuccess(Resource result) {
940
                        deleteObject(folder, i + 1, array, callback);
941
                    }
942

    
943
                    @Override
944
                    public void onError(Throwable t) {
945
                        GWT.log("", t);
946
                                                setError(t);
947
                        displayError("System error unable to delete folder: " + t.getMessage());
948
                        deleteObject(folder, i + 1, array, callback);
949
                    }
950

    
951
                                    @Override
952
                                    protected void onUnauthorized(Response response) {
953
                                            sessionExpired();
954
                                    }
955
                };
956
                delete.setHeader("X-Auth-Token", getToken());
957
                Scheduler.get().scheduleDeferred(delete);
958
            }
959
            else if (o != null) {
960
                String subdir = o.get("subdir").isString().stringValue();
961
                subdir = subdir.substring(0, subdir.length() - 1);
962
                String path = getApiPath() + folder.getOwner() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(subdir) + "&t=" + System.currentTimeMillis();
963
                RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
964
                builder.setHeader("X-Auth-Token", getToken());
965
                try {
966
                    builder.sendRequest("", new RequestCallback() {
967
                        @Override
968
                        public void onResponseReceived(Request request, Response response) {
969
                            if (response.getStatusCode() == Response.SC_OK) {
970
                                JSONValue json = JSONParser.parseStrict(response.getText());
971
                                JSONArray array2 = json.isArray();
972
                                if (array2 != null) {
973
                                    int l = array.size();
974
                                    for (int j=0; j<array2.size(); j++) {
975
                                        array.set(l++, array2.get(j));
976
                                    }
977
                                }
978
                                deleteObject(folder, i + 1, array, callback);
979
                            }
980
                        }
981

    
982
                        @Override
983
                        public void onError(Request request, Throwable exception) {
984
                                setError(exception);
985
                            displayError("System error unable to delete folder: " + exception.getMessage());
986
                        }
987
                    });
988
                }
989
                catch (RequestException e) {
990
                }
991
            }
992
        }
993
        else {
994
                if (folder.isContainer()) {
995
                        updateFolder(folder, true, new Command() {
996
                                        
997
                                        @Override
998
                                        public void execute() {
999
                                                updateStatistics();
1000
                                                if (callback != null)
1001
                                                        callback.execute();
1002
                                        }
1003
                                }, false);
1004
                        return;
1005
                }
1006
            String path = folder.getUri();
1007
            DeleteRequest deleteFolder = new DeleteRequest(getApiPath(), getUsername(), URL.encode(path)) {
1008
                @Override
1009
                public void onSuccess(Resource result) {
1010
                    updateFolder(folder.getParent(), true, new Command() {
1011
                                                
1012
                                                @Override
1013
                                                public void execute() {
1014
                                                        folderTreeSelectionModel.setSelected(folder.getParent(), true);
1015
                                                        updateStatistics();
1016
                                                        if (callback != null)
1017
                                                                callback.execute();
1018
                                                }
1019
                                        }, true);
1020
                }
1021

    
1022
                @Override
1023
                public void onError(Throwable t) {
1024
                    GWT.log("", t);
1025
                                        setError(t);
1026
                    if (t instanceof RestException) {
1027
                            if (((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND)
1028
                                    displayError("Unable to delete folder: "+((RestException) t).getHttpStatusText());
1029
                            else
1030
                                    onSuccess(null);
1031
                    }
1032
                    else
1033
                        displayError("System error unable to delete folder: " + t.getMessage());
1034
                }
1035

    
1036
                                @Override
1037
                                protected void onUnauthorized(Response response) {
1038
                                        sessionExpired();
1039
                                }
1040
            };
1041
            deleteFolder.setHeader("X-Auth-Token", getToken());
1042
            Scheduler.get().scheduleDeferred(deleteFolder);
1043
        }
1044
    }
1045

    
1046
    public FolderTreeView getFolderTreeView() {
1047
        return folderTreeView;
1048
    }
1049

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

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

    
1071
                                @Override
1072
                                protected void onUnauthorized(Response response) {
1073
                                        sessionExpired();
1074
                                }
1075
            };
1076
            copyFile.setHeader("X-Auth-Token", getToken());
1077
            copyFile.setHeader("X-Copy-From", URL.encodePathSegment(file.getUri()));
1078
            if (!file.getOwner().equals(targetUsername))
1079
                    copyFile.setHeader("X-Source-Account", URL.encodePathSegment(file.getOwner()));
1080
            copyFile.setHeader("Content-Type", file.getContentType());
1081
            Scheduler.get().scheduleDeferred(copyFile);
1082
        }
1083
        else  if (callback != null) {
1084
            callback.execute();
1085
        }
1086
    }
1087

    
1088
    public void copySubfolders(final Iterator<Folder> iter, final String targetUsername, final String targetUri, final Command callback) {
1089
        if (iter.hasNext()) {
1090
            final Folder f = iter.next();
1091
            copyFolder(f, targetUsername, targetUri, new Command() {
1092
                                
1093
                                @Override
1094
                                public void execute() {
1095
                                        copySubfolders(iter, targetUsername, targetUri, callback);
1096
                                }
1097
                        });
1098
        }
1099
        else  if (callback != null) {
1100
            callback.execute();
1101
        }
1102
    }
1103

    
1104
    public void copyFolder(final Folder f, final String targetUsername, final String targetUri, final Command callback) {
1105
        String path = targetUri + "/" + f.getName();
1106
        PutRequest createFolder = new PutRequest(getApiPath(), targetUsername, path) {
1107
            @Override
1108
            public void onSuccess(Resource result) {
1109
                    GetRequest<Folder> getFolder = new GetRequest<Folder>(Folder.class, getApiPath(), f.getOwner(), "/" + f.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(f.getPrefix()), f) {
1110

    
1111
                                        @Override
1112
                                        public void onSuccess(final Folder _f) {
1113
                                Iterator<File> iter = _f.getFiles().iterator();
1114
                                copyFiles(iter, targetUsername, targetUri + "/" + _f.getName(), new Command() {
1115
                                    @Override
1116
                                    public void execute() {
1117
                                        Iterator<Folder> iterf = _f.getSubfolders().iterator();
1118
                                        copySubfolders(iterf, targetUsername, targetUri + "/" + _f.getName(), callback);
1119
                                    }
1120
                                });
1121
                                        }
1122

    
1123
                                        @Override
1124
                                        public void onError(Throwable t) {
1125
                                GWT.log("", t);
1126
                                                setError(t);
1127
                                if (t instanceof RestException) {
1128
                                    displayError("Unable to get folder: " + ((RestException) t).getHttpStatusText());
1129
                                }
1130
                                else
1131
                                    displayError("System error getting folder: " + t.getMessage());
1132
                                        }
1133

    
1134
                                        @Override
1135
                                        protected void onUnauthorized(Response response) {
1136
                                                sessionExpired();
1137
                                        }
1138
                                };
1139
                                getFolder.setHeader("X-Auth-Token", getToken());
1140
                                Scheduler.get().scheduleDeferred(getFolder);
1141
            }
1142

    
1143
            @Override
1144
            public void onError(Throwable t) {
1145
                GWT.log("", t);
1146
                                setError(t);
1147
               if (t instanceof RestException) {
1148
                    displayError("Unable to create folder: " + ((RestException) t).getHttpStatusText());
1149
                }
1150
                else
1151
                    displayError("System error creating folder: " + t.getMessage());
1152
            }
1153

    
1154
                        @Override
1155
                        protected void onUnauthorized(Response response) {
1156
                                sessionExpired();
1157
                        }
1158
        };
1159
        createFolder.setHeader("X-Auth-Token", getToken());
1160
        createFolder.setHeader("Accept", "*/*");
1161
        createFolder.setHeader("Content-Length", "0");
1162
        createFolder.setHeader("Content-Type", "application/folder");
1163
        Scheduler.get().scheduleDeferred(createFolder);
1164
    }
1165
    
1166
    public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1167
            selectionModels.add(model);
1168
    }
1169

    
1170
        public OtherSharedTreeView getOtherSharedTreeView() {
1171
                return otherSharedTreeView;
1172
        }
1173

    
1174
        public void updateTrash(boolean showFiles, Command callback) {
1175
                updateFolder(trash, showFiles, callback, true);
1176
        }
1177

    
1178
        public void updateGroupsNode() {
1179
                groupTreeView.updateGroupNode(null);
1180
        }
1181

    
1182
        public Group addGroup(String groupname) {
1183
                Group newGroup = new Group(groupname);
1184
                account.addGroup(newGroup);
1185
                groupTreeView.updateGroupNode(null);
1186
                return newGroup;
1187
        }
1188

    
1189
        public void removeGroup(Group group) {
1190
                account.removeGroup(group);
1191
                updateGroupsNode();
1192
        }
1193

    
1194
        public TreeView getSelectedTree() {
1195
                return selectedTree;
1196
        }
1197
        
1198
        public void setSelectedTree(TreeView selected) {
1199
                selectedTree = selected;
1200
        }
1201

    
1202
        public Folder getSelection() {
1203
                if (selectedTree != null)
1204
                        return selectedTree.getSelection();
1205
                return null;
1206
        }
1207

    
1208
        public void showFolderStatistics(int folderFileCount) {
1209
                numOfFiles.setHTML(String.valueOf(folderFileCount));
1210
        }
1211

    
1212
        public GroupTreeView getGroupTreeView() {
1213
                return groupTreeView;
1214
        }
1215

    
1216
        public void sessionExpired() {
1217
                new SessionExpiredDialog(this).center();
1218
        }
1219

    
1220
        public void updateRootFolder(Command callback) {
1221
                updateFolder(account.getPithos(), false, callback, true);
1222
        }
1223

    
1224
        void createMySharedTree() {
1225
                mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1226
                mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1227
                    @Override
1228
                    public void onSelectionChange(SelectionChangeEvent event) {
1229
                        if (mysharedTreeSelectionModel.getSelectedObject() != null) {
1230
                            deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1231
                            upload.setEnabled(false);
1232
                            disableUploadArea();
1233
                            updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1234
                                        showRelevantToolbarButtons();
1235
                        }
1236
                                else {
1237
                                        if (getSelectedTree().equals(mysharedTreeView))
1238
                                                setSelectedTree(null);
1239
                                        if (getSelectedTree() == null)
1240
                                                showRelevantToolbarButtons();
1241
                                }
1242
                     }
1243
                });
1244
                selectionModels.add(mysharedTreeSelectionModel);
1245
                mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1246
                mysharedTreeViewModel.initialize(new Command() {
1247
                        
1248
                        @Override
1249
                        public void execute() {
1250
                            mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1251
                                trees.insert(mysharedTreeView, 2);
1252
                                treeViews.add(mysharedTreeView);
1253
                                createOtherSharedTree();
1254
                        }
1255
                });
1256
        }
1257

    
1258
        void createOtherSharedTree() {
1259
                otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1260
                otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1261
                    @Override
1262
                    public void onSelectionChange(SelectionChangeEvent event) {
1263
                        if (otherSharedTreeSelectionModel.getSelectedObject() != null) {
1264
                            deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1265
                            applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1266
                            updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true, null);
1267
                                        showRelevantToolbarButtons();
1268
                        }
1269
                                else {
1270
                                        if (getSelectedTree().equals(otherSharedTreeView))
1271
                                                setSelectedTree(null);
1272
                                        if (getSelectedTree() == null)
1273
                                                showRelevantToolbarButtons();
1274
                                }
1275
                     }
1276
                });
1277
                selectionModels.add(otherSharedTreeSelectionModel);
1278
                otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1279
                otherSharedTreeViewModel.initialize(new Command() {
1280
                        
1281
                        @Override
1282
                        public void execute() {
1283
                            otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel);
1284
                                trees.insert(otherSharedTreeView, 1);
1285
                                treeViews.add(otherSharedTreeView);
1286
                                scheduleResfresh();
1287
                        }
1288
                });
1289
        }
1290

    
1291
        public native void log1(String message)/*-{
1292
                $wnd.console.log(message);
1293
        }-*/;
1294

    
1295
        public String getErrorData() {
1296
                if (error != null)
1297
                        return error.toString();
1298
                return "";
1299
        }
1300
        
1301
        public void setError(Throwable t) {
1302
                error = t;
1303
        }
1304
        
1305
        public void showRelevantToolbarButtons() {
1306
                toolbar.showRelevantButtons();
1307
        }
1308

    
1309
        public FileUploadDialog getFileUploadDialog() {
1310
                if (fileUploadDialog == null)
1311
                        fileUploadDialog = new FileUploadDialog(this);
1312
                return fileUploadDialog;
1313
        }
1314

    
1315
        public void hideUploadIndicator() {
1316
                upload.removeStyleName("pithos-uploadButton-loading");
1317
                upload.setTitle("");
1318
        }
1319
        
1320
        public void showUploadIndicator() {
1321
                upload.addStyleName("pithos-uploadButton-loading");
1322
                upload.setTitle("Upload in progress. Click for details.");
1323
        }
1324

    
1325
        public void scheduleFolderHeadCommand(final Folder folder, final Command callback) {
1326
                if (folder == null) {
1327
                        if (callback != null)
1328
                                callback.execute();
1329
                }
1330
                else {
1331
                        HeadRequest<Folder> headFolder = new HeadRequest<Folder>(Folder.class, getApiPath(), folder.getOwner(), folder.getUri(), folder) {
1332
        
1333
                                @Override
1334
                                public void onSuccess(Folder _result) {
1335
                                        if (callback != null)
1336
                                                callback.execute();
1337
                                }
1338
        
1339
                                @Override
1340
                                public void onError(Throwable t) {
1341
                                if (t instanceof RestException) {
1342
                                        if (((RestException) t).getHttpStatusCode() == Response.SC_NOT_FOUND) {
1343
                                final String path = folder.getUri();
1344
                                PutRequest newFolder = new PutRequest(getApiPath(), folder.getOwner(), path) {
1345
                                    @Override
1346
                                    public void onSuccess(Resource _result) {
1347
                                            scheduleFolderHeadCommand(folder, callback);
1348
                                    }
1349
        
1350
                                    @Override
1351
                                    public void onError(Throwable _t) {
1352
                                        GWT.log("", _t);
1353
                                                                setError(_t);
1354
                                        if(_t instanceof RestException){
1355
                                            displayError("Unable to create folder: " + ((RestException) _t).getHttpStatusText());
1356
                                        }
1357
                                        else
1358
                                            displayError("System error creating folder: " + _t.getMessage());
1359
                                    }
1360
        
1361
                                                    @Override
1362
                                                    protected void onUnauthorized(Response response) {
1363
                                                            sessionExpired();
1364
                                                    }
1365
                                };
1366
                                newFolder.setHeader("X-Auth-Token", getToken());
1367
                                newFolder.setHeader("Content-Type", "application/folder");
1368
                                newFolder.setHeader("Accept", "*/*");
1369
                                newFolder.setHeader("Content-Length", "0");
1370
                                Scheduler.get().scheduleDeferred(newFolder);
1371
                                        }
1372
                                        else
1373
                                                displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
1374
                                }
1375
                                else
1376
                                    displayError("System error heading folder: " + t.getMessage());
1377
        
1378
                                GWT.log("Error heading folder", t);
1379
                                        setError(t);
1380
                                }
1381
        
1382
                                @Override
1383
                                protected void onUnauthorized(Response response) {
1384
                                        sessionExpired();
1385
                                }
1386
                        };
1387
                        headFolder.setHeader("X-Auth-Token", getToken());
1388
                        Scheduler.get().scheduleDeferred(headFolder);
1389
                }
1390
        }
1391

    
1392
        public void scheduleFileHeadCommand(File f, final Command callback) {
1393
                HeadRequest<File> headFile = new HeadRequest<File>(File.class, getApiPath(), f.getOwner(), f.getUri(), f) {
1394

    
1395
                        @Override
1396
                        public void onSuccess(File _result) {
1397
                                if (callback != null)
1398
                                        callback.execute();
1399
                        }
1400

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

    
1411
                        @Override
1412
                        protected void onUnauthorized(Response response) {
1413
                                sessionExpired();
1414
                        }
1415
                };
1416
                headFile.setHeader("X-Auth-Token", getToken());
1417
                Scheduler.get().scheduleDeferred(headFile);
1418
        }
1419

    
1420
        public boolean isMySharedSelected() {
1421
                return getSelectedTree().equals(getMySharedTreeView());
1422
        }
1423
        
1424
        private Folder getUploadFolder() {
1425
                if (folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1426
                        return getSelection();
1427
                }
1428
                return null;
1429
        }
1430
        
1431
        private void updateUploadFolder() {
1432
                updateUploadFolder(null);
1433
        }
1434
        
1435
        private void updateUploadFolder(final JsArrayString urls) {
1436
                if (folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1437
                        Folder f = getSelection();
1438
                        if (getSelectedTree().equals(getFolderTreeView()))
1439
                                updateFolder(f, true, new Command() {
1440
                                
1441
                                        @Override
1442
                                        public void execute() {
1443
                                                updateStatistics();
1444
                                                if (urls != null)
1445
                                                        selectUploadedFiles(urls);
1446
                                        }
1447
                                }, false);
1448
                        else
1449
                                updateOtherSharedFolder(f, true, null);
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
                if (!uploadAlert.isShowing())
1473
                        uploadAlert.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
1474
                                
1475
                                @Override
1476
                                public void setPosition(int offsetWidth, int offsetHeight) {
1477
                                        uploadAlert.setPopupPosition((Window.getClientWidth() - offsetWidth)/2, statusPanel.getAbsoluteTop() - offsetHeight);
1478
                                }
1479
                        });
1480
                uploadAlert.setNumOfFiles(nOfFiles);
1481
        }
1482
        
1483
        public void hideUploadAlert() {
1484
                if (uploadAlert != null && uploadAlert.isShowing())
1485
                        uploadAlert.hide();
1486
        }
1487
        
1488
        public void selectUploadedFiles(JsArrayString urls) {
1489
                List<String> selectedUrls = new ArrayList<String>();
1490
                for (int i=0; i<urls.length(); i++)
1491
                        selectedUrls.add(urls.get(i));
1492
                fileList.selectByUrl(selectedUrls);
1493
        }
1494
        
1495
        public void deleteAndCreateTrash() {
1496
                DeleteRequest delete = new DeleteRequest(getApiPath(), getUsername(), "/trash") {
1497
                        
1498
                        @Override
1499
                        protected void onUnauthorized(Response response) {
1500
                                sessionExpired();
1501
                        }
1502
                        
1503
                        @Override
1504
                        public void onSuccess(Resource result) {
1505
                                createTrashContainer(null);
1506
                        }
1507
                        
1508
                        @Override
1509
                        public void onError(Throwable t) {
1510
                GWT.log("Error deleting trash", t);
1511
                                setError(t);
1512
                if (t instanceof RestException)
1513
                    displayError("Error deleting trash: " + ((RestException) t).getHttpStatusText());
1514
                else
1515
                    displayError("System error deleting trash: " + t.getMessage());
1516
                        }
1517
                };
1518
                delete.setHeader("X-Auth-Token", getToken());
1519
                Scheduler.get().scheduleDeferred(delete);
1520
        }
1521
}