2 * Copyright 2011 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.Scheduler;
38 import com.google.gwt.core.client.Scheduler.ScheduledCommand;
39 import com.google.gwt.event.dom.client.ContextMenuEvent;
40 import com.google.gwt.event.dom.client.ContextMenuHandler;
41 import com.google.gwt.event.shared.GwtEvent;
42 import com.google.gwt.event.shared.GwtEvent.Type;
43 import com.google.gwt.view.client.SelectionChangeEvent;
44 import com.google.gwt.view.client.SingleSelectionModel;
45 import gr.grnet.pithos.web.client.clipboard.Clipboard;
46 import gr.grnet.pithos.web.client.commands.GetUserCommand;
47 import gr.grnet.pithos.web.client.foldertree.AccountResource;
48 import gr.grnet.pithos.web.client.foldertree.File;
49 import gr.grnet.pithos.web.client.foldertree.Folder;
50 import gr.grnet.pithos.web.client.foldertree.FolderTreeView;
51 import gr.grnet.pithos.web.client.foldertree.FolderTreeViewModel;
52 import gr.grnet.pithos.web.client.rest.GetRequest;
53 import gr.grnet.pithos.web.client.rest.RestException;
54 import gr.grnet.pithos.web.client.rest.resource.FileResource;
55 import gr.grnet.pithos.web.client.rest.resource.OtherUserResource;
56 import gr.grnet.pithos.web.client.rest.resource.RestResource;
57 import gr.grnet.pithos.web.client.rest.resource.RestResourceWrapper;
58 import gr.grnet.pithos.web.client.rest.resource.SharedResource;
59 import gr.grnet.pithos.web.client.rest.resource.TrashResource;
60 import gr.grnet.pithos.web.client.rest.resource.UserResource;
62 import java.util.ArrayList;
63 import java.util.Arrays;
64 import java.util.Date;
65 import java.util.HashMap;
66 import java.util.Iterator;
67 import java.util.List;
69 import com.google.gwt.core.client.EntryPoint;
70 import com.google.gwt.core.client.GWT;
71 import com.google.gwt.event.logical.shared.ResizeEvent;
72 import com.google.gwt.event.logical.shared.ResizeHandler;
73 import com.google.gwt.event.logical.shared.SelectionEvent;
74 import com.google.gwt.event.logical.shared.SelectionHandler;
75 import com.google.gwt.http.client.URL;
76 import com.google.gwt.i18n.client.DateTimeFormat;
77 import com.google.gwt.resources.client.ClientBundle;
78 import com.google.gwt.resources.client.ImageResource;
79 import com.google.gwt.user.client.Cookies;
80 import com.google.gwt.user.client.DOM;
81 import com.google.gwt.user.client.Event;
82 import com.google.gwt.user.client.History;
83 import com.google.gwt.user.client.Window;
84 import com.google.gwt.user.client.ui.AbstractImagePrototype;
85 import com.google.gwt.user.client.ui.DecoratedTabPanel;
86 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
87 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
88 import com.google.gwt.user.client.ui.RootPanel;
89 import com.google.gwt.user.client.ui.TabPanel;
90 import com.google.gwt.user.client.ui.VerticalPanel;
94 * Entry point classes define <code>onModuleLoad()</code>.
96 public class GSS implements EntryPoint, ResizeHandler {
99 * A constant that denotes the completion of an IncrementalCommand.
101 public static final boolean DONE = false;
103 public static final int VISIBLE_FILE_COUNT = 25;
106 * Instantiate an application-level image bundle. This object will provide
107 * programmatic access to all the images needed by widgets.
109 private static Images images = (Images) GWT.create(Images.class);
111 public String getUsername() {
115 public void setAccount(AccountResource acct) {
119 public AccountResource getAccount() {
124 * An aggregate image bundle that pulls together all the images for this
125 * application into a single bundle.
127 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 {
129 @Source("gr/grnet/pithos/resources/document.png")
130 ImageResource folders();
132 @Source("gr/grnet/pithos/resources/edit_group_22.png")
133 ImageResource groups();
135 @Source("gr/grnet/pithos/resources/search.png")
136 ImageResource search();
140 * The single GSS instance.
142 private static GSS singleton;
145 * Gets the singleton GSS instance.
147 * @return the GSS object
149 public static GSS get() {
150 if (GSS.singleton == null)
151 GSS.singleton = new GSS();
152 return GSS.singleton;
156 * The Application Clipboard implementation;
158 private Clipboard clipboard = new Clipboard();
160 private UserResource currentUserResource;
163 * The top panel that contains the menu bar.
165 private TopPanel topPanel;
168 * The panel that contains the various system messages.
170 private MessagePanel messagePanel = new MessagePanel(GSS.images);
173 * The bottom panel that contains the status bar.
175 private StatusPanel statusPanel = null;
178 * The top right panel that displays the logged in user details
180 private UserDetailsPanel userDetailsPanel = new UserDetailsPanel();
183 * The file list widget.
185 private FileList fileList;
188 * The tab panel that occupies the right side of the screen.
190 private TabPanel inner = new DecoratedTabPanel(){
192 // public void onBrowserEvent(com.google.gwt.user.client.Event event) {
193 // if (DOM.eventGetType(event) == Event.ONCONTEXTMENU){
194 // if(isFileListShowing()){
195 // getFileList().showContextMenu(event);
203 * The split panel that will contain the left and right panels.
205 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
208 * The widget that displays the tree of folders.
211 private CellTreeView treeView = null;
213 * The currently selected item in the application, for use by the Edit menu
214 * commands. Potential types are Folder, File, User and Group.
216 private Object currentSelection;
220 * The WebDAV password of the current user
222 private String webDAVPassword;
224 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
226 private String username = null;
229 * The authentication token of the current user.
231 private String token;
233 private SingleSelectionModel<Folder> folderTreeSelectionModel;
234 private FolderTreeViewModel folderTreeViewModel;
235 private FolderTreeView folderTreeView;
237 private AccountResource account;
240 public void onModuleLoad() {
241 // Initialize the singleton before calling the constructors of the
242 // various widgets that might call GSS.get().
244 if (parseUserCredentials())
248 private void initialize() {
249 topPanel = new TopPanel(GSS.images);
250 topPanel.setWidth("100%");
252 messagePanel.setWidth("100%");
253 messagePanel.setVisible(false);
256 // Inner contains the various lists.
257 inner.sinkEvents(Event.ONCONTEXTMENU);
258 inner.setAnimationEnabled(true);
259 inner.getTabBar().addStyleName("pithos-MainTabBar");
260 inner.getDeckPanel().addStyleName("pithos-MainTabPanelBottom");
262 inner.setWidth("100%");
264 inner.addSelectionHandler(new SelectionHandler<Integer>() {
267 public void onSelection(SelectionEvent<Integer> event) {
268 int tabIndex = event.getSelectedItem();
271 fileList.updateCurrentlyShowingStats();
277 folderTreeSelectionModel = new SingleSelectionModel<Folder>();
278 folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
280 public void onSelectionChange(SelectionChangeEvent event) {
281 Folder f = folderTreeSelectionModel.getSelectedObject();
286 folderTreeViewModel = new FolderTreeViewModel(folderTreeSelectionModel);
287 folderTreeView = new FolderTreeView(folderTreeViewModel);
289 fileList = new FileList(images, folderTreeView);
290 inner.add(fileList, createHeaderHTML(AbstractImagePrototype.create(images.folders()), "Files"), true);
292 // Add the left and right panels to the split panel.
293 splitPanel.setLeftWidget(folderTreeView);
294 splitPanel.setRightWidget(inner);
295 splitPanel.setSplitPosition("25%");
296 splitPanel.setSize("100%", "100%");
297 splitPanel.addStyleName("pithos-splitPanel");
299 // Create a dock panel that will contain the menu bar at the top,
300 // the shortcuts to the left, the status bar at the bottom and the
301 // right panel taking the rest.
302 VerticalPanel outer = new VerticalPanel();
304 outer.add(messagePanel);
305 outer.add(splitPanel);
306 statusPanel = new StatusPanel(GSS.images);
307 outer.add(statusPanel);
308 outer.setWidth("100%");
309 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
313 // Hook the window resize event, so that we can adjust the UI.
314 Window.addResizeHandler(this);
315 // Clear out the window's built-in margin, because we want to take
316 // advantage of the entire client area.
317 Window.setMargin("0px");
318 // Finally, add the outer panel to the RootPanel, so that it will be
320 RootPanel.get().add(outer);
321 // Call the window resized handler to get the initial sizes setup. Doing
322 // this in a deferred command causes it to occur after all widgets'
323 // sizes have been computed by the browser.
324 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
327 public void execute() {
328 onWindowResized(Window.getClientHeight());
332 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
334 public void execute() {
340 private void showFiles(Folder f) {
342 Set<File> files = f.getFiles();
343 Iterator<File> iter = files.iterator();
344 fetchFile(iter, files);
347 private void fetchFile(final Iterator<File> iter, final Set<File> files) {
348 if (iter.hasNext()) {
349 File file = iter.next();
350 String path = getApiPath() + username + "/" + file.getContainer() + "/" + file.getPath() + "?format=json";
351 GetRequest<File> getFile = new GetRequest<File>(File.class, path, file) {
353 public void onSuccess(File result) {
354 fetchFile(iter, files);
358 public void onError(Throwable t) {
359 GWT.log("Error getting file", t);
360 if (t instanceof RestException)
361 GSS.get().displayError("Error getting file: " + ((RestException) t).getHttpStatusText());
363 GSS.get().displayError("System error fetching file: " + t.getMessage());
366 getFile.setHeader("X-Auth-Token", "0000");
367 Scheduler.get().scheduleDeferred(getFile);
370 fileList.setFiles(new ArrayList<File>(files));
374 * Parse and store the user credentials to the appropriate fields.
376 private boolean parseUserCredentials() {
377 Configuration conf = (Configuration) GWT.create(Configuration.class);
378 String cookie = conf.authCookie();
379 String auth = Cookies.getCookie(cookie);
385 String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
386 if (authSplit.length != 2) {
391 username = authSplit[0];
392 token = authSplit[1];
399 * Redirect the user to the login page for authentication.
401 protected void authenticateUser() {
402 Configuration conf = (Configuration) GWT.create(Configuration.class);
404 // Window.Location.assign(GWT.getModuleBaseURL() + conf.loginUrl() + "?next=" + Window.Location.getHref());
405 Cookies.setCookie(conf.authCookie(), "test" + conf.cookieSeparator() + "0000");
406 Window.Location.assign(GWT.getModuleBaseURL() + "GSS.html");
409 private void fetchAccount() {
410 String path = getApiPath() + username + "?format=json";
412 GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, path) {
414 public void onSuccess(AccountResource result) {
416 statusPanel.displayStats(account);
417 folderTreeViewModel.initialize(account);
422 public void onError(Throwable t) {
423 GWT.log("Error getting account", t);
424 if (t instanceof RestException)
425 GSS.get().displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
427 GSS.get().displayError("System error fetching user data: " + t.getMessage());
430 getAccount.setHeader("X-Auth-Token", token);
431 Scheduler.get().scheduleDeferred(getAccount);
435 * Clear the cookie and redirect the user to the logout page.
438 Configuration conf = (Configuration) GWT.create(Configuration.class);
439 String cookie = conf.authCookie();
440 String domain = Window.Location.getHostName();
441 String path = Window.Location.getPath();
442 Cookies.setCookie(cookie, "", null, domain, path, false);
443 String baseUrl = GWT.getModuleBaseURL();
444 String homeUrl = baseUrl.substring(0, baseUrl.indexOf(path));
445 Window.Location.assign(homeUrl + conf.logoutUrl());
449 * Creates an HTML fragment that places an image & caption together, for use
452 * @param imageProto an image prototype for an image
453 * @param caption the group caption
454 * @return the header HTML fragment
456 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
457 String captionHTML = "<table class='caption' cellpadding='0' "
458 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
459 + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'> "
460 + caption + "</b></td></tr></table>";
464 private void onWindowResized(int height) {
465 // Adjust the split panel to take up the available room in the window.
466 int newHeight = height - splitPanel.getAbsoluteTop() - 44;
469 splitPanel.setHeight("" + newHeight);
470 inner.setHeight("" + newHeight);
474 public void onResize(ResizeEvent event) {
475 int height = event.getHeight();
476 onWindowResized(height);
479 public boolean isFileListShowing() {
480 int tab = inner.getTabBar().getSelectedTab();
486 public boolean isSearchResultsShowing() {
487 int tab = inner.getTabBar().getSelectedTab();
494 * Make the file list visible.
498 public void showFileList(boolean update) {
500 getTreeView().refreshCurrentNode(true);
503 RestResource currentFolder = getTreeView().getSelection();
504 if(currentFolder!=null){
505 showFileList(currentFolder);
511 public void showFileList(RestResource r) {
512 showFileList(r,true);
515 public void showFileList(RestResource r, boolean clearSelection) {
516 RestResource currentFolder = r;
517 if(currentFolder!=null){
518 List<FileResource> files = null;
519 if (currentFolder instanceof RestResourceWrapper) {
520 RestResourceWrapper folder = (RestResourceWrapper) currentFolder;
521 files = folder.getResource().getFiles();
528 * Display the 'loading' indicator.
530 public void showLoadingIndicator(String message, String path) {
532 String[] split = path.split("/");
533 message = message +" "+URL.decode(split[split.length-1]);
535 topPanel.getLoading().show(message);
539 * Hide the 'loading' indicator.
541 public void hideLoadingIndicator() {
542 topPanel.getLoading().hide();
546 * A native JavaScript method to reach out to the browser's window and
547 * invoke its resizeTo() method.
549 * @param x the new width
550 * @param y the new height
552 public static native void resizeTo(int x, int y) /*-{
557 * A helper method that returns true if the user's list is currently visible
558 * and false if it is hidden.
560 * @return true if the user list is visible
562 public boolean isUserListVisible() {
563 return inner.getTabBar().getSelectedTab() == 1;
567 * Display an error message.
569 * @param msg the message to display
571 public void displayError(String msg) {
572 messagePanel.displayError(msg);
576 * Display a warning message.
578 * @param msg the message to display
580 public void displayWarning(String msg) {
581 messagePanel.displayWarning(msg);
585 * Display an informational message.
587 * @param msg the message to display
589 public void displayInformation(String msg) {
590 messagePanel.displayInformation(msg);
594 * Retrieve the folders.
596 * @return the folders
598 public Folders getFolders() {
603 * Retrieve the currentSelection.
605 * @return the currentSelection
607 public Object getCurrentSelection() {
608 return currentSelection;
612 * Modify the currentSelection.
614 * @param newCurrentSelection the currentSelection to set
616 public void setCurrentSelection(Object newCurrentSelection) {
617 currentSelection = newCurrentSelection;
621 * Retrieve the fileList.
623 * @return the fileList
625 public FileList getFileList() {
630 * Retrieve the topPanel.
632 * @return the topPanel
634 TopPanel getTopPanel() {
639 * Retrieve the clipboard.
641 * @return the clipboard
643 public Clipboard getClipboard() {
647 public StatusPanel getStatusPanel() {
652 * Retrieve the userDetailsPanel.
654 * @return the userDetailsPanel
656 public UserDetailsPanel getUserDetailsPanel() {
657 return userDetailsPanel;
662 public String getToken() {
666 public String getWebDAVPassword() {
667 return webDAVPassword;
671 * Retrieve the currentUserResource.
673 * @return the currentUserResource
675 public UserResource getCurrentUserResource() {
676 return currentUserResource;
680 * Modify the currentUserResource.
682 * @param newUser the new currentUserResource
684 public void setCurrentUserResource(UserResource newUser) {
685 currentUserResource = newUser;
688 public static native void preventIESelection() /*-{
689 $doc.body.onselectstart = function () { return false; };
692 public static native void enableIESelection() /*-{
693 if ($doc.body.onselectstart != null)
694 $doc.body.onselectstart = null;
698 * @return the absolute path of the API root URL
700 public String getApiPath() {
701 Configuration conf = (Configuration) GWT.create(Configuration.class);
702 return conf.apiPath();
706 * Convert server date to local time according to browser timezone
707 * and format it according to localized pattern.
708 * Time is always formatted to 24hr format.
709 * NB: This assumes that server runs in UTC timezone. Otherwise
710 * we would need to adjust for server time offset as well.
715 public static String formatLocalDateTime(Date date) {
716 Date convertedDate = new Date(date.getTime() - date.getTimezoneOffset());
717 final DateTimeFormat dateFormatter = DateTimeFormat.getShortDateFormat();
718 final DateTimeFormat timeFormatter = DateTimeFormat.getFormat("HH:mm");
719 String datePart = dateFormatter.format(convertedDate);
720 String timePart = timeFormatter.format(convertedDate);
721 return datePart + " " + timePart;
725 * History support for folder navigation
726 * adds a new browser history entry
730 public void updateHistory(String key){
731 // Replace any whitespace of the initial string to "+"
732 // String result = key.replaceAll("\\s","+");
733 // Add a new browser history entry.
734 // History.newItem(result);
735 History.newItem(key);
739 * This method examines the token input and add a "/" at the end in case it's omitted.
740 * This happens only in Files/trash/, Files/shared/, Files/others.
743 * @return the formated token with a "/" at the end or the same tokenInput parameter
746 private String handleSpecialFolderNames(String tokenInput){
747 List<String> pathsToCheck = Arrays.asList("Files/trash", "Files/shared", "Files/others");
748 if(pathsToCheck.contains(tokenInput))
749 return tokenInput + "/";
755 * Reject illegal resource names, like '.' or '..' or slashes '/'.
757 static boolean isValidResourceName(String name) {
758 if (".".equals(name) || "..".equals(name) || name.contains("/"))
763 public void putUserToMap(String _userName, String _userFullName){
764 userFullNameMap.put(_userName, _userFullName);
767 public String findUserFullName(String _userName){
768 return userFullNameMap.get(_userName);
770 public String getUserFullName(String _userName) {
772 if (GSS.get().findUserFullName(_userName) == null)
773 //if there is no userFullName found then the map fills with the given _userName,
774 //so userFullName = _userName
775 GSS.get().putUserToMap(_userName, _userName);
776 else if(GSS.get().findUserFullName(_userName).indexOf('@') != -1){
777 //if the userFullName = _userName the GetUserCommand updates the userFullName in the map
778 GetUserCommand guc = new GetUserCommand(_userName);
781 return GSS.get().findUserFullName(_userName);
784 * Retrieve the treeView.
786 * @return the treeView
788 public CellTreeView getTreeView() {
792 public void onResourceUpdate(RestResource resource,boolean clearSelection){
793 if(resource instanceof RestResourceWrapper || resource instanceof OtherUserResource || resource instanceof TrashResource || resource instanceof SharedResource){
794 if(getTreeView().getSelection()!=null&&getTreeView().getSelection().getUri().equals(resource.getUri()))
795 showFileList(resource,clearSelection);