2 * Copyright (c) 2011 Greek Research and Technology Network
4 package gr.grnet.pithos.web.client;
6 import gr.grnet.pithos.web.client.clipboard.Clipboard;
7 import gr.grnet.pithos.web.client.commands.GetUserCommand;
8 import gr.grnet.pithos.web.client.rest.GetCommand;
9 import gr.grnet.pithos.web.client.rest.RestException;
10 import gr.grnet.pithos.web.client.rest.resource.FileResource;
11 import gr.grnet.pithos.web.client.rest.resource.OtherUserResource;
12 import gr.grnet.pithos.web.client.rest.resource.RestResource;
13 import gr.grnet.pithos.web.client.rest.resource.RestResourceWrapper;
14 import gr.grnet.pithos.web.client.rest.resource.SharedResource;
15 import gr.grnet.pithos.web.client.rest.resource.TrashResource;
16 import gr.grnet.pithos.web.client.rest.resource.UserResource;
18 import java.util.ArrayList;
19 import java.util.Arrays;
20 import java.util.Date;
21 import java.util.HashMap;
22 import java.util.List;
24 import com.google.gwt.core.client.EntryPoint;
25 import com.google.gwt.core.client.GWT;
26 import com.google.gwt.event.logical.shared.ResizeEvent;
27 import com.google.gwt.event.logical.shared.ResizeHandler;
28 import com.google.gwt.event.logical.shared.SelectionEvent;
29 import com.google.gwt.event.logical.shared.SelectionHandler;
30 import com.google.gwt.event.logical.shared.ValueChangeEvent;
31 import com.google.gwt.event.logical.shared.ValueChangeHandler;
32 import com.google.gwt.http.client.URL;
33 import com.google.gwt.i18n.client.DateTimeFormat;
34 import com.google.gwt.resources.client.ClientBundle;
35 import com.google.gwt.resources.client.ImageResource;
36 import com.google.gwt.user.client.Command;
37 import com.google.gwt.user.client.Cookies;
38 import com.google.gwt.user.client.DOM;
39 import com.google.gwt.user.client.DeferredCommand;
40 import com.google.gwt.user.client.Event;
41 import com.google.gwt.user.client.History;
42 import com.google.gwt.user.client.Window;
43 import com.google.gwt.user.client.ui.AbstractImagePrototype;
44 import com.google.gwt.user.client.ui.DecoratedTabPanel;
45 import com.google.gwt.user.client.ui.DockPanel;
46 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
47 import com.google.gwt.user.client.ui.HasVerticalAlignment;
48 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
49 import com.google.gwt.user.client.ui.RootPanel;
50 import com.google.gwt.user.client.ui.TabPanel;
51 import com.google.gwt.user.client.ui.VerticalPanel;
53 * Entry point classes define <code>onModuleLoad()</code>.
55 public class GSS implements EntryPoint, ResizeHandler {
58 * A constant that denotes the completion of an IncrementalCommand.
60 public static final boolean DONE = false;
62 public static final int VISIBLE_FILE_COUNT = 25;
65 * Instantiate an application-level image bundle. This object will provide
66 * programmatic access to all the images needed by widgets.
68 private static Images images = (Images) GWT.create(Images.class);
70 private GlassPanel glassPanel = new GlassPanel();
73 * An aggregate image bundle that pulls together all the images for this
74 * application into a single bundle.
76 public interface Images extends ClientBundle, TopPanel.Images, StatusPanel.Images, FileMenu.Images, EditMenu.Images, SettingsMenu.Images, GroupMenu.Images, FilePropertiesDialog.Images, MessagePanel.Images, FileList.Images, SearchResults.Images, Search.Images, Groups.Images, CellTreeView.Images {
78 @Source("gr/grnet/pithos/resources/document.png")
79 ImageResource folders();
81 @Source("gr/grnet/pithos/resources/edit_group_22.png")
82 ImageResource groups();
84 @Source("gr/grnet/pithos/resources/search.png")
85 ImageResource search();
89 * The single GSS instance.
91 private static GSS singleton;
94 * Gets the singleton GSS instance.
96 * @return the GSS object
98 public static GSS get() {
99 if (GSS.singleton == null)
100 GSS.singleton = new GSS();
101 return GSS.singleton;
105 * The Application Clipboard implementation;
107 private Clipboard clipboard = new Clipboard();
109 private UserResource currentUserResource;
112 * The top panel that contains the menu bar.
114 private TopPanel topPanel;
117 * The panel that contains the various system messages.
119 private MessagePanel messagePanel = new MessagePanel(GSS.images);
122 * The bottom panel that contains the status bar.
124 private StatusPanel statusPanel = new StatusPanel(GSS.images);
127 * The top right panel that displays the logged in user details
129 private UserDetailsPanel userDetailsPanel = new UserDetailsPanel();
132 * The file list widget.
134 private FileList fileList;
137 * The group list widget.
139 private Groups groups = new Groups(images);
142 * The search result widget.
144 private SearchResults searchResults;
147 * The tab panel that occupies the right side of the screen.
149 private TabPanel inner = new DecoratedTabPanel(){
151 public void onBrowserEvent(com.google.gwt.user.client.Event event) {
152 if (DOM.eventGetType(event) == Event.ONCONTEXTMENU){
153 if(isFileListShowing()){
154 getFileList().showContextMenu(event);
156 else if(isUserListVisible()){
157 getGroups().setCurrent(null);
158 getGroups().showPopup(event.getClientX(),event.getClientY());
165 * The split panel that will contain the left and right panels.
167 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
170 * The horizontal panel that will contain the search and status panels.
172 private DockPanel searchStatus = new DockPanel();
177 private Search search;
180 * The widget that displays the tree of folders.
183 private CellTreeView treeView = new CellTreeView(images);
185 * The currently selected item in the application, for use by the Edit menu
186 * commands. Potential types are Folder, File, User and Group.
188 private Object currentSelection;
191 * The authentication token of the current user.
193 private String token;
196 * The WebDAV password of the current user
198 private String webDAVPassword;
202 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
205 public void onModuleLoad() {
206 // Initialize the singleton before calling the constructors of the
207 // various widgets that might call GSS.get().
209 RootPanel.get().add(glassPanel, 0, 0);
210 parseUserCredentials();
212 topPanel = new TopPanel(GSS.images);
213 topPanel.setWidth("100%");
215 messagePanel.setWidth("100%");
216 messagePanel.setVisible(false);
218 search = new Search(images);
219 searchStatus.add(search, DockPanel.WEST);
220 searchStatus.add(userDetailsPanel, DockPanel.EAST);
221 searchStatus.setCellHorizontalAlignment(userDetailsPanel, HasHorizontalAlignment.ALIGN_RIGHT);
222 searchStatus.setCellVerticalAlignment(search, HasVerticalAlignment.ALIGN_MIDDLE);
223 searchStatus.setCellVerticalAlignment(userDetailsPanel, HasVerticalAlignment.ALIGN_MIDDLE);
224 searchStatus.setWidth("100%");
226 fileList = new FileList(images);
228 searchResults = new SearchResults(images);
230 // Inner contains the various lists.
231 inner.sinkEvents(Event.ONCONTEXTMENU);
232 inner.setAnimationEnabled(true);
233 inner.getTabBar().addStyleName("pithos-MainTabBar");
234 inner.getDeckPanel().addStyleName("pithos-MainTabPanelBottom");
235 inner.add(fileList, createHeaderHTML(AbstractImagePrototype.create(images.folders()), "Files"), true);
237 inner.add(groups, createHeaderHTML(AbstractImagePrototype.create(images.groups()), "Groups"), true);
238 inner.add(searchResults, createHeaderHTML(AbstractImagePrototype.create(images.search()), "Search Results"), true);
239 //inner.add(new CellTreeView(images), createHeaderHTML(AbstractImagePrototype.create(images.search()), "Cell tree sample"), true);
240 inner.setWidth("100%");
243 inner.addSelectionHandler(new SelectionHandler<Integer>() {
246 public void onSelection(SelectionEvent<Integer> event) {
247 int tabIndex = event.getSelectedItem();
248 // TreeItem treeItem = GSS.get().getFolders().getCurrent();
251 // Files tab selected
252 //fileList.clearSelectedRows();
253 fileList.updateCurrentlyShowingStats();
256 // Groups tab selected
257 groups.updateCurrentlyShowingStats();
258 updateHistory("Groups");
261 // Search tab selected
262 searchResults.clearSelectedRows();
263 searchResults.updateCurrentlyShowingStats();
264 updateHistory("Search");
269 // If the application starts with no history token, redirect to a new "Files" state
270 String initToken = History.getToken();
271 if(initToken.length() == 0)
272 History.newItem("Files");
273 // Add history listener to handle any history events
274 History.addValueChangeHandler(new ValueChangeHandler<String>() {
276 public void onValueChange(ValueChangeEvent<String> event) {
277 String tokenInput = event.getValue();
278 String historyToken = handleSpecialFolderNames(tokenInput);
280 if(historyToken.equals("Search"))
282 else if(historyToken.equals("Groups"))
284 else if(historyToken.equals("Files")|| historyToken.length()==0)
288 PopupTree popupTree = GSS.get().getFolders().getPopupTree();
289 TreeItem treeObj = GSS.get().getFolders().getPopupTree().getTreeItem(historyToken);
290 SelectionEvent.fire(popupTree, treeObj);
293 } catch (IndexOutOfBoundsException e) {
299 // Add the left and right panels to the split panel.
300 splitPanel.setLeftWidget(treeView);
301 splitPanel.setRightWidget(inner);
302 splitPanel.setSplitPosition("25%");
303 splitPanel.setSize("100%", "100%");
304 splitPanel.addStyleName("pithos-splitPanel");
306 // Create a dock panel that will contain the menu bar at the top,
307 // the shortcuts to the left, the status bar at the bottom and the
308 // right panel taking the rest.
309 VerticalPanel outer = new VerticalPanel();
311 outer.add(searchStatus);
312 outer.add(messagePanel);
313 outer.add(splitPanel);
314 outer.add(statusPanel);
315 outer.setWidth("100%");
316 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
320 // Hook the window resize event, so that we can adjust the UI.
321 Window.addResizeHandler(this);
322 // Clear out the window's built-in margin, because we want to take
323 // advantage of the entire client area.
324 Window.setMargin("0px");
325 // Finally, add the outer panel to the RootPanel, so that it will be
327 RootPanel.get().add(outer);
328 // Call the window resized handler to get the initial sizes setup. Doing
329 // this in a deferred command causes it to occur after all widgets'
330 // sizes have been computed by the browser.
331 DeferredCommand.addCommand(new Command() {
334 public void execute() {
335 onWindowResized(Window.getClientHeight());
341 * Fetches the User object for the specified username.
343 * @param username the username of the user
345 private void fetchUser(final String username) {
346 String path = getApiPath() + username + "/";
347 GetCommand<UserResource> getUserCommand = new GetCommand<UserResource>(UserResource.class, username, path, null) {
350 public void onComplete() {
352 currentUserResource = getResult();
353 final String announcement = currentUserResource.getAnnouncement();
354 if (announcement != null)
355 DeferredCommand.addCommand(new Command() {
358 public void execute() {
359 displayInformation(announcement);
365 public void onError(Throwable t) {
366 GWT.log("Fetching user error", t);
367 if (t instanceof RestException)
368 GSS.get().displayError("No user found:" + ((RestException) t).getHttpStatusText());
370 GSS.get().displayError("System error fetching user data:" + t.getMessage());
374 DeferredCommand.addCommand(getUserCommand);
378 * Parse and store the user credentials to the appropriate fields.
380 private void parseUserCredentials() {
381 Configuration conf = (Configuration) GWT.create(Configuration.class);
382 String cookie = conf.authCookie();
383 String auth = Cookies.getCookie(cookie);
386 // Redundant, but silences warnings about possible auth NPE, below.
389 int sepIndex = auth.indexOf(conf.cookieSeparator());
392 token = auth.substring(sepIndex + 1);
393 final String username = auth.substring(0, sepIndex);
394 if (username == null)
397 refreshWebDAVPassword();
399 DeferredCommand.addCommand(new Command() {
402 public void execute() {
409 * Redirect the user to the login page for authentication.
411 protected void authenticateUser() {
412 Configuration conf = (Configuration) GWT.create(Configuration.class);
413 //IMPORTANT: Temporary circumvention of the Shiboleth login process for development and testing
414 //Some time in the future the comment line will be restored
415 //Window.Location.assign(GWT.getModuleBaseURL() + conf.loginUrl() + "?next=" + GWT.getModuleBaseURL());
416 Cookies.setCookie(conf.authCookie(), "chstath@ebs.gr" + conf.cookieSeparator() + "triapoulakiakathontan");
417 Window.Location.assign(GWT.getModuleBaseURL());
421 * Clear the cookie and redirect the user to the logout page.
424 Configuration conf = (Configuration) GWT.create(Configuration.class);
425 String cookie = conf.authCookie();
426 String domain = Window.Location.getHostName();
427 String path = Window.Location.getPath();
428 Cookies.setCookie(cookie, "", null, domain, path, false);
429 String baseUrl = GWT.getModuleBaseURL();
430 String homeUrl = baseUrl.substring(0, baseUrl.indexOf(path));
431 Window.Location.assign(homeUrl + conf.logoutUrl());
435 * Creates an HTML fragment that places an image & caption together, for use
438 * @param imageProto an image prototype for an image
439 * @param caption the group caption
440 * @return the header HTML fragment
442 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
443 String captionHTML = "<table class='caption' cellpadding='0' "
444 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
445 + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'> "
446 + caption + "</b></td></tr></table>";
450 private void onWindowResized(int height) {
451 // Adjust the split panel to take up the available room in the window.
452 int newHeight = height - splitPanel.getAbsoluteTop() - 44;
455 splitPanel.setHeight("" + newHeight);
456 inner.setHeight("" + newHeight);
457 /*if(isFileListShowing()){
458 getFileList().setHeight("" + (newHeight-50));
463 public void onResize(ResizeEvent event) {
464 int height = event.getHeight();
465 onWindowResized(height);
468 public boolean isFileListShowing() {
469 int tab = inner.getTabBar().getSelectedTab();
475 public boolean isSearchResultsShowing() {
476 int tab = inner.getTabBar().getSelectedTab();
483 * Make the user list visible.
485 public void showUserList() {
490 * Make the file list visible.
492 public void showFileList() {
493 fileList.updateFileCache(true /*clear selection*/);
498 * Make the file list visible.
502 public void showFileList(boolean update) {
504 getTreeView().refreshCurrentNode(true);
507 RestResource currentFolder = getTreeView().getSelection();
508 if(currentFolder!=null){
509 showFileList(currentFolder);
515 public void showFileList(RestResource r) {
516 showFileList(r,true);
519 public void showFileList(RestResource r, boolean clearSelection) {
520 RestResource currentFolder = r;
521 if(currentFolder!=null){
522 List<FileResource> files = null;
523 if (currentFolder instanceof RestResourceWrapper) {
524 RestResourceWrapper folder = (RestResourceWrapper) currentFolder;
525 files = folder.getResource().getFiles();
526 } else if (currentFolder instanceof TrashResource) {
527 TrashResource folder = (TrashResource) currentFolder;
528 files = folder.getFiles();
530 else if (currentFolder instanceof SharedResource) {
531 SharedResource folder = (SharedResource) currentFolder;
532 files = folder.getFiles();
534 else if (currentFolder instanceof OtherUserResource) {
535 OtherUserResource folder = (OtherUserResource) currentFolder;
536 files = folder.getFiles();
539 getFileList().setFiles(files);
541 getFileList().setFiles(new ArrayList<FileResource>());
543 fileList.updateFileCache(clearSelection /*clear selection*/);
548 * Make the search results visible.
550 * @param query the search query string
552 public void showSearchResults(String query) {
553 searchResults.updateFileCache(query);
554 searchResults.updateCurrentlyShowingStats();
559 * Display the 'loading' indicator.
561 public void showLoadingIndicator(String message, String path) {
563 String[] split = path.split("/");
564 message = message +" "+URL.decode(split[split.length-1]);
566 topPanel.getLoading().show(message);
570 * Hide the 'loading' indicator.
572 public void hideLoadingIndicator() {
573 topPanel.getLoading().hide();
577 * A native JavaScript method to reach out to the browser's window and
578 * invoke its resizeTo() method.
580 * @param x the new width
581 * @param y the new height
583 public static native void resizeTo(int x, int y) /*-{
588 * A helper method that returns true if the user's list is currently visible
589 * and false if it is hidden.
591 * @return true if the user list is visible
593 public boolean isUserListVisible() {
594 return inner.getTabBar().getSelectedTab() == 1;
598 * Display an error message.
600 * @param msg the message to display
602 public void displayError(String msg) {
603 messagePanel.displayError(msg);
607 * Display a warning message.
609 * @param msg the message to display
611 public void displayWarning(String msg) {
612 messagePanel.displayWarning(msg);
616 * Display an informational message.
618 * @param msg the message to display
620 public void displayInformation(String msg) {
621 messagePanel.displayInformation(msg);
625 * Retrieve the folders.
627 * @return the folders
629 public Folders getFolders() {
634 * Retrieve the search.
643 * Retrieve the currentSelection.
645 * @return the currentSelection
647 public Object getCurrentSelection() {
648 return currentSelection;
652 * Modify the currentSelection.
654 * @param newCurrentSelection the currentSelection to set
656 public void setCurrentSelection(Object newCurrentSelection) {
657 currentSelection = newCurrentSelection;
661 * Retrieve the groups.
665 public Groups getGroups() {
670 * Retrieve the fileList.
672 * @return the fileList
674 public FileList getFileList() {
678 public SearchResults getSearchResults() {
679 return searchResults;
683 * Retrieve the topPanel.
685 * @return the topPanel
687 TopPanel getTopPanel() {
692 * Retrieve the clipboard.
694 * @return the clipboard
696 public Clipboard getClipboard() {
700 public StatusPanel getStatusPanel() {
705 * Retrieve the userDetailsPanel.
707 * @return the userDetailsPanel
709 public UserDetailsPanel getUserDetailsPanel() {
710 return userDetailsPanel;
715 public String getToken() {
719 public String getWebDAVPassword() {
720 return webDAVPassword;
723 public void removeGlassPanel() {
724 glassPanel.removeFromParent();
728 * Retrieve the currentUserResource.
730 * @return the currentUserResource
732 public UserResource getCurrentUserResource() {
733 return currentUserResource;
737 * Modify the currentUserResource.
739 * @param newUser the new currentUserResource
741 public void setCurrentUserResource(UserResource newUser) {
742 currentUserResource = newUser;
745 public static native void preventIESelection() /*-{
746 $doc.body.onselectstart = function () { return false; };
749 public static native void enableIESelection() /*-{
750 if ($doc.body.onselectstart != null)
751 $doc.body.onselectstart = null;
755 * @return the absolute path of the API root URL
757 public String getApiPath() {
758 Configuration conf = (Configuration) GWT.create(Configuration.class);
759 return GWT.getModuleBaseURL() + conf.apiPath();
762 public void refreshWebDAVPassword() {
763 Configuration conf = (Configuration) GWT.create(Configuration.class);
764 String domain = Window.Location.getHostName();
765 String path = Window.Location.getPath();
766 String cookie = conf.webdavCookie();
767 webDAVPassword = Cookies.getCookie(cookie);
768 Cookies.setCookie(cookie, "", null, domain, path, false);
772 * Convert server date to local time according to browser timezone
773 * and format it according to localized pattern.
774 * Time is always formatted to 24hr format.
775 * NB: This assumes that server runs in UTC timezone. Otherwise
776 * we would need to adjust for server time offset as well.
781 public static String formatLocalDateTime(Date date) {
782 Date convertedDate = new Date(date.getTime() - date.getTimezoneOffset());
783 final DateTimeFormat dateFormatter = DateTimeFormat.getShortDateFormat();
784 final DateTimeFormat timeFormatter = DateTimeFormat.getFormat("HH:mm");
785 String datePart = dateFormatter.format(convertedDate);
786 String timePart = timeFormatter.format(convertedDate);
787 return datePart + " " + timePart;
791 * History support for folder navigation
792 * adds a new browser history entry
796 public void updateHistory(String key){
797 // Replace any whitespace of the initial string to "+"
798 // String result = key.replaceAll("\\s","+");
799 // Add a new browser history entry.
800 // History.newItem(result);
801 History.newItem(key);
805 * This method examines the token input and add a "/" at the end in case it's omitted.
806 * This happens only in Files/trash/, Files/shared/, Files/others.
809 * @return the formated token with a "/" at the end or the same tokenInput parameter
812 private String handleSpecialFolderNames(String tokenInput){
813 List<String> pathsToCheck = Arrays.asList("Files/trash", "Files/shared", "Files/others");
814 if(pathsToCheck.contains(tokenInput))
815 return tokenInput + "/";
821 * Reject illegal resource names, like '.' or '..' or slashes '/'.
823 static boolean isValidResourceName(String name) {
824 if (".".equals(name) || "..".equals(name) || name.contains("/"))
829 public void putUserToMap(String _userName, String _userFullName){
830 userFullNameMap.put(_userName, _userFullName);
833 public String findUserFullName(String _userName){
834 return userFullNameMap.get(_userName);
836 public String getUserFullName(String _userName) {
838 if (GSS.get().findUserFullName(_userName) == null)
839 //if there is no userFullName found then the map fills with the given _userName,
840 //so userFullName = _userName
841 GSS.get().putUserToMap(_userName, _userName);
842 else if(GSS.get().findUserFullName(_userName).indexOf('@') != -1){
843 //if the userFullName = _userName the GetUserCommand updates the userFullName in the map
844 GetUserCommand guc = new GetUserCommand(_userName);
847 return GSS.get().findUserFullName(_userName);
850 * Retrieve the treeView.
852 * @return the treeView
854 public CellTreeView getTreeView() {
858 public void onResourceUpdate(RestResource resource,boolean clearSelection){
859 if(resource instanceof RestResourceWrapper || resource instanceof OtherUserResource || resource instanceof TrashResource || resource instanceof SharedResource){
860 if(getTreeView().getSelection()!=null&&getTreeView().getSelection().getUri().equals(resource.getUri()))
861 showFileList(resource,clearSelection);