2 * Copyright 2011-2012 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 gr.grnet.pithos.web.client.commands.UploadFileCommand;
38 import gr.grnet.pithos.web.client.foldertree.AccountResource;
39 import gr.grnet.pithos.web.client.foldertree.File;
40 import gr.grnet.pithos.web.client.foldertree.Folder;
41 import gr.grnet.pithos.web.client.foldertree.FolderTreeView;
42 import gr.grnet.pithos.web.client.foldertree.FolderTreeViewModel;
43 import gr.grnet.pithos.web.client.foldertree.Resource;
44 import gr.grnet.pithos.web.client.grouptree.Group;
45 import gr.grnet.pithos.web.client.grouptree.GroupTreeView;
46 import gr.grnet.pithos.web.client.grouptree.GroupTreeViewModel;
47 import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeView;
48 import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeViewModel;
49 import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeView;
50 import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeViewModel;
51 import gr.grnet.pithos.web.client.rest.DeleteRequest;
52 import gr.grnet.pithos.web.client.rest.GetRequest;
53 import gr.grnet.pithos.web.client.rest.HeadRequest;
54 import gr.grnet.pithos.web.client.rest.PutRequest;
55 import gr.grnet.pithos.web.client.rest.RestException;
57 import java.util.ArrayList;
58 import java.util.HashMap;
59 import java.util.Iterator;
60 import java.util.List;
63 import com.google.gwt.core.client.EntryPoint;
64 import com.google.gwt.core.client.GWT;
65 import com.google.gwt.core.client.Scheduler;
66 import com.google.gwt.core.client.Scheduler.RepeatingCommand;
67 import com.google.gwt.core.client.Scheduler.ScheduledCommand;
68 import com.google.gwt.event.dom.client.ClickEvent;
69 import com.google.gwt.event.dom.client.ClickHandler;
70 import com.google.gwt.event.logical.shared.ResizeEvent;
71 import com.google.gwt.event.logical.shared.ResizeHandler;
72 import com.google.gwt.http.client.Request;
73 import com.google.gwt.http.client.RequestBuilder;
74 import com.google.gwt.http.client.RequestCallback;
75 import com.google.gwt.http.client.RequestException;
76 import com.google.gwt.http.client.Response;
77 import com.google.gwt.http.client.URL;
78 import com.google.gwt.i18n.client.Dictionary;
79 import com.google.gwt.i18n.client.NumberFormat;
80 import com.google.gwt.json.client.JSONArray;
81 import com.google.gwt.json.client.JSONObject;
82 import com.google.gwt.json.client.JSONParser;
83 import com.google.gwt.json.client.JSONString;
84 import com.google.gwt.json.client.JSONValue;
85 import com.google.gwt.resources.client.ImageResource;
86 import com.google.gwt.resources.client.ImageResource.ImageOptions;
87 import com.google.gwt.user.client.Command;
88 import com.google.gwt.user.client.Cookies;
89 import com.google.gwt.user.client.Event;
90 import com.google.gwt.user.client.History;
91 import com.google.gwt.user.client.Window;
92 import com.google.gwt.user.client.ui.AbstractImagePrototype;
93 import com.google.gwt.user.client.ui.Button;
94 import com.google.gwt.user.client.ui.Composite;
95 import com.google.gwt.user.client.ui.HTML;
96 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
97 import com.google.gwt.user.client.ui.HasVerticalAlignment;
98 import com.google.gwt.user.client.ui.HorizontalPanel;
99 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
100 import com.google.gwt.user.client.ui.RootPanel;
101 import com.google.gwt.user.client.ui.VerticalPanel;
102 import com.google.gwt.view.client.SelectionChangeEvent;
103 import com.google.gwt.view.client.SelectionChangeEvent.Handler;
104 import com.google.gwt.view.client.SingleSelectionModel;
107 * Entry point classes define <code>onModuleLoad()</code>.
109 public class Pithos implements EntryPoint, ResizeHandler {
111 public static final String HOME_CONTAINER = "pithos";
113 public static final String TRASH_CONTAINER = "trash";
115 public static final Configuration config = GWT.create(Configuration.class);
118 * Instantiate an application-level image bundle. This object will provide
119 * programmatic access to all the images needed by widgets.
121 static Images images = (Images) GWT.create(Images.class);
123 public String getUsername() {
127 public void setAccount(AccountResource acct) {
131 public AccountResource getAccount() {
135 public void updateFolder(Folder f, boolean showfiles, Command callback, final boolean openParent) {
136 folderTreeView.updateFolder(f, showfiles, callback, openParent);
139 public void updateGroupNode(Group group) {
140 groupTreeView.updateGroupNode(group);
143 public void updateMySharedRoot() {
144 mysharedTreeView.updateRoot();
147 public void updateSharedFolder(Folder f, boolean showfiles) {
148 mysharedTreeView.updateFolder(f, showfiles);
151 public void updateOtherSharedFolder(Folder f, boolean showfiles) {
152 otherSharedTreeView.updateFolder(f, showfiles);
155 public MysharedTreeView getMySharedTreeView() {
156 return mysharedTreeView;
160 * An aggregate image bundle that pulls together all the images for this
161 * application into a single bundle.
163 public interface Images extends TopPanel.Images, FileList.Images, ToolsMenu.Images {
165 @Source("gr/grnet/pithos/resources/document.png")
166 ImageResource folders();
168 @Source("gr/grnet/pithos/resources/advancedsettings.png")
169 @ImageOptions(width=32, height=32)
170 ImageResource tools();
173 private Throwable error;
176 * The Application Clipboard implementation;
178 private Clipboard clipboard = new Clipboard();
181 * The top panel that contains the menu bar.
183 private TopPanel topPanel;
186 * The panel that contains the various system messages.
188 private MessagePanel messagePanel = new MessagePanel(this, Pithos.images);
191 * The bottom panel that contains the status bar.
193 private StatusPanel statusPanel = null;
196 * The file list widget.
198 private FileList fileList;
201 * The tab panel that occupies the right side of the screen.
203 private VerticalPanel inner = new VerticalPanel();
207 * The split panel that will contain the left and right panels.
209 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
212 * The currently selected item in the application, for use by the Edit menu
213 * commands. Potential types are Folder, File, User and Group.
215 private Object currentSelection;
217 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
219 private String username = null;
222 * The authentication token of the current user.
224 private String token;
228 SingleSelectionModel<Folder> folderTreeSelectionModel;
229 FolderTreeViewModel folderTreeViewModel;
230 FolderTreeView folderTreeView;
232 SingleSelectionModel<Folder> mysharedTreeSelectionModel;
233 MysharedTreeViewModel mysharedTreeViewModel;
234 MysharedTreeView mysharedTreeView = null;;
236 protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
237 OtherSharedTreeViewModel otherSharedTreeViewModel;
238 OtherSharedTreeView otherSharedTreeView = null;
240 GroupTreeViewModel groupTreeViewModel;
241 private GroupTreeView groupTreeView;
243 TreeView selectedTree;
244 protected AccountResource account;
248 List<Composite> treeViews = new ArrayList<Composite>();
250 @SuppressWarnings("rawtypes") List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
254 private HTML usedBytes;
256 private HTML totalBytes;
258 private HTML usedPercent;
260 private HTML numOfFiles;
262 private Toolbar toolbar;
264 private FileUploadDialog fileUploadDialog;
267 public void onModuleLoad() {
268 if (parseUserCredentials())
272 private void initialize() {
273 boolean bareContent = Window.Location.getParameter("noframe") != null;
274 String contentWidth = bareContent ? "100%" : "75%";
276 VerticalPanel outer = new VerticalPanel();
277 outer.setWidth("100%");
279 outer.addStyleName("pithos-outer");
283 topPanel = new TopPanel(this, Pithos.images);
284 topPanel.setWidth("100%");
286 outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
289 messagePanel.setVisible(false);
290 outer.add(messagePanel);
291 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
292 outer.setCellVerticalAlignment(messagePanel, HasVerticalAlignment.ALIGN_MIDDLE);
294 HorizontalPanel header = new HorizontalPanel();
295 header.addStyleName("pithos-header");
296 header.setWidth(contentWidth);
298 header.addStyleName("pithos-header-noframe");
299 upload = new Button("Upload", new ClickHandler() {
301 public void onClick(ClickEvent event) {
302 if (getSelection() != null)
303 new UploadFileCommand(Pithos.this, null, getSelection()).execute();
306 upload.addStyleName("pithos-uploadButton");
308 header.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_LEFT);
309 header.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
311 toolbar = new Toolbar(this);
313 header.setCellHorizontalAlignment(toolbar, HasHorizontalAlignment.ALIGN_CENTER);
314 header.setCellVerticalAlignment(toolbar, HasVerticalAlignment.ALIGN_MIDDLE);
316 HorizontalPanel folderStatistics = new HorizontalPanel();
317 folderStatistics.addStyleName("pithos-folderStatistics");
318 numOfFiles = new HTML();
319 folderStatistics.add(numOfFiles);
320 folderStatistics.setCellVerticalAlignment(numOfFiles, HasVerticalAlignment.ALIGN_MIDDLE);
321 HTML numOfFilesLabel = new HTML(" Files");
322 folderStatistics.add(numOfFilesLabel);
323 folderStatistics.setCellVerticalAlignment(numOfFilesLabel, HasVerticalAlignment.ALIGN_MIDDLE);
324 header.add(folderStatistics);
325 header.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
326 header.setCellVerticalAlignment(folderStatistics, HasVerticalAlignment.ALIGN_MIDDLE);
327 header.setCellWidth(folderStatistics, "40px");
329 outer.setCellHorizontalAlignment(header, HasHorizontalAlignment.ALIGN_CENTER);
330 // Inner contains the various lists.nner
331 inner.sinkEvents(Event.ONCONTEXTMENU);
332 inner.setWidth("100%");
334 folderTreeSelectionModel = new SingleSelectionModel<Folder>();
335 folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
337 public void onSelectionChange(SelectionChangeEvent event) {
338 if (folderTreeSelectionModel.getSelectedObject() != null) {
339 deselectOthers(folderTreeView, folderTreeSelectionModel);
340 applyPermissions(folderTreeSelectionModel.getSelectedObject());
341 Folder f = folderTreeSelectionModel.getSelectedObject();
342 updateFolder(f, true, new Command() {
345 public void execute() {
349 showRelevantToolbarButtons();
352 if (getSelectedTree().equals(folderTreeView))
353 setSelectedTree(null);
354 if (getSelectedTree() == null)
355 showRelevantToolbarButtons();
359 selectionModels.add(folderTreeSelectionModel);
361 folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
362 folderTreeView = new FolderTreeView(folderTreeViewModel);
363 treeViews.add(folderTreeView);
365 fileList = new FileList(this, images, folderTreeView);
368 groupTreeViewModel = new GroupTreeViewModel(this);
369 groupTreeView = new GroupTreeView(groupTreeViewModel);
370 treeViews.add(groupTreeView);
372 trees = new VerticalPanel();
373 trees.setWidth("100%");
376 // HorizontalPanel treeHeader = new HorizontalPanel();
377 // treeHeader.addStyleName("pithos-treeHeader");
378 // treeHeader.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
379 // treeHeader.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
380 // treeHeader.add(statistics);
381 // treeHeader.setCellHorizontalAlignment(statistics, HasHorizontalAlignment.ALIGN_LEFT);
382 // trees.add(treeHeader);
384 trees.add(folderTreeView);
386 HorizontalPanel separator = new HorizontalPanel();
387 separator.addStyleName("pithos-statisticsSeparator");
388 trees.add(separator);
390 HorizontalPanel statistics = new HorizontalPanel();
391 statistics.addStyleName("pithos-statistics");
392 statistics.add(new HTML("Used: "));
393 usedBytes = new HTML();
394 statistics.add(usedBytes);
395 statistics.add(new HTML(" of "));
396 totalBytes = new HTML();
397 statistics.add(totalBytes);
398 statistics.add(new HTML(" ("));
399 usedPercent = new HTML();
400 statistics.add(usedPercent);
401 statistics.add(new HTML(")"));
402 trees.add(statistics);
404 trees.add(groupTreeView);
405 // Add the left and right panels to the split panel.
406 splitPanel.setLeftWidget(trees);
407 splitPanel.setRightWidget(inner);
408 splitPanel.setSplitPosition("219px");
409 splitPanel.setSize("100%", "100%");
410 splitPanel.addStyleName("pithos-splitPanel");
411 splitPanel.setWidth(contentWidth);
412 outer.add(splitPanel);
413 outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
416 statusPanel = new StatusPanel();
417 statusPanel.setWidth("100%");
418 outer.add(statusPanel);
419 outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
422 splitPanel.addStyleName("pithos-splitPanel-noframe");
424 // Hook the window resize event, so that we can adjust the UI.
425 Window.addResizeHandler(this);
426 // Clear out the window's built-in margin, because we want to take
427 // advantage of the entire client area.
428 Window.setMargin("0px");
429 // Finally, add the outer panel to the RootPanel, so that it will be
431 RootPanel.get().add(outer);
432 // Call the window resized handler to get the initial sizes setup. Doing
433 // this in a deferred command causes it to occur after all widgets'
434 // sizes have been computed by the browser.
435 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
438 public void execute() {
439 onWindowResized(Window.getClientHeight());
443 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
445 public void execute() {
446 fetchAccount(new Command() {
449 public void execute() {
450 if (!account.hasHomeContainer())
451 createHomeContainer(account, this);
452 else if (!account.hasTrashContainer())
453 createTrashContainer(this);
455 for (Folder f : account.getContainers())
456 if (f.getName().equals(Pithos.TRASH_CONTAINER)) {
460 folderTreeViewModel.initialize(account, new Command() {
463 public void execute() {
464 createMySharedTree();
467 groupTreeViewModel.initialize();
475 Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {
478 public boolean execute() {
479 Folder f = getSelection();
481 if (getSelectedTree().equals(folderTreeView))
482 updateFolder(f, true, null, false);
483 else if (getSelectedTree().equals(mysharedTreeView))
484 updateSharedFolder(f, true);
491 public void applyPermissions(Folder f) {
494 upload.setEnabled(false);
496 Boolean[] perms = f.getPermissions().get(username);
497 if (f.getOwner().equals(username) || (perms != null && perms[1] != null && perms[1])) {
498 upload.setEnabled(true);
501 upload.setEnabled(false);
505 upload.setEnabled(false);
508 @SuppressWarnings({ "rawtypes", "unchecked" })
509 public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
510 selectedTree = _selectedTree;
512 for (Composite c : treeViews)
513 if (c.equals(selectedTree))
514 c.addStyleName("cellTreeWidget-selectedTree");
516 c.removeStyleName("cellTreeWidget-selectedTree");
518 for (SingleSelectionModel s : selectionModels)
519 if (!s.equals(model) && s.getSelectedObject() != null)
520 s.setSelected(s.getSelectedObject(), false);
523 public void showFiles(final Folder f) {
524 Set<File> files = f.getFiles();
528 public void showFiles(Set<File> files) {
529 fileList.setFiles(new ArrayList<File>(files));
533 * Parse and store the user credentials to the appropriate fields.
535 private boolean parseUserCredentials() {
536 username = Window.Location.getParameter("user");
537 token = Window.Location.getParameter("token");
538 Configuration conf = (Configuration) GWT.create(Configuration.class);
539 Dictionary otherProperties = Dictionary.getDictionary("otherProperties");
540 if (username == null || username.length() == 0 || token == null || token.length() == 0) {
541 String cookie = otherProperties.get("authCookie");
542 String auth = Cookies.getCookie(cookie);
547 if (auth.startsWith("\""))
548 auth = auth.substring(1);
549 if (auth.endsWith("\""))
550 auth = auth.substring(0, auth.length() - 1);
551 String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
552 if (authSplit.length != 2) {
556 username = authSplit[0];
557 token = authSplit[1];
560 Cookies.setCookie(otherProperties.get("authCookie"), username + conf.cookieSeparator() + token, null, "", "/", false);
562 String gotoUrl = Window.Location.getParameter("goto");
563 if (gotoUrl != null && gotoUrl.length() > 0) {
564 Window.Location.assign(gotoUrl);
571 * Redirect the user to the login page for authentication.
573 protected void authenticateUser() {
574 Dictionary otherProperties = Dictionary.getDictionary("otherProperties");
575 Window.Location.assign(otherProperties.get("loginUrl") + Window.Location.getHref());
578 protected void fetchAccount(final Command callback) {
579 String path = "?format=json";
581 GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getApiPath(), username, path) {
583 public void onSuccess(AccountResource _result) {
585 if (callback != null)
590 public void onError(Throwable t) {
591 GWT.log("Error getting account", t);
593 if (t instanceof RestException)
594 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
596 displayError("System error fetching user data: " + t.getMessage());
600 protected void onUnauthorized(Response response) {
604 getAccount.setHeader("X-Auth-Token", token);
605 Scheduler.get().scheduleDeferred(getAccount);
608 public void updateStatistics() {
609 HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getApiPath(), username, "", account) {
612 public void onSuccess(AccountResource _result) {
617 public void onError(Throwable t) {
618 GWT.log("Error getting account", t);
620 if (t instanceof RestException)
621 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
623 displayError("System error fetching user data: " + t.getMessage());
627 protected void onUnauthorized(Response response) {
631 headAccount.setHeader("X-Auth-Token", token);
632 Scheduler.get().scheduleDeferred(headAccount);
635 protected void showStatistics() {
636 usedBytes.setHTML(String.valueOf(account.getFileSizeAsString()));
637 totalBytes.setHTML(String.valueOf(account.getQuotaAsString()));
638 NumberFormat nf = NumberFormat.getPercentFormat();
639 usedPercent.setHTML(nf.format(account.getUsedPercentage()));
642 protected void createHomeContainer(final AccountResource _account, final Command callback) {
643 String path = "/" + Pithos.HOME_CONTAINER;
644 PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
646 public void onSuccess(Resource result) {
647 if (!_account.hasTrashContainer())
648 createTrashContainer(callback);
650 fetchAccount(callback);
654 public void onError(Throwable t) {
655 GWT.log("Error creating pithos", t);
657 if (t instanceof RestException)
658 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
660 displayError("System error Error creating pithos: " + t.getMessage());
664 protected void onUnauthorized(Response response) {
668 createPithos.setHeader("X-Auth-Token", getToken());
669 Scheduler.get().scheduleDeferred(createPithos);
672 protected void createTrashContainer(final Command callback) {
673 String path = "/" + Pithos.TRASH_CONTAINER;
674 PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
676 public void onSuccess(Resource result) {
677 fetchAccount(callback);
681 public void onError(Throwable t) {
682 GWT.log("Error creating pithos", t);
684 if (t instanceof RestException)
685 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
687 displayError("System error Error creating pithos: " + t.getMessage());
691 protected void onUnauthorized(Response response) {
695 createPithos.setHeader("X-Auth-Token", getToken());
696 Scheduler.get().scheduleDeferred(createPithos);
700 * Creates an HTML fragment that places an image & caption together, for use
703 * @param imageProto an image prototype for an image
704 * @param caption the group caption
705 * @return the header HTML fragment
707 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
708 String captionHTML = "<table class='caption' cellpadding='0' "
709 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
710 + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'> "
711 + caption + "</b></td></tr></table>";
715 protected void onWindowResized(int height) {
716 // Adjust the split panel to take up the available room in the window.
717 int newHeight = height - splitPanel.getAbsoluteTop();
720 splitPanel.setHeight("" + newHeight);
721 inner.setHeight("" + newHeight);
725 public void onResize(ResizeEvent event) {
726 int height = event.getHeight();
727 onWindowResized(height);
731 * Display an error message.
733 * @param msg the message to display
735 public void displayError(String msg) {
736 messagePanel.displayError(msg);
740 * Display a warning message.
742 * @param msg the message to display
744 public void displayWarning(String msg) {
745 messagePanel.displayWarning(msg);
749 * Display an informational message.
751 * @param msg the message to display
753 public void displayInformation(String msg) {
754 messagePanel.displayInformation(msg);
758 * Retrieve the fileList.
760 * @return the fileList
762 public FileList getFileList() {
767 * Retrieve the topPanel.
769 * @return the topPanel
771 TopPanel getTopPanel() {
776 * Retrieve the clipboard.
778 * @return the clipboard
780 public Clipboard getClipboard() {
784 public StatusPanel getStatusPanel() {
788 public String getToken() {
792 public static native void preventIESelection() /*-{
793 $doc.body.onselectstart = function () { return false; };
796 public static native void enableIESelection() /*-{
797 if ($doc.body.onselectstart != null)
798 $doc.body.onselectstart = null;
802 * @return the absolute path of the API root URL
804 public String getApiPath() {
805 Configuration conf = (Configuration) GWT.create(Configuration.class);
806 return conf.apiPath();
810 * History support for folder navigation
811 * adds a new browser history entry
815 public void updateHistory(String key){
816 // Replace any whitespace of the initial string to "+"
817 // String result = key.replaceAll("\\s","+");
818 // Add a new browser history entry.
819 // History.newItem(result);
820 History.newItem(key);
823 public void deleteFolder(final Folder folder, final Command callback) {
824 String path = getApiPath() + folder.getOwner() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(folder.getPrefix()) + "&t=" + System.currentTimeMillis();
825 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
826 builder.setHeader("X-Auth-Token", getToken());
828 builder.sendRequest("", new RequestCallback() {
830 public void onResponseReceived(Request request, Response response) {
831 if (response.getStatusCode() == Response.SC_OK) {
832 JSONValue json = JSONParser.parseStrict(response.getText());
833 JSONArray array = json.isArray();
836 deleteObject(folder, i, array, callback);
842 public void onError(Request request, Throwable exception) {
844 displayError("System error unable to delete folder: " + exception.getMessage());
848 catch (RequestException e) {
852 void deleteObject(final Folder folder, final int i, final JSONArray array, final Command callback) {
853 if (i < array.size()) {
854 JSONObject o = array.get(i).isObject();
855 if (o != null && !o.containsKey("subdir")) {
856 JSONString name = o.get("name").isString();
857 String path = "/" + folder.getContainer() + "/" + name.stringValue();
858 DeleteRequest delete = new DeleteRequest(getApiPath(), folder.getOwner(), URL.encode(path)) {
860 public void onSuccess(Resource result) {
861 deleteObject(folder, i + 1, array, callback);
865 public void onError(Throwable t) {
868 displayError("System error unable to delete folder: " + t.getMessage());
872 protected void onUnauthorized(Response response) {
876 delete.setHeader("X-Auth-Token", getToken());
877 Scheduler.get().scheduleDeferred(delete);
879 else if (o != null) {
880 String subdir = o.get("subdir").isString().stringValue();
881 subdir = subdir.substring(0, subdir.length() - 1);
882 String path = getApiPath() + getUsername() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(subdir) + "&t=" + System.currentTimeMillis();
883 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
884 builder.setHeader("X-Auth-Token", getToken());
886 builder.sendRequest("", new RequestCallback() {
888 public void onResponseReceived(Request request, Response response) {
889 if (response.getStatusCode() == Response.SC_OK) {
890 JSONValue json = JSONParser.parseStrict(response.getText());
891 JSONArray array2 = json.isArray();
892 if (array2 != null) {
893 int l = array.size();
894 for (int j=0; j<array2.size(); j++) {
895 array.set(l++, array2.get(j));
898 deleteObject(folder, i + 1, array, callback);
903 public void onError(Request request, Throwable exception) {
905 displayError("System error unable to delete folder: " + exception.getMessage());
909 catch (RequestException e) {
914 String path = folder.getUri();
915 DeleteRequest deleteFolder = new DeleteRequest(getApiPath(), getUsername(), URL.encode(path)) {
917 public void onSuccess(Resource result) {
918 updateFolder(folder.getParent(), true, new Command() {
921 public void execute() {
922 folderTreeSelectionModel.setSelected(folder.getParent(), true);
924 if (callback != null)
931 public void onError(Throwable t) {
934 if (t instanceof RestException) {
935 if (((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND)
936 displayError("Unable to delete folder: "+((RestException) t).getHttpStatusText());
941 displayError("System error unable to delete folder: " + t.getMessage());
945 protected void onUnauthorized(Response response) {
949 deleteFolder.setHeader("X-Auth-Token", getToken());
950 Scheduler.get().scheduleDeferred(deleteFolder);
954 public FolderTreeView getFolderTreeView() {
955 return folderTreeView;
958 public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
959 if (iter.hasNext()) {
960 File file = iter.next();
961 String path = targetUri + "/" + file.getName();
962 PutRequest copyFile = new PutRequest(getApiPath(), targetUsername, path) {
964 public void onSuccess(Resource result) {
965 copyFiles(iter, targetUsername, targetUri, callback);
969 public void onError(Throwable t) {
972 if (t instanceof RestException) {
973 displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
976 displayError("System error unable to copy file: "+t.getMessage());
980 protected void onUnauthorized(Response response) {
984 copyFile.setHeader("X-Auth-Token", getToken());
985 copyFile.setHeader("X-Copy-From", URL.encodePathSegment(file.getUri()));
986 if (!file.getOwner().equals(targetUsername))
987 copyFile.setHeader("X-Source-Account", URL.encodePathSegment(file.getOwner()));
988 copyFile.setHeader("Content-Type", file.getContentType());
989 Scheduler.get().scheduleDeferred(copyFile);
991 else if (callback != null) {
996 public void copySubfolders(final Iterator<Folder> iter, final String targetUsername, final String targetUri, final Command callback) {
997 if (iter.hasNext()) {
998 final Folder f = iter.next();
999 copyFolder(f, targetUsername, targetUri, new Command() {
1002 public void execute() {
1003 copySubfolders(iter, targetUsername, targetUri, callback);
1007 else if (callback != null) {
1012 public void copyFolder(final Folder f, final String targetUsername, final String targetUri, final Command callback) {
1013 String path = targetUri + "/" + f.getName();
1014 PutRequest createFolder = new PutRequest(getApiPath(), targetUsername, path) {
1016 public void onSuccess(Resource result) {
1017 GetRequest<Folder> getFolder = new GetRequest<Folder>(Folder.class, getApiPath(), f.getOwner(), "/" + f.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(f.getPrefix()), f) {
1020 public void onSuccess(final Folder _f) {
1021 Iterator<File> iter = _f.getFiles().iterator();
1022 copyFiles(iter, targetUsername, targetUri + "/" + _f.getName(), new Command() {
1024 public void execute() {
1025 Iterator<Folder> iterf = _f.getSubfolders().iterator();
1026 copySubfolders(iterf, targetUsername, targetUri + "/" + _f.getName(), callback);
1032 public void onError(Throwable t) {
1035 if (t instanceof RestException) {
1036 displayError("Unable to get folder: " + ((RestException) t).getHttpStatusText());
1039 displayError("System error getting folder: " + t.getMessage());
1043 protected void onUnauthorized(Response response) {
1047 getFolder.setHeader("X-Auth-Token", getToken());
1048 Scheduler.get().scheduleDeferred(getFolder);
1052 public void onError(Throwable t) {
1055 if (t instanceof RestException) {
1056 displayError("Unable to create folder: " + ((RestException) t).getHttpStatusText());
1059 displayError("System error creating folder: " + t.getMessage());
1063 protected void onUnauthorized(Response response) {
1067 createFolder.setHeader("X-Auth-Token", getToken());
1068 createFolder.setHeader("Accept", "*/*");
1069 createFolder.setHeader("Content-Length", "0");
1070 createFolder.setHeader("Content-Type", "application/folder");
1071 Scheduler.get().scheduleDeferred(createFolder);
1074 public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1075 selectionModels.add(model);
1078 public OtherSharedTreeView getOtherSharedTreeView() {
1079 return otherSharedTreeView;
1082 public void updateTrash(boolean showFiles, Command callback) {
1083 updateFolder(trash, showFiles, callback, true);
1086 public void updateGroupsNode() {
1087 groupTreeView.updateGroupNode(null);
1090 public void addGroup(String groupname) {
1091 Group newGroup = new Group(groupname);
1092 account.addGroup(newGroup);
1093 groupTreeView.updateGroupNode(null);
1096 public void removeGroup(Group group) {
1097 account.removeGroup(group);
1101 public TreeView getSelectedTree() {
1102 return selectedTree;
1105 public void setSelectedTree(TreeView selected) {
1106 selectedTree = selected;
1109 public Folder getSelection() {
1110 return selectedTree.getSelection();
1113 public void showFolderStatistics(int folderFileCount) {
1114 numOfFiles.setHTML(String.valueOf(folderFileCount));
1117 public GroupTreeView getGroupTreeView() {
1118 return groupTreeView;
1121 public void sessionExpired() {
1122 new SessionExpiredDialog(this).center();
1125 public void updateRootFolder(Command callback) {
1126 updateFolder(account.getPithos(), false, callback, true);
1129 void createMySharedTree() {
1130 mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1131 mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1133 public void onSelectionChange(SelectionChangeEvent event) {
1134 if (mysharedTreeSelectionModel.getSelectedObject() != null) {
1135 deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1136 upload.setEnabled(false);
1137 updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1138 showRelevantToolbarButtons();
1141 if (getSelectedTree().equals(mysharedTreeView))
1142 setSelectedTree(null);
1143 if (getSelectedTree() == null)
1144 showRelevantToolbarButtons();
1148 selectionModels.add(mysharedTreeSelectionModel);
1149 mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1150 mysharedTreeViewModel.initialize(new Command() {
1153 public void execute() {
1154 mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1155 trees.insert(mysharedTreeView, 4);
1156 treeViews.add(mysharedTreeView);
1157 createOtherSharedTree();
1162 void createOtherSharedTree() {
1163 otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1164 otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1166 public void onSelectionChange(SelectionChangeEvent event) {
1167 if (otherSharedTreeSelectionModel.getSelectedObject() != null) {
1168 deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1169 otherSharedTreeView.addStyleName("cellTreeWidget-selectedTree");
1170 applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1171 updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true);
1172 showRelevantToolbarButtons();
1175 if (getSelectedTree().equals(otherSharedTreeView))
1176 setSelectedTree(null);
1177 if (getSelectedTree() == null)
1178 showRelevantToolbarButtons();
1182 selectionModels.add(otherSharedTreeSelectionModel);
1183 otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1184 otherSharedTreeViewModel.initialize(new Command() {
1187 public void execute() {
1188 otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel);
1189 trees.insert(otherSharedTreeView, 4);
1190 treeViews.add(otherSharedTreeView);
1195 public native void log1(String message)/*-{
1196 $wnd.console.log(message);
1199 public String getErrorData() {
1201 return error.toString();
1205 public void setError(Throwable t) {
1209 public void showRelevantToolbarButtons() {
1210 toolbar.showRelevantButtons();
1213 public FileUploadDialog getFileUploadDialog() {
1214 if (fileUploadDialog == null)
1215 fileUploadDialog = new FileUploadDialog(this);
1216 return fileUploadDialog;
1219 public void hideUploadIndicator() {
1220 upload.removeStyleName("pithos-uploadButton-loading");
1221 upload.setTitle("");
1224 public void showUploadIndicator() {
1225 upload.addStyleName("pithos-uploadButton-loading");
1226 upload.setTitle("Upload in progress. Click for details.");
1229 public void scheduleFolderHeadCommand(final Folder folder, final Command callback) {
1230 if (folder == null) {
1231 if (callback != null)
1235 HeadRequest<Folder> headFolder = new HeadRequest<Folder>(Folder.class, getApiPath(), folder.getOwner(), folder.getUri(), folder) {
1238 public void onSuccess(Folder _result) {
1239 if (callback != null)
1244 public void onError(Throwable t) {
1245 if (t instanceof RestException) {
1246 if (((RestException) t).getHttpStatusCode() == Response.SC_NOT_FOUND) {
1247 final String path = folder.getUri();
1248 PutRequest newFolder = new PutRequest(getApiPath(), folder.getOwner(), path) {
1250 public void onSuccess(Resource _result) {
1251 scheduleFolderHeadCommand(folder, callback);
1255 public void onError(Throwable _t) {
1258 if(_t instanceof RestException){
1259 displayError("Unable to create folder: " + ((RestException) _t).getHttpStatusText());
1262 displayError("System error creating folder: " + _t.getMessage());
1266 protected void onUnauthorized(Response response) {
1270 newFolder.setHeader("X-Auth-Token", getToken());
1271 newFolder.setHeader("Content-Type", "application/folder");
1272 newFolder.setHeader("Accept", "*/*");
1273 newFolder.setHeader("Content-Length", "0");
1274 Scheduler.get().scheduleDeferred(newFolder);
1277 displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
1280 displayError("System error heading folder: " + t.getMessage());
1282 GWT.log("Error heading folder", t);
1287 protected void onUnauthorized(Response response) {
1291 headFolder.setHeader("X-Auth-Token", getToken());
1292 Scheduler.get().scheduleDeferred(headFolder);
1296 public void scheduleFileHeadCommand(File f, final Command callback) {
1297 HeadRequest<File> headFile = new HeadRequest<File>(File.class, getApiPath(), f.getOwner(), f.getUri(), f) {
1300 public void onSuccess(File _result) {
1301 if (callback != null)
1306 public void onError(Throwable t) {
1307 GWT.log("Error heading file", t);
1309 if (t instanceof RestException)
1310 displayError("Error heading file: " + ((RestException) t).getHttpStatusText());
1312 displayError("System error heading file: " + t.getMessage());
1316 protected void onUnauthorized(Response response) {
1320 headFile.setHeader("X-Auth-Token", getToken());
1321 Scheduler.get().scheduleDeferred(headFile);