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.ClickEvent;
40 import com.google.gwt.event.dom.client.ClickHandler;
41 import com.google.gwt.http.client.Request;
42 import com.google.gwt.http.client.RequestBuilder;
43 import com.google.gwt.http.client.RequestCallback;
44 import com.google.gwt.http.client.RequestException;
45 import com.google.gwt.http.client.Response;
46 import com.google.gwt.json.client.JSONArray;
47 import com.google.gwt.json.client.JSONObject;
48 import com.google.gwt.json.client.JSONParser;
49 import com.google.gwt.json.client.JSONString;
50 import com.google.gwt.json.client.JSONValue;
51 import com.google.gwt.user.client.Command;
52 import com.google.gwt.user.client.ui.Button;
53 import com.google.gwt.user.client.ui.HTML;
54 import com.google.gwt.user.client.ui.HasHorizontalAlignment.HorizontalAlignmentConstant;
55 import com.google.gwt.user.client.ui.HasVerticalAlignment;
56 import com.google.gwt.user.client.ui.HorizontalPanel;
57 import com.google.gwt.user.client.ui.Image;
58 import com.google.gwt.user.client.ui.PushButton;
59 import com.google.gwt.view.client.SelectionChangeEvent;
60 import com.google.gwt.view.client.SelectionChangeEvent.Handler;
61 import com.google.gwt.view.client.SingleSelectionModel;
62 import gr.grnet.pithos.web.client.commands.UploadFileCommand;
63 import gr.grnet.pithos.web.client.foldertree.AccountResource;
64 import gr.grnet.pithos.web.client.foldertree.File;
65 import gr.grnet.pithos.web.client.foldertree.Folder;
66 import gr.grnet.pithos.web.client.foldertree.FolderTreeView;
67 import gr.grnet.pithos.web.client.foldertree.FolderTreeViewModel;
68 import gr.grnet.pithos.web.client.foldertree.Resource;
69 import gr.grnet.pithos.web.client.rest.DeleteRequest;
70 import gr.grnet.pithos.web.client.rest.GetRequest;
71 import gr.grnet.pithos.web.client.rest.PutRequest;
72 import gr.grnet.pithos.web.client.rest.RestException;
74 import gr.grnet.pithos.web.client.tagtree.Tag;
75 import gr.grnet.pithos.web.client.tagtree.TagTreeView;
76 import gr.grnet.pithos.web.client.tagtree.TagTreeViewModel;
77 import java.util.ArrayList;
78 import java.util.Arrays;
79 import java.util.Date;
80 import java.util.HashMap;
81 import java.util.Iterator;
82 import java.util.List;
84 import com.google.gwt.core.client.EntryPoint;
85 import com.google.gwt.core.client.GWT;
86 import com.google.gwt.event.logical.shared.ResizeEvent;
87 import com.google.gwt.event.logical.shared.ResizeHandler;
88 import com.google.gwt.event.logical.shared.SelectionEvent;
89 import com.google.gwt.event.logical.shared.SelectionHandler;
90 import com.google.gwt.i18n.client.DateTimeFormat;
91 import com.google.gwt.resources.client.ClientBundle;
92 import com.google.gwt.resources.client.ImageResource;
93 import com.google.gwt.user.client.Cookies;
94 import com.google.gwt.user.client.Event;
95 import com.google.gwt.user.client.History;
96 import com.google.gwt.user.client.Window;
97 import com.google.gwt.user.client.ui.AbstractImagePrototype;
98 import com.google.gwt.user.client.ui.DecoratedTabPanel;
99 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
100 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
101 import com.google.gwt.user.client.ui.RootPanel;
102 import com.google.gwt.user.client.ui.TabPanel;
103 import com.google.gwt.user.client.ui.VerticalPanel;
104 import java.util.Set;
107 * Entry point classes define <code>onModuleLoad()</code>.
109 public class Pithos implements EntryPoint, ResizeHandler {
112 * A constant that denotes the completion of an IncrementalCommand.
114 public static final boolean DONE = false;
116 public static final int VISIBLE_FILE_COUNT = 25;
119 * Instantiate an application-level image bundle. This object will provide
120 * programmatic access to all the images needed by widgets.
122 private static Images images = (Images) GWT.create(Images.class);
124 public String getUsername() {
128 public void setAccount(AccountResource acct) {
132 public AccountResource getAccount() {
136 public void updateFolder(Folder f, boolean showfiles) {
137 folderTreeView.updateFolder(f, showfiles);
140 public void updateTag(Tag t) {
141 tagTreeView.updateTag(t);
144 public void updateTags() {
145 tagTreeViewModel.initialize(getAllTags());
148 public List<Tag> getAllTags() {
149 List<Tag> tagList = new ArrayList<Tag>();
150 for (Folder f : account.getContainers()) {
151 for (String t : f.getTags()) {
152 tagList.add(new Tag(t));
159 * An aggregate image bundle that pulls together all the images for this
160 * application into a single bundle.
162 public interface Images extends ClientBundle, TopPanel.Images, FilePropertiesDialog.Images, MessagePanel.Images, FileList.Images {
164 @Source("gr/grnet/pithos/resources/document.png")
165 ImageResource folders();
167 @Source("gr/grnet/pithos/resources/edit_group_22.png")
168 ImageResource groups();
170 @Source("gr/grnet/pithos/resources/search.png")
171 ImageResource search();
175 * The Application Clipboard implementation;
177 private Clipboard clipboard = new Clipboard();
180 * The top panel that contains the menu bar.
182 private TopPanel topPanel;
185 * The panel that contains the various system messages.
187 private MessagePanel messagePanel = new MessagePanel(Pithos.images);
190 * The bottom panel that contains the status bar.
192 private StatusPanel statusPanel = null;
195 * The file list widget.
197 private FileList fileList;
200 * The tab panel that occupies the right side of the screen.
202 private VerticalPanel inner = new VerticalPanel();
206 * The split panel that will contain the left and right panels.
208 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
211 * The currently selected item in the application, for use by the Edit menu
212 * commands. Potential types are Folder, File, User and Group.
214 private Object currentSelection;
218 * The WebDAV password of the current user
220 private String webDAVPassword;
222 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
224 private String username = null;
227 * The authentication token of the current user.
229 private String token;
231 private SingleSelectionModel<Folder> folderTreeSelectionModel;
232 private FolderTreeViewModel folderTreeViewModel;
233 private FolderTreeView folderTreeView;
235 private SingleSelectionModel<Tag> tagTreeSelectionModel;
236 private TagTreeViewModel tagTreeViewModel;
237 private TagTreeView tagTreeView;
239 private AccountResource account;
242 public void onModuleLoad() {
243 if (parseUserCredentials())
247 private void initialize() {
248 VerticalPanel outer = new VerticalPanel();
249 outer.setWidth("100%");
251 topPanel = new TopPanel(this, Pithos.images);
252 topPanel.setWidth("100%");
255 messagePanel.setWidth("100%");
256 messagePanel.setVisible(false);
257 outer.add(messagePanel);
258 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
261 // Inner contains the various lists.
262 inner.sinkEvents(Event.ONCONTEXTMENU);
263 inner.setWidth("100%");
265 HorizontalPanel rightside = new HorizontalPanel();
266 rightside.addStyleName("pithos-rightSide");
267 rightside.setSpacing(5);
269 PushButton parentButton = new PushButton(new Image(images.asc()), new ClickHandler() {
271 public void onClick(ClickEvent event) {
275 parentButton.addStyleName("pithos-parentButton");
276 rightside.add(parentButton);
278 HTML folderStatistics = new HTML("5 Files (size: 1.1GB)");
279 folderStatistics.addStyleName("pithos-folderStatistics");
280 rightside.add(folderStatistics);
281 inner.add(rightside);
282 inner.setCellHorizontalAlignment(rightside, HasHorizontalAlignment.ALIGN_RIGHT);
283 inner.setCellVerticalAlignment(rightside, HasVerticalAlignment.ALIGN_MIDDLE);
284 inner.setCellHeight(rightside, "60px");
286 folderTreeSelectionModel = new SingleSelectionModel<Folder>();
287 folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
289 public void onSelectionChange(SelectionChangeEvent event) {
290 if (folderTreeSelectionModel.getSelectedObject() != null) {
291 tagTreeSelectionModel.setSelected(tagTreeSelectionModel.getSelectedObject(), false);
292 Folder f = folderTreeSelectionModel.getSelectedObject();
293 updateFolder(f, true);
298 folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
299 folderTreeView = new FolderTreeView(folderTreeViewModel);
301 fileList = new FileList(this, images, folderTreeView);
304 tagTreeSelectionModel = new SingleSelectionModel<Tag>();
305 tagTreeSelectionModel.addSelectionChangeHandler(new Handler() {
307 public void onSelectionChange(SelectionChangeEvent event) {
308 if (tagTreeSelectionModel.getSelectedObject() != null) {
309 folderTreeSelectionModel.setSelected(folderTreeSelectionModel.getSelectedObject(), false);
310 Tag t = tagTreeSelectionModel.getSelectedObject();
315 tagTreeViewModel = new TagTreeViewModel(this, tagTreeSelectionModel);
316 tagTreeView = new TagTreeView(tagTreeViewModel);
318 VerticalPanel trees = new VerticalPanel();
320 Button upload = new Button("Upload File", new ClickHandler() {
322 public void onClick(ClickEvent event) {
323 new UploadFileCommand(Pithos.this, null, folderTreeView.getSelection()).execute();
326 upload.addStyleName("pithos-uploadButton");
329 HorizontalPanel treeHeader = new HorizontalPanel();
330 treeHeader.addStyleName("pithos-treeHeader");
331 treeHeader.add(new HTML("Total Files: 6 | Used: 2.1 of 50 GB (4.2%)"));
332 trees.add(treeHeader);
334 trees.add(folderTreeView);
335 trees.add(tagTreeView);
336 // Add the left and right panels to the split panel.
337 splitPanel.setLeftWidget(trees);
338 splitPanel.setRightWidget(inner);
339 splitPanel.setSplitPosition("25%");
340 splitPanel.setSize("100%", "100%");
341 splitPanel.addStyleName("pithos-splitPanel");
342 outer.add(splitPanel);
344 statusPanel = new StatusPanel();
345 outer.add(statusPanel);
348 // Hook the window resize event, so that we can adjust the UI.
349 Window.addResizeHandler(this);
350 // Clear out the window's built-in margin, because we want to take
351 // advantage of the entire client area.
352 Window.setMargin("0px");
353 // Finally, add the outer panel to the RootPanel, so that it will be
355 RootPanel.get().add(outer);
356 // Call the window resized handler to get the initial sizes setup. Doing
357 // this in a deferred command causes it to occur after all widgets'
358 // sizes have been computed by the browser.
359 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
362 public void execute() {
363 onWindowResized(Window.getClientHeight());
367 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
369 public void execute() {
375 public void showFiles(Folder f) {
376 Set<File> files = f.getFiles();
380 public void showFiles(Set<File> files) {
381 //Iterator<File> iter = files.iterator();
382 //fetchFile(iter, files);
383 fileList.setFiles(new ArrayList<File>(files));
386 private void fetchFile(final Iterator<File> iter, final Set<File> files) {
387 if (iter.hasNext()) {
388 File file = iter.next();
389 String path = file.getUri() + "?format=json";
390 GetRequest<File> getFile = new GetRequest<File>(File.class, getApiPath(), username, path, file) {
392 public void onSuccess(File result) {
393 fetchFile(iter, files);
397 public void onError(Throwable t) {
398 GWT.log("Error getting file", t);
399 if (t instanceof RestException)
400 displayError("Error getting file: " + ((RestException) t).getHttpStatusText());
402 displayError("System error fetching file: " + t.getMessage());
405 getFile.setHeader("X-Auth-Token", "0000");
406 Scheduler.get().scheduleDeferred(getFile);
409 fileList.setFiles(new ArrayList<File>(files));
413 * Parse and store the user credentials to the appropriate fields.
415 private boolean parseUserCredentials() {
416 username = Window.Location.getParameter("user");
417 token = Window.Location.getParameter("token");
418 Configuration conf = (Configuration) GWT.create(Configuration.class);
419 if (username == null || username.length() == 0 || token == null || token.length() == 0) {
420 String cookie = conf.authCookie();
421 String auth = Cookies.getCookie(cookie);
427 String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
428 if (authSplit.length != 2) {
433 username = authSplit[0];
434 token = authSplit[1];
440 Cookies.setCookie(conf.authCookie(), username + conf.cookieSeparator() + token);
446 * Redirect the user to the login page for authentication.
448 protected void authenticateUser() {
449 Configuration conf = (Configuration) GWT.create(Configuration.class);
450 Window.Location.assign(Window.Location.getHost() + conf.loginUrl() + "?next=" + Window.Location.getHref());
453 private void fetchAccount() {
454 String path = "?format=json";
456 GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getApiPath(), username, path) {
458 public void onSuccess(AccountResource result) {
460 if (account.getContainers().isEmpty())
461 createHomeContainers();
463 folderTreeViewModel.initialize(account);
467 public void onError(Throwable t) {
468 GWT.log("Error getting account", t);
469 if (t instanceof RestException)
470 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
472 displayError("System error fetching user data: " + t.getMessage());
475 getAccount.setHeader("X-Auth-Token", token);
476 Scheduler.get().scheduleDeferred(getAccount);
479 private void createHomeContainers() {
480 String path = "/pithos";
481 PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
483 public void onSuccess(Resource result) {
488 public void onError(Throwable t) {
489 GWT.log("Error creating pithos", t);
490 if (t instanceof RestException)
491 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
493 displayError("System error Error creating pithos: " + t.getMessage());
496 createPithos.setHeader("X-Auth-Token", getToken());
497 Scheduler.get().scheduleDeferred(createPithos);
501 * Creates an HTML fragment that places an image & caption together, for use
504 * @param imageProto an image prototype for an image
505 * @param caption the group caption
506 * @return the header HTML fragment
508 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
509 String captionHTML = "<table class='caption' cellpadding='0' "
510 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
511 + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'> "
512 + caption + "</b></td></tr></table>";
516 private void onWindowResized(int height) {
517 // Adjust the split panel to take up the available room in the window.
518 int newHeight = height - splitPanel.getAbsoluteTop() - 60;
521 splitPanel.setHeight("" + newHeight);
522 inner.setHeight("" + newHeight);
526 public void onResize(ResizeEvent event) {
527 int height = event.getHeight();
528 onWindowResized(height);
532 * Display an error message.
534 * @param msg the message to display
536 public void displayError(String msg) {
537 messagePanel.displayError(msg);
541 * Display a warning message.
543 * @param msg the message to display
545 public void displayWarning(String msg) {
546 messagePanel.displayWarning(msg);
550 * Display an informational message.
552 * @param msg the message to display
554 public void displayInformation(String msg) {
555 messagePanel.displayInformation(msg);
559 * Retrieve the fileList.
561 * @return the fileList
563 public FileList getFileList() {
568 * Retrieve the topPanel.
570 * @return the topPanel
572 TopPanel getTopPanel() {
577 * Retrieve the clipboard.
579 * @return the clipboard
581 public Clipboard getClipboard() {
585 public StatusPanel getStatusPanel() {
589 public String getToken() {
593 public String getWebDAVPassword() {
594 return webDAVPassword;
597 public static native void preventIESelection() /*-{
598 $doc.body.onselectstart = function () { return false; };
601 public static native void enableIESelection() /*-{
602 if ($doc.body.onselectstart != null)
603 $doc.body.onselectstart = null;
607 * @return the absolute path of the API root URL
609 public String getApiPath() {
610 Configuration conf = (Configuration) GWT.create(Configuration.class);
611 return conf.apiPath();
615 * History support for folder navigation
616 * adds a new browser history entry
620 public void updateHistory(String key){
621 // Replace any whitespace of the initial string to "+"
622 // String result = key.replaceAll("\\s","+");
623 // Add a new browser history entry.
624 // History.newItem(result);
625 History.newItem(key);
628 public void deleteFolder(final Folder folder) {
629 String path = getApiPath() + getUsername() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + folder.getPrefix();
630 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
631 builder.setHeader("If-Modified-Since", "0");
632 builder.setHeader("X-Auth-Token", getToken());
634 builder.sendRequest("", new RequestCallback() {
636 public void onResponseReceived(Request request, Response response) {
637 if (response.getStatusCode() == Response.SC_OK) {
638 JSONValue json = JSONParser.parseStrict(response.getText());
639 JSONArray array = json.isArray();
642 deleteObject(folder, i, array);
648 public void onError(Request request, Throwable exception) {
649 displayError("System error unable to delete folder: " + exception.getMessage());
653 catch (RequestException e) {
657 public void deleteObject(final Folder folder, final int i, final JSONArray array) {
658 if (i < array.size()) {
659 JSONObject o = array.get(i).isObject();
660 if (o != null && !o.containsKey("subdir")) {
661 JSONString name = o.get("name").isString();
662 String path = "/" + folder.getContainer() + "/" + name.stringValue();
663 DeleteRequest delete = new DeleteRequest(getApiPath(), getUsername(), path) {
665 public void onSuccess(Resource result) {
666 deleteObject(folder, i + 1, array);
670 public void onError(Throwable t) {
672 displayError("System error unable to delete folder: " + t.getMessage());
675 delete.setHeader("X-Auth-Token", getToken());
676 Scheduler.get().scheduleDeferred(delete);
679 String subdir = o.get("subdir").isString().stringValue();
680 subdir = subdir.substring(0, subdir.length() - 1);
681 String path = getApiPath() + getUsername() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + subdir;
682 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
683 builder.setHeader("If-Modified-Since", "0");
684 builder.setHeader("X-Auth-Token", getToken());
686 builder.sendRequest("", new RequestCallback() {
688 public void onResponseReceived(Request request, Response response) {
689 if (response.getStatusCode() == Response.SC_OK) {
690 JSONValue json = JSONParser.parseStrict(response.getText());
691 JSONArray array2 = json.isArray();
692 if (array2 != null) {
693 int l = array.size();
694 for (int j=0; j<array2.size(); j++) {
695 array.set(l++, array2.get(j));
698 deleteObject(folder, i + 1, array);
703 public void onError(Request request, Throwable exception) {
704 displayError("System error unable to delete folder: " + exception.getMessage());
708 catch (RequestException e) {
713 String path = folder.getUri();
714 DeleteRequest deleteFolder = new DeleteRequest(getApiPath(), getUsername(), path) {
716 public void onSuccess(Resource result) {
717 updateFolder(folder.getParent(), true);
721 public void onError(Throwable t) {
723 if (t instanceof RestException) {
724 displayError("Unable to delete folder: "+((RestException) t).getHttpStatusText());
727 displayError("System error unable to delete folder: " + t.getMessage());
730 deleteFolder.setHeader("X-Auth-Token", getToken());
731 Scheduler.get().scheduleDeferred(deleteFolder);
735 public FolderTreeView getFolderTreeView() {
736 return folderTreeView;
739 public void copyFiles(final Iterator<File> iter, final String targetUri, final Command callback) {
740 if (iter.hasNext()) {
741 File file = iter.next();
742 String path = targetUri + "/" + file.getName();
743 PutRequest copyFile = new PutRequest(getApiPath(), getUsername(), path) {
745 public void onSuccess(Resource result) {
746 copyFiles(iter, targetUri, callback);
750 public void onError(Throwable t) {
752 if (t instanceof RestException) {
753 displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
756 displayError("System error unable to copy file: "+t.getMessage());
759 copyFile.setHeader("X-Auth-Token", getToken());
760 copyFile.setHeader("X-Copy-From", file.getUri());
761 Scheduler.get().scheduleDeferred(copyFile);
763 else if (callback != null) {
768 public void copySubfolders(final Iterator<Folder> iter, final String targetUri, final Command callback) {
769 if (iter.hasNext()) {
770 final Folder f = iter.next();
771 copyFolder(f, targetUri, callback);
773 else if (callback != null) {
778 public void copyFolder(final Folder f, final String targetUri, final Command callback) {
779 String path = targetUri + "/" + f.getName();
780 PutRequest createFolder = new PutRequest(getApiPath(), getUsername(), path) {
782 public void onSuccess(Resource result) {
783 Iterator<File> iter = f.getFiles().iterator();
784 copyFiles(iter, targetUri + "/" + f.getName(), new Command() {
786 public void execute() {
787 Iterator<Folder> iterf = f.getSubfolders().iterator();
788 copySubfolders(iterf, targetUri + "/" + f.getName(), new Command() {
790 public void execute() {
799 public void onError(Throwable t) {
801 if (t instanceof RestException) {
802 displayError("Unable to create folder:" + ((RestException) t).getHttpStatusText());
805 displayError("System error creating folder:" + t.getMessage());
808 createFolder.setHeader("X-Auth-Token", getToken());
809 createFolder.setHeader("Accept", "*/*");
810 createFolder.setHeader("Content-Length", "0");
811 createFolder.setHeader("Content-Type", "application/folder");
812 Scheduler.get().scheduleDeferred(createFolder);