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.PithosDisclosurePanel.Style;
38 import gr.grnet.pithos.web.client.commands.UploadFileCommand;
39 import gr.grnet.pithos.web.client.foldertree.AccountResource;
40 import gr.grnet.pithos.web.client.foldertree.File;
41 import gr.grnet.pithos.web.client.foldertree.Folder;
42 import gr.grnet.pithos.web.client.foldertree.FolderTreeView;
43 import gr.grnet.pithos.web.client.foldertree.FolderTreeViewModel;
44 import gr.grnet.pithos.web.client.foldertree.Resource;
45 import gr.grnet.pithos.web.client.grouptree.Group;
46 import gr.grnet.pithos.web.client.grouptree.GroupTreeView;
47 import gr.grnet.pithos.web.client.grouptree.GroupTreeViewModel;
48 import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeView;
49 import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeViewModel;
50 import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeView;
51 import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeViewModel;
52 import gr.grnet.pithos.web.client.rest.DeleteRequest;
53 import gr.grnet.pithos.web.client.rest.GetRequest;
54 import gr.grnet.pithos.web.client.rest.HeadRequest;
55 import gr.grnet.pithos.web.client.rest.PutRequest;
56 import gr.grnet.pithos.web.client.rest.RestException;
58 import java.util.ArrayList;
59 import java.util.HashMap;
60 import java.util.Iterator;
61 import java.util.List;
64 import com.google.gwt.core.client.EntryPoint;
65 import com.google.gwt.core.client.GWT;
66 import com.google.gwt.core.client.Scheduler;
67 import com.google.gwt.core.client.Scheduler.RepeatingCommand;
68 import com.google.gwt.core.client.Scheduler.ScheduledCommand;
69 import com.google.gwt.event.dom.client.ClickEvent;
70 import com.google.gwt.event.dom.client.ClickHandler;
71 import com.google.gwt.event.logical.shared.ResizeEvent;
72 import com.google.gwt.event.logical.shared.ResizeHandler;
73 import com.google.gwt.http.client.Request;
74 import com.google.gwt.http.client.RequestBuilder;
75 import com.google.gwt.http.client.RequestCallback;
76 import com.google.gwt.http.client.RequestException;
77 import com.google.gwt.http.client.Response;
78 import com.google.gwt.http.client.URL;
79 import com.google.gwt.i18n.client.Dictionary;
80 import com.google.gwt.i18n.client.NumberFormat;
81 import com.google.gwt.json.client.JSONArray;
82 import com.google.gwt.json.client.JSONObject;
83 import com.google.gwt.json.client.JSONParser;
84 import com.google.gwt.json.client.JSONString;
85 import com.google.gwt.json.client.JSONValue;
86 import com.google.gwt.resources.client.ClientBundle;
87 import com.google.gwt.resources.client.CssResource;
88 import com.google.gwt.resources.client.ImageResource;
89 import com.google.gwt.resources.client.ClientBundle.Source;
90 import com.google.gwt.resources.client.ImageResource.ImageOptions;
91 import com.google.gwt.user.client.Command;
92 import com.google.gwt.user.client.Cookies;
93 import com.google.gwt.user.client.Event;
94 import com.google.gwt.user.client.History;
95 import com.google.gwt.user.client.Window;
96 import com.google.gwt.user.client.ui.AbstractImagePrototype;
97 import com.google.gwt.user.client.ui.Button;
98 import com.google.gwt.user.client.ui.Composite;
99 import com.google.gwt.user.client.ui.HTML;
100 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
101 import com.google.gwt.user.client.ui.HasVerticalAlignment;
102 import com.google.gwt.user.client.ui.HorizontalPanel;
103 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
104 import com.google.gwt.user.client.ui.RootPanel;
105 import com.google.gwt.user.client.ui.VerticalPanel;
106 import com.google.gwt.view.client.SelectionChangeEvent;
107 import com.google.gwt.view.client.SelectionChangeEvent.Handler;
108 import com.google.gwt.view.client.SingleSelectionModel;
111 * Entry point classes define <code>onModuleLoad()</code>.
113 public class Pithos implements EntryPoint, ResizeHandler {
115 public static final String HOME_CONTAINER = "pithos";
117 public static final String TRASH_CONTAINER = "trash";
119 public static final Configuration config = GWT.create(Configuration.class);
121 public interface Style extends CssResource {
122 String commandAnchor();
125 public interface Resources extends ClientBundle {
126 @Source("Pithos.css")
130 public static Resources resources = GWT.create(Resources.class);
133 * Instantiate an application-level image bundle. This object will provide
134 * programmatic access to all the images needed by widgets.
136 static Images images = (Images) GWT.create(Images.class);
138 public String getUsername() {
142 public void setAccount(AccountResource acct) {
146 public AccountResource getAccount() {
150 public void updateFolder(Folder f, boolean showfiles, Command callback, final boolean openParent) {
151 folderTreeView.updateFolder(f, showfiles, callback, openParent);
154 public void updateGroupNode(Group group) {
155 groupTreeView.updateGroupNode(group);
158 public void updateMySharedRoot() {
159 mysharedTreeView.updateRoot();
162 public void updateSharedFolder(Folder f, boolean showfiles, Command callback) {
163 mysharedTreeView.updateFolder(f, showfiles, callback);
166 public void updateSharedFolder(Folder f, boolean showfiles) {
167 updateSharedFolder(f, showfiles, null);
170 public void updateOtherSharedFolder(Folder f, boolean showfiles) {
171 otherSharedTreeView.updateFolder(f, showfiles);
174 public MysharedTreeView getMySharedTreeView() {
175 return mysharedTreeView;
179 * An aggregate image bundle that pulls together all the images for this
180 * application into a single bundle.
182 public interface Images extends TopPanel.Images, FileList.Images, ToolsMenu.Images {
184 @Source("gr/grnet/pithos/resources/document.png")
185 ImageResource folders();
187 @Source("gr/grnet/pithos/resources/advancedsettings.png")
188 @ImageOptions(width=32, height=32)
189 ImageResource tools();
192 private Throwable error;
195 * The Application Clipboard implementation;
197 private Clipboard clipboard = new Clipboard();
200 * The top panel that contains the menu bar.
202 private TopPanel topPanel;
205 * The panel that contains the various system messages.
207 private MessagePanel messagePanel = new MessagePanel(this, Pithos.images);
210 * The bottom panel that contains the status bar.
212 private StatusPanel statusPanel = null;
215 * The file list widget.
217 private FileList fileList;
220 * The tab panel that occupies the right side of the screen.
222 private VerticalPanel inner = new VerticalPanel();
226 * The split panel that will contain the left and right panels.
228 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
231 * The currently selected item in the application, for use by the Edit menu
232 * commands. Potential types are Folder, File, User and Group.
234 private Object currentSelection;
236 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
238 private String username = null;
241 * The authentication token of the current user.
243 private String token;
247 SingleSelectionModel<Folder> folderTreeSelectionModel;
248 FolderTreeViewModel folderTreeViewModel;
249 FolderTreeView folderTreeView;
251 SingleSelectionModel<Folder> mysharedTreeSelectionModel;
252 MysharedTreeViewModel mysharedTreeViewModel;
253 MysharedTreeView mysharedTreeView = null;;
255 protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
256 OtherSharedTreeViewModel otherSharedTreeViewModel;
257 OtherSharedTreeView otherSharedTreeView = null;
259 GroupTreeViewModel groupTreeViewModel;
260 GroupTreeView groupTreeView;
262 TreeView selectedTree;
263 protected AccountResource account;
267 List<Composite> treeViews = new ArrayList<Composite>();
269 @SuppressWarnings("rawtypes") List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
273 private HTML numOfFiles;
275 private Toolbar toolbar;
277 private FileUploadDialog fileUploadDialog;
280 public void onModuleLoad() {
281 if (parseUserCredentials())
285 private void initialize() {
286 resources.pithosCss().ensureInjected();
287 boolean bareContent = Window.Location.getParameter("noframe") != null;
288 String contentWidth = bareContent ? "100%" : "75%";
290 VerticalPanel outer = new VerticalPanel();
291 outer.setWidth("100%");
293 outer.addStyleName("pithos-outer");
297 topPanel = new TopPanel(this, Pithos.images);
298 topPanel.setWidth("100%");
300 outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
303 messagePanel.setVisible(false);
304 outer.add(messagePanel);
305 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
306 outer.setCellVerticalAlignment(messagePanel, HasVerticalAlignment.ALIGN_MIDDLE);
308 HorizontalPanel header = new HorizontalPanel();
309 header.addStyleName("pithos-header");
310 header.setWidth(contentWidth);
312 header.addStyleName("pithos-header-noframe");
313 upload = new Button("Upload", new ClickHandler() {
315 public void onClick(ClickEvent event) {
316 if (getSelection() != null)
317 new UploadFileCommand(Pithos.this, null, getSelection()).execute();
320 upload.addStyleName("pithos-uploadButton");
322 header.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_LEFT);
323 header.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
325 toolbar = new Toolbar(this);
327 header.setCellHorizontalAlignment(toolbar, HasHorizontalAlignment.ALIGN_CENTER);
328 header.setCellVerticalAlignment(toolbar, HasVerticalAlignment.ALIGN_MIDDLE);
330 HorizontalPanel folderStatistics = new HorizontalPanel();
331 folderStatistics.addStyleName("pithos-folderStatistics");
332 numOfFiles = new HTML();
333 folderStatistics.add(numOfFiles);
334 folderStatistics.setCellVerticalAlignment(numOfFiles, HasVerticalAlignment.ALIGN_MIDDLE);
335 HTML numOfFilesLabel = new HTML(" Files");
336 folderStatistics.add(numOfFilesLabel);
337 folderStatistics.setCellVerticalAlignment(numOfFilesLabel, HasVerticalAlignment.ALIGN_MIDDLE);
338 header.add(folderStatistics);
339 header.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
340 header.setCellVerticalAlignment(folderStatistics, HasVerticalAlignment.ALIGN_MIDDLE);
341 header.setCellWidth(folderStatistics, "40px");
343 outer.setCellHorizontalAlignment(header, HasHorizontalAlignment.ALIGN_CENTER);
344 // Inner contains the various lists.nner
345 inner.sinkEvents(Event.ONCONTEXTMENU);
346 inner.setWidth("100%");
348 folderTreeSelectionModel = new SingleSelectionModel<Folder>();
349 folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
351 public void onSelectionChange(SelectionChangeEvent event) {
352 if (folderTreeSelectionModel.getSelectedObject() != null) {
353 deselectOthers(folderTreeView, folderTreeSelectionModel);
354 applyPermissions(folderTreeSelectionModel.getSelectedObject());
355 Folder f = folderTreeSelectionModel.getSelectedObject();
356 updateFolder(f, true, new Command() {
359 public void execute() {
363 showRelevantToolbarButtons();
366 if (getSelectedTree().equals(folderTreeView))
367 setSelectedTree(null);
368 if (getSelectedTree() == null)
369 showRelevantToolbarButtons();
373 selectionModels.add(folderTreeSelectionModel);
375 folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
376 folderTreeView = new FolderTreeView(folderTreeViewModel);
377 treeViews.add(folderTreeView);
379 fileList = new FileList(this, images);
382 trees = new VerticalPanel();
383 trees.setWidth("100%");
385 // Add the left and right panels to the split panel.
386 splitPanel.setLeftWidget(trees);
387 splitPanel.setRightWidget(inner);
388 splitPanel.setSplitPosition("219px");
389 splitPanel.setSize("100%", "100%");
390 splitPanel.addStyleName("pithos-splitPanel");
391 splitPanel.setWidth(contentWidth);
392 outer.add(splitPanel);
393 outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
396 statusPanel = new StatusPanel();
397 statusPanel.setWidth("100%");
398 outer.add(statusPanel);
399 outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
402 splitPanel.addStyleName("pithos-splitPanel-noframe");
404 // Hook the window resize event, so that we can adjust the UI.
405 Window.addResizeHandler(this);
406 // Clear out the window's built-in margin, because we want to take
407 // advantage of the entire client area.
408 Window.setMargin("0px");
409 // Finally, add the outer panel to the RootPanel, so that it will be
411 RootPanel.get().add(outer);
412 // Call the window resized handler to get the initial sizes setup. Doing
413 // this in a deferred command causes it to occur after all widgets'
414 // sizes have been computed by the browser.
415 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
418 public void execute() {
419 onWindowResized(Window.getClientHeight());
423 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
425 public void execute() {
426 fetchAccount(new Command() {
429 public void execute() {
430 if (!account.hasHomeContainer())
431 createHomeContainer(account, this);
432 else if (!account.hasTrashContainer())
433 createTrashContainer(this);
435 for (Folder f : account.getContainers())
436 if (f.getName().equals(Pithos.TRASH_CONTAINER)) {
440 trees.add(folderTreeView);
441 folderTreeViewModel.initialize(account, new Command() {
444 public void execute() {
445 createMySharedTree();
449 HorizontalPanel separator = new HorizontalPanel();
450 separator.addStyleName("pithos-statisticsSeparator");
451 separator.add(new HTML(""));
452 trees.add(separator);
454 groupTreeViewModel = new GroupTreeViewModel(Pithos.this);
455 groupTreeView = new GroupTreeView(groupTreeViewModel);
456 treeViews.add(groupTreeView);
457 trees.add(groupTreeView);
458 folderTreeView.showStatistics(account);
465 Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {
468 public boolean execute() {
469 Folder f = getSelection();
471 if (getSelectedTree().equals(folderTreeView))
472 updateFolder(f, true, null, false);
473 else if (getSelectedTree().equals(mysharedTreeView))
474 updateSharedFolder(f, true);
481 public void applyPermissions(Folder f) {
484 upload.setEnabled(false);
486 Boolean[] perms = f.getPermissions().get(username);
487 if (f.getOwner().equals(username) || (perms != null && perms[1] != null && perms[1])) {
488 upload.setEnabled(true);
491 upload.setEnabled(false);
495 upload.setEnabled(false);
498 @SuppressWarnings({ "rawtypes", "unchecked" })
499 public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
500 selectedTree = _selectedTree;
502 for (SingleSelectionModel s : selectionModels)
503 if (!s.equals(model) && s.getSelectedObject() != null)
504 s.setSelected(s.getSelectedObject(), false);
507 public void showFiles(final Folder f) {
508 Set<File> files = f.getFiles();
512 public void showFiles(Set<File> files) {
513 fileList.setFiles(new ArrayList<File>(files));
517 * Parse and store the user credentials to the appropriate fields.
519 private boolean parseUserCredentials() {
520 Configuration conf = (Configuration) GWT.create(Configuration.class);
521 Dictionary otherProperties = Dictionary.getDictionary("otherProperties");
522 String cookie = otherProperties.get("authCookie");
523 String auth = Cookies.getCookie(cookie);
528 if (auth.startsWith("\""))
529 auth = auth.substring(1);
530 if (auth.endsWith("\""))
531 auth = auth.substring(0, auth.length() - 1);
532 String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
533 if (authSplit.length != 2) {
537 username = authSplit[0];
538 token = authSplit[1];
540 String gotoUrl = Window.Location.getParameter("goto");
541 if (gotoUrl != null && gotoUrl.length() > 0) {
542 Window.Location.assign(gotoUrl);
549 * Redirect the user to the login page for authentication.
551 protected void authenticateUser() {
552 Dictionary otherProperties = Dictionary.getDictionary("otherProperties");
553 Window.Location.assign(otherProperties.get("loginUrl") + Window.Location.getHref());
556 protected void fetchAccount(final Command callback) {
557 String path = "?format=json";
559 GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getApiPath(), username, path) {
561 public void onSuccess(AccountResource _result) {
563 if (callback != null)
568 public void onError(Throwable t) {
569 GWT.log("Error getting account", t);
571 if (t instanceof RestException)
572 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
574 displayError("System error fetching user data: " + t.getMessage());
578 protected void onUnauthorized(Response response) {
582 getAccount.setHeader("X-Auth-Token", token);
583 Scheduler.get().scheduleDeferred(getAccount);
586 public void updateStatistics() {
587 HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getApiPath(), username, "", account) {
590 public void onSuccess(AccountResource _result) {
591 folderTreeView.showStatistics(account);
595 public void onError(Throwable t) {
596 GWT.log("Error getting account", t);
598 if (t instanceof RestException)
599 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
601 displayError("System error fetching user data: " + t.getMessage());
605 protected void onUnauthorized(Response response) {
609 headAccount.setHeader("X-Auth-Token", token);
610 Scheduler.get().scheduleDeferred(headAccount);
613 protected void createHomeContainer(final AccountResource _account, final Command callback) {
614 String path = "/" + Pithos.HOME_CONTAINER;
615 PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
617 public void onSuccess(Resource result) {
618 if (!_account.hasTrashContainer())
619 createTrashContainer(callback);
621 fetchAccount(callback);
625 public void onError(Throwable t) {
626 GWT.log("Error creating pithos", t);
628 if (t instanceof RestException)
629 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
631 displayError("System error Error creating pithos: " + t.getMessage());
635 protected void onUnauthorized(Response response) {
639 createPithos.setHeader("X-Auth-Token", getToken());
640 Scheduler.get().scheduleDeferred(createPithos);
643 protected void createTrashContainer(final Command callback) {
644 String path = "/" + Pithos.TRASH_CONTAINER;
645 PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
647 public void onSuccess(Resource result) {
648 fetchAccount(callback);
652 public void onError(Throwable t) {
653 GWT.log("Error creating pithos", t);
655 if (t instanceof RestException)
656 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
658 displayError("System error Error creating pithos: " + t.getMessage());
662 protected void onUnauthorized(Response response) {
666 createPithos.setHeader("X-Auth-Token", getToken());
667 Scheduler.get().scheduleDeferred(createPithos);
671 * Creates an HTML fragment that places an image & caption together, for use
674 * @param imageProto an image prototype for an image
675 * @param caption the group caption
676 * @return the header HTML fragment
678 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
679 String captionHTML = "<table class='caption' cellpadding='0' "
680 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
681 + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'> "
682 + caption + "</b></td></tr></table>";
686 protected void onWindowResized(int height) {
687 // Adjust the split panel to take up the available room in the window.
688 int newHeight = height - splitPanel.getAbsoluteTop();
691 splitPanel.setHeight("" + newHeight);
692 inner.setHeight("" + newHeight);
696 public void onResize(ResizeEvent event) {
697 int height = event.getHeight();
698 onWindowResized(height);
702 * Display an error message.
704 * @param msg the message to display
706 public void displayError(String msg) {
707 messagePanel.displayError(msg);
711 * Display a warning message.
713 * @param msg the message to display
715 public void displayWarning(String msg) {
716 messagePanel.displayWarning(msg);
720 * Display an informational message.
722 * @param msg the message to display
724 public void displayInformation(String msg) {
725 messagePanel.displayInformation(msg);
729 * Retrieve the fileList.
731 * @return the fileList
733 public FileList getFileList() {
738 * Retrieve the topPanel.
740 * @return the topPanel
742 TopPanel getTopPanel() {
747 * Retrieve the clipboard.
749 * @return the clipboard
751 public Clipboard getClipboard() {
755 public StatusPanel getStatusPanel() {
759 public String getToken() {
763 public static native void preventIESelection() /*-{
764 $doc.body.onselectstart = function () { return false; };
767 public static native void enableIESelection() /*-{
768 if ($doc.body.onselectstart != null)
769 $doc.body.onselectstart = null;
773 * @return the absolute path of the API root URL
775 public String getApiPath() {
776 Configuration conf = (Configuration) GWT.create(Configuration.class);
777 return conf.apiPath();
781 * History support for folder navigation
782 * adds a new browser history entry
786 public void updateHistory(String key){
787 // Replace any whitespace of the initial string to "+"
788 // String result = key.replaceAll("\\s","+");
789 // Add a new browser history entry.
790 // History.newItem(result);
791 History.newItem(key);
794 public void deleteFolder(final Folder folder, final Command callback) {
795 String path = getApiPath() + folder.getOwner() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(folder.getPrefix()) + "&t=" + System.currentTimeMillis();
796 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
797 builder.setHeader("X-Auth-Token", getToken());
799 builder.sendRequest("", new RequestCallback() {
801 public void onResponseReceived(Request request, Response response) {
802 if (response.getStatusCode() == Response.SC_OK) {
803 JSONValue json = JSONParser.parseStrict(response.getText());
804 JSONArray array = json.isArray();
807 deleteObject(folder, i, array, callback);
813 public void onError(Request request, Throwable exception) {
815 displayError("System error unable to delete folder: " + exception.getMessage());
819 catch (RequestException e) {
823 void deleteObject(final Folder folder, final int i, final JSONArray array, final Command callback) {
824 if (i < array.size()) {
825 JSONObject o = array.get(i).isObject();
826 if (o != null && !o.containsKey("subdir")) {
827 JSONString name = o.get("name").isString();
828 String path = "/" + folder.getContainer() + "/" + name.stringValue();
829 DeleteRequest delete = new DeleteRequest(getApiPath(), folder.getOwner(), URL.encode(path)) {
831 public void onSuccess(Resource result) {
832 deleteObject(folder, i + 1, array, callback);
836 public void onError(Throwable t) {
839 displayError("System error unable to delete folder: " + t.getMessage());
843 protected void onUnauthorized(Response response) {
847 delete.setHeader("X-Auth-Token", getToken());
848 Scheduler.get().scheduleDeferred(delete);
850 else if (o != null) {
851 String subdir = o.get("subdir").isString().stringValue();
852 subdir = subdir.substring(0, subdir.length() - 1);
853 String path = getApiPath() + getUsername() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(subdir) + "&t=" + System.currentTimeMillis();
854 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
855 builder.setHeader("X-Auth-Token", getToken());
857 builder.sendRequest("", new RequestCallback() {
859 public void onResponseReceived(Request request, Response response) {
860 if (response.getStatusCode() == Response.SC_OK) {
861 JSONValue json = JSONParser.parseStrict(response.getText());
862 JSONArray array2 = json.isArray();
863 if (array2 != null) {
864 int l = array.size();
865 for (int j=0; j<array2.size(); j++) {
866 array.set(l++, array2.get(j));
869 deleteObject(folder, i + 1, array, callback);
874 public void onError(Request request, Throwable exception) {
876 displayError("System error unable to delete folder: " + exception.getMessage());
880 catch (RequestException e) {
885 String path = folder.getUri();
886 DeleteRequest deleteFolder = new DeleteRequest(getApiPath(), getUsername(), URL.encode(path)) {
888 public void onSuccess(Resource result) {
889 updateFolder(folder.getParent(), true, new Command() {
892 public void execute() {
893 folderTreeSelectionModel.setSelected(folder.getParent(), true);
895 if (callback != null)
902 public void onError(Throwable t) {
905 if (t instanceof RestException) {
906 if (((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND)
907 displayError("Unable to delete folder: "+((RestException) t).getHttpStatusText());
912 displayError("System error unable to delete folder: " + t.getMessage());
916 protected void onUnauthorized(Response response) {
920 deleteFolder.setHeader("X-Auth-Token", getToken());
921 Scheduler.get().scheduleDeferred(deleteFolder);
925 public FolderTreeView getFolderTreeView() {
926 return folderTreeView;
929 public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
930 if (iter.hasNext()) {
931 File file = iter.next();
932 String path = targetUri + "/" + file.getName();
933 PutRequest copyFile = new PutRequest(getApiPath(), targetUsername, path) {
935 public void onSuccess(Resource result) {
936 copyFiles(iter, targetUsername, targetUri, callback);
940 public void onError(Throwable t) {
943 if (t instanceof RestException) {
944 displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
947 displayError("System error unable to copy file: "+t.getMessage());
951 protected void onUnauthorized(Response response) {
955 copyFile.setHeader("X-Auth-Token", getToken());
956 copyFile.setHeader("X-Copy-From", URL.encodePathSegment(file.getUri()));
957 if (!file.getOwner().equals(targetUsername))
958 copyFile.setHeader("X-Source-Account", URL.encodePathSegment(file.getOwner()));
959 copyFile.setHeader("Content-Type", file.getContentType());
960 Scheduler.get().scheduleDeferred(copyFile);
962 else if (callback != null) {
967 public void copySubfolders(final Iterator<Folder> iter, final String targetUsername, final String targetUri, final Command callback) {
968 if (iter.hasNext()) {
969 final Folder f = iter.next();
970 copyFolder(f, targetUsername, targetUri, new Command() {
973 public void execute() {
974 copySubfolders(iter, targetUsername, targetUri, callback);
978 else if (callback != null) {
983 public void copyFolder(final Folder f, final String targetUsername, final String targetUri, final Command callback) {
984 String path = targetUri + "/" + f.getName();
985 PutRequest createFolder = new PutRequest(getApiPath(), targetUsername, path) {
987 public void onSuccess(Resource result) {
988 GetRequest<Folder> getFolder = new GetRequest<Folder>(Folder.class, getApiPath(), f.getOwner(), "/" + f.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(f.getPrefix()), f) {
991 public void onSuccess(final Folder _f) {
992 Iterator<File> iter = _f.getFiles().iterator();
993 copyFiles(iter, targetUsername, targetUri + "/" + _f.getName(), new Command() {
995 public void execute() {
996 Iterator<Folder> iterf = _f.getSubfolders().iterator();
997 copySubfolders(iterf, targetUsername, targetUri + "/" + _f.getName(), callback);
1003 public void onError(Throwable t) {
1006 if (t instanceof RestException) {
1007 displayError("Unable to get folder: " + ((RestException) t).getHttpStatusText());
1010 displayError("System error getting folder: " + t.getMessage());
1014 protected void onUnauthorized(Response response) {
1018 getFolder.setHeader("X-Auth-Token", getToken());
1019 Scheduler.get().scheduleDeferred(getFolder);
1023 public void onError(Throwable t) {
1026 if (t instanceof RestException) {
1027 displayError("Unable to create folder: " + ((RestException) t).getHttpStatusText());
1030 displayError("System error creating folder: " + t.getMessage());
1034 protected void onUnauthorized(Response response) {
1038 createFolder.setHeader("X-Auth-Token", getToken());
1039 createFolder.setHeader("Accept", "*/*");
1040 createFolder.setHeader("Content-Length", "0");
1041 createFolder.setHeader("Content-Type", "application/folder");
1042 Scheduler.get().scheduleDeferred(createFolder);
1045 public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1046 selectionModels.add(model);
1049 public OtherSharedTreeView getOtherSharedTreeView() {
1050 return otherSharedTreeView;
1053 public void updateTrash(boolean showFiles, Command callback) {
1054 updateFolder(trash, showFiles, callback, true);
1057 public void updateGroupsNode() {
1058 groupTreeView.updateGroupNode(null);
1061 public Group addGroup(String groupname) {
1062 Group newGroup = new Group(groupname);
1063 account.addGroup(newGroup);
1064 groupTreeView.updateGroupNode(null);
1068 public void removeGroup(Group group) {
1069 account.removeGroup(group);
1073 public TreeView getSelectedTree() {
1074 return selectedTree;
1077 public void setSelectedTree(TreeView selected) {
1078 selectedTree = selected;
1081 public Folder getSelection() {
1082 if (selectedTree != null)
1083 return selectedTree.getSelection();
1087 public void showFolderStatistics(int folderFileCount) {
1088 numOfFiles.setHTML(String.valueOf(folderFileCount));
1091 public GroupTreeView getGroupTreeView() {
1092 return groupTreeView;
1095 public void sessionExpired() {
1096 new SessionExpiredDialog(this).center();
1099 public void updateRootFolder(Command callback) {
1100 updateFolder(account.getPithos(), false, callback, true);
1103 void createMySharedTree() {
1104 mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1105 mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1107 public void onSelectionChange(SelectionChangeEvent event) {
1108 if (mysharedTreeSelectionModel.getSelectedObject() != null) {
1109 deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1110 upload.setEnabled(false);
1111 updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1112 showRelevantToolbarButtons();
1115 if (getSelectedTree().equals(mysharedTreeView))
1116 setSelectedTree(null);
1117 if (getSelectedTree() == null)
1118 showRelevantToolbarButtons();
1122 selectionModels.add(mysharedTreeSelectionModel);
1123 mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1124 mysharedTreeViewModel.initialize(new Command() {
1127 public void execute() {
1128 mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1129 trees.insert(mysharedTreeView, 2);
1130 treeViews.add(mysharedTreeView);
1131 createOtherSharedTree();
1136 void createOtherSharedTree() {
1137 otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1138 otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1140 public void onSelectionChange(SelectionChangeEvent event) {
1141 if (otherSharedTreeSelectionModel.getSelectedObject() != null) {
1142 deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1143 applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1144 updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true);
1145 showRelevantToolbarButtons();
1148 if (getSelectedTree().equals(otherSharedTreeView))
1149 setSelectedTree(null);
1150 if (getSelectedTree() == null)
1151 showRelevantToolbarButtons();
1155 selectionModels.add(otherSharedTreeSelectionModel);
1156 otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1157 otherSharedTreeViewModel.initialize(new Command() {
1160 public void execute() {
1161 otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel);
1162 trees.insert(otherSharedTreeView, 1);
1163 treeViews.add(otherSharedTreeView);
1168 public native void log1(String message)/*-{
1169 $wnd.console.log(message);
1172 public String getErrorData() {
1174 return error.toString();
1178 public void setError(Throwable t) {
1182 public void showRelevantToolbarButtons() {
1183 toolbar.showRelevantButtons();
1186 public FileUploadDialog getFileUploadDialog() {
1187 if (fileUploadDialog == null)
1188 fileUploadDialog = new FileUploadDialog(this);
1189 return fileUploadDialog;
1192 public void hideUploadIndicator() {
1193 upload.removeStyleName("pithos-uploadButton-loading");
1194 upload.setTitle("");
1197 public void showUploadIndicator() {
1198 upload.addStyleName("pithos-uploadButton-loading");
1199 upload.setTitle("Upload in progress. Click for details.");
1202 public void scheduleFolderHeadCommand(final Folder folder, final Command callback) {
1203 if (folder == null) {
1204 if (callback != null)
1208 HeadRequest<Folder> headFolder = new HeadRequest<Folder>(Folder.class, getApiPath(), folder.getOwner(), folder.getUri(), folder) {
1211 public void onSuccess(Folder _result) {
1212 if (callback != null)
1217 public void onError(Throwable t) {
1218 if (t instanceof RestException) {
1219 if (((RestException) t).getHttpStatusCode() == Response.SC_NOT_FOUND) {
1220 final String path = folder.getUri();
1221 PutRequest newFolder = new PutRequest(getApiPath(), folder.getOwner(), path) {
1223 public void onSuccess(Resource _result) {
1224 scheduleFolderHeadCommand(folder, callback);
1228 public void onError(Throwable _t) {
1231 if(_t instanceof RestException){
1232 displayError("Unable to create folder: " + ((RestException) _t).getHttpStatusText());
1235 displayError("System error creating folder: " + _t.getMessage());
1239 protected void onUnauthorized(Response response) {
1243 newFolder.setHeader("X-Auth-Token", getToken());
1244 newFolder.setHeader("Content-Type", "application/folder");
1245 newFolder.setHeader("Accept", "*/*");
1246 newFolder.setHeader("Content-Length", "0");
1247 Scheduler.get().scheduleDeferred(newFolder);
1250 displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
1253 displayError("System error heading folder: " + t.getMessage());
1255 GWT.log("Error heading folder", t);
1260 protected void onUnauthorized(Response response) {
1264 headFolder.setHeader("X-Auth-Token", getToken());
1265 Scheduler.get().scheduleDeferred(headFolder);
1269 public void scheduleFileHeadCommand(File f, final Command callback) {
1270 HeadRequest<File> headFile = new HeadRequest<File>(File.class, getApiPath(), f.getOwner(), f.getUri(), f) {
1273 public void onSuccess(File _result) {
1274 if (callback != null)
1279 public void onError(Throwable t) {
1280 GWT.log("Error heading file", t);
1282 if (t instanceof RestException)
1283 displayError("Error heading file: " + ((RestException) t).getHttpStatusText());
1285 displayError("System error heading file: " + t.getMessage());
1289 protected void onUnauthorized(Response response) {
1293 headFile.setHeader("X-Auth-Token", getToken());
1294 Scheduler.get().scheduleDeferred(headFile);
1297 public boolean isMySharedSelected() {
1298 return getSelectedTree().equals(getMySharedTreeView());