2 * Copyright 2011 GRNET S.A. All rights reserved.
4 * Redistribution and use in source and binary forms, with or
5 * without modification, are permitted provided that the following
8 * 1. Redistributions of source code must retain the above
9 * copyright notice, this list of conditions and the following
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.
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.
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.
35 package gr.grnet.pithos.web.client;
37 import gr.grnet.pithos.web.client.commands.NewFolderCommand;
38 import gr.grnet.pithos.web.client.commands.PropertiesCommand;
39 import gr.grnet.pithos.web.client.commands.UploadFileCommand;
40 import gr.grnet.pithos.web.client.foldertree.AccountResource;
41 import gr.grnet.pithos.web.client.foldertree.File;
42 import gr.grnet.pithos.web.client.foldertree.Folder;
43 import gr.grnet.pithos.web.client.foldertree.FolderTreeView;
44 import gr.grnet.pithos.web.client.foldertree.FolderTreeViewModel;
45 import gr.grnet.pithos.web.client.foldertree.Resource;
46 import gr.grnet.pithos.web.client.grouptree.Group;
47 import gr.grnet.pithos.web.client.grouptree.GroupTreeView;
48 import gr.grnet.pithos.web.client.grouptree.GroupTreeViewModel;
49 import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeView;
50 import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeViewModel;
51 import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeView;
52 import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeViewModel;
53 import gr.grnet.pithos.web.client.rest.DeleteRequest;
54 import gr.grnet.pithos.web.client.rest.GetRequest;
55 import gr.grnet.pithos.web.client.rest.HeadRequest;
56 import gr.grnet.pithos.web.client.rest.PutRequest;
57 import gr.grnet.pithos.web.client.rest.RestException;
58 import gr.grnet.pithos.web.client.tagtree.Tag;
59 import gr.grnet.pithos.web.client.tagtree.TagTreeView;
60 import gr.grnet.pithos.web.client.tagtree.TagTreeViewModel;
62 import java.util.ArrayList;
63 import java.util.Date;
64 import java.util.HashMap;
65 import java.util.Iterator;
66 import java.util.List;
69 import com.google.gwt.core.client.EntryPoint;
70 import com.google.gwt.core.client.GWT;
71 import com.google.gwt.core.client.Scheduler;
72 import com.google.gwt.core.client.Scheduler.ScheduledCommand;
73 import com.google.gwt.dom.client.Style.Display;
74 import com.google.gwt.event.dom.client.ClickEvent;
75 import com.google.gwt.event.dom.client.ClickHandler;
76 import com.google.gwt.event.logical.shared.ResizeEvent;
77 import com.google.gwt.event.logical.shared.ResizeHandler;
78 import com.google.gwt.http.client.Request;
79 import com.google.gwt.http.client.RequestBuilder;
80 import com.google.gwt.http.client.RequestCallback;
81 import com.google.gwt.http.client.RequestException;
82 import com.google.gwt.http.client.Response;
83 import com.google.gwt.http.client.URL;
84 import com.google.gwt.i18n.client.NumberFormat;
85 import com.google.gwt.json.client.JSONArray;
86 import com.google.gwt.json.client.JSONObject;
87 import com.google.gwt.json.client.JSONParser;
88 import com.google.gwt.json.client.JSONString;
89 import com.google.gwt.json.client.JSONValue;
90 import com.google.gwt.resources.client.ImageResource;
91 import com.google.gwt.resources.client.ImageResource.ImageOptions;
92 import com.google.gwt.user.client.Command;
93 import com.google.gwt.user.client.Cookies;
94 import com.google.gwt.user.client.Event;
95 import com.google.gwt.user.client.History;
96 import com.google.gwt.user.client.Window;
97 import com.google.gwt.user.client.ui.AbstractImagePrototype;
98 import com.google.gwt.user.client.ui.Anchor;
99 import com.google.gwt.user.client.ui.Button;
100 import com.google.gwt.user.client.ui.Composite;
101 import com.google.gwt.user.client.ui.FlowPanel;
102 import com.google.gwt.user.client.ui.HTML;
103 import com.google.gwt.user.client.ui.HTMLPanel;
104 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
105 import com.google.gwt.user.client.ui.HasVerticalAlignment;
106 import com.google.gwt.user.client.ui.HorizontalPanel;
107 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
108 import com.google.gwt.user.client.ui.Image;
109 import com.google.gwt.user.client.ui.RootPanel;
110 import com.google.gwt.user.client.ui.VerticalPanel;
111 import com.google.gwt.view.client.SelectionChangeEvent;
112 import com.google.gwt.view.client.SelectionChangeEvent.Handler;
113 import com.google.gwt.view.client.SingleSelectionModel;
116 * Entry point classes define <code>onModuleLoad()</code>.
118 public class Pithos implements EntryPoint, ResizeHandler {
120 public static final String HOME_CONTAINER = "pithos";
122 public static final String TRASH_CONTAINER = "trash";
125 * Instantiate an application-level image bundle. This object will provide
126 * programmatic access to all the images needed by widgets.
128 static Images images = (Images) GWT.create(Images.class);
130 public String getUsername() {
134 public void setAccount(AccountResource acct) {
138 public AccountResource getAccount() {
142 public void updateFolder(Folder f, boolean showfiles, Command callback) {
143 folderTreeView.updateFolder(f, showfiles, callback);
146 public void updateGroupNode(Group group) {
147 groupTreeView.updateGroupNode(group);
150 public void updateMySharedRoot() {
151 mysharedTreeView.updateRoot();
154 public void updateSharedFolder(Folder f, boolean showfiles) {
155 mysharedTreeView.updateFolder(f, showfiles);
158 public void updateOtherSharedFolder(Folder f, boolean showfiles) {
159 otherSharedTreeView.updateFolder(f, showfiles);
162 public List<Tag> getAllTags() {
163 List<Tag> tagList = new ArrayList<Tag>();
164 for (Folder f : account.getContainers()) {
165 for (String t : f.getTags()) {
166 tagList.add(new Tag(t));
172 public MysharedTreeView getMySharedTreeView() {
173 return mysharedTreeView;
177 * An aggregate image bundle that pulls together all the images for this
178 * application into a single bundle.
180 public interface Images extends TopPanel.Images, FileList.Images, ToolsMenu.Images {
182 @Source("gr/grnet/pithos/resources/document.png")
183 ImageResource folders();
185 @Source("gr/grnet/pithos/resources/advancedsettings.png")
186 @ImageOptions(width=32, height=32)
187 ImageResource tools();
190 private Throwable error;
193 * The Application Clipboard implementation;
195 private Clipboard clipboard = new Clipboard();
198 * The top panel that contains the menu bar.
200 private TopPanel topPanel;
203 * The panel that contains the various system messages.
205 private MessagePanel messagePanel = new MessagePanel(this, Pithos.images);
208 * The bottom panel that contains the status bar.
210 private StatusPanel statusPanel = null;
213 * The file list widget.
215 private FileList fileList;
218 * The tab panel that occupies the right side of the screen.
220 private VerticalPanel inner = new VerticalPanel();
224 * The split panel that will contain the left and right panels.
226 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
229 * The currently selected item in the application, for use by the Edit menu
230 * commands. Potential types are Folder, File, User and Group.
232 private Object currentSelection;
234 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
236 private String username = null;
239 * The authentication token of the current user.
241 private String token;
245 SingleSelectionModel<Folder> folderTreeSelectionModel;
246 FolderTreeViewModel folderTreeViewModel;
247 FolderTreeView folderTreeView;
249 SingleSelectionModel<Folder> mysharedTreeSelectionModel;
250 MysharedTreeViewModel mysharedTreeViewModel;
251 MysharedTreeView mysharedTreeView = null;;
253 protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
254 OtherSharedTreeViewModel otherSharedTreeViewModel;
255 OtherSharedTreeView otherSharedTreeView = null;
257 GroupTreeViewModel groupTreeViewModel;
258 private GroupTreeView groupTreeView;
260 TreeView selectedTree;
261 protected AccountResource account;
265 List<Composite> treeViews = new ArrayList<Composite>();
267 @SuppressWarnings("rawtypes") List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
271 private HTML usedBytes;
273 private HTML totalBytes;
275 private HTML usedPercent;
277 private HTML numOfFiles;
279 private Anchor refreshButton;
281 private Anchor toolsButton;
284 public void onModuleLoad() {
285 if (parseUserCredentials())
289 private void initialize() {
290 boolean bareContent = Window.Location.getParameter("noframe") != null;
291 String contentWidth = bareContent ? "100%" : "75%";
293 VerticalPanel outer = new VerticalPanel();
294 outer.setWidth("100%");
296 outer.addStyleName("pithos-outer");
300 topPanel = new TopPanel(this, Pithos.images);
301 topPanel.setWidth("100%");
303 outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
306 HorizontalPanel header = new HorizontalPanel();
307 header.addStyleName("pithos-header");
308 header.setWidth(contentWidth);
310 header.addStyleName("pithos-header-noframe");
311 upload = new Button("Upload File", new ClickHandler() {
313 public void onClick(@SuppressWarnings("unused") ClickEvent event) {
314 new UploadFileCommand(Pithos.this, null, getSelection()).execute();
317 upload.addStyleName("pithos-uploadButton");
319 header.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_LEFT);
320 header.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
322 messagePanel.setVisible(false);
323 header.add(messagePanel);
324 header.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
325 header.setCellVerticalAlignment(messagePanel, HasVerticalAlignment.ALIGN_MIDDLE);
327 FlowPanel toolbar = new FlowPanel();
328 toolbar.getElement().setId("toolbar");
329 toolbar.addStyleName("clearfix");
330 toolbar.getElement().getStyle().setDisplay(Display.BLOCK);
332 Anchor newFolderButton = new Anchor("<span class='ico'></span><span class='title'>New folder</span>", true);
333 newFolderButton.getElement().setId("newfolder-button");
334 newFolderButton.addStyleName("pithos-toolbarItem");
335 newFolderButton.addClickHandler(new ClickHandler() {
338 public void onClick(@SuppressWarnings("unused") ClickEvent event) {
339 Folder folder = getSelectedTree().getSelection();
340 if (folder != null) {
341 Boolean[] permissions = folder.getPermissions().get(getUsername());
342 boolean canWrite = folder.getOwner().equals(getUsername()) || (permissions!= null && permissions[1] != null && permissions[1]);
344 if (!folder.isInTrash() && canWrite)
345 new NewFolderCommand(Pithos.this, null, folder).execute();
349 toolbar.add(newFolderButton);
351 Anchor shareFolderButton = new Anchor("<span class='ico'></span><span class='title'>Share folder</span>", true);
352 shareFolderButton.getElement().setId("sharefolder-button");
353 shareFolderButton.addStyleName("pithos-toolbarItem");
354 shareFolderButton.addClickHandler(new ClickHandler() {
357 public void onClick(@SuppressWarnings("unused") ClickEvent event) {
358 Folder folder = getSelectedTree().getSelection();
359 if (folder != null) {
360 Boolean[] permissions = folder.getPermissions().get(getUsername());
361 boolean canWrite = folder.getOwner().equals(getUsername()) || (permissions!= null && permissions[1] != null && permissions[1]);
362 boolean isFolderTreeSelected = selectedTree.equals(getFolderTreeView());
364 if (!folder.isInTrash() && canWrite && isFolderTreeSelected && !folder.isContainer())
365 new PropertiesCommand(Pithos.this, null, folder, PropertiesCommand.PERMISSIONS).execute();
369 toolbar.add(shareFolderButton);
371 refreshButton = new Anchor("<span class='ico'></span><span class='title'>Refresh</span>", true);
372 refreshButton.getElement().setId("refresh-button");
373 refreshButton.addStyleName("pithos-toolbarItem");
374 refreshButton.addClickHandler(new ClickHandler() {
377 public void onClick(@SuppressWarnings("unused") ClickEvent event) {
378 boolean isFolderTreeSelected = selectedTree.equals(getFolderTreeView());
379 boolean otherSharedTreeSelected = selectedTree.equals(getOtherSharedTreeView());
380 Folder folder = getSelectedTree().getSelection();
382 if (folder != null && (isFolderTreeSelected || otherSharedTreeSelected))
383 updateFolder(folder, true, new Command() {
386 public void execute() {
392 toolbar.add(refreshButton);
394 toolsButton = new Anchor("<span class='ico'></span><span class='title'>More...</span>", true);
395 toolsButton.getElement().setId("tools-button");
396 toolsButton.addStyleName("pithos-toolbarItem");
397 toolsButton.addClickHandler(new ClickHandler() {
400 public void onClick(ClickEvent event) {
401 ToolsMenu menu = new ToolsMenu(Pithos.this, images, getSelectedTree(), getSelectedTree().getSelection(), getFileList().getSelectedFiles());
402 if (!menu.isEmpty()) {
403 menu.setPopupPosition(event.getClientX(), event.getClientY());
408 toolbar.add(toolsButton);
411 header.setCellHorizontalAlignment(toolbar, HasHorizontalAlignment.ALIGN_CENTER);
412 header.setCellVerticalAlignment(toolbar, HasVerticalAlignment.ALIGN_MIDDLE);
413 // header.setCellWidth(toolbar, "40px");
415 HorizontalPanel folderStatistics = new HorizontalPanel();
416 folderStatistics.addStyleName("pithos-folderStatistics");
417 numOfFiles = new HTML();
418 folderStatistics.add(numOfFiles);
419 folderStatistics.setCellVerticalAlignment(numOfFiles, HasVerticalAlignment.ALIGN_MIDDLE);
420 HTML numOfFilesLabel = new HTML(" Files");
421 folderStatistics.add(numOfFilesLabel);
422 folderStatistics.setCellVerticalAlignment(numOfFilesLabel, HasVerticalAlignment.ALIGN_MIDDLE);
423 header.add(folderStatistics);
424 header.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
425 header.setCellVerticalAlignment(folderStatistics, HasVerticalAlignment.ALIGN_MIDDLE);
426 header.setCellWidth(folderStatistics, "40px");
428 outer.setCellHorizontalAlignment(header, HasHorizontalAlignment.ALIGN_CENTER);
429 // Inner contains the various lists.nner
430 inner.sinkEvents(Event.ONCONTEXTMENU);
431 inner.setWidth("100%");
433 folderTreeSelectionModel = new SingleSelectionModel<Folder>();
434 folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
436 public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
437 if (folderTreeSelectionModel.getSelectedObject() != null) {
438 deselectOthers(folderTreeView, folderTreeSelectionModel);
439 applyPermissions(folderTreeSelectionModel.getSelectedObject());
440 Folder f = folderTreeSelectionModel.getSelectedObject();
441 updateFolder(f, true, new Command() {
444 public void execute() {
451 selectionModels.add(folderTreeSelectionModel);
453 folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
454 folderTreeView = new FolderTreeView(folderTreeViewModel);
455 treeViews.add(folderTreeView);
457 fileList = new FileList(this, images, folderTreeView);
460 groupTreeViewModel = new GroupTreeViewModel(this);
461 groupTreeView = new GroupTreeView(groupTreeViewModel);
462 treeViews.add(groupTreeView);
464 trees = new VerticalPanel();
465 trees.setWidth("100%");
468 HorizontalPanel treeHeader = new HorizontalPanel();
469 treeHeader.addStyleName("pithos-treeHeader");
470 treeHeader.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
471 treeHeader.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
472 HorizontalPanel statistics = new HorizontalPanel();
473 statistics.addStyleName("pithos-statistics");
474 statistics.add(new HTML("Used: "));
475 usedBytes = new HTML();
476 statistics.add(usedBytes);
477 statistics.add(new HTML(" of "));
478 totalBytes = new HTML();
479 statistics.add(totalBytes);
480 statistics.add(new HTML(" ("));
481 usedPercent = new HTML();
482 statistics.add(usedPercent);
483 statistics.add(new HTML(")"));
484 treeHeader.add(statistics);
485 treeHeader.setCellHorizontalAlignment(statistics, HasHorizontalAlignment.ALIGN_LEFT);
486 trees.add(treeHeader);
488 trees.add(folderTreeView);
489 trees.add(groupTreeView);
490 // Add the left and right panels to the split panel.
491 splitPanel.setLeftWidget(trees);
492 splitPanel.setRightWidget(inner);
493 splitPanel.setSplitPosition("35%");
494 splitPanel.setSize("100%", "100%");
495 splitPanel.addStyleName("pithos-splitPanel");
496 splitPanel.setWidth(contentWidth);
497 outer.add(splitPanel);
498 outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
501 statusPanel = new StatusPanel();
502 statusPanel.setWidth("100%");
503 outer.add(statusPanel);
504 outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
507 splitPanel.addStyleName("pithos-splitPanel-noframe");
509 // Hook the window resize event, so that we can adjust the UI.
510 Window.addResizeHandler(this);
511 // Clear out the window's built-in margin, because we want to take
512 // advantage of the entire client area.
513 Window.setMargin("0px");
514 // Finally, add the outer panel to the RootPanel, so that it will be
516 RootPanel.get().add(outer);
517 // Call the window resized handler to get the initial sizes setup. Doing
518 // this in a deferred command causes it to occur after all widgets'
519 // sizes have been computed by the browser.
520 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
523 public void execute() {
524 onWindowResized(Window.getClientHeight());
528 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
530 public void execute() {
531 fetchAccount(new Command() {
534 public void execute() {
535 if (!account.hasHomeContainer())
536 createHomeContainer(account, this);
537 else if (!account.hasTrashContainer())
538 createTrashContainer(this);
540 for (Folder f : account.getContainers())
541 if (f.getName().equals(Pithos.TRASH_CONTAINER)) {
545 folderTreeViewModel.initialize(account, new Command() {
548 public void execute() {
549 createMySharedTree();
552 groupTreeViewModel.initialize();
560 // Scheduler.get().scheduleDeferred(new Command() {
563 // public void execute() {
564 // displayError("lalala");
570 public void applyPermissions(Folder f) {
573 upload.setEnabled(false);
575 Boolean[] perms = f.getPermissions().get(username);
576 if (f.getOwner().equals(username) || (perms != null && perms[1] != null && perms[1])) {
577 upload.setEnabled(true);
580 upload.setEnabled(false);
584 upload.setEnabled(false);
587 @SuppressWarnings({ "rawtypes", "unchecked" })
588 public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
589 selectedTree = _selectedTree;
591 for (Composite c : treeViews)
592 if (c.equals(selectedTree))
593 c.addStyleName("cellTreeWidget-selectedTree");
595 c.removeStyleName("cellTreeWidget-selectedTree");
597 for (SingleSelectionModel s : selectionModels)
598 if (!s.equals(model))
599 s.setSelected(s.getSelectedObject(), false);
602 public void showFiles(final Folder f) {
603 Set<File> files = f.getFiles();
607 public void showFiles(Set<File> files) {
608 fileList.setFiles(new ArrayList<File>(files));
611 protected void fetchFile(final Iterator<File> iter, final Set<File> files) {
612 if (iter.hasNext()) {
613 File file = iter.next();
614 String path = file.getUri() + "?format=json";
615 GetRequest<File> getFile = new GetRequest<File>(File.class, getApiPath(), username, path, file) {
617 public void onSuccess(@SuppressWarnings("unused") File _result) {
618 fetchFile(iter, files);
622 public void onError(Throwable t) {
623 GWT.log("Error getting file", t);
625 if (t instanceof RestException)
626 displayError("Error getting file: " + ((RestException) t).getHttpStatusText());
628 displayError("System error fetching file: " + t.getMessage());
632 protected void onUnauthorized(Response response) {
636 getFile.setHeader("X-Auth-Token", "0000");
637 Scheduler.get().scheduleDeferred(getFile);
640 fileList.setFiles(new ArrayList<File>(files));
644 * Parse and store the user credentials to the appropriate fields.
646 private boolean parseUserCredentials() {
647 username = Window.Location.getParameter("user");
648 token = Window.Location.getParameter("token");
649 Configuration conf = (Configuration) GWT.create(Configuration.class);
650 if (username == null || username.length() == 0 || token == null || token.length() == 0) {
651 String cookie = conf.authCookie();
652 String auth = Cookies.getCookie(cookie);
657 if (auth.startsWith("\""))
658 auth = auth.substring(1);
659 if (auth.endsWith("\""))
660 auth = auth.substring(0, auth.length() - 1);
661 String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
662 if (authSplit.length != 2) {
666 username = authSplit[0];
667 token = authSplit[1];
671 Cookies.setCookie(conf.authCookie(), username + conf.cookieSeparator() + token, null, "", "/", false);
676 * Redirect the user to the login page for authentication.
678 protected void authenticateUser() {
679 Configuration conf = (Configuration) GWT.create(Configuration.class);
680 Window.Location.assign(conf.loginUrl() + "?next=" + Window.Location.getHref());
683 protected void fetchAccount(final Command callback) {
684 String path = "?format=json";
686 GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getApiPath(), username, path) {
688 public void onSuccess(AccountResource _result) {
690 if (callback != null)
695 public void onError(Throwable t) {
696 GWT.log("Error getting account", t);
698 if (t instanceof RestException)
699 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
701 displayError("System error fetching user data: " + t.getMessage());
705 protected void onUnauthorized(Response response) {
709 getAccount.setHeader("X-Auth-Token", token);
710 Scheduler.get().scheduleDeferred(getAccount);
713 public void updateStatistics() {
714 HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getApiPath(), username, "", account) {
717 public void onSuccess(@SuppressWarnings("unused") AccountResource _result) {
722 public void onError(Throwable t) {
723 GWT.log("Error getting account", t);
725 if (t instanceof RestException)
726 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
728 displayError("System error fetching user data: " + t.getMessage());
732 protected void onUnauthorized(Response response) {
736 headAccount.setHeader("X-Auth-Token", token);
737 Scheduler.get().scheduleDeferred(headAccount);
740 protected void showStatistics() {
741 usedBytes.setHTML(String.valueOf(account.getFileSizeAsString()));
742 totalBytes.setHTML(String.valueOf(account.getQuotaAsString()));
743 NumberFormat nf = NumberFormat.getPercentFormat();
744 usedPercent.setHTML(nf.format(account.getUsedPercentage()));
747 protected void createHomeContainer(final AccountResource _account, final Command callback) {
748 String path = "/" + Pithos.HOME_CONTAINER;
749 PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
751 public void onSuccess(@SuppressWarnings("unused") Resource result) {
752 if (!_account.hasTrashContainer())
753 createTrashContainer(callback);
755 fetchAccount(callback);
759 public void onError(Throwable t) {
760 GWT.log("Error creating pithos", t);
762 if (t instanceof RestException)
763 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
765 displayError("System error Error creating pithos: " + t.getMessage());
769 protected void onUnauthorized(Response response) {
773 createPithos.setHeader("X-Auth-Token", getToken());
774 Scheduler.get().scheduleDeferred(createPithos);
777 protected void createTrashContainer(final Command callback) {
778 String path = "/" + Pithos.TRASH_CONTAINER;
779 PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
781 public void onSuccess(@SuppressWarnings("unused") Resource result) {
782 fetchAccount(callback);
786 public void onError(Throwable t) {
787 GWT.log("Error creating pithos", t);
789 if (t instanceof RestException)
790 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
792 displayError("System error Error creating pithos: " + t.getMessage());
796 protected void onUnauthorized(Response response) {
800 createPithos.setHeader("X-Auth-Token", getToken());
801 Scheduler.get().scheduleDeferred(createPithos);
805 * Creates an HTML fragment that places an image & caption together, for use
808 * @param imageProto an image prototype for an image
809 * @param caption the group caption
810 * @return the header HTML fragment
812 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
813 String captionHTML = "<table class='caption' cellpadding='0' "
814 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
815 + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'> "
816 + caption + "</b></td></tr></table>";
820 protected void onWindowResized(int height) {
821 // Adjust the split panel to take up the available room in the window.
822 int newHeight = height - splitPanel.getAbsoluteTop();
825 splitPanel.setHeight("" + newHeight);
826 inner.setHeight("" + newHeight);
830 public void onResize(ResizeEvent event) {
831 int height = event.getHeight();
832 onWindowResized(height);
836 * Display an error message.
838 * @param msg the message to display
840 public void displayError(String msg) {
841 messagePanel.displayError(msg);
845 * Display a warning message.
847 * @param msg the message to display
849 public void displayWarning(String msg) {
850 messagePanel.displayWarning(msg);
854 * Display an informational message.
856 * @param msg the message to display
858 public void displayInformation(String msg) {
859 messagePanel.displayInformation(msg);
863 * Retrieve the fileList.
865 * @return the fileList
867 public FileList getFileList() {
872 * Retrieve the topPanel.
874 * @return the topPanel
876 TopPanel getTopPanel() {
881 * Retrieve the clipboard.
883 * @return the clipboard
885 public Clipboard getClipboard() {
889 public StatusPanel getStatusPanel() {
893 public String getToken() {
897 public static native void preventIESelection() /*-{
898 $doc.body.onselectstart = function () { return false; };
901 public static native void enableIESelection() /*-{
902 if ($doc.body.onselectstart != null)
903 $doc.body.onselectstart = null;
907 * @return the absolute path of the API root URL
909 public String getApiPath() {
910 Configuration conf = (Configuration) GWT.create(Configuration.class);
911 return conf.apiPath();
915 * History support for folder navigation
916 * adds a new browser history entry
920 public void updateHistory(String key){
921 // Replace any whitespace of the initial string to "+"
922 // String result = key.replaceAll("\\s","+");
923 // Add a new browser history entry.
924 // History.newItem(result);
925 History.newItem(key);
928 public void deleteFolder(final Folder folder) {
929 String path = getApiPath() + folder.getOwner() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(folder.getPrefix()) + "&t=" + System.currentTimeMillis();
930 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
931 builder.setHeader("X-Auth-Token", getToken());
933 builder.sendRequest("", new RequestCallback() {
935 public void onResponseReceived(@SuppressWarnings("unused") Request request, Response response) {
936 if (response.getStatusCode() == Response.SC_OK) {
937 JSONValue json = JSONParser.parseStrict(response.getText());
938 JSONArray array = json.isArray();
941 deleteObject(folder, i, array);
947 public void onError(@SuppressWarnings("unused") Request request, Throwable exception) {
949 displayError("System error unable to delete folder: " + exception.getMessage());
953 catch (RequestException e) {
957 void deleteObject(final Folder folder, final int i, final JSONArray array) {
958 if (i < array.size()) {
959 JSONObject o = array.get(i).isObject();
960 if (o != null && !o.containsKey("subdir")) {
961 JSONString name = o.get("name").isString();
962 String path = "/" + folder.getContainer() + "/" + name.stringValue();
963 DeleteRequest delete = new DeleteRequest(getApiPath(), folder.getOwner(), path) {
965 public void onSuccess(@SuppressWarnings("unused") Resource result) {
966 deleteObject(folder, i + 1, array);
970 public void onError(Throwable t) {
973 displayError("System error unable to delete folder: " + t.getMessage());
977 protected void onUnauthorized(Response response) {
981 delete.setHeader("X-Auth-Token", getToken());
982 Scheduler.get().scheduleDeferred(delete);
984 else if (o != null) {
985 String subdir = o.get("subdir").isString().stringValue();
986 subdir = subdir.substring(0, subdir.length() - 1);
987 String path = getApiPath() + getUsername() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(subdir) + "&t=" + System.currentTimeMillis();
988 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
989 builder.setHeader("X-Auth-Token", getToken());
991 builder.sendRequest("", new RequestCallback() {
993 public void onResponseReceived(@SuppressWarnings("unused") Request request, Response response) {
994 if (response.getStatusCode() == Response.SC_OK) {
995 JSONValue json = JSONParser.parseStrict(response.getText());
996 JSONArray array2 = json.isArray();
997 if (array2 != null) {
998 int l = array.size();
999 for (int j=0; j<array2.size(); j++) {
1000 array.set(l++, array2.get(j));
1003 deleteObject(folder, i + 1, array);
1008 public void onError(@SuppressWarnings("unused") Request request, Throwable exception) {
1009 setError(exception);
1010 displayError("System error unable to delete folder: " + exception.getMessage());
1014 catch (RequestException e) {
1019 String path = folder.getUri();
1020 DeleteRequest deleteFolder = new DeleteRequest(getApiPath(), getUsername(), path) {
1022 public void onSuccess(@SuppressWarnings("unused") Resource result) {
1023 updateFolder(folder.getParent(), true, new Command() {
1026 public void execute() {
1033 public void onError(Throwable t) {
1036 if (t instanceof RestException) {
1037 if (((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND)
1038 displayError("Unable to delete folder: "+((RestException) t).getHttpStatusText());
1043 displayError("System error unable to delete folder: " + t.getMessage());
1047 protected void onUnauthorized(Response response) {
1051 deleteFolder.setHeader("X-Auth-Token", getToken());
1052 Scheduler.get().scheduleDeferred(deleteFolder);
1056 public FolderTreeView getFolderTreeView() {
1057 return folderTreeView;
1060 public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
1061 if (iter.hasNext()) {
1062 File file = iter.next();
1063 String path = targetUri + "/" + file.getName();
1064 PutRequest copyFile = new PutRequest(getApiPath(), targetUsername, path) {
1066 public void onSuccess(@SuppressWarnings("unused") Resource result) {
1067 copyFiles(iter, targetUsername, targetUri, callback);
1071 public void onError(Throwable t) {
1074 if (t instanceof RestException) {
1075 displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
1078 displayError("System error unable to copy file: "+t.getMessage());
1082 protected void onUnauthorized(Response response) {
1086 copyFile.setHeader("X-Auth-Token", getToken());
1087 copyFile.setHeader("X-Copy-From", URL.encodePathSegment(file.getUri()));
1088 if (!file.getOwner().equals(targetUsername))
1089 copyFile.setHeader("X-Source-Account", URL.encodePathSegment(file.getOwner()));
1090 copyFile.setHeader("Content-Type", file.getContentType());
1091 Scheduler.get().scheduleDeferred(copyFile);
1093 else if (callback != null) {
1098 public void copySubfolders(final Iterator<Folder> iter, final String targetUsername, final String targetUri, final Command callback) {
1099 if (iter.hasNext()) {
1100 final Folder f = iter.next();
1101 copyFolder(f, targetUsername, targetUri, new Command() {
1104 public void execute() {
1105 copySubfolders(iter, targetUsername, targetUri, callback);
1109 else if (callback != null) {
1114 public void copyFolder(final Folder f, final String targetUsername, final String targetUri, final Command callback) {
1115 String path = targetUri + "/" + f.getName();
1116 PutRequest createFolder = new PutRequest(getApiPath(), targetUsername, path) {
1118 public void onSuccess(@SuppressWarnings("unused") Resource result) {
1119 GetRequest<Folder> getFolder = new GetRequest<Folder>(Folder.class, getApiPath(), f.getOwner(), "/" + f.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(f.getPrefix()), f) {
1122 public void onSuccess(final Folder _f) {
1123 Iterator<File> iter = _f.getFiles().iterator();
1124 copyFiles(iter, targetUsername, targetUri + "/" + _f.getName(), new Command() {
1126 public void execute() {
1127 Iterator<Folder> iterf = _f.getSubfolders().iterator();
1128 copySubfolders(iterf, targetUsername, targetUri + "/" + _f.getName(), callback);
1134 public void onError(Throwable t) {
1137 if (t instanceof RestException) {
1138 displayError("Unable to get folder: " + ((RestException) t).getHttpStatusText());
1141 displayError("System error getting folder: " + t.getMessage());
1145 protected void onUnauthorized(Response response) {
1149 getFolder.setHeader("X-Auth-Token", getToken());
1150 Scheduler.get().scheduleDeferred(getFolder);
1154 public void onError(Throwable t) {
1157 if (t instanceof RestException) {
1158 displayError("Unable to create folder: " + ((RestException) t).getHttpStatusText());
1161 displayError("System error creating folder: " + t.getMessage());
1165 protected void onUnauthorized(Response response) {
1169 createFolder.setHeader("X-Auth-Token", getToken());
1170 createFolder.setHeader("Accept", "*/*");
1171 createFolder.setHeader("Content-Length", "0");
1172 createFolder.setHeader("Content-Type", "application/folder");
1173 Scheduler.get().scheduleDeferred(createFolder);
1176 public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1177 selectionModels.add(model);
1180 public OtherSharedTreeView getOtherSharedTreeView() {
1181 return otherSharedTreeView;
1184 public void updateTrash(boolean showFiles, Command callback) {
1185 updateFolder(trash, showFiles, callback);
1188 public void updateGroupsNode() {
1189 groupTreeView.updateGroupNode(null);
1192 public void addGroup(String groupname) {
1193 Group newGroup = new Group(groupname);
1194 account.addGroup(newGroup);
1195 groupTreeView.updateGroupNode(null);
1198 public void removeGroup(Group group) {
1199 account.removeGroup(group);
1203 public TreeView getSelectedTree() {
1204 return selectedTree;
1207 public Folder getSelection() {
1208 return selectedTree.getSelection();
1211 public void showFolderStatistics(int folderFileCount) {
1212 numOfFiles.setHTML(String.valueOf(folderFileCount));
1215 public GroupTreeView getGroupTreeView() {
1216 return groupTreeView;
1219 public void sessionExpired() {
1220 new SessionExpiredDialog(this).center();
1223 public void updateRootFolder(Command callback) {
1224 updateFolder(account.getPithos(), false, callback);
1227 void createMySharedTree() {
1228 mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1229 mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1231 public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
1232 if (mysharedTreeSelectionModel.getSelectedObject() != null) {
1233 deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1234 upload.setEnabled(false);
1235 updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1239 selectionModels.add(mysharedTreeSelectionModel);
1240 mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1241 mysharedTreeViewModel.initialize(new Command() {
1244 public void execute() {
1245 mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1246 trees.insert(mysharedTreeView, 2);
1247 treeViews.add(mysharedTreeView);
1248 createOtherSharedTree();
1253 void createOtherSharedTree() {
1254 otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1255 otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1257 public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
1258 if (otherSharedTreeSelectionModel.getSelectedObject() != null) {
1259 deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1260 otherSharedTreeView.addStyleName("cellTreeWidget-selectedTree");
1261 applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1262 updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true);
1266 selectionModels.add(otherSharedTreeSelectionModel);
1267 otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1268 otherSharedTreeViewModel.initialize(new Command() {
1271 public void execute() {
1272 otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel);
1273 trees.insert(otherSharedTreeView, 3);
1274 treeViews.add(otherSharedTreeView);
1279 public void logoff() {
1280 Configuration conf = (Configuration) GWT.create(Configuration.class);
1281 Cookies.removeCookie(conf.authCookie(), "/");
1282 Cookies.removeCookie(conf.authTokenCookie(), "/");
1283 for (String s: Cookies.getCookieNames())
1284 if (s.startsWith(conf.shibSessionCookiePrefix()))
1285 Cookies.removeCookie(s, "/");
1286 Window.Location.assign(Window.Location.getPath());
1289 public String getErrorData() {
1291 return error.toString();
1295 public void setError(Throwable t) {