use http caching by using IF-MODIFIED-SINCE HEADERS and handling response accordingly
[pithos] / src / gr / ebs / gss / client / GSS.java
1 /*
2  * Copyright 2007, 2008, 2009 Electronic Business Systems Ltd.
3  *
4  * This file is part of GSS.
5  *
6  * GSS is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * GSS is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with GSS.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 package gr.ebs.gss.client;
20
21 import gr.ebs.gss.client.clipboard.Clipboard;
22 import gr.ebs.gss.client.dnd.DnDFocusPanel;
23 import gr.ebs.gss.client.dnd.DnDSimpleFocusPanel;
24 import gr.ebs.gss.client.rest.GetCommand;
25 import gr.ebs.gss.client.rest.RestException;
26 import gr.ebs.gss.client.rest.resource.FileResource;
27 import gr.ebs.gss.client.rest.resource.FolderResource;
28 import gr.ebs.gss.client.rest.resource.TrashResource;
29 import gr.ebs.gss.client.rest.resource.UserResource;
30
31 import java.util.Iterator;
32 import java.util.List;
33
34 import com.allen_sauer.gwt.dnd.client.DragContext;
35 import com.allen_sauer.gwt.dnd.client.PickupDragController;
36 import com.allen_sauer.gwt.dnd.client.VetoDragException;
37 import com.google.gwt.core.client.EntryPoint;
38 import com.google.gwt.core.client.GWT;
39 import com.google.gwt.event.logical.shared.ResizeEvent;
40 import com.google.gwt.event.logical.shared.ResizeHandler;
41 import com.google.gwt.event.logical.shared.SelectionEvent;
42 import com.google.gwt.event.logical.shared.SelectionHandler;
43 import com.google.gwt.resources.client.ClientBundle;
44 import com.google.gwt.resources.client.ImageResource;
45 import com.google.gwt.user.client.Command;
46 import com.google.gwt.user.client.Cookies;
47 import com.google.gwt.user.client.DOM;
48 import com.google.gwt.user.client.DeferredCommand;
49 import com.google.gwt.user.client.Window;
50 import com.google.gwt.user.client.ui.AbsolutePanel;
51 import com.google.gwt.user.client.ui.AbstractImagePrototype;
52 import com.google.gwt.user.client.ui.DecoratedTabPanel;
53 import com.google.gwt.user.client.ui.DockPanel;
54 import com.google.gwt.user.client.ui.HTML;
55 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
56 import com.google.gwt.user.client.ui.HasVerticalAlignment;
57 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
58 import com.google.gwt.user.client.ui.Label;
59 import com.google.gwt.user.client.ui.RootPanel;
60 import com.google.gwt.user.client.ui.TabPanel;
61 import com.google.gwt.user.client.ui.TreeItem;
62 import com.google.gwt.user.client.ui.VerticalPanel;
63 import com.google.gwt.user.client.ui.Widget;
64
65
66 /**
67  * Entry point classes define <code>onModuleLoad()</code>.
68  */
69 public class GSS implements EntryPoint, ResizeHandler {
70
71         /**
72          * A constant that denotes the completion of an IncrementalCommand.
73          */
74         public static final boolean DONE = false;
75
76         public static final int VISIBLE_FILE_COUNT = 100;
77
78         /**
79          * Instantiate an application-level image bundle. This object will provide
80          * programmatic access to all the images needed by widgets.
81          */
82         private static Images images = (Images) GWT.create(Images.class);
83         private GlassPanel glassPanel = new GlassPanel();
84
85         /**
86          * An aggregate image bundle that pulls together all the images for this
87          * application into a single bundle.
88          */
89         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, Folders.Images {
90
91                 @Source("gr/ebs/gss/resources/document.png")
92                 ImageResource folders();
93
94                 @Source("gr/ebs/gss/resources/edit_group_22.png")
95                 ImageResource groups();
96
97                 @Source("gr/ebs/gss/resources/search.png")
98                 ImageResource search();
99         }
100
101         /**
102          * The single GSS instance.
103          */
104         private static GSS singleton;
105
106         /**
107          * Gets the singleton GSS instance.
108          *
109          * @return the GSS object
110          */
111         public static GSS get() {
112                 if (GSS.singleton == null)
113                         GSS.singleton = new GSS();
114                 return GSS.singleton;
115         }
116
117         /**
118          * The Application Clipboard implementation;
119          */
120         private Clipboard clipboard = new Clipboard();
121
122         private UserResource currentUserResource;
123
124         /**
125          * The top panel that contains the menu bar.
126          */
127         private TopPanel topPanel;
128
129         /**
130          * The panel that contains the various system messages.
131          */
132         private MessagePanel messagePanel = new MessagePanel(GSS.images);
133
134         /**
135          * The bottom panel that contains the status bar.
136          */
137         private StatusPanel statusPanel = new StatusPanel(GSS.images);
138
139         /**
140          * The top right panel that displays the logged in user details
141          */
142         private UserDetailsPanel userDetailsPanel = new UserDetailsPanel();
143
144         /**
145          * The file list widget.
146          */
147         private FileList fileList;
148
149         /**
150          * The group list widget.
151          */
152         private Groups groups  = new Groups(images);
153
154         /**
155          * The search result widget.
156          */
157         private SearchResults searchResults;
158
159         /**
160          * A widget that displays a message indicating that communication with the
161          * server is underway.
162          */
163         private LoadingIndicator loading;
164
165         /**
166          * The tab panel that occupies the right side of the screen.
167          */
168         private TabPanel inner = new DecoratedTabPanel();
169
170         /**
171          * The split panel that will contain the left and right panels.
172          */
173         private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
174
175         /**
176          * The horizontal panel that will contain the search and status panels.
177          */
178         private DockPanel searchStatus = new DockPanel();
179
180         /**
181          * The search widget.
182          */
183         private Search search;
184
185         /**
186          * The widget that displays the tree of folders.
187          */
188         private Folders folders = new Folders(images);
189
190         /**
191          * The currently selected item in the application, for use by the Edit menu
192          * commands. Potential types are Folder, File, User and Group.
193          */
194         private Object currentSelection;
195
196         /**
197          * The authentication token of the current user.
198          */
199         private String token;
200
201         /**
202          * The WebDAV password of the current user
203          */
204         private String webDAVPassword;
205
206         private PickupDragController dragController;
207
208         public void onModuleLoad() {
209                 // Initialize the singleton before calling the constructors of the
210                 // various widgets that might call GSS.get().
211                 singleton = this;
212                 RootPanel.get().add(glassPanel, 0, 0);
213                 parseUserCredentials();
214                 dragController = new PickupDragController(RootPanel.get(), false) {
215
216                         @Override
217                         public void previewDragStart() throws VetoDragException {
218                             super.previewDragStart();
219                             if (context.selectedWidgets.isEmpty())
220                                         throw new VetoDragException();
221
222                             if(context.draggable != null)
223                                         if(context.draggable instanceof DnDFocusPanel){
224                                                 DnDFocusPanel toDrop = (DnDFocusPanel) context.draggable;
225                                                 //prevent drag and drop for trashed files and for unselected tree items
226                                                 if(toDrop.getFiles() != null && folders.isTrashItem(folders.getCurrent()))
227                                                         throw new VetoDragException();
228                                                 else if(toDrop.getItem() != null && !toDrop.getItem().equals(folders.getCurrent()))
229                                                         throw new VetoDragException();
230                                                 else if(toDrop.getItem() != null && !toDrop.getItem().isDraggable())
231                                                         throw new VetoDragException();
232
233                                     }
234                                 else if(context.draggable instanceof DnDSimpleFocusPanel){
235                                         DnDSimpleFocusPanel toDrop = (DnDSimpleFocusPanel) context.draggable;
236                                                 //prevent drag and drop for trashed files and for unselected tree items
237                                                 if(toDrop.getFiles() != null && folders.isTrashItem(folders.getCurrent()))
238                                                         throw new VetoDragException();
239                                 }
240                           }
241
242                         @Override
243                         protected Widget newDragProxy(DragContext aContext) {
244                                 AbsolutePanel container = new AbsolutePanel();
245                                 DOM.setStyleAttribute(container.getElement(), "overflow", "visible");
246                                 for (Iterator iterator = aContext.selectedWidgets.iterator(); iterator.hasNext();) {
247                                         HTML html = null;
248                                         Widget widget = (Widget) iterator.next();
249                                         if(widget instanceof DnDFocusPanel){
250                                                 DnDFocusPanel book = (DnDFocusPanel) widget;
251                                                 html = book.cloneHTML();
252                                         }
253                                         else if(widget instanceof DnDSimpleFocusPanel){
254                                                 DnDSimpleFocusPanel book = (DnDSimpleFocusPanel) widget;
255                                                 html = book.cloneHTML();
256                                         }
257                                         if(html == null)
258                                                 container.add(new Label("Drag ME"));
259                                         else
260                                                 container.add(html);
261                                 }
262                                 return container;
263                         }
264                 };
265                 dragController.setBehaviorDragProxy(true);
266                 dragController.setBehaviorMultipleSelection(false);
267                 topPanel = new TopPanel(GSS.images);
268                 topPanel.setWidth("100%");
269
270                 messagePanel.setWidth("100%");
271                 messagePanel.setVisible(false);
272
273                 search = new Search(images);
274                 searchStatus.add(search, DockPanel.WEST);
275                 searchStatus.add(userDetailsPanel, DockPanel.EAST);
276                 searchStatus.setCellHorizontalAlignment(userDetailsPanel, HasHorizontalAlignment.ALIGN_RIGHT);
277                 searchStatus.setCellVerticalAlignment(search, HasVerticalAlignment.ALIGN_MIDDLE);
278                 searchStatus.setCellVerticalAlignment(userDetailsPanel, HasVerticalAlignment.ALIGN_MIDDLE);
279                 searchStatus.setWidth("100%");
280
281                 fileList = new FileList(images);
282
283                 searchResults = new SearchResults(images);
284
285                 // Inner contains the various lists.
286                 inner.setAnimationEnabled(true);
287                 inner.getTabBar().addStyleName("gss-MainTabBar");
288                 inner.getDeckPanel().addStyleName("gss-MainTabPanelBottom");
289                 inner.add(fileList, createHeaderHTML(AbstractImagePrototype.create(images.folders()), "Files"), true);
290
291                 inner.add(groups, createHeaderHTML(AbstractImagePrototype.create(images.groups()), "Groups"), true);
292                 inner.add(searchResults, createHeaderHTML(AbstractImagePrototype.create(images.search()), "Search Results"), true);
293                 inner.setWidth("100%");
294                 inner.selectTab(0);
295
296                 inner.addSelectionHandler(new SelectionHandler<Integer>() {
297
298                         @Override
299                         public void onSelection(SelectionEvent<Integer> event) {
300                                 int tabIndex= event.getSelectedItem();
301                                 switch (tabIndex) {
302                                 case 0:
303                                         fileList.clearSelectedRows();
304                                         fileList.updateCurrentlyShowingStats();
305                                         break;
306                                 case 1:
307                                         groups.updateCurrentlyShowingStats();
308                                         break;
309                                 case 2:
310                                         searchResults.clearSelectedRows();
311                                         searchResults.updateCurrentlyShowingStats();
312                                         break;
313                         }
314                         }
315                 });
316
317                 // Add the left and right panels to the split panel.
318                 splitPanel.setLeftWidget(folders);
319                 splitPanel.setRightWidget(inner);
320                 splitPanel.setSplitPosition("25%");
321                 splitPanel.setSize("100%", "100%");
322                 splitPanel.addStyleName("gss-splitPanel");
323
324                 // Create a dock panel that will contain the menu bar at the top,
325                 // the shortcuts to the left, the status bar at the bottom and the
326                 // right panel taking the rest.
327                 VerticalPanel outer = new VerticalPanel();
328                 outer.add(topPanel);
329                 outer.add(searchStatus);
330                 outer.add(messagePanel);
331                 outer.add(splitPanel);
332                 outer.add(statusPanel);
333                 outer.setWidth("100%");
334                 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
335
336                 outer.setSpacing(4);
337
338                 loading = new LoadingIndicator();
339                 // Hook the window resize event, so that we can adjust the UI.
340                 Window.addResizeHandler(this);
341                 // Clear out the window's built-in margin, because we want to take
342                 // advantage of the entire client area.
343                 Window.setMargin("0px");
344                 // Finally, add the outer panel to the RootPanel, so that it will be
345                 // displayed.
346                 RootPanel.get().add(outer);
347                 // Call the window resized handler to get the initial sizes setup. Doing
348                 // this in a deferred command causes it to occur after all widgets'
349                 // sizes have been computed by the browser.
350                 DeferredCommand.addCommand(new Command() {
351                         public void execute() {
352                                 onWindowResized(Window.getClientHeight());
353                         }
354                 });
355         }
356
357         /**
358          * Fetches the User object for the specified username.
359          *
360          * @param username the username of the user
361          */
362         private void fetchUser(final String username) {
363                 String path = getApiPath() + username + "/";
364                 GetCommand<UserResource> getUserCommand = new GetCommand<UserResource>(UserResource.class, username, path, null){
365
366                         @Override
367                         public void onComplete() {
368                                 currentUserResource = getResult();
369                                 final String announcement = currentUserResource.getAnnouncement();
370                                 if (announcement != null)
371                                         DeferredCommand.addCommand(new Command() {
372                                                 public void execute() {
373                                                         displayInformation(announcement);
374                                                 }
375                                         });
376                         }
377
378                         @Override
379                         public void onError(Throwable t) {
380                                 GWT.log("Fetching user error", t);
381                                 if(t instanceof RestException)
382                                         GSS.get().displayError("No user found:"+((RestException)t).getHttpStatusText());
383                                 else
384                                         GSS.get().displayError("System error fetching user data:"+t.getMessage());
385                                 authenticateUser();
386                         }
387                 };
388                 DeferredCommand.addCommand(getUserCommand);
389         }
390
391         /**
392          * Parse and store the user credentials to the appropriate fields.
393          */
394         private void parseUserCredentials() {
395                 Configuration conf = (Configuration) GWT.create(Configuration.class);
396                 String cookie = conf.authCookie();
397                 String auth = Cookies.getCookie(cookie);
398                 String domain = Window.Location.getHostName();
399                 String path = Window.Location.getPath();
400                 Cookies.setCookie(cookie, "", null, domain, path, false);
401                 if (auth == null) {
402                         authenticateUser();
403                         // Redundant, but silences warnings about possible auth NPE, below.
404                         return;
405                 }
406                 int sepIndex = auth.indexOf(conf.cookieSeparator());
407                 if (sepIndex == -1)
408                         authenticateUser();
409                 token = auth.substring(sepIndex + 1, auth.length());
410                 final String username = auth.substring(0, sepIndex);
411                 if (username == null)
412                         authenticateUser();
413
414                 refreshWebDAVPassword();
415
416                 DeferredCommand.addCommand(new Command() {
417                         public void execute() {
418                                 fetchUser(username);
419                         }
420                 });
421         }
422
423         /**
424          * Redirect the user to the login page for authentication.
425          */
426         protected void authenticateUser() {
427                 Configuration conf = (Configuration) GWT.create(Configuration.class);
428                 Window.Location.assign(conf.loginUrl() + "?next=" + GWT.getModuleBaseURL());
429         }
430
431         /**
432          * Redirect the user to the logout page.
433          */
434         void logout() {
435                 Configuration conf = (Configuration) GWT.create(Configuration.class);
436                 Window.Location.assign(conf.logoutUrl());
437         }
438
439         /**
440          * Creates an HTML fragment that places an image & caption together, for use
441          * in a group header.
442          *
443          * @param imageProto an image prototype for an image
444          * @param caption the group caption
445          * @return the header HTML fragment
446          */
447         private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
448                 String captionHTML = "<table class='caption' cellpadding='0' " +
449                                 "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML() +
450                                 "</td><td class='rcaption'><b style='white-space:nowrap'>&nbsp;" +
451                                 caption + "</b></td></tr></table>";
452                 return captionHTML;
453         }
454
455
456         private void onWindowResized(int height) {
457                 // Adjust the split panel to take up the available room in the window.
458                 int newHeight = height - splitPanel.getAbsoluteTop() - 44;
459                 if (newHeight < 1)
460                         newHeight = 1;
461                 splitPanel.setHeight("" + newHeight);
462         }
463
464         @Override
465         public void onResize(ResizeEvent event) {
466                 int height = event.getHeight();
467                 onWindowResized(height);
468         }
469
470         public boolean isFileListShowing(){
471                 int tab = inner.getTabBar().getSelectedTab();
472                 if(tab == 0) return true;
473                 return false;
474         }
475
476         public boolean isSearchResultsShowing(){
477                 int tab = inner.getTabBar().getSelectedTab();
478                 if(tab == 2) return true;
479                 return false;
480         }
481
482         /**
483          * Make the user list visible.
484          */
485         public void showUserList() {
486                 inner.selectTab(1);
487         }
488
489         /**
490          * Make the file list visible.
491          */
492         public void showFileList() {
493                 fileList.updateFileCache(false, true /*clear selection*/);
494                 inner.selectTab(0);
495         }
496
497         /**
498          * Make the file list visible.
499          * @param update
500          */
501         public void showFileList(boolean update) {
502                 TreeItem currentFolder = getFolders().getCurrent();
503                 if (currentFolder != null) {
504                         List<FileResource> files = null;
505                         Object cachedObject = currentFolder.getUserObject();
506                         if (cachedObject instanceof FolderResource) {
507                                 FolderResource folder = (FolderResource) cachedObject;
508                                 files = folder.getFiles();
509                         } else if (cachedObject instanceof TrashResource) {
510                                 TrashResource folder = (TrashResource) cachedObject;
511                                 files = folder.getFiles();
512                         }
513                         if (files != null)
514                                 getFileList().setFiles(files);
515                 }
516                 fileList.updateFileCache(update, true /*clear selection*/);
517                 inner.selectTab(0);
518         }
519
520         /**
521          * Make the search results visible.
522          * @param query the search query string
523          */
524         public void showSearchResults(String query) {
525                 searchResults.updateFileCache(query);
526                 searchResults.updateCurrentlyShowingStats();
527                 inner.selectTab(2);
528         }
529
530         /**
531          * Display the 'loading' indicator.
532          */
533         public void showLoadingIndicator() {
534                 loading.center();
535         }
536
537         /**
538          * Hide the 'loading' indicator.
539          */
540         public void hideLoadingIndicator() {
541                 loading.hide();
542         }
543
544         /**
545          * A native JavaScript method to reach out to the browser's window and
546          * invoke its resizeTo() method.
547          *
548          * @param x the new width
549          * @param y the new height
550          */
551         public static native void resizeTo(int x, int y) /*-{
552          $wnd.resizeTo(x,y);
553         }-*/;
554
555         /**
556          * A helper method that returns true if the user's list is currently visible
557          * and false if it is hidden.
558          *
559          * @return true if the user list is visible
560          */
561         public boolean isUserListVisible() {
562                 return inner.getTabBar().getSelectedTab() == 1;
563         }
564
565         /**
566          * Display an error message.
567          *
568          * @param msg the message to display
569          */
570         public void displayError(String msg) {
571                 messagePanel.displayError(msg);
572         }
573
574         /**
575          * Display a warning message.
576          *
577          * @param msg the message to display
578          */
579         public void displayWarning(String msg) {
580                 messagePanel.displayWarning(msg);
581         }
582
583         /**
584          * Display an informational message.
585          *
586          * @param msg the message to display
587          */
588         public void displayInformation(String msg) {
589                 messagePanel.displayInformation(msg);
590         }
591
592         /**
593          * Retrieve the folders.
594          *
595          * @return the folders
596          */
597         public Folders getFolders() {
598                 return folders;
599         }
600
601         /**
602          * Retrieve the search.
603          *
604          * @return the search
605          */
606         Search getSearch() {
607                 return search;
608         }
609
610         /**
611          * Retrieve the currentSelection.
612          *
613          * @return the currentSelection
614          */
615         public Object getCurrentSelection() {
616                 return currentSelection;
617         }
618
619         /**
620          * Modify the currentSelection.
621          *
622          * @param newCurrentSelection the currentSelection to set
623          */
624         public void setCurrentSelection(Object newCurrentSelection) {
625                 currentSelection = newCurrentSelection;
626         }
627
628         /**
629          * Retrieve the groups.
630          *
631          * @return the groups
632          */
633         public Groups getGroups() {
634                 return groups;
635         }
636
637         /**
638          * Retrieve the fileList.
639          *
640          * @return the fileList
641          */
642         public FileList getFileList() {
643                 return fileList;
644         }
645
646         public SearchResults getSearchResults(){
647                 return searchResults;
648         }
649
650         /**
651          * Retrieve the topPanel.
652          *
653          * @return the topPanel
654          */
655         TopPanel getTopPanel() {
656                 return topPanel;
657         }
658
659         /**
660          * Retrieve the clipboard.
661          *
662          * @return the clipboard
663          */
664         public Clipboard getClipboard() {
665                 return clipboard;
666         }
667
668
669         public StatusPanel getStatusPanel(){
670                 return statusPanel;
671         }
672
673
674         /**
675          * Retrieve the userDetailsPanel.
676          *
677          * @return the userDetailsPanel
678          */
679         public UserDetailsPanel getUserDetailsPanel() {
680                 return userDetailsPanel;
681         }
682
683         /**
684          * Retrieve the dragController.
685          *
686          * @return the dragController
687          */
688         public PickupDragController getDragController() {
689                 return dragController;
690         }
691
692         public String getToken(){
693                 return token;
694         }
695
696         public String getWebDAVPassword() {
697                 return webDAVPassword;
698         }
699
700         public void removeGlassPanel(){
701                 glassPanel.removeFromParent();
702         }
703
704         /**
705          * Retrieve the currentUserResource.
706          *
707          * @return the currentUserResource
708          */
709         public UserResource getCurrentUserResource() {
710                 return currentUserResource;
711         }
712
713         /**
714          * Modify the currentUserResource.
715          *
716          * @param newUser the new currentUserResource
717          */
718         public void setCurrentUserResource(UserResource newUser) {
719                 currentUserResource = newUser;
720         }
721
722         public static native void preventIESelection() /*-{
723         $doc.body.onselectstart = function () { return false; };
724         }-*/;
725
726         public static native void enableIESelection() /*-{
727                 if ($doc.body.onselectstart != null)
728                         $doc.body.onselectstart = null;
729         }-*/;
730
731         /**
732          * @return the absolute path of the API root URL
733          */
734         public String getApiPath() {
735                 Configuration conf = (Configuration) GWT.create(Configuration.class);
736                 return GWT.getModuleBaseURL() + conf.apiPath();
737         }
738
739         public void refreshWebDAVPassword() {
740                 Configuration conf = (Configuration) GWT.create(Configuration.class);
741                 String domain = Window.Location.getHostName();
742                 String path = Window.Location.getPath();
743                 String cookie = conf.webdavCookie();
744                 webDAVPassword = Cookies.getCookie(cookie);
745                 Cookies.setCookie(cookie, "", null, domain, path, false);
746         }
747
748
749 }