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.view.client.SelectionChangeEvent;
9 import com.google.gwt.view.client.SingleSelectionModel;
10 import gr.grnet.pithos.web.client.clipboard.Clipboard;
11 import gr.grnet.pithos.web.client.commands.GetUserCommand;
12 import gr.grnet.pithos.web.client.foldertree.AccountResource;
13 import gr.grnet.pithos.web.client.foldertree.File;
14 import gr.grnet.pithos.web.client.foldertree.Folder;
15 import gr.grnet.pithos.web.client.foldertree.FolderTreeView;
16 import gr.grnet.pithos.web.client.foldertree.FolderTreeViewModel;
17 import gr.grnet.pithos.web.client.rest.GetRequest;
18 import gr.grnet.pithos.web.client.rest.RestException;
19 import gr.grnet.pithos.web.client.rest.resource.FileResource;
20 import gr.grnet.pithos.web.client.rest.resource.OtherUserResource;
21 import gr.grnet.pithos.web.client.rest.resource.RestResource;
22 import gr.grnet.pithos.web.client.rest.resource.RestResourceWrapper;
23 import gr.grnet.pithos.web.client.rest.resource.SharedResource;
24 import gr.grnet.pithos.web.client.rest.resource.TrashResource;
25 import gr.grnet.pithos.web.client.rest.resource.UserResource;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.Date;
30 import java.util.HashMap;
31 import java.util.Iterator;
32 import java.util.List;
34 import com.google.gwt.core.client.EntryPoint;
35 import com.google.gwt.core.client.GWT;
36 import com.google.gwt.event.logical.shared.ResizeEvent;
37 import com.google.gwt.event.logical.shared.ResizeHandler;
38 import com.google.gwt.event.logical.shared.SelectionEvent;
39 import com.google.gwt.event.logical.shared.SelectionHandler;
40 import com.google.gwt.http.client.URL;
41 import com.google.gwt.i18n.client.DateTimeFormat;
42 import com.google.gwt.resources.client.ClientBundle;
43 import com.google.gwt.resources.client.ImageResource;
44 import com.google.gwt.user.client.Cookies;
45 import com.google.gwt.user.client.DOM;
46 import com.google.gwt.user.client.Event;
47 import com.google.gwt.user.client.History;
48 import com.google.gwt.user.client.Window;
49 import com.google.gwt.user.client.ui.AbstractImagePrototype;
50 import com.google.gwt.user.client.ui.DecoratedTabPanel;
51 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
52 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
53 import com.google.gwt.user.client.ui.RootPanel;
54 import com.google.gwt.user.client.ui.TabPanel;
55 import com.google.gwt.user.client.ui.VerticalPanel;
59 * Entry point classes define <code>onModuleLoad()</code>.
61 public class GSS implements EntryPoint, ResizeHandler {
64 * A constant that denotes the completion of an IncrementalCommand.
66 public static final boolean DONE = false;
68 public static final int VISIBLE_FILE_COUNT = 25;
71 * Instantiate an application-level image bundle. This object will provide
72 * programmatic access to all the images needed by widgets.
74 private static Images images = (Images) GWT.create(Images.class);
76 public String getUsername() {
80 public void setAccount(AccountResource acct) {
84 public AccountResource getAccount() {
89 * An aggregate image bundle that pulls together all the images for this
90 * application into a single bundle.
92 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 {
94 @Source("gr/grnet/pithos/resources/document.png")
95 ImageResource folders();
97 @Source("gr/grnet/pithos/resources/edit_group_22.png")
98 ImageResource groups();
100 @Source("gr/grnet/pithos/resources/search.png")
101 ImageResource search();
105 * The single GSS instance.
107 private static GSS singleton;
110 * Gets the singleton GSS instance.
112 * @return the GSS object
114 public static GSS get() {
115 if (GSS.singleton == null)
116 GSS.singleton = new GSS();
117 return GSS.singleton;
121 * The Application Clipboard implementation;
123 private Clipboard clipboard = new Clipboard();
125 private UserResource currentUserResource;
128 * The top panel that contains the menu bar.
130 private TopPanel topPanel;
133 * The panel that contains the various system messages.
135 private MessagePanel messagePanel = new MessagePanel(GSS.images);
138 * The bottom panel that contains the status bar.
140 private StatusPanel statusPanel = null;
143 * The top right panel that displays the logged in user details
145 private UserDetailsPanel userDetailsPanel = new UserDetailsPanel();
148 * The file list widget.
150 private FileList fileList;
153 * The tab panel that occupies the right side of the screen.
155 private TabPanel inner = new DecoratedTabPanel(){
157 public void onBrowserEvent(com.google.gwt.user.client.Event event) {
158 if (DOM.eventGetType(event) == Event.ONCONTEXTMENU){
159 if(isFileListShowing()){
160 getFileList().showContextMenu(event);
167 * The split panel that will contain the left and right panels.
169 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
172 * The widget that displays the tree of folders.
175 private CellTreeView treeView = null;
177 * The currently selected item in the application, for use by the Edit menu
178 * commands. Potential types are Folder, File, User and Group.
180 private Object currentSelection;
184 * The WebDAV password of the current user
186 private String webDAVPassword;
188 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
190 private String username = null;
193 * The authentication token of the current user.
195 private String token;
197 private SingleSelectionModel<Folder> folderTreeSelectionModel;
198 private FolderTreeViewModel folderTreeViewModel;
199 private FolderTreeView folderTreeView;
201 private AccountResource account;
204 public void onModuleLoad() {
205 // Initialize the singleton before calling the constructors of the
206 // various widgets that might call GSS.get().
208 if (parseUserCredentials())
212 private void initialize() {
213 topPanel = new TopPanel(GSS.images);
214 topPanel.setWidth("100%");
216 messagePanel.setWidth("100%");
217 messagePanel.setVisible(false);
220 // Inner contains the various lists.
221 inner.sinkEvents(Event.ONCONTEXTMENU);
222 inner.setAnimationEnabled(true);
223 inner.getTabBar().addStyleName("pithos-MainTabBar");
224 inner.getDeckPanel().addStyleName("pithos-MainTabPanelBottom");
226 inner.setWidth("100%");
228 inner.addSelectionHandler(new SelectionHandler<Integer>() {
231 public void onSelection(SelectionEvent<Integer> event) {
232 int tabIndex = event.getSelectedItem();
235 fileList.updateCurrentlyShowingStats();
241 folderTreeSelectionModel = new SingleSelectionModel<Folder>();
242 folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
244 public void onSelectionChange(SelectionChangeEvent event) {
245 Folder f = folderTreeSelectionModel.getSelectedObject();
250 folderTreeViewModel = new FolderTreeViewModel(folderTreeSelectionModel);
251 folderTreeView = new FolderTreeView(folderTreeViewModel);
253 fileList = new FileList(images, folderTreeView);
254 inner.add(fileList, createHeaderHTML(AbstractImagePrototype.create(images.folders()), "Files"), true);
256 // Add the left and right panels to the split panel.
257 splitPanel.setLeftWidget(folderTreeView);
258 splitPanel.setRightWidget(inner);
259 splitPanel.setSplitPosition("25%");
260 splitPanel.setSize("100%", "100%");
261 splitPanel.addStyleName("pithos-splitPanel");
263 // Create a dock panel that will contain the menu bar at the top,
264 // the shortcuts to the left, the status bar at the bottom and the
265 // right panel taking the rest.
266 VerticalPanel outer = new VerticalPanel();
268 outer.add(messagePanel);
269 outer.add(splitPanel);
270 statusPanel = new StatusPanel(GSS.images);
271 outer.add(statusPanel);
272 outer.setWidth("100%");
273 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
277 // Hook the window resize event, so that we can adjust the UI.
278 Window.addResizeHandler(this);
279 // Clear out the window's built-in margin, because we want to take
280 // advantage of the entire client area.
281 Window.setMargin("0px");
282 // Finally, add the outer panel to the RootPanel, so that it will be
284 RootPanel.get().add(outer);
285 // Call the window resized handler to get the initial sizes setup. Doing
286 // this in a deferred command causes it to occur after all widgets'
287 // sizes have been computed by the browser.
288 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
291 public void execute() {
292 onWindowResized(Window.getClientHeight());
296 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
298 public void execute() {
304 private void showFiles(Folder f) {
306 Set<File> files = f.getFiles();
307 Iterator<File> iter = files.iterator();
308 fetchFile(iter, files);
311 private void fetchFile(final Iterator<File> iter, final Set<File> files) {
312 if (iter.hasNext()) {
313 File file = iter.next();
314 String path = getApiPath() + username + "/" + file.getContainer() + "/" + file.getPath() + "?format=json";
315 GetRequest<File> getFile = new GetRequest<File>(File.class, path, file) {
317 public void onSuccess(File result) {
318 fetchFile(iter, files);
322 public void onError(Throwable t) {
323 GWT.log("Error getting file", t);
324 if (t instanceof RestException)
325 GSS.get().displayError("Error getting file: " + ((RestException) t).getHttpStatusText());
327 GSS.get().displayError("System error fetching file: " + t.getMessage());
330 getFile.setHeader("X-Auth-Token", "0000");
331 Scheduler.get().scheduleDeferred(getFile);
334 fileList.setFiles(new ArrayList<File>(files));
338 * Parse and store the user credentials to the appropriate fields.
340 private boolean parseUserCredentials() {
341 Configuration conf = (Configuration) GWT.create(Configuration.class);
342 String cookie = conf.authCookie();
343 String auth = Cookies.getCookie(cookie);
349 String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
350 if (authSplit.length != 2) {
355 username = authSplit[0];
356 token = authSplit[1];
363 * Redirect the user to the login page for authentication.
365 protected void authenticateUser() {
366 Configuration conf = (Configuration) GWT.create(Configuration.class);
368 // Window.Location.assign(GWT.getModuleBaseURL() + conf.loginUrl() + "?next=" + Window.Location.getHref());
369 Cookies.setCookie(conf.authCookie(), "test" + conf.cookieSeparator() + "0000");
370 Window.Location.assign(GWT.getModuleBaseURL() + "GSS.html");
373 private void fetchAccount() {
374 String path = getApiPath() + username + "?format=json";
376 GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, path) {
378 public void onSuccess(AccountResource result) {
380 statusPanel.displayStats(account);
381 folderTreeViewModel.initialize(account);
386 public void onError(Throwable t) {
387 GWT.log("Error getting account", t);
388 if (t instanceof RestException)
389 GSS.get().displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
391 GSS.get().displayError("System error fetching user data: " + t.getMessage());
394 getAccount.setHeader("X-Auth-Token", token);
395 Scheduler.get().scheduleDeferred(getAccount);
399 * Clear the cookie and redirect the user to the logout page.
402 Configuration conf = (Configuration) GWT.create(Configuration.class);
403 String cookie = conf.authCookie();
404 String domain = Window.Location.getHostName();
405 String path = Window.Location.getPath();
406 Cookies.setCookie(cookie, "", null, domain, path, false);
407 String baseUrl = GWT.getModuleBaseURL();
408 String homeUrl = baseUrl.substring(0, baseUrl.indexOf(path));
409 Window.Location.assign(homeUrl + conf.logoutUrl());
413 * Creates an HTML fragment that places an image & caption together, for use
416 * @param imageProto an image prototype for an image
417 * @param caption the group caption
418 * @return the header HTML fragment
420 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
421 String captionHTML = "<table class='caption' cellpadding='0' "
422 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
423 + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'> "
424 + caption + "</b></td></tr></table>";
428 private void onWindowResized(int height) {
429 // Adjust the split panel to take up the available room in the window.
430 int newHeight = height - splitPanel.getAbsoluteTop() - 44;
433 splitPanel.setHeight("" + newHeight);
434 inner.setHeight("" + newHeight);
438 public void onResize(ResizeEvent event) {
439 int height = event.getHeight();
440 onWindowResized(height);
443 public boolean isFileListShowing() {
444 int tab = inner.getTabBar().getSelectedTab();
450 public boolean isSearchResultsShowing() {
451 int tab = inner.getTabBar().getSelectedTab();
458 * Make the file list visible.
462 public void showFileList(boolean update) {
464 getTreeView().refreshCurrentNode(true);
467 RestResource currentFolder = getTreeView().getSelection();
468 if(currentFolder!=null){
469 showFileList(currentFolder);
475 public void showFileList(RestResource r) {
476 showFileList(r,true);
479 public void showFileList(RestResource r, boolean clearSelection) {
480 RestResource currentFolder = r;
481 if(currentFolder!=null){
482 List<FileResource> files = null;
483 if (currentFolder instanceof RestResourceWrapper) {
484 RestResourceWrapper folder = (RestResourceWrapper) currentFolder;
485 files = folder.getResource().getFiles();
492 * Display the 'loading' indicator.
494 public void showLoadingIndicator(String message, String path) {
496 String[] split = path.split("/");
497 message = message +" "+URL.decode(split[split.length-1]);
499 topPanel.getLoading().show(message);
503 * Hide the 'loading' indicator.
505 public void hideLoadingIndicator() {
506 topPanel.getLoading().hide();
510 * A native JavaScript method to reach out to the browser's window and
511 * invoke its resizeTo() method.
513 * @param x the new width
514 * @param y the new height
516 public static native void resizeTo(int x, int y) /*-{
521 * A helper method that returns true if the user's list is currently visible
522 * and false if it is hidden.
524 * @return true if the user list is visible
526 public boolean isUserListVisible() {
527 return inner.getTabBar().getSelectedTab() == 1;
531 * Display an error message.
533 * @param msg the message to display
535 public void displayError(String msg) {
536 messagePanel.displayError(msg);
540 * Display a warning message.
542 * @param msg the message to display
544 public void displayWarning(String msg) {
545 messagePanel.displayWarning(msg);
549 * Display an informational message.
551 * @param msg the message to display
553 public void displayInformation(String msg) {
554 messagePanel.displayInformation(msg);
558 * Retrieve the folders.
560 * @return the folders
562 public Folders getFolders() {
567 * Retrieve the currentSelection.
569 * @return the currentSelection
571 public Object getCurrentSelection() {
572 return currentSelection;
576 * Modify the currentSelection.
578 * @param newCurrentSelection the currentSelection to set
580 public void setCurrentSelection(Object newCurrentSelection) {
581 currentSelection = newCurrentSelection;
585 * Retrieve the fileList.
587 * @return the fileList
589 public FileList getFileList() {
594 * Retrieve the topPanel.
596 * @return the topPanel
598 TopPanel getTopPanel() {
603 * Retrieve the clipboard.
605 * @return the clipboard
607 public Clipboard getClipboard() {
611 public StatusPanel getStatusPanel() {
616 * Retrieve the userDetailsPanel.
618 * @return the userDetailsPanel
620 public UserDetailsPanel getUserDetailsPanel() {
621 return userDetailsPanel;
626 public String getToken() {
630 public String getWebDAVPassword() {
631 return webDAVPassword;
635 * Retrieve the currentUserResource.
637 * @return the currentUserResource
639 public UserResource getCurrentUserResource() {
640 return currentUserResource;
644 * Modify the currentUserResource.
646 * @param newUser the new currentUserResource
648 public void setCurrentUserResource(UserResource newUser) {
649 currentUserResource = newUser;
652 public static native void preventIESelection() /*-{
653 $doc.body.onselectstart = function () { return false; };
656 public static native void enableIESelection() /*-{
657 if ($doc.body.onselectstart != null)
658 $doc.body.onselectstart = null;
662 * @return the absolute path of the API root URL
664 public String getApiPath() {
665 Configuration conf = (Configuration) GWT.create(Configuration.class);
666 return conf.apiPath();
670 * Convert server date to local time according to browser timezone
671 * and format it according to localized pattern.
672 * Time is always formatted to 24hr format.
673 * NB: This assumes that server runs in UTC timezone. Otherwise
674 * we would need to adjust for server time offset as well.
679 public static String formatLocalDateTime(Date date) {
680 Date convertedDate = new Date(date.getTime() - date.getTimezoneOffset());
681 final DateTimeFormat dateFormatter = DateTimeFormat.getShortDateFormat();
682 final DateTimeFormat timeFormatter = DateTimeFormat.getFormat("HH:mm");
683 String datePart = dateFormatter.format(convertedDate);
684 String timePart = timeFormatter.format(convertedDate);
685 return datePart + " " + timePart;
689 * History support for folder navigation
690 * adds a new browser history entry
694 public void updateHistory(String key){
695 // Replace any whitespace of the initial string to "+"
696 // String result = key.replaceAll("\\s","+");
697 // Add a new browser history entry.
698 // History.newItem(result);
699 History.newItem(key);
703 * This method examines the token input and add a "/" at the end in case it's omitted.
704 * This happens only in Files/trash/, Files/shared/, Files/others.
707 * @return the formated token with a "/" at the end or the same tokenInput parameter
710 private String handleSpecialFolderNames(String tokenInput){
711 List<String> pathsToCheck = Arrays.asList("Files/trash", "Files/shared", "Files/others");
712 if(pathsToCheck.contains(tokenInput))
713 return tokenInput + "/";
719 * Reject illegal resource names, like '.' or '..' or slashes '/'.
721 static boolean isValidResourceName(String name) {
722 if (".".equals(name) || "..".equals(name) || name.contains("/"))
727 public void putUserToMap(String _userName, String _userFullName){
728 userFullNameMap.put(_userName, _userFullName);
731 public String findUserFullName(String _userName){
732 return userFullNameMap.get(_userName);
734 public String getUserFullName(String _userName) {
736 if (GSS.get().findUserFullName(_userName) == null)
737 //if there is no userFullName found then the map fills with the given _userName,
738 //so userFullName = _userName
739 GSS.get().putUserToMap(_userName, _userName);
740 else if(GSS.get().findUserFullName(_userName).indexOf('@') != -1){
741 //if the userFullName = _userName the GetUserCommand updates the userFullName in the map
742 GetUserCommand guc = new GetUserCommand(_userName);
745 return GSS.get().findUserFullName(_userName);
748 * Retrieve the treeView.
750 * @return the treeView
752 public CellTreeView getTreeView() {
756 public void onResourceUpdate(RestResource resource,boolean clearSelection){
757 if(resource instanceof RestResourceWrapper || resource instanceof OtherUserResource || resource instanceof TrashResource || resource instanceof SharedResource){
758 if(getTreeView().getSelection()!=null&&getTreeView().getSelection().getUri().equals(resource.getUri()))
759 showFileList(resource,clearSelection);