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];
845 String gotoUrl = Window.Location.getParameter("goto");
846 if(gotoUrl != null && gotoUrl.length() > 0) {
847 Window.Location.assign(gotoUrl);
854 * Redirect the user to the login page for authentication.
856 protected void authenticateUser() {
857 Dictionary otherProperties = Dictionary.getDictionary(Const.OTHER_PROPERTIES);
858 Window.Location.assign(otherProperties.get(Const.LOGIN_URL) + Window.Location.getHref());
861 public void fetchAccount(final Command callback) {
862 String path = "?format=json";
864 GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getStorageAPIURL(), userID, path) {
866 public void onSuccess(AccountResource accountResource) {
867 account = accountResource;
868 if(callback != null) {
872 final List<String> memberIDs = new ArrayList<String>();
873 final List<Group> groups = account.getGroups();
874 for(Group group : groups) {
875 memberIDs.addAll(group.getMemberIDs());
877 memberIDs.add(Pithos.this.getUserID());
879 final List<String> theUnknown = Pithos.this.filterUserIDsWithUnknownDisplayName(memberIDs);
880 // Initialize the user catalog
881 new UpdateUserCatalogs(Pithos.this, theUnknown).scheduleDeferred();
882 LOG("Called new UpdateUserCatalogs(Pithos.this, theUnknown).scheduleDeferred();");
886 public void onError(Throwable t) {
887 LOG("Error getting account", t);
889 if(t instanceof RestException) {
890 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
893 displayError("System error fetching user data: " + t.getMessage());
898 protected void onUnauthorized(Response response) {
902 getAccount.setHeader(Const.X_AUTH_TOKEN, userToken);
903 Scheduler.get().scheduleDeferred(getAccount);
906 public void updateStatistics() {
907 HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getStorageAPIURL(), userID, "", account) {
910 public void onSuccess(AccountResource _result) {
911 folderTreeView.showStatistics(account);
915 public void onError(Throwable t) {
916 LOG("Error getting account", t);
918 if(t instanceof RestException) {
919 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
922 displayError("System error fetching user data: " + t.getMessage());
927 protected void onUnauthorized(Response response) {
931 headAccount.setHeader(Const.X_AUTH_TOKEN, userToken);
932 Scheduler.get().scheduleDeferred(headAccount);
935 protected void createHomeContainer(final AccountResource _account, final Command callback) {
936 String path = "/" + Const.HOME_CONTAINER;
937 PutRequest createPithos = new PutRequest(getStorageAPIURL(), getUserID(), path) {
939 public void onSuccess(Resource result) {
940 if(!_account.hasTrashContainer()) {
941 createTrashContainer(callback);
944 fetchAccount(callback);
949 public void onError(Throwable t) {
950 LOG("Error creating pithos", t);
952 if(t instanceof RestException) {
953 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
956 displayError("System error Error creating pithos: " + t.getMessage());
961 protected void onUnauthorized(Response response) {
965 createPithos.setHeader(Const.X_AUTH_TOKEN, getUserToken());
966 Scheduler.get().scheduleDeferred(createPithos);
969 protected void createTrashContainer(final Command callback) {
970 String path = "/" + Const.TRASH_CONTAINER;
971 PutRequest createPithos = new PutRequest(getStorageAPIURL(), getUserID(), path) {
973 public void onSuccess(Resource result) {
974 fetchAccount(callback);
978 public void onError(Throwable t) {
979 LOG("Error creating pithos", t);
981 if(t instanceof RestException) {
982 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
985 displayError("System error Error creating pithos: " + t.getMessage());
990 protected void onUnauthorized(Response response) {
994 createPithos.setHeader(Const.X_AUTH_TOKEN, getUserToken());
995 Scheduler.get().scheduleDeferred(createPithos);
999 * Creates an HTML fragment that places an image & caption together, for use
1000 * in a group header.
1002 * @param imageProto an image prototype for an image
1003 * @param caption the group caption
1004 * @return the header HTML fragment
1006 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
1007 String captionHTML = "<table class='caption' cellpadding='0' "
1008 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
1009 + "</td><td id =" + caption + " class='rcaption'><b style='white-space:nowrap'> "
1010 + caption + "</b></td></tr></table>";
1014 protected void onWindowResized(int height) {
1015 // Adjust the split panel to take up the available room in the window.
1016 int newHeight = height - splitPanel.getAbsoluteTop() - 153;
1020 splitPanel.setHeight("" + newHeight);
1021 inner.setHeight("" + newHeight);
1024 native boolean isCloudbarReady()/*-{
1025 if ($wnd.$("div.cloudbar") && $wnd.$("div.cloudbar").height() > 0)
1031 public void onResize(ResizeEvent event) {
1032 int height = event.getHeight();
1033 onWindowResized(height);
1037 * Display an error message.
1039 * @param msg the message to display
1041 public void displayError(String msg) {
1042 messagePanel.displayError(msg);
1043 onWindowResized(Window.getClientHeight());
1047 * Display a warning message.
1049 * @param msg the message to display
1051 public void displayWarning(String msg) {
1052 messagePanel.displayWarning(msg);
1053 onWindowResized(Window.getClientHeight());
1057 * Display an informational message.
1059 * @param msg the message to display
1061 public void displayInformation(String msg) {
1062 messagePanel.displayInformation(msg);
1063 onWindowResized(Window.getClientHeight());
1067 * Retrieve the fileList.
1069 * @return the fileList
1071 public FileList getFileList() {
1076 * Retrieve the topPanel.
1078 * @return the topPanel
1080 TopPanel getTopPanel() {
1085 * Retrieve the clipboard.
1087 * @return the clipboard
1089 public Clipboard getClipboard() {
1093 public StatusPanel getStatusPanel() {
1097 public String getUserToken() {
1101 public static native void preventIESelection() /*-{
1102 $doc.body.onselectstart = function () {
1107 public static native void enableIESelection() /*-{
1108 if ($doc.body.onselectstart != null)
1109 $doc.body.onselectstart = null;
1112 public static String getStorageAPIURL() {
1113 return STORAGE_API_URL;
1116 public static String getStorageViewURL() {
1117 return STORAGE_VIEW_URL;
1120 public static boolean isShowCopyrightMessage() {
1121 return SHOW_COPYRIGHT;
1124 public static String getUserCatalogsURL() {
1125 return USER_CATALOGS_API_URL;
1128 public static String getFileViewURL(File file) {
1129 return Pithos.getStorageViewURL() + file.getOwnerID() + file.getUri();
1133 * History support for folder navigation
1134 * adds a new browser history entry
1138 public void updateHistory(String key) {
1139 // Replace any whitespace of the initial string to "+"
1140 // String result = key.replaceAll("\\s","+");
1141 // Add a new browser history entry.
1142 // History.newItem(result);
1143 History.newItem(key);
1146 public void deleteFolder(final Folder folder, final Command callback) {
1147 final PleaseWaitPopup pwp = new PleaseWaitPopup();
1149 String path = "/" + folder.getContainer() + "/" + folder.getPrefix() + "?delimiter=/" + "&t=" + System.currentTimeMillis();
1150 DeleteRequest deleteFolder = new DeleteRequest(getStorageAPIURL(), folder.getOwnerID(), path) {
1153 protected void onUnauthorized(Response response) {
1159 public void onSuccess(Resource result) {
1160 updateFolder(folder.getParent(), true, new Command() {
1163 public void execute() {
1164 folderTreeSelectionModel.setSelected(folder.getParent(), true);
1166 if(callback != null) {
1175 public void onError(Throwable t) {
1178 if(t instanceof RestException) {
1179 if(((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND) {
1180 displayError("Unable to delete folder: " + ((RestException) t).getHttpStatusText());
1187 displayError("System error unable to delete folder: " + t.getMessage());
1192 deleteFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1193 Scheduler.get().scheduleDeferred(deleteFolder);
1196 public FolderTreeView getFolderTreeView() {
1197 return folderTreeView;
1200 public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
1201 if(iter.hasNext()) {
1202 File file = iter.next();
1203 String path = targetUri + "/" + file.getName();
1204 PutRequest copyFile = new PutRequest(getStorageAPIURL(), targetUsername, path) {
1206 public void onSuccess(Resource result) {
1207 copyFiles(iter, targetUsername, targetUri, callback);
1211 public void onError(Throwable t) {
1214 if(t instanceof RestException) {
1215 displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
1218 displayError("System error unable to copy file: " + t.getMessage());
1223 protected void onUnauthorized(Response response) {
1227 copyFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1228 copyFile.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(file.getUri()));
1229 if(!file.getOwnerID().equals(targetUsername)) {
1230 copyFile.setHeader(Const.X_SOURCE_ACCOUNT, URL.encodePathSegment(file.getOwnerID()));
1232 copyFile.setHeader(Const.CONTENT_TYPE, file.getContentType());
1233 Scheduler.get().scheduleDeferred(copyFile);
1235 else if(callback != null) {
1240 public void copyFolder(final Folder f, final String targetUsername, final String targetUri, boolean move, final Command callback) {
1241 String path = targetUri + "?delimiter=/";
1242 PutRequest copyFolder = new PutRequest(getStorageAPIURL(), targetUsername, path) {
1244 public void onSuccess(Resource result) {
1245 if(callback != null) {
1251 public void onError(Throwable t) {
1254 if(t instanceof RestException) {
1255 displayError("Unable to copy folder: " + ((RestException) t).getHttpStatusText());
1258 displayError("System error copying folder: " + t.getMessage());
1263 protected void onUnauthorized(Response response) {
1267 copyFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1268 copyFolder.setHeader(Const.ACCEPT, "*/*");
1269 copyFolder.setHeader(Const.CONTENT_LENGTH, "0");
1270 copyFolder.setHeader(Const.CONTENT_TYPE, "application/directory");
1271 if(!f.getOwnerID().equals(targetUsername)) {
1272 copyFolder.setHeader(Const.X_SOURCE_ACCOUNT, f.getOwnerID());
1275 copyFolder.setHeader(Const.X_MOVE_FROM, URL.encodePathSegment(f.getUri()));
1278 copyFolder.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(f.getUri()));
1280 Scheduler.get().scheduleDeferred(copyFolder);
1283 public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1284 selectionModels.add(model);
1287 public OtherSharedTreeView getOtherSharedTreeView() {
1288 return otherSharedTreeView;
1291 public void updateTrash(boolean showFiles, Command callback) {
1292 updateFolder(trash, showFiles, callback, true);
1295 public void updateGroupsNode() {
1296 groupTreeView.updateGroupNode(null);
1299 public Group addGroup(String groupname) {
1300 Group newGroup = new Group(groupname);
1301 account.addGroup(newGroup);
1302 groupTreeView.updateGroupNode(null);
1306 public void removeGroup(Group group) {
1307 account.removeGroup(group);
1311 public TreeView getSelectedTree() {
1312 return selectedTree;
1315 public void setSelectedTree(TreeView selected) {
1316 selectedTree = selected;
1319 public Folder getSelection() {
1320 if(selectedTree != null) {
1321 return selectedTree.getSelection();
1326 public void showFolderStatistics(int folderFileCount) {
1327 numOfFiles.setHTML(String.valueOf(folderFileCount));
1330 public GroupTreeView getGroupTreeView() {
1331 return groupTreeView;
1334 public void sessionExpired() {
1335 new SessionExpiredDialog(this).center();
1338 public void updateRootFolder(Command callback) {
1339 updateFolder(account.getPithos(), false, callback, true);
1342 void createMySharedTree() {
1343 LOG("Pithos::createMySharedTree()");
1344 mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1345 mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1347 public void onSelectionChange(SelectionChangeEvent event) {
1348 if(mysharedTreeSelectionModel.getSelectedObject() != null) {
1349 deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1350 upload.setEnabled(false);
1351 disableUploadArea();
1352 updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1353 showRelevantToolbarButtons();
1356 if(getSelectedTree().equals(mysharedTreeView)) {
1357 setSelectedTree(null);
1359 if(getSelectedTree() == null) {
1360 showRelevantToolbarButtons();
1365 selectionModels.add(mysharedTreeSelectionModel);
1366 mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1367 mysharedTreeViewModel.initialize(new Command() {
1370 public void execute() {
1371 mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1372 trees.insert(mysharedTreeView, 2);
1373 treeViews.add(mysharedTreeView);
1374 createOtherSharedTree();
1379 void createOtherSharedTree() {
1380 LOG("Pithos::createOtherSharedTree()");
1381 otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1382 otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1384 public void onSelectionChange(SelectionChangeEvent event) {
1385 if(otherSharedTreeSelectionModel.getSelectedObject() != null) {
1386 deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1387 applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1388 updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true, null);
1389 showRelevantToolbarButtons();
1392 if(getSelectedTree().equals(otherSharedTreeView)) {
1393 setSelectedTree(null);
1395 if(getSelectedTree() == null) {
1396 showRelevantToolbarButtons();
1401 selectionModels.add(otherSharedTreeSelectionModel);
1402 otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1403 // #3784 We show it empty...
1404 otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel, true);
1405 trees.insert(otherSharedTreeView, 1);
1407 LOG("Pithos::createOtherSharedTree(), initializing otherSharedTreeViewModel with a callback");
1408 otherSharedTreeViewModel.initialize(new Command() {
1410 public void execute() {
1411 // #3784 ... then remove the empty stuff and add a new view with the populated model
1412 trees.remove(otherSharedTreeView);
1414 otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel, false);
1415 trees.insert(otherSharedTreeView, 1);
1416 treeViews.add(otherSharedTreeView);
1422 public String getErrorData() {
1423 final StringBuilder sb = new StringBuilder();
1424 final String NL = Const.NL;
1425 Throwable t = this.error;
1427 sb.append(t.toString());
1429 StackTraceElement[] traces = t.getStackTrace();
1430 for(StackTraceElement trace : traces) {
1432 sb.append(trace.getClassName());
1434 sb.append(trace.getMethodName());
1435 sb.append("() at ");
1436 sb.append(trace.getFileName());
1438 sb.append(trace.getLineNumber());
1445 return sb.toString();
1448 public void setError(Throwable t) {
1453 public void showRelevantToolbarButtons() {
1454 toolbar.showRelevantButtons();
1457 public FileUploadDialog getFileUploadDialog() {
1458 if(fileUploadDialog == null) {
1459 fileUploadDialog = new FileUploadDialog(this);
1461 return fileUploadDialog;
1464 public void hideUploadIndicator() {
1465 upload.removeStyleName("pithos-uploadButton-loading");
1466 upload.setTitle("");
1469 public void showUploadIndicator() {
1470 upload.addStyleName("pithos-uploadButton-loading");
1471 upload.setTitle("Upload in progress. Click for details.");
1474 public void scheduleFolderHeadCommand(final Folder folder, final Command callback) {
1475 if(folder == null) {
1476 if(callback != null) {
1481 HeadRequest<Folder> headFolder = new HeadRequest<Folder>(Folder.class, getStorageAPIURL(), folder.getOwnerID(), folder.getUri(), folder) {
1484 public void onSuccess(Folder _result) {
1485 if(callback != null) {
1491 public void onError(Throwable t) {
1492 if(t instanceof RestException) {
1493 if(((RestException) t).getHttpStatusCode() == Response.SC_NOT_FOUND) {
1494 final String path = folder.getUri();
1495 PutRequest newFolder = new PutRequest(getStorageAPIURL(), folder.getOwnerID(), path) {
1497 public void onSuccess(Resource _result) {
1498 scheduleFolderHeadCommand(folder, callback);
1502 public void onError(Throwable _t) {
1504 if(_t instanceof RestException) {
1505 displayError("Unable to create folder: " + ((RestException) _t).getHttpStatusText());
1508 displayError("System error creating folder: " + _t.getMessage());
1513 protected void onUnauthorized(Response response) {
1517 newFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1518 newFolder.setHeader(Const.CONTENT_TYPE, "application/folder");
1519 newFolder.setHeader(Const.ACCEPT, "*/*");
1520 newFolder.setHeader(Const.CONTENT_LENGTH, "0");
1521 Scheduler.get().scheduleDeferred(newFolder);
1523 else if(((RestException) t).getHttpStatusCode() == Response.SC_FORBIDDEN) {
1527 displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
1531 displayError("System error heading folder: " + t.getMessage());
1534 LOG("Error heading folder", t);
1539 protected void onUnauthorized(Response response) {
1543 headFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1544 Scheduler.get().scheduleDeferred(headFolder);
1548 public void scheduleFileHeadCommand(File f, final Command callback) {
1549 HeadRequest<File> headFile = new HeadRequest<File>(File.class, getStorageAPIURL(), f.getOwnerID(), f.getUri(), f) {
1552 public void onSuccess(File _result) {
1553 if(callback != null) {
1559 public void onError(Throwable t) {
1560 LOG("Error heading file", t);
1562 if(t instanceof RestException) {
1563 displayError("Error heading file: " + ((RestException) t).getHttpStatusText());
1566 displayError("System error heading file: " + t.getMessage());
1571 protected void onUnauthorized(Response response) {
1575 headFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1576 Scheduler.get().scheduleDeferred(headFile);
1579 public boolean isMySharedSelected() {
1580 return getSelectedTree().equals(getMySharedTreeView());
1583 private Folder getUploadFolder() {
1584 if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1585 return getSelection();
1590 private void updateUploadFolder() {
1591 updateUploadFolder(null);
1594 private void updateUploadFolder(final JsArrayString urls) {
1595 if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1596 Folder f = getSelection();
1597 if(getSelectedTree().equals(getFolderTreeView())) {
1598 updateFolder(f, true, new Command() {
1601 public void execute() {
1604 selectUploadedFiles(urls);
1610 updateOtherSharedFolder(f, true, null);
1615 public native void disableUploadArea() /*-{
1616 var uploader = $wnd.$("#uploader").pluploadQueue();
1617 var dropElm = $wnd.document.getElementById('rightPanel');
1618 $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1621 public native void enableUploadArea() /*-{
1622 var uploader = $wnd.$("#uploader").pluploadQueue();
1623 var dropElm = $wnd.document.getElementById('rightPanel');
1624 $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1625 if (uploader.runtime == 'html5') {
1626 uploader.settings.drop_element = 'rightPanel';
1627 uploader.trigger('PostInit');
1631 public void showUploadAlert(int nOfFiles) {
1632 if(uploadAlert == null) {
1633 uploadAlert = new UploadAlert(this, nOfFiles);
1635 if(!uploadAlert.isShowing()) {
1636 uploadAlert.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
1639 public void setPosition(int offsetWidth, int offsetHeight) {
1640 uploadAlert.setPopupPosition((Window.getClientWidth() - offsetWidth) / 2, statusPanel.getAbsoluteTop() - offsetHeight);
1644 uploadAlert.setNumOfFiles(nOfFiles);
1647 public void hideUploadAlert() {
1648 if(uploadAlert != null && uploadAlert.isShowing()) {
1653 public void selectUploadedFiles(JsArrayString urls) {
1654 List<String> selectedUrls = new ArrayList<String>();
1655 for(int i = 0; i < urls.length(); i++) {
1656 selectedUrls.add(urls.get(i));
1658 fileList.selectByUrl(selectedUrls);
1661 public void purgeContainer(final Folder container) {
1662 String path = "/" + container.getName() + "?delimiter=/";
1663 DeleteRequest delete = new DeleteRequest(getStorageAPIURL(), getUserID(), path) {
1666 protected void onUnauthorized(Response response) {
1671 public void onSuccess(Resource result) {
1672 updateFolder(container, true, null, true);
1676 public void onError(Throwable t) {
1677 LOG("Error deleting trash", t);
1679 if(t instanceof RestException) {
1680 displayError("Error deleting trash: " + ((RestException) t).getHttpStatusText());
1683 displayError("System error deleting trash: " + t.getMessage());
1687 delete.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1688 Scheduler.get().scheduleDeferred(delete);