2 * Copyright (c) 2011 Greek Research and Technology Network
4 package gr.grnet.pithos.web.client;
6 import com.google.gwt.core.client.Scheduler;
7 import com.google.gwt.core.client.Scheduler.ScheduledCommand;
8 import com.google.gwt.user.client.ui.DockPanel;
9 import com.google.gwt.user.client.ui.HasVerticalAlignment;
10 import com.google.gwt.view.client.ListDataProvider;
11 import com.google.gwt.view.client.SelectionChangeEvent;
12 import com.google.gwt.view.client.SelectionChangeEvent.Handler;
13 import com.google.gwt.view.client.SingleSelectionModel;
14 import com.google.gwt.view.client.TreeViewModel.NodeInfo;
15 import gr.grnet.pithos.web.client.clipboard.Clipboard;
16 import gr.grnet.pithos.web.client.commands.GetUserCommand;
17 import gr.grnet.pithos.web.client.foldertree.AccountResource;
18 import gr.grnet.pithos.web.client.foldertree.File;
19 import gr.grnet.pithos.web.client.foldertree.Folder;
20 import gr.grnet.pithos.web.client.foldertree.FolderTreeView;
21 import gr.grnet.pithos.web.client.foldertree.FolderTreeViewModel;
22 import gr.grnet.pithos.web.client.rest.GetRequest;
23 import gr.grnet.pithos.web.client.rest.RestException;
24 import gr.grnet.pithos.web.client.rest.resource.FileResource;
25 import gr.grnet.pithos.web.client.rest.resource.OtherUserResource;
26 import gr.grnet.pithos.web.client.rest.resource.RestResource;
27 import gr.grnet.pithos.web.client.rest.resource.RestResourceWrapper;
28 import gr.grnet.pithos.web.client.rest.resource.SharedResource;
29 import gr.grnet.pithos.web.client.rest.resource.TrashResource;
30 import gr.grnet.pithos.web.client.rest.resource.UserResource;
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.Date;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.List;
39 import com.google.gwt.core.client.EntryPoint;
40 import com.google.gwt.core.client.GWT;
41 import com.google.gwt.event.logical.shared.ResizeEvent;
42 import com.google.gwt.event.logical.shared.ResizeHandler;
43 import com.google.gwt.event.logical.shared.SelectionEvent;
44 import com.google.gwt.event.logical.shared.SelectionHandler;
45 import com.google.gwt.http.client.URL;
46 import com.google.gwt.i18n.client.DateTimeFormat;
47 import com.google.gwt.resources.client.ClientBundle;
48 import com.google.gwt.resources.client.ImageResource;
49 import com.google.gwt.user.client.Command;
50 import com.google.gwt.user.client.Cookies;
51 import com.google.gwt.user.client.DOM;
52 import com.google.gwt.user.client.DeferredCommand;
53 import com.google.gwt.user.client.Event;
54 import com.google.gwt.user.client.History;
55 import com.google.gwt.user.client.Window;
56 import com.google.gwt.user.client.ui.AbstractImagePrototype;
57 import com.google.gwt.user.client.ui.DecoratedTabPanel;
58 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
59 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
60 import com.google.gwt.user.client.ui.RootPanel;
61 import com.google.gwt.user.client.ui.TabPanel;
62 import com.google.gwt.user.client.ui.VerticalPanel;
66 * Entry point classes define <code>onModuleLoad()</code>.
68 public class GSS implements EntryPoint, ResizeHandler {
71 * A constant that denotes the completion of an IncrementalCommand.
73 public static final boolean DONE = false;
75 public static final int VISIBLE_FILE_COUNT = 25;
78 * Instantiate an application-level image bundle. This object will provide
79 * programmatic access to all the images needed by widgets.
81 private static Images images = (Images) GWT.create(Images.class);
83 public String getUsername() {
87 public void setAccount(AccountResource acct) {
91 public AccountResource getAccount() {
96 * An aggregate image bundle that pulls together all the images for this
97 * application into a single bundle.
99 public interface Images extends ClientBundle, TopPanel.Images, StatusPanel.Images, FileMenu.Images, EditMenu.Images, SettingsMenu.Images, FilePropertiesDialog.Images, MessagePanel.Images, FileList.Images, Search.Images, CellTreeView.Images {
101 @Source("gr/grnet/pithos/resources/document.png")
102 ImageResource folders();
104 @Source("gr/grnet/pithos/resources/edit_group_22.png")
105 ImageResource groups();
107 @Source("gr/grnet/pithos/resources/search.png")
108 ImageResource search();
112 * The single GSS instance.
114 private static GSS singleton;
117 * Gets the singleton GSS instance.
119 * @return the GSS object
121 public static GSS get() {
122 if (GSS.singleton == null)
123 GSS.singleton = new GSS();
124 return GSS.singleton;
128 * The Application Clipboard implementation;
130 private Clipboard clipboard = new Clipboard();
132 private UserResource currentUserResource;
135 * The top panel that contains the menu bar.
137 private TopPanel topPanel;
140 * The panel that contains the various system messages.
142 private MessagePanel messagePanel = new MessagePanel(GSS.images);
145 * The bottom panel that contains the status bar.
147 private StatusPanel statusPanel = null;
150 * The top right panel that displays the logged in user details
152 private UserDetailsPanel userDetailsPanel = new UserDetailsPanel();
155 * The file list widget.
157 private FileList fileList;
160 * The tab panel that occupies the right side of the screen.
162 private TabPanel inner = new DecoratedTabPanel(){
164 public void onBrowserEvent(com.google.gwt.user.client.Event event) {
165 if (DOM.eventGetType(event) == Event.ONCONTEXTMENU){
166 if(isFileListShowing()){
167 getFileList().showContextMenu(event);
174 * The split panel that will contain the left and right panels.
176 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
179 * The widget that displays the tree of folders.
182 private CellTreeView treeView = null;
184 * The currently selected item in the application, for use by the Edit menu
185 * commands. Potential types are Folder, File, User and Group.
187 private Object currentSelection;
191 * The WebDAV password of the current user
193 private String webDAVPassword;
195 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
197 private String username = null;
200 * The authentication token of the current user.
202 private String token;
204 private SingleSelectionModel<Folder> folderTreeSelectionModel;
205 private FolderTreeViewModel folderTreeViewModel;
206 private FolderTreeView folderTreeView;
208 private AccountResource account;
211 public void onModuleLoad() {
212 // Initialize the singleton before calling the constructors of the
213 // various widgets that might call GSS.get().
215 if (parseUserCredentials())
219 private void initialize() {
220 topPanel = new TopPanel(GSS.images);
221 topPanel.setWidth("100%");
223 messagePanel.setWidth("100%");
224 messagePanel.setVisible(false);
227 // Inner contains the various lists.
228 inner.sinkEvents(Event.ONCONTEXTMENU);
229 inner.setAnimationEnabled(true);
230 inner.getTabBar().addStyleName("pithos-MainTabBar");
231 inner.getDeckPanel().addStyleName("pithos-MainTabPanelBottom");
233 inner.setWidth("100%");
235 inner.addSelectionHandler(new SelectionHandler<Integer>() {
238 public void onSelection(SelectionEvent<Integer> event) {
239 int tabIndex = event.getSelectedItem();
242 fileList.updateCurrentlyShowingStats();
248 folderTreeSelectionModel = new SingleSelectionModel<Folder>();
249 folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
251 public void onSelectionChange(SelectionChangeEvent event) {
252 Folder f = folderTreeSelectionModel.getSelectedObject();
257 folderTreeViewModel = new FolderTreeViewModel(folderTreeSelectionModel);
258 folderTreeView = new FolderTreeView(folderTreeViewModel);
260 fileList = new FileList(images, folderTreeView);
261 inner.add(fileList, createHeaderHTML(AbstractImagePrototype.create(images.folders()), "Files"), true);
263 // Add the left and right panels to the split panel.
264 splitPanel.setLeftWidget(folderTreeView);
265 splitPanel.setRightWidget(inner);
266 splitPanel.setSplitPosition("25%");
267 splitPanel.setSize("100%", "100%");
268 splitPanel.addStyleName("pithos-splitPanel");
270 // Create a dock panel that will contain the menu bar at the top,
271 // the shortcuts to the left, the status bar at the bottom and the
272 // right panel taking the rest.
273 VerticalPanel outer = new VerticalPanel();
275 outer.add(messagePanel);
276 outer.add(splitPanel);
277 statusPanel = new StatusPanel(GSS.images);
278 outer.add(statusPanel);
279 outer.setWidth("100%");
280 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
284 // Hook the window resize event, so that we can adjust the UI.
285 Window.addResizeHandler(this);
286 // Clear out the window's built-in margin, because we want to take
287 // advantage of the entire client area.
288 Window.setMargin("0px");
289 // Finally, add the outer panel to the RootPanel, so that it will be
291 RootPanel.get().add(outer);
292 // Call the window resized handler to get the initial sizes setup. Doing
293 // this in a deferred command causes it to occur after all widgets'
294 // sizes have been computed by the browser.
295 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
298 public void execute() {
299 onWindowResized(Window.getClientHeight());
303 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
305 public void execute() {
311 private void showFiles(Folder f) {
312 Set<File> files = f.getFiles();
313 fileList.setFiles(new ArrayList<File>(files));
318 * Parse and store the user credentials to the appropriate fields.
320 private boolean parseUserCredentials() {
321 Configuration conf = (Configuration) GWT.create(Configuration.class);
322 String cookie = conf.authCookie();
323 String auth = Cookies.getCookie(cookie);
329 String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
330 if (authSplit.length != 2) {
335 username = authSplit[0];
336 token = authSplit[1];
343 * Redirect the user to the login page for authentication.
345 protected void authenticateUser() {
346 Configuration conf = (Configuration) GWT.create(Configuration.class);
348 // Window.Location.assign(GWT.getModuleBaseURL() + conf.loginUrl() + "?next=" + Window.Location.getHref());
349 Cookies.setCookie(conf.authCookie(), "test" + conf.cookieSeparator() + "0000");
350 Window.Location.assign(GWT.getModuleBaseURL() + "GSS.html");
353 private void fetchAccount() {
354 String path = getApiPath() + username + "?format=json";
356 GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, path) {
358 public void onSuccess(AccountResource result) {
360 statusPanel.displayStats(account);
361 folderTreeViewModel.initialize(account);
366 public void onError(Throwable t) {
367 GWT.log("Error getting account", t);
368 if (t instanceof RestException)
369 GSS.get().displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
371 GSS.get().displayError("System error fetching user data: " + t.getMessage());
374 getAccount.setHeader("X-Auth-Token", token);
375 Scheduler.get().scheduleDeferred(getAccount);
379 * Clear the cookie and redirect the user to the logout page.
382 Configuration conf = (Configuration) GWT.create(Configuration.class);
383 String cookie = conf.authCookie();
384 String domain = Window.Location.getHostName();
385 String path = Window.Location.getPath();
386 Cookies.setCookie(cookie, "", null, domain, path, false);
387 String baseUrl = GWT.getModuleBaseURL();
388 String homeUrl = baseUrl.substring(0, baseUrl.indexOf(path));
389 Window.Location.assign(homeUrl + conf.logoutUrl());
393 * Creates an HTML fragment that places an image & caption together, for use
396 * @param imageProto an image prototype for an image
397 * @param caption the group caption
398 * @return the header HTML fragment
400 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
401 String captionHTML = "<table class='caption' cellpadding='0' "
402 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
403 + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'> "
404 + caption + "</b></td></tr></table>";
408 private void onWindowResized(int height) {
409 // Adjust the split panel to take up the available room in the window.
410 int newHeight = height - splitPanel.getAbsoluteTop() - 44;
413 splitPanel.setHeight("" + newHeight);
414 inner.setHeight("" + newHeight);
418 public void onResize(ResizeEvent event) {
419 int height = event.getHeight();
420 onWindowResized(height);
423 public boolean isFileListShowing() {
424 int tab = inner.getTabBar().getSelectedTab();
430 public boolean isSearchResultsShowing() {
431 int tab = inner.getTabBar().getSelectedTab();
438 * Make the file list visible.
442 public void showFileList(boolean update) {
444 getTreeView().refreshCurrentNode(true);
447 RestResource currentFolder = getTreeView().getSelection();
448 if(currentFolder!=null){
449 showFileList(currentFolder);
455 public void showFileList(RestResource r) {
456 showFileList(r,true);
459 public void showFileList(RestResource r, boolean clearSelection) {
460 RestResource currentFolder = r;
461 if(currentFolder!=null){
462 List<FileResource> files = null;
463 if (currentFolder instanceof RestResourceWrapper) {
464 RestResourceWrapper folder = (RestResourceWrapper) currentFolder;
465 files = folder.getResource().getFiles();
472 * Display the 'loading' indicator.
474 public void showLoadingIndicator(String message, String path) {
476 String[] split = path.split("/");
477 message = message +" "+URL.decode(split[split.length-1]);
479 topPanel.getLoading().show(message);
483 * Hide the 'loading' indicator.
485 public void hideLoadingIndicator() {
486 topPanel.getLoading().hide();
490 * A native JavaScript method to reach out to the browser's window and
491 * invoke its resizeTo() method.
493 * @param x the new width
494 * @param y the new height
496 public static native void resizeTo(int x, int y) /*-{
501 * A helper method that returns true if the user's list is currently visible
502 * and false if it is hidden.
504 * @return true if the user list is visible
506 public boolean isUserListVisible() {
507 return inner.getTabBar().getSelectedTab() == 1;
511 * Display an error message.
513 * @param msg the message to display
515 public void displayError(String msg) {
516 messagePanel.displayError(msg);
520 * Display a warning message.
522 * @param msg the message to display
524 public void displayWarning(String msg) {
525 messagePanel.displayWarning(msg);
529 * Display an informational message.
531 * @param msg the message to display
533 public void displayInformation(String msg) {
534 messagePanel.displayInformation(msg);
538 * Retrieve the folders.
540 * @return the folders
542 public Folders getFolders() {
547 * Retrieve the currentSelection.
549 * @return the currentSelection
551 public Object getCurrentSelection() {
552 return currentSelection;
556 * Modify the currentSelection.
558 * @param newCurrentSelection the currentSelection to set
560 public void setCurrentSelection(Object newCurrentSelection) {
561 currentSelection = newCurrentSelection;
565 * Retrieve the fileList.
567 * @return the fileList
569 public FileList getFileList() {
574 * Retrieve the topPanel.
576 * @return the topPanel
578 TopPanel getTopPanel() {
583 * Retrieve the clipboard.
585 * @return the clipboard
587 public Clipboard getClipboard() {
591 public StatusPanel getStatusPanel() {
596 * Retrieve the userDetailsPanel.
598 * @return the userDetailsPanel
600 public UserDetailsPanel getUserDetailsPanel() {
601 return userDetailsPanel;
606 public String getToken() {
610 public String getWebDAVPassword() {
611 return webDAVPassword;
615 * Retrieve the currentUserResource.
617 * @return the currentUserResource
619 public UserResource getCurrentUserResource() {
620 return currentUserResource;
624 * Modify the currentUserResource.
626 * @param newUser the new currentUserResource
628 public void setCurrentUserResource(UserResource newUser) {
629 currentUserResource = newUser;
632 public static native void preventIESelection() /*-{
633 $doc.body.onselectstart = function () { return false; };
636 public static native void enableIESelection() /*-{
637 if ($doc.body.onselectstart != null)
638 $doc.body.onselectstart = null;
642 * @return the absolute path of the API root URL
644 public String getApiPath() {
645 Configuration conf = (Configuration) GWT.create(Configuration.class);
646 return conf.apiPath();
650 * Convert server date to local time according to browser timezone
651 * and format it according to localized pattern.
652 * Time is always formatted to 24hr format.
653 * NB: This assumes that server runs in UTC timezone. Otherwise
654 * we would need to adjust for server time offset as well.
659 public static String formatLocalDateTime(Date date) {
660 Date convertedDate = new Date(date.getTime() - date.getTimezoneOffset());
661 final DateTimeFormat dateFormatter = DateTimeFormat.getShortDateFormat();
662 final DateTimeFormat timeFormatter = DateTimeFormat.getFormat("HH:mm");
663 String datePart = dateFormatter.format(convertedDate);
664 String timePart = timeFormatter.format(convertedDate);
665 return datePart + " " + timePart;
669 * History support for folder navigation
670 * adds a new browser history entry
674 public void updateHistory(String key){
675 // Replace any whitespace of the initial string to "+"
676 // String result = key.replaceAll("\\s","+");
677 // Add a new browser history entry.
678 // History.newItem(result);
679 History.newItem(key);
683 * This method examines the token input and add a "/" at the end in case it's omitted.
684 * This happens only in Files/trash/, Files/shared/, Files/others.
687 * @return the formated token with a "/" at the end or the same tokenInput parameter
690 private String handleSpecialFolderNames(String tokenInput){
691 List<String> pathsToCheck = Arrays.asList("Files/trash", "Files/shared", "Files/others");
692 if(pathsToCheck.contains(tokenInput))
693 return tokenInput + "/";
699 * Reject illegal resource names, like '.' or '..' or slashes '/'.
701 static boolean isValidResourceName(String name) {
702 if (".".equals(name) || "..".equals(name) || name.contains("/"))
707 public void putUserToMap(String _userName, String _userFullName){
708 userFullNameMap.put(_userName, _userFullName);
711 public String findUserFullName(String _userName){
712 return userFullNameMap.get(_userName);
714 public String getUserFullName(String _userName) {
716 if (GSS.get().findUserFullName(_userName) == null)
717 //if there is no userFullName found then the map fills with the given _userName,
718 //so userFullName = _userName
719 GSS.get().putUserToMap(_userName, _userName);
720 else if(GSS.get().findUserFullName(_userName).indexOf('@') != -1){
721 //if the userFullName = _userName the GetUserCommand updates the userFullName in the map
722 GetUserCommand guc = new GetUserCommand(_userName);
725 return GSS.get().findUserFullName(_userName);
728 * Retrieve the treeView.
730 * @return the treeView
732 public CellTreeView getTreeView() {
736 public void onResourceUpdate(RestResource resource,boolean clearSelection){
737 if(resource instanceof RestResourceWrapper || resource instanceof OtherUserResource || resource instanceof TrashResource || resource instanceof SharedResource){
738 if(getTreeView().getSelection()!=null&&getTreeView().getSelection().getUri().equals(resource.getUri()))
739 showFileList(resource,clearSelection);