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;
84 private static final boolean EnableScheduledRefresh = true; // Make false only for debugging purposes.
86 public static final Set<String> HTTPHeadersToIgnoreInLOG = new HashSet<String>();
88 HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_CONNECTION);
89 HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_DATE);
90 HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_KEEP_ALIVE);
91 HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_SERVER);
92 HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_VARY);
93 HTTPHeadersToIgnoreInLOG.add(Const.IF_MODIFIED_SINCE);
96 public static final Configuration config = GWT.create(Configuration.class);
97 public static final String CONFIG_API_PATH = config.apiPath();
99 LOG("CONFIG_API_PATH = ", CONFIG_API_PATH);
102 public static final Dictionary otherProperties = Dictionary.getDictionary(Const.OTHER_PROPERTIES);
103 public static String getFromOtherPropertiesOrDefault(String key, String def) {
105 final String value = otherProperties.get(key);
106 return value == null ? def : value;
113 public static String getFromOtherPropertiesOrNull(String key) {
114 return getFromOtherPropertiesOrDefault(key, null);
117 private static final boolean SHOW_COPYRIGHT;
119 final String valueStr = getFromOtherPropertiesOrDefault("SHOW_COPYRIGHT", "true").trim().toLowerCase();
120 SHOW_COPYRIGHT = "true".equals(valueStr);
121 LOG("SHOW_COPYRIGHT = '", valueStr, "' ==> ", SHOW_COPYRIGHT);
124 public static final String OTHERPROPS_STORAGE_API_URL = getFromOtherPropertiesOrNull("STORAGE_API_URL");
125 public static final String OTHERPROPS_USER_CATALOGS_API_URL = getFromOtherPropertiesOrNull("USER_CATALOGS_API_URL");
127 LOG("STORAGE_API_URL = ", OTHERPROPS_STORAGE_API_URL);
128 LOG("USER_CATALOGS_API_URL = ", OTHERPROPS_USER_CATALOGS_API_URL);
131 public static final String STORAGE_API_URL;
133 if(OTHERPROPS_STORAGE_API_URL != null) {
134 STORAGE_API_URL = OTHERPROPS_STORAGE_API_URL;
136 else if(CONFIG_API_PATH != null) {
137 STORAGE_API_URL = CONFIG_API_PATH;
140 throw new RuntimeException("Unknown STORAGE_API_URL");
143 LOG("Computed STORAGE_API_URL = ", STORAGE_API_URL);
146 public static final String STORAGE_VIEW_URL;
148 final String viewURL = getFromOtherPropertiesOrNull("STORAGE_VIEW_URL");
149 if(viewURL != null) {
150 STORAGE_VIEW_URL = viewURL;
153 STORAGE_VIEW_URL = STORAGE_API_URL;
156 LOG("Computed STORAGE_VIEW_URL = ", STORAGE_VIEW_URL);
159 public static final String PUBLIC_LINK_VIEW_PREFIX = getFromOtherPropertiesOrDefault("PUBLIC_LINK_VIEW_PREFIX", "");
161 public static final String USER_CATALOGS_API_URL;
163 if(OTHERPROPS_USER_CATALOGS_API_URL != null) {
164 USER_CATALOGS_API_URL = OTHERPROPS_USER_CATALOGS_API_URL;
166 else if(OTHERPROPS_STORAGE_API_URL != null) {
167 throw new RuntimeException("STORAGE_API_URL is defined but USER_CATALOGS_API_URL is not");
170 // https://server.com/v1/ --> https://server.com
171 String url = CONFIG_API_PATH;
172 url = Helpers.stripTrailing(url, "/");
173 url = Helpers.upToIncludingLastPart(url, "/");
174 url = Helpers.stripTrailing(url, "/");
175 url = url + "/user_catalogs";
177 USER_CATALOGS_API_URL = url;
179 LOG("Computed USER_CATALOGS_API_URL = ", USER_CATALOGS_API_URL);
183 public interface Style extends CssResource {
184 String commandAnchor();
188 @ClassName("gwt-HTML")
191 String uploadAlert();
193 String uploadAlertLink();
195 String uploadAlertProgress();
197 String uploadAlertPercent();
199 String uploadAlertClose();
202 public interface Resources extends ClientBundle {
203 @Source("Pithos.css")
206 @Source("gr/grnet/pithos/resources/close-popup.png")
207 ImageResource closePopup();
210 public static Resources resources = GWT.create(Resources.class);
213 * Instantiate an application-level image bundle. This object will provide
214 * programmatic access to all the images needed by widgets.
216 static Images images = (Images) GWT.create(Images.class);
218 public String getUserID() {
222 public UserCatalogs getUserCatalogs() {
226 public String getCurrentUserDisplayNameOrID() {
227 final String displayName = userCatalogs.getDisplayName(getUserID());
228 return displayName == null ? getUserID() : displayName;
231 public boolean hasDisplayNameForUserID(String userID) {
232 return userCatalogs.getDisplayName(userID) != null;
235 public boolean hasIDForUserDisplayName(String userDisplayName) {
236 return userCatalogs.getID(userDisplayName) != null;
239 public String getDisplayNameForUserID(String userID) {
240 return userCatalogs.getDisplayName(userID);
243 public String getIDForUserDisplayName(String userDisplayName) {
244 return userCatalogs.getID(userDisplayName);
247 public List<String> getDisplayNamesForUserIDs(List<String> userIDs) {
248 if(userIDs == null) {
249 userIDs = new ArrayList<String>();
251 final List<String> userDisplayNames = new ArrayList<String>();
252 for(String userID : userIDs) {
253 final String displayName = getDisplayNameForUserID(userID);
254 userDisplayNames.add(displayName);
257 return userDisplayNames;
260 public List<String> filterUserIDsWithUnknownDisplayName(Collection<String> userIDs) {
261 if(userIDs == null) {
262 userIDs = new ArrayList<String>();
264 final List<String> filtered = new ArrayList<String>();
265 for(String userID : userIDs) {
266 if(!this.userCatalogs.hasID(userID)) {
267 filtered.add(userID);
273 public void setAccount(AccountResource acct) {
277 public AccountResource getAccount() {
281 public void updateFolder(Folder f, boolean showfiles, Command callback, final boolean openParent) {
282 folderTreeView.updateFolder(f, showfiles, callback, openParent);
285 public void updateGroupNode(Group group) {
286 groupTreeView.updateGroupNode(group);
289 public void updateMySharedRoot() {
290 mysharedTreeView.updateRoot();
293 public void updateSharedFolder(Folder f, boolean showfiles, Command callback) {
294 mysharedTreeView.updateFolder(f, showfiles, callback);
297 public void updateSharedFolder(Folder f, boolean showfiles) {
298 updateSharedFolder(f, showfiles, null);
301 public void updateOtherSharedFolder(Folder f, boolean showfiles, Command callback) {
302 otherSharedTreeView.updateFolder(f, showfiles, callback);
305 public MysharedTreeView getMySharedTreeView() {
306 return mysharedTreeView;
310 * An aggregate image bundle that pulls together all the images for this
311 * application into a single bundle.
313 public interface Images extends TopPanel.Images, FileList.Images, ToolsMenu.Images {
315 @Source("gr/grnet/pithos/resources/document.png")
316 ImageResource folders();
318 @Source("gr/grnet/pithos/resources/advancedsettings.png")
319 @ImageOptions(width = 32, height = 32)
320 ImageResource tools();
323 private Throwable error;
326 * The Application Clipboard implementation;
328 private Clipboard clipboard = new Clipboard();
331 * The top panel that contains the menu bar.
333 private TopPanel topPanel;
336 * The panel that contains the various system messages.
338 private MessagePanel messagePanel = new MessagePanel(this, Pithos.images);
341 * The bottom panel that contains the status bar.
343 StatusPanel statusPanel = null;
346 * The file list widget.
348 private FileList fileList;
351 * The tab panel that occupies the right side of the screen.
353 private VerticalPanel inner = new VerticalPanel();
357 * The split panel that will contain the left and right panels.
359 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
362 * The currently selected item in the application, for use by the Edit menu
363 * commands. Potential types are Folder, File, User and Group.
365 private Object currentSelection;
367 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
370 * The ID that uniquely identifies the user in Pithos+.
371 * Currently this is a UUID. It used to be the user's email.
373 private String userID = null;
376 * Holds mappings from user UUIDs to emails and vice-versa.
378 private UserCatalogs userCatalogs = new UserCatalogs();
381 * The authentication token of the current user.
383 private String userToken;
387 SingleSelectionModel<Folder> folderTreeSelectionModel;
388 FolderTreeViewModel folderTreeViewModel;
389 FolderTreeView folderTreeView;
391 SingleSelectionModel<Folder> mysharedTreeSelectionModel;
392 MysharedTreeViewModel mysharedTreeViewModel;
393 MysharedTreeView mysharedTreeView = null;
395 protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
396 OtherSharedTreeViewModel otherSharedTreeViewModel;
397 OtherSharedTreeView otherSharedTreeView = null;
399 GroupTreeViewModel groupTreeViewModel;
400 GroupTreeView groupTreeView;
402 TreeView selectedTree;
403 protected AccountResource account;
407 List<Composite> treeViews = new ArrayList<Composite>();
409 @SuppressWarnings("rawtypes")
410 List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
412 public Button upload;
414 private HTML numOfFiles;
416 private Toolbar toolbar;
418 private FileUploadDialog fileUploadDialog = new FileUploadDialog(this);
420 UploadAlert uploadAlert;
425 public void onModuleLoad() {
426 if(parseUserCredentials()) {
431 static native void __ConsoleLog(String message) /*-{
432 try { console.log(message); } catch (e) {}
435 public static void LOGError(Throwable error, StringBuilder sb) {
436 if(!isLOGEnabled()) { return; }
438 sb.append("\nException: [" + error.toString().replace("\n", "\n ") + "]");
439 Throwable cause = error.getCause();
441 sb.append("\nCauses:\n");
442 while(cause != null) {
444 sb.append("[" + cause.toString().replace("\n", "\n ") + "]");
446 cause = cause.getCause();
453 StackTraceElement[] stackTrace = error.getStackTrace();
454 sb.append("Stack trace (" + stackTrace.length + " elements):\n");
455 for(int i = 0; i < stackTrace.length; i++) {
456 StackTraceElement errorElem = stackTrace[i];
457 sb.append(" [" + i + "] ");
458 sb.append(errorElem.toString());
463 public static void LOGError(Throwable error) {
464 if(!isLOGEnabled()) { return; }
466 final StringBuilder sb = new StringBuilder();
468 if(sb.length() > 0) {
469 __ConsoleLog(sb.toString());
473 public static boolean isLOGEnabled() {
477 public static void LOG(Object ...args) {
478 if(!isLOGEnabled()) { return; }
480 final StringBuilder sb = new StringBuilder();
481 for(Object arg : args) {
482 if(arg instanceof Throwable) {
483 LOGError((Throwable) arg, sb);
490 if(sb.length() > 0) {
491 __ConsoleLog(sb.toString());
495 private void initialize() {
496 userCatalogs.updateWithIDAndName("*", "All Pithos users");
498 lastModified = new Date(); //Initialize if-modified-since value with now.
499 resources.pithosCss().ensureInjected();
500 boolean bareContent = Window.Location.getParameter("noframe") != null;
501 String contentWidth = bareContent ? Const.PERCENT_100 : Const.PERCENT_75;
503 VerticalPanel outer = new VerticalPanel();
504 outer.setWidth(Const.PERCENT_100);
506 outer.addStyleName("pithos-outer");
510 topPanel = new TopPanel(this, Pithos.images);
511 topPanel.setWidth(Const.PERCENT_100);
513 outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
516 messagePanel.setVisible(false);
517 outer.add(messagePanel);
518 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
519 outer.setCellVerticalAlignment(messagePanel, HasVerticalAlignment.ALIGN_MIDDLE);
521 HorizontalPanel header = new HorizontalPanel();
522 header.addStyleName("pithos-header");
523 header.setWidth(contentWidth);
525 header.addStyleName("pithos-header-noframe");
527 upload = new Button("Upload", new ClickHandler() {
529 public void onClick(ClickEvent event) {
530 if(getSelection() != null) {
531 new UploadFileCommand(Pithos.this, null, getSelection()).execute();
535 upload.addStyleName("pithos-uploadButton");
537 header.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_LEFT);
538 header.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
540 toolbar = new Toolbar(this);
542 header.setCellHorizontalAlignment(toolbar, HasHorizontalAlignment.ALIGN_CENTER);
543 header.setCellVerticalAlignment(toolbar, HasVerticalAlignment.ALIGN_MIDDLE);
545 HorizontalPanel folderStatistics = new HorizontalPanel();
546 folderStatistics.addStyleName("pithos-folderStatistics");
547 numOfFiles = new HTML();
548 folderStatistics.add(numOfFiles);
549 folderStatistics.setCellVerticalAlignment(numOfFiles, HasVerticalAlignment.ALIGN_MIDDLE);
550 HTML numOfFilesLabel = new HTML(" Files");
551 folderStatistics.add(numOfFilesLabel);
552 folderStatistics.setCellVerticalAlignment(numOfFilesLabel, HasVerticalAlignment.ALIGN_MIDDLE);
553 header.add(folderStatistics);
554 header.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
555 header.setCellVerticalAlignment(folderStatistics, HasVerticalAlignment.ALIGN_MIDDLE);
556 header.setCellWidth(folderStatistics, "40px");
558 outer.setCellHorizontalAlignment(header, HasHorizontalAlignment.ALIGN_CENTER);
559 // Inner contains the various lists
560 inner.sinkEvents(Event.ONCONTEXTMENU);
561 inner.setWidth(Const.PERCENT_100);
563 folderTreeSelectionModel = new SingleSelectionModel<Folder>();
564 folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
566 public void onSelectionChange(SelectionChangeEvent event) {
567 if(folderTreeSelectionModel.getSelectedObject() != null) {
568 deselectOthers(folderTreeView, folderTreeSelectionModel);
569 applyPermissions(folderTreeSelectionModel.getSelectedObject());
570 Folder f = folderTreeSelectionModel.getSelectedObject();
571 updateFolder(f, true, new Command() {
574 public void execute() {
578 showRelevantToolbarButtons();
581 if(getSelectedTree().equals(folderTreeView)) {
582 setSelectedTree(null);
584 if(getSelectedTree() == null) {
585 showRelevantToolbarButtons();
590 selectionModels.add(folderTreeSelectionModel);
592 folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
593 folderTreeView = new FolderTreeView(folderTreeViewModel);
594 treeViews.add(folderTreeView);
596 fileList = new FileList(this, images);
599 trees = new VerticalPanel();
600 trees.setWidth(Const.PERCENT_100);
602 // Add the left and right panels to the split panel.
603 splitPanel.setLeftWidget(trees);
604 FlowPanel right = new FlowPanel();
605 right.getElement().setId("rightPanel");
607 splitPanel.setRightWidget(right);
608 splitPanel.setSplitPosition("219px");
609 splitPanel.setSize(Const.PERCENT_100, Const.PERCENT_100);
610 splitPanel.addStyleName("pithos-splitPanel");
611 splitPanel.setWidth(contentWidth);
612 outer.add(splitPanel);
613 outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
616 statusPanel = new StatusPanel();
617 statusPanel.setWidth(Const.PERCENT_100);
618 outer.add(statusPanel);
619 outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
622 splitPanel.addStyleName("pithos-splitPanel-noframe");
625 // Hook the window resize event, so that we can adjust the UI.
626 Window.addResizeHandler(this);
627 // Clear out the window's built-in margin, because we want to take
628 // advantage of the entire client area.
629 Window.setMargin("0px");
630 // Finally, add the outer panel to the RootPanel, so that it will be
632 RootPanel.get().add(outer);
633 // Call the window resized handler to get the initial sizes setup. Doing
634 // this in a deferred command causes it to occur after all widgets'
635 // sizes have been computed by the browser.
636 Scheduler.get().scheduleIncremental(new RepeatingCommand() {
639 public boolean execute() {
640 if(!isCloudbarReady()) {
643 onWindowResized(Window.getClientHeight());
648 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
650 public void execute() {
651 LOG("Pithos::initialize() Calling Pithos::fetchAccount()");
652 fetchAccount(new Command() {
655 public void execute() {
656 if(!account.hasHomeContainer()) {
657 createHomeContainer(account, this);
659 else if(!account.hasTrashContainer()) {
660 createTrashContainer(this);
663 for(Folder f : account.getContainers()) {
664 if(f.getName().equals(Const.TRASH_CONTAINER)) {
669 trees.add(folderTreeView);
670 folderTreeViewModel.initialize(account, new Command() {
673 public void execute() {
674 createMySharedTree();
678 HorizontalPanel separator = new HorizontalPanel();
679 separator.addStyleName("pithos-statisticsSeparator");
680 separator.add(new HTML(""));
681 trees.add(separator);
683 groupTreeViewModel = new GroupTreeViewModel(Pithos.this);
684 groupTreeView = new GroupTreeView(groupTreeViewModel);
685 treeViews.add(groupTreeView);
686 trees.add(groupTreeView);
687 folderTreeView.showStatistics(account);
695 public void scheduleRefresh() {
696 if(!Pithos.EnableScheduledRefresh) { return; }
698 Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {
701 public boolean execute() {
702 final Folder f = getSelection();
707 HeadRequest<Folder> head = new HeadRequest<Folder>(Folder.class, getStorageAPIURL(), f.getOwnerID(), "/" + f.getContainer()) {
710 public void onSuccess(Folder _result) {
711 lastModified = new Date();
712 if(getSelectedTree().equals(folderTreeView)) {
713 updateFolder(f, true, new Command() {
716 public void execute() {
722 else if(getSelectedTree().equals(mysharedTreeView)) {
723 updateSharedFolder(f, true, new Command() {
726 public void execute() {
737 public void onError(Throwable t) {
738 if(t instanceof RestException && ((RestException) t).getHttpStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
741 else if(retries >= MAX_RETRIES) {
742 LOG("Error heading folder. ", t);
744 if(t instanceof RestException) {
745 displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
748 displayError("System error heading folder: " + t.getMessage());
752 LOG("Retry ", retries);
753 Scheduler.get().scheduleDeferred(this);
758 protected void onUnauthorized(Response response) {
759 if(retries >= MAX_RETRIES) {
764 Scheduler.get().scheduleDeferred(this);
768 head.setHeader(Const.X_AUTH_TOKEN, getUserToken());
769 head.setHeader(Const.IF_MODIFIED_SINCE, DateTimeFormat.getFormat(Const.DATE_FORMAT_1).format(lastModified, TimeZone.createTimeZone(0)) + " GMT");
770 Scheduler.get().scheduleDeferred(head);
777 public void applyPermissions(Folder f) {
780 upload.setEnabled(false);
784 Boolean[] perms = f.getPermissions().get(userID);
785 if(f.getOwnerID().equals(userID) || (perms != null && perms[1] != null && perms[1])) {
786 upload.setEnabled(true);
790 upload.setEnabled(false);
796 upload.setEnabled(false);
801 @SuppressWarnings({"rawtypes", "unchecked"})
802 public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
803 selectedTree = _selectedTree;
805 for(SingleSelectionModel s : selectionModels) {
806 if(!s.equals(model) && s.getSelectedObject() != null) {
807 s.setSelected(s.getSelectedObject(), false);
812 public void showFiles(final Folder f) {
813 Set<File> files = f.getFiles();
817 public void showFiles(Set<File> files) {
818 fileList.setFiles(new ArrayList<File>(files));
822 * Parse and store the user credentials to the appropriate fields.
824 private boolean parseUserCredentials() {
825 final String cookie = otherProperties.get(Const.AUTH_COOKIE);
826 String auth = Cookies.getCookie(cookie);
831 if(auth.startsWith("\"")) {
832 auth = auth.substring(1);
834 if(auth.endsWith("\"")) {
835 auth = auth.substring(0, auth.length() - 1);
837 String[] authSplit = auth.split("\\" + config.cookieSeparator(), 2);
838 if(authSplit.length != 2) {
842 this.userID = authSplit[0];
843 this.userToken = authSplit[1];
849 * Redirect the user to the login page for authentication.
851 protected void authenticateUser() {
852 Dictionary otherProperties = Dictionary.getDictionary(Const.OTHER_PROPERTIES);
853 Window.Location.assign(otherProperties.get(Const.LOGIN_URL) + Window.Location.getHref());
856 public void fetchAccount(final Command callback) {
857 String path = "?format=json";
859 GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getStorageAPIURL(), userID, path) {
861 public void onSuccess(AccountResource accountResource) {
862 account = accountResource;
863 if(callback != null) {
867 final List<String> memberIDs = new ArrayList<String>();
868 final List<Group> groups = account.getGroups();
869 for(Group group : groups) {
870 memberIDs.addAll(group.getMemberIDs());
872 memberIDs.add(Pithos.this.getUserID());
874 final List<String> theUnknown = Pithos.this.filterUserIDsWithUnknownDisplayName(memberIDs);
875 // Initialize the user catalog
876 new UpdateUserCatalogs(Pithos.this, theUnknown).scheduleDeferred();
877 LOG("Called new UpdateUserCatalogs(Pithos.this, theUnknown).scheduleDeferred();");
881 public void onError(Throwable t) {
882 LOG("Error getting account", t);
884 if(t instanceof RestException) {
885 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
888 displayError("System error fetching user data: " + t.getMessage());
893 protected void onUnauthorized(Response response) {
897 getAccount.setHeader(Const.X_AUTH_TOKEN, userToken);
898 Scheduler.get().scheduleDeferred(getAccount);
901 public void updateStatistics() {
902 HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getStorageAPIURL(), userID, "", account) {
905 public void onSuccess(AccountResource _result) {
906 folderTreeView.showStatistics(account);
910 public void onError(Throwable t) {
911 LOG("Error getting account", t);
913 if(t instanceof RestException) {
914 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
917 displayError("System error fetching user data: " + t.getMessage());
922 protected void onUnauthorized(Response response) {
926 headAccount.setHeader(Const.X_AUTH_TOKEN, userToken);
927 Scheduler.get().scheduleDeferred(headAccount);
930 protected void createHomeContainer(final AccountResource _account, final Command callback) {
931 String path = "/" + Const.HOME_CONTAINER;
932 PutRequest createPithos = new PutRequest(getStorageAPIURL(), getUserID(), path) {
934 public void onSuccess(Resource result) {
935 if(!_account.hasTrashContainer()) {
936 createTrashContainer(callback);
939 fetchAccount(callback);
944 public void onError(Throwable t) {
945 LOG("Error creating pithos", t);
947 if(t instanceof RestException) {
948 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
951 displayError("System error Error creating pithos: " + t.getMessage());
956 protected void onUnauthorized(Response response) {
960 createPithos.setHeader(Const.X_AUTH_TOKEN, getUserToken());
961 Scheduler.get().scheduleDeferred(createPithos);
964 protected void createTrashContainer(final Command callback) {
965 String path = "/" + Const.TRASH_CONTAINER;
966 PutRequest createPithos = new PutRequest(getStorageAPIURL(), getUserID(), path) {
968 public void onSuccess(Resource result) {
969 fetchAccount(callback);
973 public void onError(Throwable t) {
974 LOG("Error creating pithos", t);
976 if(t instanceof RestException) {
977 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
980 displayError("System error Error creating pithos: " + t.getMessage());
985 protected void onUnauthorized(Response response) {
989 createPithos.setHeader(Const.X_AUTH_TOKEN, getUserToken());
990 Scheduler.get().scheduleDeferred(createPithos);
994 * Creates an HTML fragment that places an image & caption together, for use
997 * @param imageProto an image prototype for an image
998 * @param caption the group caption
999 * @return the header HTML fragment
1001 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
1002 String captionHTML = "<table class='caption' cellpadding='0' "
1003 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
1004 + "</td><td id =" + caption + " class='rcaption'><b style='white-space:nowrap'> "
1005 + caption + "</b></td></tr></table>";
1009 protected void onWindowResized(int height) {
1010 // Adjust the split panel to take up the available room in the window.
1011 int newHeight = height - splitPanel.getAbsoluteTop() - 153;
1015 splitPanel.setHeight("" + newHeight);
1016 inner.setHeight("" + newHeight);
1019 native boolean isCloudbarReady()/*-{
1020 if ($wnd.$("div.cloudbar") && $wnd.$("div.cloudbar").height() > 0)
1026 public void onResize(ResizeEvent event) {
1027 int height = event.getHeight();
1028 onWindowResized(height);
1032 * Display an error message.
1034 * @param msg the message to display
1036 public void displayError(String msg) {
1037 messagePanel.displayError(msg);
1038 onWindowResized(Window.getClientHeight());
1042 * Display a warning message.
1044 * @param msg the message to display
1046 public void displayWarning(String msg) {
1047 messagePanel.displayWarning(msg);
1048 onWindowResized(Window.getClientHeight());
1052 * Display an informational message.
1054 * @param msg the message to display
1056 public void displayInformation(String msg) {
1057 messagePanel.displayInformation(msg);
1058 onWindowResized(Window.getClientHeight());
1062 * Retrieve the fileList.
1064 * @return the fileList
1066 public FileList getFileList() {
1071 * Retrieve the topPanel.
1073 * @return the topPanel
1075 TopPanel getTopPanel() {
1080 * Retrieve the clipboard.
1082 * @return the clipboard
1084 public Clipboard getClipboard() {
1088 public StatusPanel getStatusPanel() {
1092 public String getUserToken() {
1096 public static native void preventIESelection() /*-{
1097 $doc.body.onselectstart = function () {
1102 public static native void enableIESelection() /*-{
1103 if ($doc.body.onselectstart != null)
1104 $doc.body.onselectstart = null;
1107 public static String getStorageAPIURL() {
1108 return STORAGE_API_URL;
1111 public static String getStorageViewURL() {
1112 return STORAGE_VIEW_URL;
1115 public static boolean isShowCopyrightMessage() {
1116 return SHOW_COPYRIGHT;
1119 public static String getUserCatalogsURL() {
1120 return USER_CATALOGS_API_URL;
1123 public static String getFileViewURL(File file) {
1124 return Pithos.getStorageViewURL() + file.getOwnerID() + file.getUri();
1127 public static String getVersionedFileViewURL(File file, int version) {
1128 return getFileViewURL(file) + "?version=" + version;
1132 * History support for folder navigation
1133 * adds a new browser history entry
1137 public void updateHistory(String key) {
1138 // Replace any whitespace of the initial string to "+"
1139 // String result = key.replaceAll("\\s","+");
1140 // Add a new browser history entry.
1141 // History.newItem(result);
1142 History.newItem(key);
1145 public void deleteFolder(final Folder folder, final Command callback) {
1146 final PleaseWaitPopup pwp = new PleaseWaitPopup();
1148 String path = "/" + folder.getContainer() + "/" + folder.getPrefix() + "?delimiter=/" + "&t=" + System.currentTimeMillis();
1149 DeleteRequest deleteFolder = new DeleteRequest(getStorageAPIURL(), folder.getOwnerID(), path) {
1152 protected void onUnauthorized(Response response) {
1158 public void onSuccess(Resource result) {
1159 updateFolder(folder.getParent(), true, new Command() {
1162 public void execute() {
1163 folderTreeSelectionModel.setSelected(folder.getParent(), true);
1165 if(callback != null) {
1174 public void onError(Throwable t) {
1177 if(t instanceof RestException) {
1178 if(((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND) {
1179 displayError("Unable to delete folder: " + ((RestException) t).getHttpStatusText());
1186 displayError("System error unable to delete folder: " + t.getMessage());
1191 deleteFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1192 Scheduler.get().scheduleDeferred(deleteFolder);
1195 public FolderTreeView getFolderTreeView() {
1196 return folderTreeView;
1199 public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
1200 if(iter.hasNext()) {
1201 File file = iter.next();
1202 String path = targetUri + "/" + file.getName();
1203 PutRequest copyFile = new PutRequest(getStorageAPIURL(), targetUsername, path) {
1205 public void onSuccess(Resource result) {
1206 copyFiles(iter, targetUsername, targetUri, callback);
1210 public void onError(Throwable t) {
1213 if(t instanceof RestException) {
1214 displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
1217 displayError("System error unable to copy file: " + t.getMessage());
1222 protected void onUnauthorized(Response response) {
1226 copyFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1227 copyFile.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(file.getUri()));
1228 if(!file.getOwnerID().equals(targetUsername)) {
1229 copyFile.setHeader(Const.X_SOURCE_ACCOUNT, URL.encodePathSegment(file.getOwnerID()));
1231 copyFile.setHeader(Const.CONTENT_TYPE, file.getContentType());
1232 Scheduler.get().scheduleDeferred(copyFile);
1234 else if(callback != null) {
1239 public void copyFolder(final Folder f, final String targetUsername, final String targetUri, boolean move, final Command callback) {
1240 String path = targetUri + "?delimiter=/";
1241 PutRequest copyFolder = new PutRequest(getStorageAPIURL(), targetUsername, path) {
1243 public void onSuccess(Resource result) {
1244 if(callback != null) {
1250 public void onError(Throwable t) {
1253 if(t instanceof RestException) {
1254 displayError("Unable to copy folder: " + ((RestException) t).getHttpStatusText());
1257 displayError("System error copying folder: " + t.getMessage());
1262 protected void onUnauthorized(Response response) {
1266 copyFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1267 copyFolder.setHeader(Const.ACCEPT, "*/*");
1268 copyFolder.setHeader(Const.CONTENT_LENGTH, "0");
1269 copyFolder.setHeader(Const.CONTENT_TYPE, "application/directory");
1270 if(!f.getOwnerID().equals(targetUsername)) {
1271 copyFolder.setHeader(Const.X_SOURCE_ACCOUNT, f.getOwnerID());
1274 copyFolder.setHeader(Const.X_MOVE_FROM, URL.encodePathSegment(f.getUri()));
1277 copyFolder.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(f.getUri()));
1279 Scheduler.get().scheduleDeferred(copyFolder);
1282 public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1283 selectionModels.add(model);
1286 public OtherSharedTreeView getOtherSharedTreeView() {
1287 return otherSharedTreeView;
1290 public void updateTrash(boolean showFiles, Command callback) {
1291 updateFolder(trash, showFiles, callback, true);
1294 public void updateGroupsNode() {
1295 groupTreeView.updateGroupNode(null);
1298 public Group addGroup(String groupname) {
1299 Group newGroup = new Group(groupname);
1300 account.addGroup(newGroup);
1301 groupTreeView.updateGroupNode(null);
1305 public void removeGroup(Group group) {
1306 account.removeGroup(group);
1310 public TreeView getSelectedTree() {
1311 return selectedTree;
1314 public void setSelectedTree(TreeView selected) {
1315 selectedTree = selected;
1318 public Folder getSelection() {
1319 if(selectedTree != null) {
1320 return selectedTree.getSelection();
1325 public void showFolderStatistics(int folderFileCount) {
1326 numOfFiles.setHTML(String.valueOf(folderFileCount));
1329 public GroupTreeView getGroupTreeView() {
1330 return groupTreeView;
1333 public void sessionExpired() {
1334 new SessionExpiredDialog(this).center();
1337 public void updateRootFolder(Command callback) {
1338 updateFolder(account.getPithos(), false, callback, true);
1341 void createMySharedTree() {
1342 LOG("Pithos::createMySharedTree()");
1343 mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1344 mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1346 public void onSelectionChange(SelectionChangeEvent event) {
1347 if(mysharedTreeSelectionModel.getSelectedObject() != null) {
1348 deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1349 upload.setEnabled(false);
1350 disableUploadArea();
1351 updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1352 showRelevantToolbarButtons();
1355 if(getSelectedTree().equals(mysharedTreeView)) {
1356 setSelectedTree(null);
1358 if(getSelectedTree() == null) {
1359 showRelevantToolbarButtons();
1364 selectionModels.add(mysharedTreeSelectionModel);
1365 mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1366 mysharedTreeViewModel.initialize(new Command() {
1369 public void execute() {
1370 mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1371 trees.insert(mysharedTreeView, 2);
1372 treeViews.add(mysharedTreeView);
1373 createOtherSharedTree();
1378 void createOtherSharedTree() {
1379 LOG("Pithos::createOtherSharedTree()");
1380 otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1381 otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1383 public void onSelectionChange(SelectionChangeEvent event) {
1384 if(otherSharedTreeSelectionModel.getSelectedObject() != null) {
1385 deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1386 applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1387 updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true, null);
1388 showRelevantToolbarButtons();
1391 if(getSelectedTree().equals(otherSharedTreeView)) {
1392 setSelectedTree(null);
1394 if(getSelectedTree() == null) {
1395 showRelevantToolbarButtons();
1400 selectionModels.add(otherSharedTreeSelectionModel);
1401 otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1402 // #3784 We show it empty...
1403 otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel, true);
1404 trees.insert(otherSharedTreeView, 1);
1406 LOG("Pithos::createOtherSharedTree(), initializing otherSharedTreeViewModel with a callback");
1407 otherSharedTreeViewModel.initialize(new Command() {
1409 public void execute() {
1410 // #3784 ... then remove the empty stuff and add a new view with the populated model
1411 trees.remove(otherSharedTreeView);
1413 otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel, false);
1414 trees.insert(otherSharedTreeView, 1);
1415 treeViews.add(otherSharedTreeView);
1421 public String getErrorData() {
1422 final StringBuilder sb = new StringBuilder();
1423 final String NL = Const.NL;
1424 Throwable t = this.error;
1426 sb.append(t.toString());
1428 StackTraceElement[] traces = t.getStackTrace();
1429 for(StackTraceElement trace : traces) {
1431 sb.append(trace.getClassName());
1433 sb.append(trace.getMethodName());
1434 sb.append("() at ");
1435 sb.append(trace.getFileName());
1437 sb.append(trace.getLineNumber());
1444 return sb.toString();
1447 public void setError(Throwable t) {
1452 public void showRelevantToolbarButtons() {
1453 toolbar.showRelevantButtons();
1456 public FileUploadDialog getFileUploadDialog() {
1457 if(fileUploadDialog == null) {
1458 fileUploadDialog = new FileUploadDialog(this);
1460 return fileUploadDialog;
1463 public void hideUploadIndicator() {
1464 upload.removeStyleName("pithos-uploadButton-loading");
1465 upload.setTitle("");
1468 public void showUploadIndicator() {
1469 upload.addStyleName("pithos-uploadButton-loading");
1470 upload.setTitle("Upload in progress. Click for details.");
1473 public void scheduleFolderHeadCommand(final Folder folder, final Command callback) {
1474 if(folder == null) {
1475 if(callback != null) {
1480 HeadRequest<Folder> headFolder = new HeadRequest<Folder>(Folder.class, getStorageAPIURL(), folder.getOwnerID(), folder.getUri(), folder) {
1483 public void onSuccess(Folder _result) {
1484 if(callback != null) {
1490 public void onError(Throwable t) {
1491 if(t instanceof RestException) {
1492 if(((RestException) t).getHttpStatusCode() == Response.SC_NOT_FOUND) {
1493 final String path = folder.getUri();
1494 PutRequest newFolder = new PutRequest(getStorageAPIURL(), folder.getOwnerID(), path) {
1496 public void onSuccess(Resource _result) {
1497 scheduleFolderHeadCommand(folder, callback);
1501 public void onError(Throwable _t) {
1503 if(_t instanceof RestException) {
1504 displayError("Unable to create folder: " + ((RestException) _t).getHttpStatusText());
1507 displayError("System error creating folder: " + _t.getMessage());
1512 protected void onUnauthorized(Response response) {
1516 newFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1517 newFolder.setHeader(Const.CONTENT_TYPE, "application/folder");
1518 newFolder.setHeader(Const.ACCEPT, "*/*");
1519 newFolder.setHeader(Const.CONTENT_LENGTH, "0");
1520 Scheduler.get().scheduleDeferred(newFolder);
1522 else if(((RestException) t).getHttpStatusCode() == Response.SC_FORBIDDEN) {
1526 displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
1530 displayError("System error heading folder: " + t.getMessage());
1533 LOG("Error heading folder", t);
1538 protected void onUnauthorized(Response response) {
1542 headFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1543 Scheduler.get().scheduleDeferred(headFolder);
1547 public void scheduleFileHeadCommand(File f, final Command callback) {
1548 HeadRequest<File> headFile = new HeadRequest<File>(File.class, getStorageAPIURL(), f.getOwnerID(), f.getUri(), f) {
1551 public void onSuccess(File _result) {
1552 if(callback != null) {
1558 public void onError(Throwable t) {
1559 LOG("Error heading file", t);
1561 if(t instanceof RestException) {
1562 displayError("Error heading file: " + ((RestException) t).getHttpStatusText());
1565 displayError("System error heading file: " + t.getMessage());
1570 protected void onUnauthorized(Response response) {
1574 headFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1575 Scheduler.get().scheduleDeferred(headFile);
1578 public boolean isMySharedSelected() {
1579 return getSelectedTree().equals(getMySharedTreeView());
1582 private Folder getUploadFolder() {
1583 if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1584 return getSelection();
1589 private void updateUploadFolder() {
1590 updateUploadFolder(null);
1593 private void updateUploadFolder(final JsArrayString urls) {
1594 if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1595 Folder f = getSelection();
1596 if(getSelectedTree().equals(getFolderTreeView())) {
1597 updateFolder(f, true, new Command() {
1600 public void execute() {
1603 selectUploadedFiles(urls);
1609 updateOtherSharedFolder(f, true, null);
1614 public native void disableUploadArea() /*-{
1615 var uploader = $wnd.$("#uploader").pluploadQueue();
1616 var dropElm = $wnd.document.getElementById('rightPanel');
1617 $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1620 public native void enableUploadArea() /*-{
1621 var uploader = $wnd.$("#uploader").pluploadQueue();
1622 var dropElm = $wnd.document.getElementById('rightPanel');
1623 $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1624 if (uploader.runtime == 'html5') {
1625 uploader.settings.drop_element = 'rightPanel';
1626 uploader.trigger('PostInit');
1630 public void showUploadAlert(int nOfFiles) {
1631 if(uploadAlert == null) {
1632 uploadAlert = new UploadAlert(this, nOfFiles);
1634 if(!uploadAlert.isShowing()) {
1635 uploadAlert.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
1638 public void setPosition(int offsetWidth, int offsetHeight) {
1639 uploadAlert.setPopupPosition((Window.getClientWidth() - offsetWidth) / 2, statusPanel.getAbsoluteTop() - offsetHeight);
1643 uploadAlert.setNumOfFiles(nOfFiles);
1646 public void hideUploadAlert() {
1647 if(uploadAlert != null && uploadAlert.isShowing()) {
1652 public void selectUploadedFiles(JsArrayString urls) {
1653 List<String> selectedUrls = new ArrayList<String>();
1654 for(int i = 0; i < urls.length(); i++) {
1655 selectedUrls.add(urls.get(i));
1657 fileList.selectByUrl(selectedUrls);
1660 public void purgeContainer(final Folder container) {
1661 String path = "/" + container.getName() + "?delimiter=/";
1662 DeleteRequest delete = new DeleteRequest(getStorageAPIURL(), getUserID(), path) {
1665 protected void onUnauthorized(Response response) {
1670 public void onSuccess(Resource result) {
1671 updateFolder(container, true, null, true);
1675 public void onError(Throwable t) {
1676 LOG("Error deleting trash", t);
1678 if(t instanceof RestException) {
1679 displayError("Error deleting trash: " + ((RestException) t).getHttpStatusText());
1682 displayError("System error deleting trash: " + t.getMessage());
1686 delete.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1687 Scheduler.get().scheduleDeferred(delete);