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();
356 public void onError(Throwable t) {
357 GWT.log("Fetching user error", t);
358 if (t instanceof RestException)
359 GSS.get().displayError("No user found:" + ((RestException) t).getHttpStatusText());
361 GSS.get().displayError("System error fetching user data:" + t.getMessage());
365 DeferredCommand.addCommand(getUserCommand);
369 * Parse and store the user credentials to the appropriate fields.
371 private void parseUserCredentials() {
372 // Configuration conf = (Configuration) GWT.create(Configuration.class);
373 // String cookie = conf.authCookie();
374 // String auth = Cookies.getCookie(cookie);
375 // if (auth == null) {
376 // authenticateUser();
377 // // Redundant, but silences warnings about possible auth NPE, below.
380 // int sepIndex = auth.indexOf(conf.cookieSeparator());
381 // if (sepIndex == -1)
382 // authenticateUser();
383 // token = auth.substring(sepIndex + 1);
384 // final String username = auth.substring(0, sepIndex);
385 // if (username == null)
386 // authenticateUser();
388 // refreshWebDAVPassword();
390 final String username = "test";
391 DeferredCommand.addCommand(new Command() {
394 public void execute() {
401 * Redirect the user to the login page for authentication.
403 protected void authenticateUser() {
404 // Configuration conf = (Configuration) GWT.create(Configuration.class);
405 //IMPORTANT: Temporary circumvention of the Shiboleth login process for development and testing
406 //Some time in the future the comment line will be restored
408 // Window.Location.assign(GWT.getModuleBaseURL() + conf.loginUrl() + "?next=" + Window.Location.getHref());
409 // Cookies.setCookie(conf.authCookie(), "chstath@ebs.gr" + conf.cookieSeparator() + "triapoulakiakathontan");
410 // Window.Location.assign(GWT.getModuleBaseURL());
414 * Clear the cookie and redirect the user to the logout page.
417 Configuration conf = (Configuration) GWT.create(Configuration.class);
418 String cookie = conf.authCookie();
419 String domain = Window.Location.getHostName();
420 String path = Window.Location.getPath();
421 Cookies.setCookie(cookie, "", null, domain, path, false);
422 String baseUrl = GWT.getModuleBaseURL();
423 String homeUrl = baseUrl.substring(0, baseUrl.indexOf(path));
424 Window.Location.assign(homeUrl + conf.logoutUrl());
428 * Creates an HTML fragment that places an image & caption together, for use
431 * @param imageProto an image prototype for an image
432 * @param caption the group caption
433 * @return the header HTML fragment
435 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
436 String captionHTML = "<table class='caption' cellpadding='0' "
437 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
438 + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'> "
439 + caption + "</b></td></tr></table>";
443 private void onWindowResized(int height) {
444 // Adjust the split panel to take up the available room in the window.
445 int newHeight = height - splitPanel.getAbsoluteTop() - 44;
448 splitPanel.setHeight("" + newHeight);
449 inner.setHeight("" + newHeight);
450 /*if(isFileListShowing()){
451 getFileList().setHeight("" + (newHeight-50));
456 public void onResize(ResizeEvent event) {
457 int height = event.getHeight();
458 onWindowResized(height);
461 public boolean isFileListShowing() {
462 int tab = inner.getTabBar().getSelectedTab();
468 public boolean isSearchResultsShowing() {
469 int tab = inner.getTabBar().getSelectedTab();
476 * Make the user list visible.
478 public void showUserList() {
483 * Make the file list visible.
485 public void showFileList() {
486 fileList.updateFileCache(true /*clear selection*/);
491 * Make the file list visible.
495 public void showFileList(boolean update) {
497 getTreeView().refreshCurrentNode(true);
500 RestResource currentFolder = getTreeView().getSelection();
501 if(currentFolder!=null){
502 showFileList(currentFolder);
508 public void showFileList(RestResource r) {
509 showFileList(r,true);
512 public void showFileList(RestResource r, boolean clearSelection) {
513 RestResource currentFolder = r;
514 if(currentFolder!=null){
515 List<FileResource> files = null;
516 if (currentFolder instanceof RestResourceWrapper) {
517 RestResourceWrapper folder = (RestResourceWrapper) currentFolder;
518 files = folder.getResource().getFiles();
519 } else if (currentFolder instanceof TrashResource) {
520 TrashResource folder = (TrashResource) currentFolder;
521 files = folder.getFiles();
523 else if (currentFolder instanceof SharedResource) {
524 SharedResource folder = (SharedResource) currentFolder;
525 files = folder.getFiles();
527 else if (currentFolder instanceof OtherUserResource) {
528 OtherUserResource folder = (OtherUserResource) currentFolder;
529 files = folder.getFiles();
532 getFileList().setFiles(files);
534 getFileList().setFiles(new ArrayList<FileResource>());
536 fileList.updateFileCache(clearSelection /*clear selection*/);
541 * Make the search results visible.
543 * @param query the search query string
545 public void showSearchResults(String query) {
546 searchResults.updateFileCache(query);
547 searchResults.updateCurrentlyShowingStats();
552 * Display the 'loading' indicator.
554 public void showLoadingIndicator(String message, String path) {
556 String[] split = path.split("/");
557 message = message +" "+URL.decode(split[split.length-1]);
559 topPanel.getLoading().show(message);
563 * Hide the 'loading' indicator.
565 public void hideLoadingIndicator() {
566 topPanel.getLoading().hide();
570 * A native JavaScript method to reach out to the browser's window and
571 * invoke its resizeTo() method.
573 * @param x the new width
574 * @param y the new height
576 public static native void resizeTo(int x, int y) /*-{
581 * A helper method that returns true if the user's list is currently visible
582 * and false if it is hidden.
584 * @return true if the user list is visible
586 public boolean isUserListVisible() {
587 return inner.getTabBar().getSelectedTab() == 1;
591 * Display an error message.
593 * @param msg the message to display
595 public void displayError(String msg) {
596 messagePanel.displayError(msg);
600 * Display a warning message.
602 * @param msg the message to display
604 public void displayWarning(String msg) {
605 messagePanel.displayWarning(msg);
609 * Display an informational message.
611 * @param msg the message to display
613 public void displayInformation(String msg) {
614 messagePanel.displayInformation(msg);
618 * Retrieve the folders.
620 * @return the folders
622 public Folders getFolders() {
627 * Retrieve the search.
636 * Retrieve the currentSelection.
638 * @return the currentSelection
640 public Object getCurrentSelection() {
641 return currentSelection;
645 * Modify the currentSelection.
647 * @param newCurrentSelection the currentSelection to set
649 public void setCurrentSelection(Object newCurrentSelection) {
650 currentSelection = newCurrentSelection;
654 * Retrieve the groups.
658 public Groups getGroups() {
663 * Retrieve the fileList.
665 * @return the fileList
667 public FileList getFileList() {
671 public SearchResults getSearchResults() {
672 return searchResults;
676 * Retrieve the topPanel.
678 * @return the topPanel
680 TopPanel getTopPanel() {
685 * Retrieve the clipboard.
687 * @return the clipboard
689 public Clipboard getClipboard() {
693 public StatusPanel getStatusPanel() {
698 * Retrieve the userDetailsPanel.
700 * @return the userDetailsPanel
702 public UserDetailsPanel getUserDetailsPanel() {
703 return userDetailsPanel;
708 public String getToken() {
712 public String getWebDAVPassword() {
713 return webDAVPassword;
716 public void removeGlassPanel() {
717 glassPanel.removeFromParent();
721 * Retrieve the currentUserResource.
723 * @return the currentUserResource
725 public UserResource getCurrentUserResource() {
726 return currentUserResource;
730 * Modify the currentUserResource.
732 * @param newUser the new currentUserResource
734 public void setCurrentUserResource(UserResource newUser) {
735 currentUserResource = newUser;
738 public static native void preventIESelection() /*-{
739 $doc.body.onselectstart = function () { return false; };
742 public static native void enableIESelection() /*-{
743 if ($doc.body.onselectstart != null)
744 $doc.body.onselectstart = null;
748 * @return the absolute path of the API root URL
750 public String getApiPath() {
751 Configuration conf = (Configuration) GWT.create(Configuration.class);
752 return GWT.getModuleBaseURL() + conf.apiPath();
756 * Convert server date to local time according to browser timezone
757 * and format it according to localized pattern.
758 * Time is always formatted to 24hr format.
759 * NB: This assumes that server runs in UTC timezone. Otherwise
760 * we would need to adjust for server time offset as well.
765 public static String formatLocalDateTime(Date date) {
766 Date convertedDate = new Date(date.getTime() - date.getTimezoneOffset());
767 final DateTimeFormat dateFormatter = DateTimeFormat.getShortDateFormat();
768 final DateTimeFormat timeFormatter = DateTimeFormat.getFormat("HH:mm");
769 String datePart = dateFormatter.format(convertedDate);
770 String timePart = timeFormatter.format(convertedDate);
771 return datePart + " " + timePart;
775 * History support for folder navigation
776 * adds a new browser history entry
780 public void updateHistory(String key){
781 // Replace any whitespace of the initial string to "+"
782 // String result = key.replaceAll("\\s","+");
783 // Add a new browser history entry.
784 // History.newItem(result);
785 History.newItem(key);
789 * This method examines the token input and add a "/" at the end in case it's omitted.
790 * This happens only in Files/trash/, Files/shared/, Files/others.
793 * @return the formated token with a "/" at the end or the same tokenInput parameter
796 private String handleSpecialFolderNames(String tokenInput){
797 List<String> pathsToCheck = Arrays.asList("Files/trash", "Files/shared", "Files/others");
798 if(pathsToCheck.contains(tokenInput))
799 return tokenInput + "/";
805 * Reject illegal resource names, like '.' or '..' or slashes '/'.
807 static boolean isValidResourceName(String name) {
808 if (".".equals(name) || "..".equals(name) || name.contains("/"))
813 public void putUserToMap(String _userName, String _userFullName){
814 userFullNameMap.put(_userName, _userFullName);
817 public String findUserFullName(String _userName){
818 return userFullNameMap.get(_userName);
820 public String getUserFullName(String _userName) {
822 if (GSS.get().findUserFullName(_userName) == null)
823 //if there is no userFullName found then the map fills with the given _userName,
824 //so userFullName = _userName
825 GSS.get().putUserToMap(_userName, _userName);
826 else if(GSS.get().findUserFullName(_userName).indexOf('@') != -1){
827 //if the userFullName = _userName the GetUserCommand updates the userFullName in the map
828 GetUserCommand guc = new GetUserCommand(_userName);
831 return GSS.get().findUserFullName(_userName);
834 * Retrieve the treeView.
836 * @return the treeView
838 public CellTreeView getTreeView() {
842 public void onResourceUpdate(RestResource resource,boolean clearSelection){
843 if(resource instanceof RestResourceWrapper || resource instanceof OtherUserResource || resource instanceof TrashResource || resource instanceof SharedResource){
844 if(getTreeView().getSelection()!=null&&getTreeView().getSelection().getUri().equals(resource.getUri()))
845 showFileList(resource,clearSelection);