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 getFromOtherPropertiesOrNull(String key) {
104 return otherProperties.get(key);
112 public static final String OTHERPROPS_STORAGE_API_URL = getFromOtherPropertiesOrNull("STORAGE_API_URL");
113 public static final String OTHERPROPS_USER_CATALOGS_API_URL = getFromOtherPropertiesOrNull("USER_CATALOGS_API_URL");
115 LOG("STORAGE_API_URL = ", OTHERPROPS_STORAGE_API_URL);
116 LOG("USER_CATALOGS_API_URL = ", OTHERPROPS_USER_CATALOGS_API_URL);
119 public static final String STORAGE_API_URL;
121 if(OTHERPROPS_STORAGE_API_URL != null) {
122 STORAGE_API_URL = OTHERPROPS_STORAGE_API_URL;
124 else if(CONFIG_API_PATH != null) {
125 STORAGE_API_URL = CONFIG_API_PATH;
128 throw new RuntimeException("Unknown STORAGE_API_URL");
131 LOG("Computed STORAGE_API_URL = ", STORAGE_API_URL);
134 public static final String STORAGE_VIEW_URL;
136 final String viewURL = getFromOtherPropertiesOrNull("STORAGE_VIEW_URL");
137 if(viewURL != null) {
138 STORAGE_VIEW_URL = viewURL;
141 STORAGE_VIEW_URL = STORAGE_API_URL;
144 LOG("Computed STORAGE_VIEW_URL = ", STORAGE_VIEW_URL);
147 public static final String USER_CATALOGS_API_URL;
149 if(OTHERPROPS_USER_CATALOGS_API_URL != null) {
150 USER_CATALOGS_API_URL = OTHERPROPS_USER_CATALOGS_API_URL;
152 else if(OTHERPROPS_STORAGE_API_URL != null) {
153 throw new RuntimeException("STORAGE_API_URL is defined but USER_CATALOGS_API_URL is not");
156 // https://server.com/v1/ --> https://server.com
157 String url = CONFIG_API_PATH;
158 url = Helpers.stripTrailing(url, "/");
159 url = Helpers.upToIncludingLastPart(url, "/");
160 url = Helpers.stripTrailing(url, "/");
161 url = url + "/user_catalogs";
163 USER_CATALOGS_API_URL = url;
165 LOG("Computed USER_CATALOGS_API_URL = ", USER_CATALOGS_API_URL);
169 public interface Style extends CssResource {
170 String commandAnchor();
174 @ClassName("gwt-HTML")
177 String uploadAlert();
179 String uploadAlertLink();
181 String uploadAlertProgress();
183 String uploadAlertPercent();
185 String uploadAlertClose();
188 public interface Resources extends ClientBundle {
189 @Source("Pithos.css")
192 @Source("gr/grnet/pithos/resources/close-popup.png")
193 ImageResource closePopup();
196 public static Resources resources = GWT.create(Resources.class);
199 * Instantiate an application-level image bundle. This object will provide
200 * programmatic access to all the images needed by widgets.
202 static Images images = (Images) GWT.create(Images.class);
204 public String getUserID() {
208 public UserCatalogs getUserCatalogs() {
212 public String getCurrentUserDisplayNameOrID() {
213 final String displayName = userCatalogs.getDisplayName(getUserID());
214 return displayName == null ? getUserID() : displayName;
217 public boolean hasDisplayNameForUserID(String userID) {
218 return userCatalogs.getDisplayName(userID) != null;
221 public boolean hasIDForUserDisplayName(String userDisplayName) {
222 return userCatalogs.getID(userDisplayName) != null;
225 public String getDisplayNameForUserID(String userID) {
226 return userCatalogs.getDisplayName(userID);
229 public String getIDForUserDisplayName(String userDisplayName) {
230 return userCatalogs.getID(userDisplayName);
233 public List<String> getDisplayNamesForUserIDs(List<String> userIDs) {
234 if(userIDs == null) {
235 userIDs = new ArrayList<String>();
237 final List<String> userDisplayNames = new ArrayList<String>();
238 for(String userID : userIDs) {
239 final String displayName = getDisplayNameForUserID(userID);
240 userDisplayNames.add(displayName);
243 return userDisplayNames;
246 public List<String> filterUserIDsWithUnknownDisplayName(Collection<String> userIDs) {
247 if(userIDs == null) {
248 userIDs = new ArrayList<String>();
250 final List<String> filtered = new ArrayList<String>();
251 for(String userID : userIDs) {
252 if(!this.userCatalogs.hasID(userID)) {
253 filtered.add(userID);
259 public void setAccount(AccountResource acct) {
263 public AccountResource getAccount() {
267 public void updateFolder(Folder f, boolean showfiles, Command callback, final boolean openParent) {
268 folderTreeView.updateFolder(f, showfiles, callback, openParent);
271 public void updateGroupNode(Group group) {
272 groupTreeView.updateGroupNode(group);
275 public void updateMySharedRoot() {
276 mysharedTreeView.updateRoot();
279 public void updateSharedFolder(Folder f, boolean showfiles, Command callback) {
280 mysharedTreeView.updateFolder(f, showfiles, callback);
283 public void updateSharedFolder(Folder f, boolean showfiles) {
284 updateSharedFolder(f, showfiles, null);
287 public void updateOtherSharedFolder(Folder f, boolean showfiles, Command callback) {
288 otherSharedTreeView.updateFolder(f, showfiles, callback);
291 public MysharedTreeView getMySharedTreeView() {
292 return mysharedTreeView;
296 * An aggregate image bundle that pulls together all the images for this
297 * application into a single bundle.
299 public interface Images extends TopPanel.Images, FileList.Images, ToolsMenu.Images {
301 @Source("gr/grnet/pithos/resources/document.png")
302 ImageResource folders();
304 @Source("gr/grnet/pithos/resources/advancedsettings.png")
305 @ImageOptions(width = 32, height = 32)
306 ImageResource tools();
309 private Throwable error;
312 * The Application Clipboard implementation;
314 private Clipboard clipboard = new Clipboard();
317 * The top panel that contains the menu bar.
319 private TopPanel topPanel;
322 * The panel that contains the various system messages.
324 private MessagePanel messagePanel = new MessagePanel(this, Pithos.images);
327 * The bottom panel that contains the status bar.
329 StatusPanel statusPanel = null;
332 * The file list widget.
334 private FileList fileList;
337 * The tab panel that occupies the right side of the screen.
339 private VerticalPanel inner = new VerticalPanel();
343 * The split panel that will contain the left and right panels.
345 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
348 * The currently selected item in the application, for use by the Edit menu
349 * commands. Potential types are Folder, File, User and Group.
351 private Object currentSelection;
353 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
356 * The ID that uniquely identifies the user in Pithos+.
357 * Currently this is a UUID. It used to be the user's email.
359 private String userID = null;
362 * Holds mappings from user UUIDs to emails and vice-versa.
364 private UserCatalogs userCatalogs = new UserCatalogs();
367 * The authentication token of the current user.
369 private String userToken;
373 SingleSelectionModel<Folder> folderTreeSelectionModel;
374 FolderTreeViewModel folderTreeViewModel;
375 FolderTreeView folderTreeView;
377 SingleSelectionModel<Folder> mysharedTreeSelectionModel;
378 MysharedTreeViewModel mysharedTreeViewModel;
379 MysharedTreeView mysharedTreeView = null;
381 protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
382 OtherSharedTreeViewModel otherSharedTreeViewModel;
383 OtherSharedTreeView otherSharedTreeView = null;
385 GroupTreeViewModel groupTreeViewModel;
386 GroupTreeView groupTreeView;
388 TreeView selectedTree;
389 protected AccountResource account;
393 List<Composite> treeViews = new ArrayList<Composite>();
395 @SuppressWarnings("rawtypes")
396 List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
398 public Button upload;
400 private HTML numOfFiles;
402 private Toolbar toolbar;
404 private FileUploadDialog fileUploadDialog = new FileUploadDialog(this);
406 UploadAlert uploadAlert;
411 public void onModuleLoad() {
412 if(parseUserCredentials()) {
417 static native void __ConsoleLog(String message) /*-{
418 try { console.log(message); } catch (e) {}
421 public static void LOGError(Throwable error, StringBuilder sb) {
422 if(!isLOGEnabled()) { return; }
424 sb.append("\nException: [" + error.toString().replace("\n", "\n ") + "]");
425 Throwable cause = error.getCause();
427 sb.append("\nCauses:\n");
428 while(cause != null) {
430 sb.append("[" + cause.toString().replace("\n", "\n ") + "]");
432 cause = cause.getCause();
439 StackTraceElement[] stackTrace = error.getStackTrace();
440 sb.append("Stack trace (" + stackTrace.length + " elements):\n");
441 for(int i = 0; i < stackTrace.length; i++) {
442 StackTraceElement errorElem = stackTrace[i];
443 sb.append(" [" + i + "] ");
444 sb.append(errorElem.toString());
449 public static void LOGError(Throwable error) {
450 if(!isLOGEnabled()) { return; }
452 final StringBuilder sb = new StringBuilder();
454 if(sb.length() > 0) {
455 __ConsoleLog(sb.toString());
459 public static boolean isLOGEnabled() {
463 public static void LOG(Object ...args) {
464 if(!isLOGEnabled()) { return; }
466 final StringBuilder sb = new StringBuilder();
467 for(Object arg : args) {
468 if(arg instanceof Throwable) {
469 LOGError((Throwable) arg, sb);
476 if(sb.length() > 0) {
477 __ConsoleLog(sb.toString());
481 private void initialize() {
482 userCatalogs.updateWithIDAndName("*", "All Pithos users");
484 lastModified = new Date(); //Initialize if-modified-since value with now.
485 resources.pithosCss().ensureInjected();
486 boolean bareContent = Window.Location.getParameter("noframe") != null;
487 String contentWidth = bareContent ? Const.PERCENT_100 : Const.PERCENT_75;
489 VerticalPanel outer = new VerticalPanel();
490 outer.setWidth(Const.PERCENT_100);
492 outer.addStyleName("pithos-outer");
496 topPanel = new TopPanel(this, Pithos.images);
497 topPanel.setWidth(Const.PERCENT_100);
499 outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
502 messagePanel.setVisible(false);
503 outer.add(messagePanel);
504 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
505 outer.setCellVerticalAlignment(messagePanel, HasVerticalAlignment.ALIGN_MIDDLE);
507 HorizontalPanel header = new HorizontalPanel();
508 header.addStyleName("pithos-header");
509 header.setWidth(contentWidth);
511 header.addStyleName("pithos-header-noframe");
513 upload = new Button("Upload", new ClickHandler() {
515 public void onClick(ClickEvent event) {
516 if(getSelection() != null) {
517 new UploadFileCommand(Pithos.this, null, getSelection()).execute();
521 upload.addStyleName("pithos-uploadButton");
523 header.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_LEFT);
524 header.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
526 toolbar = new Toolbar(this);
528 header.setCellHorizontalAlignment(toolbar, HasHorizontalAlignment.ALIGN_CENTER);
529 header.setCellVerticalAlignment(toolbar, HasVerticalAlignment.ALIGN_MIDDLE);
531 HorizontalPanel folderStatistics = new HorizontalPanel();
532 folderStatistics.addStyleName("pithos-folderStatistics");
533 numOfFiles = new HTML();
534 folderStatistics.add(numOfFiles);
535 folderStatistics.setCellVerticalAlignment(numOfFiles, HasVerticalAlignment.ALIGN_MIDDLE);
536 HTML numOfFilesLabel = new HTML(" Files");
537 folderStatistics.add(numOfFilesLabel);
538 folderStatistics.setCellVerticalAlignment(numOfFilesLabel, HasVerticalAlignment.ALIGN_MIDDLE);
539 header.add(folderStatistics);
540 header.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
541 header.setCellVerticalAlignment(folderStatistics, HasVerticalAlignment.ALIGN_MIDDLE);
542 header.setCellWidth(folderStatistics, "40px");
544 outer.setCellHorizontalAlignment(header, HasHorizontalAlignment.ALIGN_CENTER);
545 // Inner contains the various lists
546 inner.sinkEvents(Event.ONCONTEXTMENU);
547 inner.setWidth(Const.PERCENT_100);
549 folderTreeSelectionModel = new SingleSelectionModel<Folder>();
550 folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
552 public void onSelectionChange(SelectionChangeEvent event) {
553 if(folderTreeSelectionModel.getSelectedObject() != null) {
554 deselectOthers(folderTreeView, folderTreeSelectionModel);
555 applyPermissions(folderTreeSelectionModel.getSelectedObject());
556 Folder f = folderTreeSelectionModel.getSelectedObject();
557 updateFolder(f, true, new Command() {
560 public void execute() {
564 showRelevantToolbarButtons();
567 if(getSelectedTree().equals(folderTreeView)) {
568 setSelectedTree(null);
570 if(getSelectedTree() == null) {
571 showRelevantToolbarButtons();
576 selectionModels.add(folderTreeSelectionModel);
578 folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
579 folderTreeView = new FolderTreeView(folderTreeViewModel);
580 treeViews.add(folderTreeView);
582 fileList = new FileList(this, images);
585 trees = new VerticalPanel();
586 trees.setWidth(Const.PERCENT_100);
588 // Add the left and right panels to the split panel.
589 splitPanel.setLeftWidget(trees);
590 FlowPanel right = new FlowPanel();
591 right.getElement().setId("rightPanel");
593 splitPanel.setRightWidget(right);
594 splitPanel.setSplitPosition("219px");
595 splitPanel.setSize(Const.PERCENT_100, Const.PERCENT_100);
596 splitPanel.addStyleName("pithos-splitPanel");
597 splitPanel.setWidth(contentWidth);
598 outer.add(splitPanel);
599 outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
602 statusPanel = new StatusPanel();
603 statusPanel.setWidth(Const.PERCENT_100);
604 outer.add(statusPanel);
605 outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
608 splitPanel.addStyleName("pithos-splitPanel-noframe");
611 // Hook the window resize event, so that we can adjust the UI.
612 Window.addResizeHandler(this);
613 // Clear out the window's built-in margin, because we want to take
614 // advantage of the entire client area.
615 Window.setMargin("0px");
616 // Finally, add the outer panel to the RootPanel, so that it will be
618 RootPanel.get().add(outer);
619 // Call the window resized handler to get the initial sizes setup. Doing
620 // this in a deferred command causes it to occur after all widgets'
621 // sizes have been computed by the browser.
622 Scheduler.get().scheduleIncremental(new RepeatingCommand() {
625 public boolean execute() {
626 if(!isCloudbarReady()) {
629 onWindowResized(Window.getClientHeight());
634 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
636 public void execute() {
637 LOG("Pithos::initialize() Calling Pithos::fetchAccount()");
638 fetchAccount(new Command() {
641 public void execute() {
642 if(!account.hasHomeContainer()) {
643 createHomeContainer(account, this);
645 else if(!account.hasTrashContainer()) {
646 createTrashContainer(this);
649 for(Folder f : account.getContainers()) {
650 if(f.getName().equals(Const.TRASH_CONTAINER)) {
655 trees.add(folderTreeView);
656 folderTreeViewModel.initialize(account, new Command() {
659 public void execute() {
660 createMySharedTree();
664 HorizontalPanel separator = new HorizontalPanel();
665 separator.addStyleName("pithos-statisticsSeparator");
666 separator.add(new HTML(""));
667 trees.add(separator);
669 groupTreeViewModel = new GroupTreeViewModel(Pithos.this);
670 groupTreeView = new GroupTreeView(groupTreeViewModel);
671 treeViews.add(groupTreeView);
672 trees.add(groupTreeView);
673 folderTreeView.showStatistics(account);
681 public void scheduleResfresh() {
682 Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {
685 public boolean execute() {
686 final Folder f = getSelection();
691 HeadRequest<Folder> head = new HeadRequest<Folder>(Folder.class, getStorageAPIURL(), f.getOwnerID(), "/" + f.getContainer()) {
694 public void onSuccess(Folder _result) {
695 lastModified = new Date();
696 if(getSelectedTree().equals(folderTreeView)) {
697 updateFolder(f, true, new Command() {
700 public void execute() {
706 else if(getSelectedTree().equals(mysharedTreeView)) {
707 updateSharedFolder(f, true, new Command() {
710 public void execute() {
721 public void onError(Throwable t) {
722 if(t instanceof RestException && ((RestException) t).getHttpStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
725 else if(retries >= MAX_RETRIES) {
726 LOG("Error heading folder. ", t);
728 if(t instanceof RestException) {
729 displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
732 displayError("System error heading folder: " + t.getMessage());
736 LOG("Retry ", retries);
737 Scheduler.get().scheduleDeferred(this);
742 protected void onUnauthorized(Response response) {
743 if(retries >= MAX_RETRIES) {
748 Scheduler.get().scheduleDeferred(this);
752 head.setHeader(Const.X_AUTH_TOKEN, getUserToken());
753 head.setHeader(Const.IF_MODIFIED_SINCE, DateTimeFormat.getFormat(Const.DATE_FORMAT_1).format(lastModified, TimeZone.createTimeZone(0)) + " GMT");
754 Scheduler.get().scheduleDeferred(head);
761 public void applyPermissions(Folder f) {
764 upload.setEnabled(false);
768 Boolean[] perms = f.getPermissions().get(userID);
769 if(f.getOwnerID().equals(userID) || (perms != null && perms[1] != null && perms[1])) {
770 upload.setEnabled(true);
774 upload.setEnabled(false);
780 upload.setEnabled(false);
785 @SuppressWarnings({"rawtypes", "unchecked"})
786 public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
787 selectedTree = _selectedTree;
789 for(SingleSelectionModel s : selectionModels) {
790 if(!s.equals(model) && s.getSelectedObject() != null) {
791 s.setSelected(s.getSelectedObject(), false);
796 public void showFiles(final Folder f) {
797 Set<File> files = f.getFiles();
801 public void showFiles(Set<File> files) {
802 fileList.setFiles(new ArrayList<File>(files));
806 * Parse and store the user credentials to the appropriate fields.
808 private boolean parseUserCredentials() {
809 final String cookie = otherProperties.get(Const.AUTH_COOKIE);
810 String auth = Cookies.getCookie(cookie);
815 if(auth.startsWith("\"")) {
816 auth = auth.substring(1);
818 if(auth.endsWith("\"")) {
819 auth = auth.substring(0, auth.length() - 1);
821 String[] authSplit = auth.split("\\" + config.cookieSeparator(), 2);
822 if(authSplit.length != 2) {
826 this.userID = authSplit[0];
827 this.userToken = authSplit[1];
829 String gotoUrl = Window.Location.getParameter("goto");
830 if(gotoUrl != null && gotoUrl.length() > 0) {
831 Window.Location.assign(gotoUrl);
838 * Redirect the user to the login page for authentication.
840 protected void authenticateUser() {
841 Dictionary otherProperties = Dictionary.getDictionary(Const.OTHER_PROPERTIES);
842 Window.Location.assign(otherProperties.get(Const.LOGIN_URL) + Window.Location.getHref());
845 public void fetchAccount(final Command callback) {
846 String path = "?format=json";
848 GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getStorageAPIURL(), userID, path) {
850 public void onSuccess(AccountResource accountResource) {
851 account = accountResource;
852 if(callback != null) {
856 final List<String> memberIDs = new ArrayList<String>();
857 final List<Group> groups = account.getGroups();
858 for(Group group : groups) {
859 memberIDs.addAll(group.getMemberIDs());
861 memberIDs.add(Pithos.this.getUserID());
863 final List<String> theUnknown = Pithos.this.filterUserIDsWithUnknownDisplayName(memberIDs);
864 // Initialize the user catalog
865 new UpdateUserCatalogs(Pithos.this, theUnknown).scheduleDeferred();
866 LOG("Called new UpdateUserCatalogs(Pithos.this, theUnknown).scheduleDeferred();");
870 public void onError(Throwable t) {
871 LOG("Error getting account", t);
873 if(t instanceof RestException) {
874 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
877 displayError("System error fetching user data: " + t.getMessage());
882 protected void onUnauthorized(Response response) {
886 getAccount.setHeader(Const.X_AUTH_TOKEN, userToken);
887 Scheduler.get().scheduleDeferred(getAccount);
890 public void updateStatistics() {
891 HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getStorageAPIURL(), userID, "", account) {
894 public void onSuccess(AccountResource _result) {
895 folderTreeView.showStatistics(account);
899 public void onError(Throwable t) {
900 LOG("Error getting account", t);
902 if(t instanceof RestException) {
903 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
906 displayError("System error fetching user data: " + t.getMessage());
911 protected void onUnauthorized(Response response) {
915 headAccount.setHeader(Const.X_AUTH_TOKEN, userToken);
916 Scheduler.get().scheduleDeferred(headAccount);
919 protected void createHomeContainer(final AccountResource _account, final Command callback) {
920 String path = "/" + Const.HOME_CONTAINER;
921 PutRequest createPithos = new PutRequest(getStorageAPIURL(), getUserID(), path) {
923 public void onSuccess(Resource result) {
924 if(!_account.hasTrashContainer()) {
925 createTrashContainer(callback);
928 fetchAccount(callback);
933 public void onError(Throwable t) {
934 LOG("Error creating pithos", t);
936 if(t instanceof RestException) {
937 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
940 displayError("System error Error creating pithos: " + t.getMessage());
945 protected void onUnauthorized(Response response) {
949 createPithos.setHeader(Const.X_AUTH_TOKEN, getUserToken());
950 Scheduler.get().scheduleDeferred(createPithos);
953 protected void createTrashContainer(final Command callback) {
954 String path = "/" + Const.TRASH_CONTAINER;
955 PutRequest createPithos = new PutRequest(getStorageAPIURL(), getUserID(), path) {
957 public void onSuccess(Resource result) {
958 fetchAccount(callback);
962 public void onError(Throwable t) {
963 LOG("Error creating pithos", t);
965 if(t instanceof RestException) {
966 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
969 displayError("System error Error creating pithos: " + t.getMessage());
974 protected void onUnauthorized(Response response) {
978 createPithos.setHeader(Const.X_AUTH_TOKEN, getUserToken());
979 Scheduler.get().scheduleDeferred(createPithos);
983 * Creates an HTML fragment that places an image & caption together, for use
986 * @param imageProto an image prototype for an image
987 * @param caption the group caption
988 * @return the header HTML fragment
990 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
991 String captionHTML = "<table class='caption' cellpadding='0' "
992 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
993 + "</td><td id =" + caption + " class='rcaption'><b style='white-space:nowrap'> "
994 + caption + "</b></td></tr></table>";
998 protected void onWindowResized(int height) {
999 // Adjust the split panel to take up the available room in the window.
1000 int newHeight = height - splitPanel.getAbsoluteTop() - 153;
1004 splitPanel.setHeight("" + newHeight);
1005 inner.setHeight("" + newHeight);
1008 native boolean isCloudbarReady()/*-{
1009 if ($wnd.$("div.cloudbar") && $wnd.$("div.cloudbar").height() > 0)
1015 public void onResize(ResizeEvent event) {
1016 int height = event.getHeight();
1017 onWindowResized(height);
1021 * Display an error message.
1023 * @param msg the message to display
1025 public void displayError(String msg) {
1026 messagePanel.displayError(msg);
1027 onWindowResized(Window.getClientHeight());
1031 * Display a warning message.
1033 * @param msg the message to display
1035 public void displayWarning(String msg) {
1036 messagePanel.displayWarning(msg);
1037 onWindowResized(Window.getClientHeight());
1041 * Display an informational message.
1043 * @param msg the message to display
1045 public void displayInformation(String msg) {
1046 messagePanel.displayInformation(msg);
1047 onWindowResized(Window.getClientHeight());
1051 * Retrieve the fileList.
1053 * @return the fileList
1055 public FileList getFileList() {
1060 * Retrieve the topPanel.
1062 * @return the topPanel
1064 TopPanel getTopPanel() {
1069 * Retrieve the clipboard.
1071 * @return the clipboard
1073 public Clipboard getClipboard() {
1077 public StatusPanel getStatusPanel() {
1081 public String getUserToken() {
1085 public static native void preventIESelection() /*-{
1086 $doc.body.onselectstart = function () {
1091 public static native void enableIESelection() /*-{
1092 if ($doc.body.onselectstart != null)
1093 $doc.body.onselectstart = null;
1096 public static String getStorageAPIURL() {
1097 return STORAGE_API_URL;
1100 public static String getStorageViewURL() {
1101 return STORAGE_VIEW_URL;
1104 public static String getUserCatalogsURL() {
1105 return USER_CATALOGS_API_URL;
1109 * History support for folder navigation
1110 * adds a new browser history entry
1114 public void updateHistory(String key) {
1115 // Replace any whitespace of the initial string to "+"
1116 // String result = key.replaceAll("\\s","+");
1117 // Add a new browser history entry.
1118 // History.newItem(result);
1119 History.newItem(key);
1122 public void deleteFolder(final Folder folder, final Command callback) {
1123 final PleaseWaitPopup pwp = new PleaseWaitPopup();
1125 String path = "/" + folder.getContainer() + "/" + folder.getPrefix() + "?delimiter=/" + "&t=" + System.currentTimeMillis();
1126 DeleteRequest deleteFolder = new DeleteRequest(getStorageAPIURL(), folder.getOwnerID(), path) {
1129 protected void onUnauthorized(Response response) {
1135 public void onSuccess(Resource result) {
1136 updateFolder(folder.getParent(), true, new Command() {
1139 public void execute() {
1140 folderTreeSelectionModel.setSelected(folder.getParent(), true);
1142 if(callback != null) {
1151 public void onError(Throwable t) {
1154 if(t instanceof RestException) {
1155 if(((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND) {
1156 displayError("Unable to delete folder: " + ((RestException) t).getHttpStatusText());
1163 displayError("System error unable to delete folder: " + t.getMessage());
1168 deleteFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1169 Scheduler.get().scheduleDeferred(deleteFolder);
1172 public FolderTreeView getFolderTreeView() {
1173 return folderTreeView;
1176 public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
1177 if(iter.hasNext()) {
1178 File file = iter.next();
1179 String path = targetUri + "/" + file.getName();
1180 PutRequest copyFile = new PutRequest(getStorageAPIURL(), targetUsername, path) {
1182 public void onSuccess(Resource result) {
1183 copyFiles(iter, targetUsername, targetUri, callback);
1187 public void onError(Throwable t) {
1190 if(t instanceof RestException) {
1191 displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
1194 displayError("System error unable to copy file: " + t.getMessage());
1199 protected void onUnauthorized(Response response) {
1203 copyFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1204 copyFile.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(file.getUri()));
1205 if(!file.getOwnerID().equals(targetUsername)) {
1206 copyFile.setHeader(Const.X_SOURCE_ACCOUNT, URL.encodePathSegment(file.getOwnerID()));
1208 copyFile.setHeader(Const.CONTENT_TYPE, file.getContentType());
1209 Scheduler.get().scheduleDeferred(copyFile);
1211 else if(callback != null) {
1216 public void copyFolder(final Folder f, final String targetUsername, final String targetUri, boolean move, final Command callback) {
1217 String path = targetUri + "?delimiter=/";
1218 PutRequest copyFolder = new PutRequest(getStorageAPIURL(), targetUsername, path) {
1220 public void onSuccess(Resource result) {
1221 if(callback != null) {
1227 public void onError(Throwable t) {
1230 if(t instanceof RestException) {
1231 displayError("Unable to copy folder: " + ((RestException) t).getHttpStatusText());
1234 displayError("System error copying folder: " + t.getMessage());
1239 protected void onUnauthorized(Response response) {
1243 copyFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1244 copyFolder.setHeader(Const.ACCEPT, "*/*");
1245 copyFolder.setHeader(Const.CONTENT_LENGTH, "0");
1246 copyFolder.setHeader(Const.CONTENT_TYPE, "application/directory");
1247 if(!f.getOwnerID().equals(targetUsername)) {
1248 copyFolder.setHeader(Const.X_SOURCE_ACCOUNT, f.getOwnerID());
1251 copyFolder.setHeader(Const.X_MOVE_FROM, URL.encodePathSegment(f.getUri()));
1254 copyFolder.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(f.getUri()));
1256 Scheduler.get().scheduleDeferred(copyFolder);
1259 public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1260 selectionModels.add(model);
1263 public OtherSharedTreeView getOtherSharedTreeView() {
1264 return otherSharedTreeView;
1267 public void updateTrash(boolean showFiles, Command callback) {
1268 updateFolder(trash, showFiles, callback, true);
1271 public void updateGroupsNode() {
1272 groupTreeView.updateGroupNode(null);
1275 public Group addGroup(String groupname) {
1276 Group newGroup = new Group(groupname);
1277 account.addGroup(newGroup);
1278 groupTreeView.updateGroupNode(null);
1282 public void removeGroup(Group group) {
1283 account.removeGroup(group);
1287 public TreeView getSelectedTree() {
1288 return selectedTree;
1291 public void setSelectedTree(TreeView selected) {
1292 selectedTree = selected;
1295 public Folder getSelection() {
1296 if(selectedTree != null) {
1297 return selectedTree.getSelection();
1302 public void showFolderStatistics(int folderFileCount) {
1303 numOfFiles.setHTML(String.valueOf(folderFileCount));
1306 public GroupTreeView getGroupTreeView() {
1307 return groupTreeView;
1310 public void sessionExpired() {
1311 new SessionExpiredDialog(this).center();
1314 public void updateRootFolder(Command callback) {
1315 updateFolder(account.getPithos(), false, callback, true);
1318 void createMySharedTree() {
1319 LOG("Pithos::createMySharedTree()");
1320 mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1321 mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1323 public void onSelectionChange(SelectionChangeEvent event) {
1324 if(mysharedTreeSelectionModel.getSelectedObject() != null) {
1325 deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1326 upload.setEnabled(false);
1327 disableUploadArea();
1328 updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1329 showRelevantToolbarButtons();
1332 if(getSelectedTree().equals(mysharedTreeView)) {
1333 setSelectedTree(null);
1335 if(getSelectedTree() == null) {
1336 showRelevantToolbarButtons();
1341 selectionModels.add(mysharedTreeSelectionModel);
1342 mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1343 mysharedTreeViewModel.initialize(new Command() {
1346 public void execute() {
1347 mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1348 trees.insert(mysharedTreeView, 2);
1349 treeViews.add(mysharedTreeView);
1350 createOtherSharedTree();
1355 void createOtherSharedTree() {
1356 LOG("Pithos::createOtherSharedTree()");
1357 otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1358 otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1360 public void onSelectionChange(SelectionChangeEvent event) {
1361 if(otherSharedTreeSelectionModel.getSelectedObject() != null) {
1362 deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1363 applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1364 updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true, null);
1365 showRelevantToolbarButtons();
1368 if(getSelectedTree().equals(otherSharedTreeView)) {
1369 setSelectedTree(null);
1371 if(getSelectedTree() == null) {
1372 showRelevantToolbarButtons();
1377 selectionModels.add(otherSharedTreeSelectionModel);
1378 otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1379 // #3784 We show it empty...
1380 otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel, true);
1381 trees.insert(otherSharedTreeView, 1);
1383 LOG("Pithos::createOtherSharedTree(), initializing otherSharedTreeViewModel with a callback");
1384 otherSharedTreeViewModel.initialize(new Command() {
1386 public void execute() {
1387 // #3784 ... then remove the empty stuff and add a new view with the populated model
1388 trees.remove(otherSharedTreeView);
1390 otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel, false);
1391 trees.insert(otherSharedTreeView, 1);
1392 treeViews.add(otherSharedTreeView);
1398 public String getErrorData() {
1399 final StringBuilder sb = new StringBuilder();
1400 final String NL = Const.NL;
1401 Throwable t = this.error;
1403 sb.append(t.toString());
1405 StackTraceElement[] traces = t.getStackTrace();
1406 for(StackTraceElement trace : traces) {
1408 sb.append(trace.getClassName());
1410 sb.append(trace.getMethodName());
1411 sb.append("() at ");
1412 sb.append(trace.getFileName());
1414 sb.append(trace.getLineNumber());
1421 return sb.toString();
1424 public void setError(Throwable t) {
1429 public void showRelevantToolbarButtons() {
1430 toolbar.showRelevantButtons();
1433 public FileUploadDialog getFileUploadDialog() {
1434 if(fileUploadDialog == null) {
1435 fileUploadDialog = new FileUploadDialog(this);
1437 return fileUploadDialog;
1440 public void hideUploadIndicator() {
1441 upload.removeStyleName("pithos-uploadButton-loading");
1442 upload.setTitle("");
1445 public void showUploadIndicator() {
1446 upload.addStyleName("pithos-uploadButton-loading");
1447 upload.setTitle("Upload in progress. Click for details.");
1450 public void scheduleFolderHeadCommand(final Folder folder, final Command callback) {
1451 if(folder == null) {
1452 if(callback != null) {
1457 HeadRequest<Folder> headFolder = new HeadRequest<Folder>(Folder.class, getStorageAPIURL(), folder.getOwnerID(), folder.getUri(), folder) {
1460 public void onSuccess(Folder _result) {
1461 if(callback != null) {
1467 public void onError(Throwable t) {
1468 if(t instanceof RestException) {
1469 if(((RestException) t).getHttpStatusCode() == Response.SC_NOT_FOUND) {
1470 final String path = folder.getUri();
1471 PutRequest newFolder = new PutRequest(getStorageAPIURL(), folder.getOwnerID(), path) {
1473 public void onSuccess(Resource _result) {
1474 scheduleFolderHeadCommand(folder, callback);
1478 public void onError(Throwable _t) {
1480 if(_t instanceof RestException) {
1481 displayError("Unable to create folder: " + ((RestException) _t).getHttpStatusText());
1484 displayError("System error creating folder: " + _t.getMessage());
1489 protected void onUnauthorized(Response response) {
1493 newFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1494 newFolder.setHeader(Const.CONTENT_TYPE, "application/folder");
1495 newFolder.setHeader(Const.ACCEPT, "*/*");
1496 newFolder.setHeader(Const.CONTENT_LENGTH, "0");
1497 Scheduler.get().scheduleDeferred(newFolder);
1499 else if(((RestException) t).getHttpStatusCode() == Response.SC_FORBIDDEN) {
1503 displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
1507 displayError("System error heading folder: " + t.getMessage());
1510 LOG("Error heading folder", t);
1515 protected void onUnauthorized(Response response) {
1519 headFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1520 Scheduler.get().scheduleDeferred(headFolder);
1524 public void scheduleFileHeadCommand(File f, final Command callback) {
1525 HeadRequest<File> headFile = new HeadRequest<File>(File.class, getStorageAPIURL(), f.getOwnerID(), f.getUri(), f) {
1528 public void onSuccess(File _result) {
1529 if(callback != null) {
1535 public void onError(Throwable t) {
1536 LOG("Error heading file", t);
1538 if(t instanceof RestException) {
1539 displayError("Error heading file: " + ((RestException) t).getHttpStatusText());
1542 displayError("System error heading file: " + t.getMessage());
1547 protected void onUnauthorized(Response response) {
1551 headFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1552 Scheduler.get().scheduleDeferred(headFile);
1555 public boolean isMySharedSelected() {
1556 return getSelectedTree().equals(getMySharedTreeView());
1559 private Folder getUploadFolder() {
1560 if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1561 return getSelection();
1566 private void updateUploadFolder() {
1567 updateUploadFolder(null);
1570 private void updateUploadFolder(final JsArrayString urls) {
1571 if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1572 Folder f = getSelection();
1573 if(getSelectedTree().equals(getFolderTreeView())) {
1574 updateFolder(f, true, new Command() {
1577 public void execute() {
1580 selectUploadedFiles(urls);
1586 updateOtherSharedFolder(f, true, null);
1591 public native void disableUploadArea() /*-{
1592 var uploader = $wnd.$("#uploader").pluploadQueue();
1593 var dropElm = $wnd.document.getElementById('rightPanel');
1594 $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1597 public native void enableUploadArea() /*-{
1598 var uploader = $wnd.$("#uploader").pluploadQueue();
1599 var dropElm = $wnd.document.getElementById('rightPanel');
1600 $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1601 if (uploader.runtime == 'html5') {
1602 uploader.settings.drop_element = 'rightPanel';
1603 uploader.trigger('PostInit');
1607 public void showUploadAlert(int nOfFiles) {
1608 if(uploadAlert == null) {
1609 uploadAlert = new UploadAlert(this, nOfFiles);
1611 if(!uploadAlert.isShowing()) {
1612 uploadAlert.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
1615 public void setPosition(int offsetWidth, int offsetHeight) {
1616 uploadAlert.setPopupPosition((Window.getClientWidth() - offsetWidth) / 2, statusPanel.getAbsoluteTop() - offsetHeight);
1620 uploadAlert.setNumOfFiles(nOfFiles);
1623 public void hideUploadAlert() {
1624 if(uploadAlert != null && uploadAlert.isShowing()) {
1629 public void selectUploadedFiles(JsArrayString urls) {
1630 List<String> selectedUrls = new ArrayList<String>();
1631 for(int i = 0; i < urls.length(); i++) {
1632 selectedUrls.add(urls.get(i));
1634 fileList.selectByUrl(selectedUrls);
1637 public void purgeContainer(final Folder container) {
1638 String path = "/" + container.getName() + "?delimiter=/";
1639 DeleteRequest delete = new DeleteRequest(getStorageAPIURL(), getUserID(), path) {
1642 protected void onUnauthorized(Response response) {
1647 public void onSuccess(Resource result) {
1648 updateFolder(container, true, null, true);
1652 public void onError(Throwable t) {
1653 LOG("Error deleting trash", t);
1655 if(t instanceof RestException) {
1656 displayError("Error deleting trash: " + ((RestException) t).getHttpStatusText());
1659 displayError("System error deleting trash: " + t.getMessage());
1663 delete.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1664 Scheduler.get().scheduleDeferred(delete);