2 * Copyright 2011-2013 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 com.google.gwt.core.client.EntryPoint;
38 import com.google.gwt.core.client.GWT;
39 import com.google.gwt.core.client.JsArrayString;
40 import com.google.gwt.core.client.Scheduler;
41 import com.google.gwt.core.client.Scheduler.RepeatingCommand;
42 import com.google.gwt.core.client.Scheduler.ScheduledCommand;
43 import com.google.gwt.event.dom.client.ClickEvent;
44 import com.google.gwt.event.dom.client.ClickHandler;
45 import com.google.gwt.event.logical.shared.ResizeEvent;
46 import com.google.gwt.event.logical.shared.ResizeHandler;
47 import com.google.gwt.http.client.Response;
48 import com.google.gwt.http.client.URL;
49 import com.google.gwt.i18n.client.DateTimeFormat;
50 import com.google.gwt.i18n.client.Dictionary;
51 import com.google.gwt.i18n.client.TimeZone;
52 import com.google.gwt.resources.client.ClientBundle;
53 import com.google.gwt.resources.client.CssResource;
54 import com.google.gwt.resources.client.ImageResource;
55 import com.google.gwt.resources.client.ImageResource.ImageOptions;
56 import com.google.gwt.user.client.*;
57 import com.google.gwt.user.client.ui.*;
58 import com.google.gwt.view.client.SelectionChangeEvent;
59 import com.google.gwt.view.client.SelectionChangeEvent.Handler;
60 import com.google.gwt.view.client.SingleSelectionModel;
61 import gr.grnet.pithos.web.client.catalog.UpdateUserCatalogs;
62 import gr.grnet.pithos.web.client.catalog.UserCatalogs;
63 import gr.grnet.pithos.web.client.commands.UploadFileCommand;
64 import gr.grnet.pithos.web.client.foldertree.*;
65 import gr.grnet.pithos.web.client.grouptree.Group;
66 import gr.grnet.pithos.web.client.grouptree.GroupTreeView;
67 import gr.grnet.pithos.web.client.grouptree.GroupTreeViewModel;
68 import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeView;
69 import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeViewModel;
70 import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeView;
71 import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeViewModel;
72 import gr.grnet.pithos.web.client.rest.*;
73 import org.apache.http.HttpStatus;
78 * Entry point classes define <code>onModuleLoad()</code>.
80 public class Pithos implements EntryPoint, ResizeHandler {
81 private static final boolean IsLOGEnabled = false;
82 public static final boolean IsDetailedHTTPLOGEnabled = true;
83 public static final boolean IsFullResponseBodyLOGEnabled = true;
85 public static final Set<String> HTTPHeadersToIgnoreInLOG = new HashSet<String>();
87 HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_CONNECTION);
88 HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_DATE);
89 HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_KEEP_ALIVE);
90 HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_SERVER);
91 HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_VARY);
92 HTTPHeadersToIgnoreInLOG.add(Const.IF_MODIFIED_SINCE);
95 public static final Configuration config = GWT.create(Configuration.class);
96 public static final String CONFIG_API_PATH = config.apiPath();
98 LOG("CONFIG_API_PATH = ", CONFIG_API_PATH);
101 public static final Dictionary otherProperties = Dictionary.getDictionary(Const.OTHER_PROPERTIES);
102 public static String getFromOtherPropertiesOrDefault(String key, String def) {
104 final String value = otherProperties.get(key);
105 return value == null ? def : value;
112 public static String getFromOtherPropertiesOrNull(String key) {
113 return getFromOtherPropertiesOrDefault(key, null);
116 public static final String OTHERPROPS_STORAGE_API_URL = getFromOtherPropertiesOrNull("STORAGE_API_URL");
117 public static final String OTHERPROPS_USER_CATALOGS_API_URL = getFromOtherPropertiesOrNull("USER_CATALOGS_API_URL");
119 LOG("STORAGE_API_URL = ", OTHERPROPS_STORAGE_API_URL);
120 LOG("USER_CATALOGS_API_URL = ", OTHERPROPS_USER_CATALOGS_API_URL);
123 public static final String STORAGE_API_URL;
125 if(OTHERPROPS_STORAGE_API_URL != null) {
126 STORAGE_API_URL = OTHERPROPS_STORAGE_API_URL;
128 else if(CONFIG_API_PATH != null) {
129 STORAGE_API_URL = CONFIG_API_PATH;
132 throw new RuntimeException("Unknown STORAGE_API_URL");
135 LOG("Computed STORAGE_API_URL = ", STORAGE_API_URL);
138 public static final String STORAGE_VIEW_URL;
140 final String viewURL = getFromOtherPropertiesOrNull("STORAGE_VIEW_URL");
141 if(viewURL != null) {
142 STORAGE_VIEW_URL = viewURL;
145 STORAGE_VIEW_URL = STORAGE_API_URL;
148 LOG("Computed STORAGE_VIEW_URL = ", STORAGE_VIEW_URL);
151 public static final String PUBLIC_LINK_VIEW_PREFIX = getFromOtherPropertiesOrDefault("PUBLIC_LINK_VIEW_PREFIX", "");
153 public static final String USER_CATALOGS_API_URL;
155 if(OTHERPROPS_USER_CATALOGS_API_URL != null) {
156 USER_CATALOGS_API_URL = OTHERPROPS_USER_CATALOGS_API_URL;
158 else if(OTHERPROPS_STORAGE_API_URL != null) {
159 throw new RuntimeException("STORAGE_API_URL is defined but USER_CATALOGS_API_URL is not");
162 // https://server.com/v1/ --> https://server.com
163 String url = CONFIG_API_PATH;
164 url = Helpers.stripTrailing(url, "/");
165 url = Helpers.upToIncludingLastPart(url, "/");
166 url = Helpers.stripTrailing(url, "/");
167 url = url + "/user_catalogs";
169 USER_CATALOGS_API_URL = url;
171 LOG("Computed USER_CATALOGS_API_URL = ", USER_CATALOGS_API_URL);
175 public interface Style extends CssResource {
176 String commandAnchor();
180 @ClassName("gwt-HTML")
183 String uploadAlert();
185 String uploadAlertLink();
187 String uploadAlertProgress();
189 String uploadAlertPercent();
191 String uploadAlertClose();
194 public interface Resources extends ClientBundle {
195 @Source("Pithos.css")
198 @Source("gr/grnet/pithos/resources/close-popup.png")
199 ImageResource closePopup();
202 public static Resources resources = GWT.create(Resources.class);
205 * Instantiate an application-level image bundle. This object will provide
206 * programmatic access to all the images needed by widgets.
208 static Images images = (Images) GWT.create(Images.class);
210 public String getUserID() {
214 public UserCatalogs getUserCatalogs() {
218 public String getCurrentUserDisplayNameOrID() {
219 final String displayName = userCatalogs.getDisplayName(getUserID());
220 return displayName == null ? getUserID() : displayName;
223 public boolean hasDisplayNameForUserID(String userID) {
224 return userCatalogs.getDisplayName(userID) != null;
227 public boolean hasIDForUserDisplayName(String userDisplayName) {
228 return userCatalogs.getID(userDisplayName) != null;
231 public String getDisplayNameForUserID(String userID) {
232 return userCatalogs.getDisplayName(userID);
235 public String getIDForUserDisplayName(String userDisplayName) {
236 return userCatalogs.getID(userDisplayName);
239 public List<String> getDisplayNamesForUserIDs(List<String> userIDs) {
240 if(userIDs == null) {
241 userIDs = new ArrayList<String>();
243 final List<String> userDisplayNames = new ArrayList<String>();
244 for(String userID : userIDs) {
245 final String displayName = getDisplayNameForUserID(userID);
246 userDisplayNames.add(displayName);
249 return userDisplayNames;
252 public List<String> filterUserIDsWithUnknownDisplayName(Collection<String> userIDs) {
253 if(userIDs == null) {
254 userIDs = new ArrayList<String>();
256 final List<String> filtered = new ArrayList<String>();
257 for(String userID : userIDs) {
258 if(!this.userCatalogs.hasID(userID)) {
259 filtered.add(userID);
265 public void setAccount(AccountResource acct) {
269 public AccountResource getAccount() {
273 public void updateFolder(Folder f, boolean showfiles, Command callback, final boolean openParent) {
274 folderTreeView.updateFolder(f, showfiles, callback, openParent);
277 public void updateGroupNode(Group group) {
278 groupTreeView.updateGroupNode(group);
281 public void updateMySharedRoot() {
282 mysharedTreeView.updateRoot();
285 public void updateSharedFolder(Folder f, boolean showfiles, Command callback) {
286 mysharedTreeView.updateFolder(f, showfiles, callback);
289 public void updateSharedFolder(Folder f, boolean showfiles) {
290 updateSharedFolder(f, showfiles, null);
293 public void updateOtherSharedFolder(Folder f, boolean showfiles, Command callback) {
294 otherSharedTreeView.updateFolder(f, showfiles, callback);
297 public MysharedTreeView getMySharedTreeView() {
298 return mysharedTreeView;
302 * An aggregate image bundle that pulls together all the images for this
303 * application into a single bundle.
305 public interface Images extends TopPanel.Images, FileList.Images, ToolsMenu.Images {
307 @Source("gr/grnet/pithos/resources/document.png")
308 ImageResource folders();
310 @Source("gr/grnet/pithos/resources/advancedsettings.png")
311 @ImageOptions(width = 32, height = 32)
312 ImageResource tools();
315 private Throwable error;
318 * The Application Clipboard implementation;
320 private Clipboard clipboard = new Clipboard();
323 * The top panel that contains the menu bar.
325 private TopPanel topPanel;
328 * The panel that contains the various system messages.
330 private MessagePanel messagePanel = new MessagePanel(this, Pithos.images);
333 * The bottom panel that contains the status bar.
335 StatusPanel statusPanel = null;
338 * The file list widget.
340 private FileList fileList;
343 * The tab panel that occupies the right side of the screen.
345 private VerticalPanel inner = new VerticalPanel();
349 * The split panel that will contain the left and right panels.
351 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
354 * The currently selected item in the application, for use by the Edit menu
355 * commands. Potential types are Folder, File, User and Group.
357 private Object currentSelection;
359 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
362 * The ID that uniquely identifies the user in Pithos+.
363 * Currently this is a UUID. It used to be the user's email.
365 private String userID = null;
368 * Holds mappings from user UUIDs to emails and vice-versa.
370 private UserCatalogs userCatalogs = new UserCatalogs();
373 * The authentication token of the current user.
375 private String userToken;
379 SingleSelectionModel<Folder> folderTreeSelectionModel;
380 FolderTreeViewModel folderTreeViewModel;
381 FolderTreeView folderTreeView;
383 SingleSelectionModel<Folder> mysharedTreeSelectionModel;
384 MysharedTreeViewModel mysharedTreeViewModel;
385 MysharedTreeView mysharedTreeView = null;
387 protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
388 OtherSharedTreeViewModel otherSharedTreeViewModel;
389 OtherSharedTreeView otherSharedTreeView = null;
391 GroupTreeViewModel groupTreeViewModel;
392 GroupTreeView groupTreeView;
394 TreeView selectedTree;
395 protected AccountResource account;
399 List<Composite> treeViews = new ArrayList<Composite>();
401 @SuppressWarnings("rawtypes")
402 List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
404 public Button upload;
406 private HTML numOfFiles;
408 private Toolbar toolbar;
410 private FileUploadDialog fileUploadDialog = new FileUploadDialog(this);
412 UploadAlert uploadAlert;
417 public void onModuleLoad() {
418 if(parseUserCredentials()) {
423 static native void __ConsoleLog(String message) /*-{
424 try { console.log(message); } catch (e) {}
427 public static void LOGError(Throwable error, StringBuilder sb) {
428 if(!isLOGEnabled()) { return; }
430 sb.append("\nException: [" + error.toString().replace("\n", "\n ") + "]");
431 Throwable cause = error.getCause();
433 sb.append("\nCauses:\n");
434 while(cause != null) {
436 sb.append("[" + cause.toString().replace("\n", "\n ") + "]");
438 cause = cause.getCause();
445 StackTraceElement[] stackTrace = error.getStackTrace();
446 sb.append("Stack trace (" + stackTrace.length + " elements):\n");
447 for(int i = 0; i < stackTrace.length; i++) {
448 StackTraceElement errorElem = stackTrace[i];
449 sb.append(" [" + i + "] ");
450 sb.append(errorElem.toString());
455 public static void LOGError(Throwable error) {
456 if(!isLOGEnabled()) { return; }
458 final StringBuilder sb = new StringBuilder();
460 if(sb.length() > 0) {
461 __ConsoleLog(sb.toString());
465 public static boolean isLOGEnabled() {
469 public static void LOG(Object ...args) {
470 if(!isLOGEnabled()) { return; }
472 final StringBuilder sb = new StringBuilder();
473 for(Object arg : args) {
474 if(arg instanceof Throwable) {
475 LOGError((Throwable) arg, sb);
482 if(sb.length() > 0) {
483 __ConsoleLog(sb.toString());
487 private void initialize() {
488 userCatalogs.updateWithIDAndName("*", "All Pithos users");
490 lastModified = new Date(); //Initialize if-modified-since value with now.
491 resources.pithosCss().ensureInjected();
492 boolean bareContent = Window.Location.getParameter("noframe") != null;
493 String contentWidth = bareContent ? Const.PERCENT_100 : Const.PERCENT_75;
495 VerticalPanel outer = new VerticalPanel();
496 outer.setWidth(Const.PERCENT_100);
498 outer.addStyleName("pithos-outer");
502 topPanel = new TopPanel(this, Pithos.images);
503 topPanel.setWidth(Const.PERCENT_100);
505 outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
508 messagePanel.setVisible(false);
509 outer.add(messagePanel);
510 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
511 outer.setCellVerticalAlignment(messagePanel, HasVerticalAlignment.ALIGN_MIDDLE);
513 HorizontalPanel header = new HorizontalPanel();
514 header.addStyleName("pithos-header");
515 header.setWidth(contentWidth);
517 header.addStyleName("pithos-header-noframe");
519 upload = new Button("Upload", new ClickHandler() {
521 public void onClick(ClickEvent event) {
522 if(getSelection() != null) {
523 new UploadFileCommand(Pithos.this, null, getSelection()).execute();
527 upload.addStyleName("pithos-uploadButton");
529 header.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_LEFT);
530 header.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
532 toolbar = new Toolbar(this);
534 header.setCellHorizontalAlignment(toolbar, HasHorizontalAlignment.ALIGN_CENTER);
535 header.setCellVerticalAlignment(toolbar, HasVerticalAlignment.ALIGN_MIDDLE);
537 HorizontalPanel folderStatistics = new HorizontalPanel();
538 folderStatistics.addStyleName("pithos-folderStatistics");
539 numOfFiles = new HTML();
540 folderStatistics.add(numOfFiles);
541 folderStatistics.setCellVerticalAlignment(numOfFiles, HasVerticalAlignment.ALIGN_MIDDLE);
542 HTML numOfFilesLabel = new HTML(" Files");
543 folderStatistics.add(numOfFilesLabel);
544 folderStatistics.setCellVerticalAlignment(numOfFilesLabel, HasVerticalAlignment.ALIGN_MIDDLE);
545 header.add(folderStatistics);
546 header.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
547 header.setCellVerticalAlignment(folderStatistics, HasVerticalAlignment.ALIGN_MIDDLE);
548 header.setCellWidth(folderStatistics, "40px");
550 outer.setCellHorizontalAlignment(header, HasHorizontalAlignment.ALIGN_CENTER);
551 // Inner contains the various lists
552 inner.sinkEvents(Event.ONCONTEXTMENU);
553 inner.setWidth(Const.PERCENT_100);
555 folderTreeSelectionModel = new SingleSelectionModel<Folder>();
556 folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
558 public void onSelectionChange(SelectionChangeEvent event) {
559 if(folderTreeSelectionModel.getSelectedObject() != null) {
560 deselectOthers(folderTreeView, folderTreeSelectionModel);
561 applyPermissions(folderTreeSelectionModel.getSelectedObject());
562 Folder f = folderTreeSelectionModel.getSelectedObject();
563 updateFolder(f, true, new Command() {
566 public void execute() {
570 showRelevantToolbarButtons();
573 if(getSelectedTree().equals(folderTreeView)) {
574 setSelectedTree(null);
576 if(getSelectedTree() == null) {
577 showRelevantToolbarButtons();
582 selectionModels.add(folderTreeSelectionModel);
584 folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
585 folderTreeView = new FolderTreeView(folderTreeViewModel);
586 treeViews.add(folderTreeView);
588 fileList = new FileList(this, images);
591 trees = new VerticalPanel();
592 trees.setWidth(Const.PERCENT_100);
594 // Add the left and right panels to the split panel.
595 splitPanel.setLeftWidget(trees);
596 FlowPanel right = new FlowPanel();
597 right.getElement().setId("rightPanel");
599 splitPanel.setRightWidget(right);
600 splitPanel.setSplitPosition("219px");
601 splitPanel.setSize(Const.PERCENT_100, Const.PERCENT_100);
602 splitPanel.addStyleName("pithos-splitPanel");
603 splitPanel.setWidth(contentWidth);
604 outer.add(splitPanel);
605 outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
608 statusPanel = new StatusPanel();
609 statusPanel.setWidth(Const.PERCENT_100);
610 outer.add(statusPanel);
611 outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
614 splitPanel.addStyleName("pithos-splitPanel-noframe");
617 // Hook the window resize event, so that we can adjust the UI.
618 Window.addResizeHandler(this);
619 // Clear out the window's built-in margin, because we want to take
620 // advantage of the entire client area.
621 Window.setMargin("0px");
622 // Finally, add the outer panel to the RootPanel, so that it will be
624 RootPanel.get().add(outer);
625 // Call the window resized handler to get the initial sizes setup. Doing
626 // this in a deferred command causes it to occur after all widgets'
627 // sizes have been computed by the browser.
628 Scheduler.get().scheduleIncremental(new RepeatingCommand() {
631 public boolean execute() {
632 if(!isCloudbarReady()) {
635 onWindowResized(Window.getClientHeight());
640 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
642 public void execute() {
643 LOG("Pithos::initialize() Calling Pithos::fetchAccount()");
644 fetchAccount(new Command() {
647 public void execute() {
648 if(!account.hasHomeContainer()) {
649 createHomeContainer(account, this);
651 else if(!account.hasTrashContainer()) {
652 createTrashContainer(this);
655 for(Folder f : account.getContainers()) {
656 if(f.getName().equals(Const.TRASH_CONTAINER)) {
661 trees.add(folderTreeView);
662 folderTreeViewModel.initialize(account, new Command() {
665 public void execute() {
666 createMySharedTree();
670 HorizontalPanel separator = new HorizontalPanel();
671 separator.addStyleName("pithos-statisticsSeparator");
672 separator.add(new HTML(""));
673 trees.add(separator);
675 groupTreeViewModel = new GroupTreeViewModel(Pithos.this);
676 groupTreeView = new GroupTreeView(groupTreeViewModel);
677 treeViews.add(groupTreeView);
678 trees.add(groupTreeView);
679 folderTreeView.showStatistics(account);
687 public void scheduleResfresh() {
688 Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {
691 public boolean execute() {
692 final Folder f = getSelection();
697 HeadRequest<Folder> head = new HeadRequest<Folder>(Folder.class, getStorageAPIURL(), f.getOwnerID(), "/" + f.getContainer()) {
700 public void onSuccess(Folder _result) {
701 lastModified = new Date();
702 if(getSelectedTree().equals(folderTreeView)) {
703 updateFolder(f, true, new Command() {
706 public void execute() {
712 else if(getSelectedTree().equals(mysharedTreeView)) {
713 updateSharedFolder(f, true, new Command() {
716 public void execute() {
727 public void onError(Throwable t) {
728 if(t instanceof RestException && ((RestException) t).getHttpStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
731 else if(retries >= MAX_RETRIES) {
732 LOG("Error heading folder. ", t);
734 if(t instanceof RestException) {
735 displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
738 displayError("System error heading folder: " + t.getMessage());
742 LOG("Retry ", retries);
743 Scheduler.get().scheduleDeferred(this);
748 protected void onUnauthorized(Response response) {
749 if(retries >= MAX_RETRIES) {
754 Scheduler.get().scheduleDeferred(this);
758 head.setHeader(Const.X_AUTH_TOKEN, getUserToken());
759 head.setHeader(Const.IF_MODIFIED_SINCE, DateTimeFormat.getFormat(Const.DATE_FORMAT_1).format(lastModified, TimeZone.createTimeZone(0)) + " GMT");
760 Scheduler.get().scheduleDeferred(head);
767 public void applyPermissions(Folder f) {
770 upload.setEnabled(false);
774 Boolean[] perms = f.getPermissions().get(userID);
775 if(f.getOwnerID().equals(userID) || (perms != null && perms[1] != null && perms[1])) {
776 upload.setEnabled(true);
780 upload.setEnabled(false);
786 upload.setEnabled(false);
791 @SuppressWarnings({"rawtypes", "unchecked"})
792 public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
793 selectedTree = _selectedTree;
795 for(SingleSelectionModel s : selectionModels) {
796 if(!s.equals(model) && s.getSelectedObject() != null) {
797 s.setSelected(s.getSelectedObject(), false);
802 public void showFiles(final Folder f) {
803 Set<File> files = f.getFiles();
807 public void showFiles(Set<File> files) {
808 fileList.setFiles(new ArrayList<File>(files));
812 * Parse and store the user credentials to the appropriate fields.
814 private boolean parseUserCredentials() {
815 final String cookie = otherProperties.get(Const.AUTH_COOKIE);
816 String auth = Cookies.getCookie(cookie);
821 if(auth.startsWith("\"")) {
822 auth = auth.substring(1);
824 if(auth.endsWith("\"")) {
825 auth = auth.substring(0, auth.length() - 1);
827 String[] authSplit = auth.split("\\" + config.cookieSeparator(), 2);
828 if(authSplit.length != 2) {
832 this.userID = authSplit[0];
833 this.userToken = authSplit[1];
835 String gotoUrl = Window.Location.getParameter("goto");
836 if(gotoUrl != null && gotoUrl.length() > 0) {
837 Window.Location.assign(gotoUrl);
844 * Redirect the user to the login page for authentication.
846 protected void authenticateUser() {
847 Dictionary otherProperties = Dictionary.getDictionary(Const.OTHER_PROPERTIES);
848 Window.Location.assign(otherProperties.get(Const.LOGIN_URL) + Window.Location.getHref());
851 public void fetchAccount(final Command callback) {
852 String path = "?format=json";
854 GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getStorageAPIURL(), userID, path) {
856 public void onSuccess(AccountResource accountResource) {
857 account = accountResource;
858 if(callback != null) {
862 final List<String> memberIDs = new ArrayList<String>();
863 final List<Group> groups = account.getGroups();
864 for(Group group : groups) {
865 memberIDs.addAll(group.getMemberIDs());
867 memberIDs.add(Pithos.this.getUserID());
869 final List<String> theUnknown = Pithos.this.filterUserIDsWithUnknownDisplayName(memberIDs);
870 // Initialize the user catalog
871 new UpdateUserCatalogs(Pithos.this, theUnknown).scheduleDeferred();
872 LOG("Called new UpdateUserCatalogs(Pithos.this, theUnknown).scheduleDeferred();");
876 public void onError(Throwable t) {
877 LOG("Error getting account", t);
879 if(t instanceof RestException) {
880 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
883 displayError("System error fetching user data: " + t.getMessage());
888 protected void onUnauthorized(Response response) {
892 getAccount.setHeader(Const.X_AUTH_TOKEN, userToken);
893 Scheduler.get().scheduleDeferred(getAccount);
896 public void updateStatistics() {
897 HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getStorageAPIURL(), userID, "", account) {
900 public void onSuccess(AccountResource _result) {
901 folderTreeView.showStatistics(account);
905 public void onError(Throwable t) {
906 LOG("Error getting account", t);
908 if(t instanceof RestException) {
909 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
912 displayError("System error fetching user data: " + t.getMessage());
917 protected void onUnauthorized(Response response) {
921 headAccount.setHeader(Const.X_AUTH_TOKEN, userToken);
922 Scheduler.get().scheduleDeferred(headAccount);
925 protected void createHomeContainer(final AccountResource _account, final Command callback) {
926 String path = "/" + Const.HOME_CONTAINER;
927 PutRequest createPithos = new PutRequest(getStorageAPIURL(), getUserID(), path) {
929 public void onSuccess(Resource result) {
930 if(!_account.hasTrashContainer()) {
931 createTrashContainer(callback);
934 fetchAccount(callback);
939 public void onError(Throwable t) {
940 LOG("Error creating pithos", t);
942 if(t instanceof RestException) {
943 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
946 displayError("System error Error creating pithos: " + t.getMessage());
951 protected void onUnauthorized(Response response) {
955 createPithos.setHeader(Const.X_AUTH_TOKEN, getUserToken());
956 Scheduler.get().scheduleDeferred(createPithos);
959 protected void createTrashContainer(final Command callback) {
960 String path = "/" + Const.TRASH_CONTAINER;
961 PutRequest createPithos = new PutRequest(getStorageAPIURL(), getUserID(), path) {
963 public void onSuccess(Resource result) {
964 fetchAccount(callback);
968 public void onError(Throwable t) {
969 LOG("Error creating pithos", t);
971 if(t instanceof RestException) {
972 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
975 displayError("System error Error creating pithos: " + t.getMessage());
980 protected void onUnauthorized(Response response) {
984 createPithos.setHeader(Const.X_AUTH_TOKEN, getUserToken());
985 Scheduler.get().scheduleDeferred(createPithos);
989 * Creates an HTML fragment that places an image & caption together, for use
992 * @param imageProto an image prototype for an image
993 * @param caption the group caption
994 * @return the header HTML fragment
996 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
997 String captionHTML = "<table class='caption' cellpadding='0' "
998 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
999 + "</td><td id =" + caption + " class='rcaption'><b style='white-space:nowrap'> "
1000 + caption + "</b></td></tr></table>";
1004 protected void onWindowResized(int height) {
1005 // Adjust the split panel to take up the available room in the window.
1006 int newHeight = height - splitPanel.getAbsoluteTop() - 153;
1010 splitPanel.setHeight("" + newHeight);
1011 inner.setHeight("" + newHeight);
1014 native boolean isCloudbarReady()/*-{
1015 if ($wnd.$("div.cloudbar") && $wnd.$("div.cloudbar").height() > 0)
1021 public void onResize(ResizeEvent event) {
1022 int height = event.getHeight();
1023 onWindowResized(height);
1027 * Display an error message.
1029 * @param msg the message to display
1031 public void displayError(String msg) {
1032 messagePanel.displayError(msg);
1033 onWindowResized(Window.getClientHeight());
1037 * Display a warning message.
1039 * @param msg the message to display
1041 public void displayWarning(String msg) {
1042 messagePanel.displayWarning(msg);
1043 onWindowResized(Window.getClientHeight());
1047 * Display an informational message.
1049 * @param msg the message to display
1051 public void displayInformation(String msg) {
1052 messagePanel.displayInformation(msg);
1053 onWindowResized(Window.getClientHeight());
1057 * Retrieve the fileList.
1059 * @return the fileList
1061 public FileList getFileList() {
1066 * Retrieve the topPanel.
1068 * @return the topPanel
1070 TopPanel getTopPanel() {
1075 * Retrieve the clipboard.
1077 * @return the clipboard
1079 public Clipboard getClipboard() {
1083 public StatusPanel getStatusPanel() {
1087 public String getUserToken() {
1091 public static native void preventIESelection() /*-{
1092 $doc.body.onselectstart = function () {
1097 public static native void enableIESelection() /*-{
1098 if ($doc.body.onselectstart != null)
1099 $doc.body.onselectstart = null;
1102 public static String getStorageAPIURL() {
1103 return STORAGE_API_URL;
1106 public static String getStorageViewURL() {
1107 return STORAGE_VIEW_URL;
1110 public static String getUserCatalogsURL() {
1111 return USER_CATALOGS_API_URL;
1114 public static String getFileViewURL(File file) {
1115 return Pithos.getStorageViewURL() + file.getOwnerID() + file.getUri();
1119 * History support for folder navigation
1120 * adds a new browser history entry
1124 public void updateHistory(String key) {
1125 // Replace any whitespace of the initial string to "+"
1126 // String result = key.replaceAll("\\s","+");
1127 // Add a new browser history entry.
1128 // History.newItem(result);
1129 History.newItem(key);
1132 public void deleteFolder(final Folder folder, final Command callback) {
1133 final PleaseWaitPopup pwp = new PleaseWaitPopup();
1135 String path = "/" + folder.getContainer() + "/" + folder.getPrefix() + "?delimiter=/" + "&t=" + System.currentTimeMillis();
1136 DeleteRequest deleteFolder = new DeleteRequest(getStorageAPIURL(), folder.getOwnerID(), path) {
1139 protected void onUnauthorized(Response response) {
1145 public void onSuccess(Resource result) {
1146 updateFolder(folder.getParent(), true, new Command() {
1149 public void execute() {
1150 folderTreeSelectionModel.setSelected(folder.getParent(), true);
1152 if(callback != null) {
1161 public void onError(Throwable t) {
1164 if(t instanceof RestException) {
1165 if(((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND) {
1166 displayError("Unable to delete folder: " + ((RestException) t).getHttpStatusText());
1173 displayError("System error unable to delete folder: " + t.getMessage());
1178 deleteFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1179 Scheduler.get().scheduleDeferred(deleteFolder);
1182 public FolderTreeView getFolderTreeView() {
1183 return folderTreeView;
1186 public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
1187 if(iter.hasNext()) {
1188 File file = iter.next();
1189 String path = targetUri + "/" + file.getName();
1190 PutRequest copyFile = new PutRequest(getStorageAPIURL(), targetUsername, path) {
1192 public void onSuccess(Resource result) {
1193 copyFiles(iter, targetUsername, targetUri, callback);
1197 public void onError(Throwable t) {
1200 if(t instanceof RestException) {
1201 displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
1204 displayError("System error unable to copy file: " + t.getMessage());
1209 protected void onUnauthorized(Response response) {
1213 copyFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1214 copyFile.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(file.getUri()));
1215 if(!file.getOwnerID().equals(targetUsername)) {
1216 copyFile.setHeader(Const.X_SOURCE_ACCOUNT, URL.encodePathSegment(file.getOwnerID()));
1218 copyFile.setHeader(Const.CONTENT_TYPE, file.getContentType());
1219 Scheduler.get().scheduleDeferred(copyFile);
1221 else if(callback != null) {
1226 public void copyFolder(final Folder f, final String targetUsername, final String targetUri, boolean move, final Command callback) {
1227 String path = targetUri + "?delimiter=/";
1228 PutRequest copyFolder = new PutRequest(getStorageAPIURL(), targetUsername, path) {
1230 public void onSuccess(Resource result) {
1231 if(callback != null) {
1237 public void onError(Throwable t) {
1240 if(t instanceof RestException) {
1241 displayError("Unable to copy folder: " + ((RestException) t).getHttpStatusText());
1244 displayError("System error copying folder: " + t.getMessage());
1249 protected void onUnauthorized(Response response) {
1253 copyFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1254 copyFolder.setHeader(Const.ACCEPT, "*/*");
1255 copyFolder.setHeader(Const.CONTENT_LENGTH, "0");
1256 copyFolder.setHeader(Const.CONTENT_TYPE, "application/directory");
1257 if(!f.getOwnerID().equals(targetUsername)) {
1258 copyFolder.setHeader(Const.X_SOURCE_ACCOUNT, f.getOwnerID());
1261 copyFolder.setHeader(Const.X_MOVE_FROM, URL.encodePathSegment(f.getUri()));
1264 copyFolder.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(f.getUri()));
1266 Scheduler.get().scheduleDeferred(copyFolder);
1269 public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1270 selectionModels.add(model);
1273 public OtherSharedTreeView getOtherSharedTreeView() {
1274 return otherSharedTreeView;
1277 public void updateTrash(boolean showFiles, Command callback) {
1278 updateFolder(trash, showFiles, callback, true);
1281 public void updateGroupsNode() {
1282 groupTreeView.updateGroupNode(null);
1285 public Group addGroup(String groupname) {
1286 Group newGroup = new Group(groupname);
1287 account.addGroup(newGroup);
1288 groupTreeView.updateGroupNode(null);
1292 public void removeGroup(Group group) {
1293 account.removeGroup(group);
1297 public TreeView getSelectedTree() {
1298 return selectedTree;
1301 public void setSelectedTree(TreeView selected) {
1302 selectedTree = selected;
1305 public Folder getSelection() {
1306 if(selectedTree != null) {
1307 return selectedTree.getSelection();
1312 public void showFolderStatistics(int folderFileCount) {
1313 numOfFiles.setHTML(String.valueOf(folderFileCount));
1316 public GroupTreeView getGroupTreeView() {
1317 return groupTreeView;
1320 public void sessionExpired() {
1321 new SessionExpiredDialog(this).center();
1324 public void updateRootFolder(Command callback) {
1325 updateFolder(account.getPithos(), false, callback, true);
1328 void createMySharedTree() {
1329 LOG("Pithos::createMySharedTree()");
1330 mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1331 mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1333 public void onSelectionChange(SelectionChangeEvent event) {
1334 if(mysharedTreeSelectionModel.getSelectedObject() != null) {
1335 deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1336 upload.setEnabled(false);
1337 disableUploadArea();
1338 updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1339 showRelevantToolbarButtons();
1342 if(getSelectedTree().equals(mysharedTreeView)) {
1343 setSelectedTree(null);
1345 if(getSelectedTree() == null) {
1346 showRelevantToolbarButtons();
1351 selectionModels.add(mysharedTreeSelectionModel);
1352 mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1353 mysharedTreeViewModel.initialize(new Command() {
1356 public void execute() {
1357 mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1358 trees.insert(mysharedTreeView, 2);
1359 treeViews.add(mysharedTreeView);
1360 createOtherSharedTree();
1365 void createOtherSharedTree() {
1366 LOG("Pithos::createOtherSharedTree()");
1367 otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1368 otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1370 public void onSelectionChange(SelectionChangeEvent event) {
1371 if(otherSharedTreeSelectionModel.getSelectedObject() != null) {
1372 deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1373 applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1374 updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true, null);
1375 showRelevantToolbarButtons();
1378 if(getSelectedTree().equals(otherSharedTreeView)) {
1379 setSelectedTree(null);
1381 if(getSelectedTree() == null) {
1382 showRelevantToolbarButtons();
1387 selectionModels.add(otherSharedTreeSelectionModel);
1388 otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1389 // #3784 We show it empty...
1390 otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel, true);
1391 trees.insert(otherSharedTreeView, 1);
1393 LOG("Pithos::createOtherSharedTree(), initializing otherSharedTreeViewModel with a callback");
1394 otherSharedTreeViewModel.initialize(new Command() {
1396 public void execute() {
1397 // #3784 ... then remove the empty stuff and add a new view with the populated model
1398 trees.remove(otherSharedTreeView);
1400 otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel, false);
1401 trees.insert(otherSharedTreeView, 1);
1402 treeViews.add(otherSharedTreeView);
1408 public String getErrorData() {
1409 final StringBuilder sb = new StringBuilder();
1410 final String NL = Const.NL;
1411 Throwable t = this.error;
1413 sb.append(t.toString());
1415 StackTraceElement[] traces = t.getStackTrace();
1416 for(StackTraceElement trace : traces) {
1418 sb.append(trace.getClassName());
1420 sb.append(trace.getMethodName());
1421 sb.append("() at ");
1422 sb.append(trace.getFileName());
1424 sb.append(trace.getLineNumber());
1431 return sb.toString();
1434 public void setError(Throwable t) {
1439 public void showRelevantToolbarButtons() {
1440 toolbar.showRelevantButtons();
1443 public FileUploadDialog getFileUploadDialog() {
1444 if(fileUploadDialog == null) {
1445 fileUploadDialog = new FileUploadDialog(this);
1447 return fileUploadDialog;
1450 public void hideUploadIndicator() {
1451 upload.removeStyleName("pithos-uploadButton-loading");
1452 upload.setTitle("");
1455 public void showUploadIndicator() {
1456 upload.addStyleName("pithos-uploadButton-loading");
1457 upload.setTitle("Upload in progress. Click for details.");
1460 public void scheduleFolderHeadCommand(final Folder folder, final Command callback) {
1461 if(folder == null) {
1462 if(callback != null) {
1467 HeadRequest<Folder> headFolder = new HeadRequest<Folder>(Folder.class, getStorageAPIURL(), folder.getOwnerID(), folder.getUri(), folder) {
1470 public void onSuccess(Folder _result) {
1471 if(callback != null) {
1477 public void onError(Throwable t) {
1478 if(t instanceof RestException) {
1479 if(((RestException) t).getHttpStatusCode() == Response.SC_NOT_FOUND) {
1480 final String path = folder.getUri();
1481 PutRequest newFolder = new PutRequest(getStorageAPIURL(), folder.getOwnerID(), path) {
1483 public void onSuccess(Resource _result) {
1484 scheduleFolderHeadCommand(folder, callback);
1488 public void onError(Throwable _t) {
1490 if(_t instanceof RestException) {
1491 displayError("Unable to create folder: " + ((RestException) _t).getHttpStatusText());
1494 displayError("System error creating folder: " + _t.getMessage());
1499 protected void onUnauthorized(Response response) {
1503 newFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1504 newFolder.setHeader(Const.CONTENT_TYPE, "application/folder");
1505 newFolder.setHeader(Const.ACCEPT, "*/*");
1506 newFolder.setHeader(Const.CONTENT_LENGTH, "0");
1507 Scheduler.get().scheduleDeferred(newFolder);
1509 else if(((RestException) t).getHttpStatusCode() == Response.SC_FORBIDDEN) {
1513 displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
1517 displayError("System error heading folder: " + t.getMessage());
1520 LOG("Error heading folder", t);
1525 protected void onUnauthorized(Response response) {
1529 headFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1530 Scheduler.get().scheduleDeferred(headFolder);
1534 public void scheduleFileHeadCommand(File f, final Command callback) {
1535 HeadRequest<File> headFile = new HeadRequest<File>(File.class, getStorageAPIURL(), f.getOwnerID(), f.getUri(), f) {
1538 public void onSuccess(File _result) {
1539 if(callback != null) {
1545 public void onError(Throwable t) {
1546 LOG("Error heading file", t);
1548 if(t instanceof RestException) {
1549 displayError("Error heading file: " + ((RestException) t).getHttpStatusText());
1552 displayError("System error heading file: " + t.getMessage());
1557 protected void onUnauthorized(Response response) {
1561 headFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1562 Scheduler.get().scheduleDeferred(headFile);
1565 public boolean isMySharedSelected() {
1566 return getSelectedTree().equals(getMySharedTreeView());
1569 private Folder getUploadFolder() {
1570 if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1571 return getSelection();
1576 private void updateUploadFolder() {
1577 updateUploadFolder(null);
1580 private void updateUploadFolder(final JsArrayString urls) {
1581 if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1582 Folder f = getSelection();
1583 if(getSelectedTree().equals(getFolderTreeView())) {
1584 updateFolder(f, true, new Command() {
1587 public void execute() {
1590 selectUploadedFiles(urls);
1596 updateOtherSharedFolder(f, true, null);
1601 public native void disableUploadArea() /*-{
1602 var uploader = $wnd.$("#uploader").pluploadQueue();
1603 var dropElm = $wnd.document.getElementById('rightPanel');
1604 $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1607 public native void enableUploadArea() /*-{
1608 var uploader = $wnd.$("#uploader").pluploadQueue();
1609 var dropElm = $wnd.document.getElementById('rightPanel');
1610 $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1611 if (uploader.runtime == 'html5') {
1612 uploader.settings.drop_element = 'rightPanel';
1613 uploader.trigger('PostInit');
1617 public void showUploadAlert(int nOfFiles) {
1618 if(uploadAlert == null) {
1619 uploadAlert = new UploadAlert(this, nOfFiles);
1621 if(!uploadAlert.isShowing()) {
1622 uploadAlert.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
1625 public void setPosition(int offsetWidth, int offsetHeight) {
1626 uploadAlert.setPopupPosition((Window.getClientWidth() - offsetWidth) / 2, statusPanel.getAbsoluteTop() - offsetHeight);
1630 uploadAlert.setNumOfFiles(nOfFiles);
1633 public void hideUploadAlert() {
1634 if(uploadAlert != null && uploadAlert.isShowing()) {
1639 public void selectUploadedFiles(JsArrayString urls) {
1640 List<String> selectedUrls = new ArrayList<String>();
1641 for(int i = 0; i < urls.length(); i++) {
1642 selectedUrls.add(urls.get(i));
1644 fileList.selectByUrl(selectedUrls);
1647 public void purgeContainer(final Folder container) {
1648 String path = "/" + container.getName() + "?delimiter=/";
1649 DeleteRequest delete = new DeleteRequest(getStorageAPIURL(), getUserID(), path) {
1652 protected void onUnauthorized(Response response) {
1657 public void onSuccess(Resource result) {
1658 updateFolder(container, true, null, true);
1662 public void onError(Throwable t) {
1663 LOG("Error deleting trash", t);
1665 if(t instanceof RestException) {
1666 displayError("Error deleting trash: " + ((RestException) t).getHttpStatusText());
1669 displayError("System error deleting trash: " + t.getMessage());
1673 delete.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1674 Scheduler.get().scheduleDeferred(delete);