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.http.client.Request;
40 import com.google.gwt.http.client.RequestBuilder;
41 import com.google.gwt.http.client.RequestCallback;
42 import com.google.gwt.http.client.RequestException;
43 import com.google.gwt.http.client.Response;
44 import com.google.gwt.json.client.JSONArray;
45 import com.google.gwt.json.client.JSONObject;
46 import com.google.gwt.json.client.JSONParser;
47 import com.google.gwt.json.client.JSONString;
48 import com.google.gwt.json.client.JSONValue;
49 import com.google.gwt.user.client.Command;
50 import com.google.gwt.view.client.SelectionChangeEvent;
51 import com.google.gwt.view.client.SelectionChangeEvent.Handler;
52 import com.google.gwt.view.client.SingleSelectionModel;
53 import gr.grnet.pithos.web.client.foldertree.AccountResource;
54 import gr.grnet.pithos.web.client.foldertree.File;
55 import gr.grnet.pithos.web.client.foldertree.Folder;
56 import gr.grnet.pithos.web.client.foldertree.FolderTreeView;
57 import gr.grnet.pithos.web.client.foldertree.FolderTreeViewModel;
58 import gr.grnet.pithos.web.client.foldertree.Resource;
59 import gr.grnet.pithos.web.client.rest.DeleteRequest;
60 import gr.grnet.pithos.web.client.rest.GetRequest;
61 import gr.grnet.pithos.web.client.rest.PutRequest;
62 import gr.grnet.pithos.web.client.rest.RestException;
64 import gr.grnet.pithos.web.client.tagtree.Tag;
65 import gr.grnet.pithos.web.client.tagtree.TagTreeView;
66 import gr.grnet.pithos.web.client.tagtree.TagTreeViewModel;
67 import java.util.ArrayList;
68 import java.util.Arrays;
69 import java.util.Date;
70 import java.util.HashMap;
71 import java.util.Iterator;
72 import java.util.List;
74 import com.google.gwt.core.client.EntryPoint;
75 import com.google.gwt.core.client.GWT;
76 import com.google.gwt.event.logical.shared.ResizeEvent;
77 import com.google.gwt.event.logical.shared.ResizeHandler;
78 import com.google.gwt.event.logical.shared.SelectionEvent;
79 import com.google.gwt.event.logical.shared.SelectionHandler;
80 import com.google.gwt.i18n.client.DateTimeFormat;
81 import com.google.gwt.resources.client.ClientBundle;
82 import com.google.gwt.resources.client.ImageResource;
83 import com.google.gwt.user.client.Cookies;
84 import com.google.gwt.user.client.Event;
85 import com.google.gwt.user.client.History;
86 import com.google.gwt.user.client.Window;
87 import com.google.gwt.user.client.ui.AbstractImagePrototype;
88 import com.google.gwt.user.client.ui.DecoratedTabPanel;
89 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
90 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
91 import com.google.gwt.user.client.ui.RootPanel;
92 import com.google.gwt.user.client.ui.TabPanel;
93 import com.google.gwt.user.client.ui.VerticalPanel;
97 * Entry point classes define <code>onModuleLoad()</code>.
99 public class Pithos implements EntryPoint, ResizeHandler {
102 * A constant that denotes the completion of an IncrementalCommand.
104 public static final boolean DONE = false;
106 public static final int VISIBLE_FILE_COUNT = 25;
109 * Instantiate an application-level image bundle. This object will provide
110 * programmatic access to all the images needed by widgets.
112 private static Images images = (Images) GWT.create(Images.class);
114 public String getUsername() {
118 public void setAccount(AccountResource acct) {
122 public AccountResource getAccount() {
126 public void updateFolder(Folder f, boolean showfiles) {
127 folderTreeView.updateFolder(f, showfiles);
130 public void updateTag(Tag t) {
131 tagTreeView.updateTag(t);
134 public void updateTags() {
135 tagTreeViewModel.initialize(getAllTags());
138 public List<Tag> getAllTags() {
139 List<Tag> tagList = new ArrayList<Tag>();
140 for (Folder f : account.getContainers()) {
141 for (String t : f.getTags()) {
142 tagList.add(new Tag(t));
149 * An aggregate image bundle that pulls together all the images for this
150 * application into a single bundle.
152 public interface Images extends ClientBundle, TopPanel.Images, FilePropertiesDialog.Images, MessagePanel.Images, FileList.Images {
154 @Source("gr/grnet/pithos/resources/document.png")
155 ImageResource folders();
157 @Source("gr/grnet/pithos/resources/edit_group_22.png")
158 ImageResource groups();
160 @Source("gr/grnet/pithos/resources/search.png")
161 ImageResource search();
165 * The Application Clipboard implementation;
167 private Clipboard clipboard = new Clipboard();
170 * The top panel that contains the menu bar.
172 private TopPanel topPanel;
175 * The panel that contains the various system messages.
177 private MessagePanel messagePanel = new MessagePanel(Pithos.images);
180 * The bottom panel that contains the status bar.
182 private StatusPanel statusPanel = null;
185 * The file list widget.
187 private FileList fileList;
190 * The tab panel that occupies the right side of the screen.
192 private TabPanel inner = new DecoratedTabPanel(){
194 // public void onBrowserEvent(com.google.gwt.user.client.Event event) {
195 // if (DOM.eventGetType(event) == Event.ONCONTEXTMENU){
196 // if(isFileListShowing()){
197 // getFileList().showContextMenu(event);
205 * The split panel that will contain the left and right panels.
207 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
210 * The currently selected item in the application, for use by the Edit menu
211 * commands. Potential types are Folder, File, User and Group.
213 private Object currentSelection;
217 * The WebDAV password of the current user
219 private String webDAVPassword;
221 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
223 private String username = null;
226 * The authentication token of the current user.
228 private String token;
230 private SingleSelectionModel<Folder> folderTreeSelectionModel;
231 private FolderTreeViewModel folderTreeViewModel;
232 private FolderTreeView folderTreeView;
234 private SingleSelectionModel<Tag> tagTreeSelectionModel;
235 private TagTreeViewModel tagTreeViewModel;
236 private TagTreeView tagTreeView;
238 private AccountResource account;
241 public void onModuleLoad() {
242 if (parseUserCredentials())
246 private void initialize() {
247 topPanel = new TopPanel(this, Pithos.images);
248 topPanel.setWidth("100%");
250 messagePanel.setWidth("100%");
251 messagePanel.setVisible(false);
254 // Inner contains the various lists.
255 inner.sinkEvents(Event.ONCONTEXTMENU);
256 inner.setAnimationEnabled(true);
257 inner.getTabBar().addStyleName("pithos-MainTabBar");
258 inner.getDeckPanel().addStyleName("pithos-MainTabPanelBottom");
260 inner.setWidth("100%");
262 inner.addSelectionHandler(new SelectionHandler<Integer>() {
265 public void onSelection(SelectionEvent<Integer> event) {
266 int tabIndex = event.getSelectedItem();
274 folderTreeSelectionModel = new SingleSelectionModel<Folder>();
275 folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
277 public void onSelectionChange(SelectionChangeEvent event) {
278 if (folderTreeSelectionModel.getSelectedObject() != null) {
279 tagTreeSelectionModel.setSelected(tagTreeSelectionModel.getSelectedObject(), false);
280 Folder f = folderTreeSelectionModel.getSelectedObject();
281 updateFolder(f, true);
286 folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
287 folderTreeView = new FolderTreeView(folderTreeViewModel);
289 fileList = new FileList(this, images, folderTreeView);
290 inner.add(fileList, createHeaderHTML(AbstractImagePrototype.create(images.folders()), "Files"), true);
292 tagTreeSelectionModel = new SingleSelectionModel<Tag>();
293 tagTreeSelectionModel.addSelectionChangeHandler(new Handler() {
295 public void onSelectionChange(SelectionChangeEvent event) {
296 if (tagTreeSelectionModel.getSelectedObject() != null) {
297 folderTreeSelectionModel.setSelected(folderTreeSelectionModel.getSelectedObject(), false);
298 Tag t = tagTreeSelectionModel.getSelectedObject();
303 tagTreeViewModel = new TagTreeViewModel(this, tagTreeSelectionModel);
304 tagTreeView = new TagTreeView(tagTreeViewModel);
306 VerticalPanel trees = new VerticalPanel();
307 trees.add(folderTreeView);
308 trees.add(tagTreeView);
309 // Add the left and right panels to the split panel.
310 splitPanel.setLeftWidget(trees);
311 splitPanel.setRightWidget(inner);
312 splitPanel.setSplitPosition("25%");
313 splitPanel.setSize("100%", "100%");
314 splitPanel.addStyleName("pithos-splitPanel");
316 // Create a dock panel that will contain the menu bar at the top,
317 // the shortcuts to the left, the status bar at the bottom and the
318 // right panel taking the rest.
319 VerticalPanel outer = new VerticalPanel();
321 outer.add(messagePanel);
322 outer.add(splitPanel);
323 statusPanel = new StatusPanel();
324 outer.add(statusPanel);
325 outer.setWidth("100%");
326 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
328 // Hook the window resize event, so that we can adjust the UI.
329 Window.addResizeHandler(this);
330 // Clear out the window's built-in margin, because we want to take
331 // advantage of the entire client area.
332 Window.setMargin("0px");
333 // Finally, add the outer panel to the RootPanel, so that it will be
335 RootPanel.get().add(outer);
336 // Call the window resized handler to get the initial sizes setup. Doing
337 // this in a deferred command causes it to occur after all widgets'
338 // sizes have been computed by the browser.
339 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
342 public void execute() {
343 onWindowResized(Window.getClientHeight());
347 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
349 public void execute() {
355 public void showFiles(Folder f) {
358 fileList.showTrash();
361 fileList.showFiles();
362 Set<File> files = f.getFiles();
366 public void showFiles(Set<File> files) {
367 //Iterator<File> iter = files.iterator();
368 //fetchFile(iter, files);
369 fileList.setFiles(new ArrayList<File>(files));
372 private void fetchFile(final Iterator<File> iter, final Set<File> files) {
373 if (iter.hasNext()) {
374 File file = iter.next();
375 String path = file.getUri() + "?format=json";
376 GetRequest<File> getFile = new GetRequest<File>(File.class, getApiPath(), username, path, file) {
378 public void onSuccess(File result) {
379 fetchFile(iter, files);
383 public void onError(Throwable t) {
384 GWT.log("Error getting file", t);
385 if (t instanceof RestException)
386 displayError("Error getting file: " + ((RestException) t).getHttpStatusText());
388 displayError("System error fetching file: " + t.getMessage());
391 getFile.setHeader("X-Auth-Token", "0000");
392 Scheduler.get().scheduleDeferred(getFile);
395 fileList.setFiles(new ArrayList<File>(files));
399 * Parse and store the user credentials to the appropriate fields.
401 private boolean parseUserCredentials() {
402 username = Window.Location.getParameter("user");
403 token = Window.Location.getParameter("token");
404 Configuration conf = (Configuration) GWT.create(Configuration.class);
405 if (username == null || username.length() == 0 || token == null || token.length() == 0) {
406 String cookie = conf.authCookie();
407 String auth = Cookies.getCookie(cookie);
413 String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
414 if (authSplit.length != 2) {
419 username = authSplit[0];
420 token = authSplit[1];
426 Cookies.setCookie(conf.authCookie(), username + conf.cookieSeparator() + token);
432 * Redirect the user to the login page for authentication.
434 protected void authenticateUser() {
435 Configuration conf = (Configuration) GWT.create(Configuration.class);
436 Window.Location.assign(Window.Location.getHost() + conf.loginUrl() + "?next=" + Window.Location.getHref());
439 private void fetchAccount() {
440 String path = "?format=json";
442 GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getApiPath(), username, path) {
444 public void onSuccess(AccountResource result) {
447 if (account.getContainers().isEmpty())
448 createHomeContainers();
450 folderTreeViewModel.initialize(account);
454 public void onError(Throwable t) {
455 GWT.log("Error getting account", t);
456 if (t instanceof RestException)
457 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
459 displayError("System error fetching user data: " + t.getMessage());
462 getAccount.setHeader("X-Auth-Token", token);
463 Scheduler.get().scheduleDeferred(getAccount);
466 private void createHomeContainers() {
467 String path = "/pithos";
468 PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
470 public void onSuccess(Resource result) {
475 public void onError(Throwable t) {
476 GWT.log("Error creating pithos", t);
477 if (t instanceof RestException)
478 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
480 displayError("System error Error creating pithos: " + t.getMessage());
483 createPithos.setHeader("X-Auth-Token", getToken());
484 Scheduler.get().scheduleDeferred(createPithos);
488 * Creates an HTML fragment that places an image & caption together, for use
491 * @param imageProto an image prototype for an image
492 * @param caption the group caption
493 * @return the header HTML fragment
495 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
496 String captionHTML = "<table class='caption' cellpadding='0' "
497 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
498 + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'> "
499 + caption + "</b></td></tr></table>";
503 private void onWindowResized(int height) {
504 // Adjust the split panel to take up the available room in the window.
505 int newHeight = height - splitPanel.getAbsoluteTop() - 60;
508 splitPanel.setHeight("" + newHeight);
509 inner.setHeight("" + newHeight);
513 public void onResize(ResizeEvent event) {
514 int height = event.getHeight();
515 onWindowResized(height);
519 * Display an error message.
521 * @param msg the message to display
523 public void displayError(String msg) {
524 messagePanel.displayError(msg);
528 * Display a warning message.
530 * @param msg the message to display
532 public void displayWarning(String msg) {
533 messagePanel.displayWarning(msg);
537 * Display an informational message.
539 * @param msg the message to display
541 public void displayInformation(String msg) {
542 messagePanel.displayInformation(msg);
546 * Retrieve the fileList.
548 * @return the fileList
550 public FileList getFileList() {
555 * Retrieve the topPanel.
557 * @return the topPanel
559 TopPanel getTopPanel() {
564 * Retrieve the clipboard.
566 * @return the clipboard
568 public Clipboard getClipboard() {
572 public StatusPanel getStatusPanel() {
576 public String getToken() {
580 public String getWebDAVPassword() {
581 return webDAVPassword;
584 public static native void preventIESelection() /*-{
585 $doc.body.onselectstart = function () { return false; };
588 public static native void enableIESelection() /*-{
589 if ($doc.body.onselectstart != null)
590 $doc.body.onselectstart = null;
594 * @return the absolute path of the API root URL
596 public String getApiPath() {
597 Configuration conf = (Configuration) GWT.create(Configuration.class);
598 return conf.apiPath();
602 * History support for folder navigation
603 * adds a new browser history entry
607 public void updateHistory(String key){
608 // Replace any whitespace of the initial string to "+"
609 // String result = key.replaceAll("\\s","+");
610 // Add a new browser history entry.
611 // History.newItem(result);
612 History.newItem(key);
615 public void deleteFolder(final Folder folder) {
616 String path = getApiPath() + getUsername() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + folder.getPrefix();
617 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
618 builder.setHeader("If-Modified-Since", "0");
619 builder.setHeader("X-Auth-Token", getToken());
621 builder.sendRequest("", new RequestCallback() {
623 public void onResponseReceived(Request request, Response response) {
624 if (response.getStatusCode() == Response.SC_OK) {
625 JSONValue json = JSONParser.parseStrict(response.getText());
626 JSONArray array = json.isArray();
629 deleteObject(folder, i, array);
635 public void onError(Request request, Throwable exception) {
636 displayError("System error unable to delete folder: " + exception.getMessage());
640 catch (RequestException e) {
644 public void deleteObject(final Folder folder, final int i, final JSONArray array) {
645 if (i < array.size()) {
646 JSONObject o = array.get(i).isObject();
647 if (o != null && !o.containsKey("subdir")) {
648 JSONString name = o.get("name").isString();
649 String path = "/" + folder.getContainer() + "/" + name.stringValue();
650 DeleteRequest delete = new DeleteRequest(getApiPath(), getUsername(), path) {
652 public void onSuccess(Resource result) {
653 deleteObject(folder, i + 1, array);
657 public void onError(Throwable t) {
659 displayError("System error unable to delete folder: " + t.getMessage());
662 delete.setHeader("X-Auth-Token", getToken());
663 Scheduler.get().scheduleDeferred(delete);
666 String subdir = o.get("subdir").isString().stringValue();
667 subdir = subdir.substring(0, subdir.length() - 1);
668 String path = getApiPath() + getUsername() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + subdir;
669 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
670 builder.setHeader("If-Modified-Since", "0");
671 builder.setHeader("X-Auth-Token", getToken());
673 builder.sendRequest("", new RequestCallback() {
675 public void onResponseReceived(Request request, Response response) {
676 if (response.getStatusCode() == Response.SC_OK) {
677 JSONValue json = JSONParser.parseStrict(response.getText());
678 JSONArray array2 = json.isArray();
679 if (array2 != null) {
680 int l = array.size();
681 for (int j=0; j<array2.size(); j++) {
682 array.set(l++, array2.get(j));
685 deleteObject(folder, i + 1, array);
690 public void onError(Request request, Throwable exception) {
691 displayError("System error unable to delete folder: " + exception.getMessage());
695 catch (RequestException e) {
700 String path = folder.getUri();
701 DeleteRequest deleteFolder = new DeleteRequest(getApiPath(), getUsername(), path) {
703 public void onSuccess(Resource result) {
704 updateFolder(folder.getParent(), true);
708 public void onError(Throwable t) {
710 if (t instanceof RestException) {
711 displayError("Unable to delete folder: "+((RestException) t).getHttpStatusText());
714 displayError("System error unable to delete folder: " + t.getMessage());
717 deleteFolder.setHeader("X-Auth-Token", getToken());
718 Scheduler.get().scheduleDeferred(deleteFolder);
722 public FolderTreeView getFolderTreeView() {
723 return folderTreeView;
726 public void copyFiles(final Iterator<File> iter, final String targetUri, final Command callback) {
727 if (iter.hasNext()) {
728 File file = iter.next();
729 String path = targetUri + "/" + file.getName();
730 PutRequest copyFile = new PutRequest(getApiPath(), getUsername(), path) {
732 public void onSuccess(Resource result) {
733 copyFiles(iter, targetUri, callback);
737 public void onError(Throwable t) {
739 if (t instanceof RestException) {
740 displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
743 displayError("System error unable to copy file: "+t.getMessage());
746 copyFile.setHeader("X-Auth-Token", getToken());
747 copyFile.setHeader("X-Copy-From", file.getUri());
748 Scheduler.get().scheduleDeferred(copyFile);
750 else if (callback != null) {
755 public void copySubfolders(final Iterator<Folder> iter, final String targetUri, final Command callback) {
756 if (iter.hasNext()) {
757 final Folder f = iter.next();
758 copyFolder(f, targetUri, callback);
760 else if (callback != null) {
765 public void copyFolder(final Folder f, final String targetUri, final Command callback) {
766 String path = targetUri + "/" + f.getName();
767 PutRequest createFolder = new PutRequest(getApiPath(), getUsername(), path) {
769 public void onSuccess(Resource result) {
770 Iterator<File> iter = f.getFiles().iterator();
771 copyFiles(iter, targetUri + "/" + f.getName(), new Command() {
773 public void execute() {
774 Iterator<Folder> iterf = f.getSubfolders().iterator();
775 copySubfolders(iterf, targetUri + "/" + f.getName(), new Command() {
777 public void execute() {
786 public void onError(Throwable t) {
788 if (t instanceof RestException) {
789 displayError("Unable to create folder:" + ((RestException) t).getHttpStatusText());
792 displayError("System error creating folder:" + t.getMessage());
795 createFolder.setHeader("X-Auth-Token", getToken());
796 createFolder.setHeader("Accept", "*/*");
797 createFolder.setHeader("Content-Length", "0");
798 createFolder.setHeader("Content-Type", "application/folder");
799 Scheduler.get().scheduleDeferred(createFolder);