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;
56 import gr.grnet.pithos.web.client.tagtree.Tag;
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.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) {
136 folderTreeView.updateFolder(f, showfiles, callback);
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() {
350 showRelevantToolbarButtons();
353 selectionModels.add(folderTreeSelectionModel);
355 folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
356 folderTreeView = new FolderTreeView(folderTreeViewModel);
357 treeViews.add(folderTreeView);
359 fileList = new FileList(this, images, folderTreeView);
362 groupTreeViewModel = new GroupTreeViewModel(this);
363 groupTreeView = new GroupTreeView(groupTreeViewModel);
364 treeViews.add(groupTreeView);
366 trees = new VerticalPanel();
367 trees.setWidth("100%");
370 HorizontalPanel treeHeader = new HorizontalPanel();
371 treeHeader.addStyleName("pithos-treeHeader");
372 treeHeader.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
373 treeHeader.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
374 HorizontalPanel statistics = new HorizontalPanel();
375 statistics.addStyleName("pithos-statistics");
376 statistics.add(new HTML("Used: "));
377 usedBytes = new HTML();
378 statistics.add(usedBytes);
379 statistics.add(new HTML(" of "));
380 totalBytes = new HTML();
381 statistics.add(totalBytes);
382 statistics.add(new HTML(" ("));
383 usedPercent = new HTML();
384 statistics.add(usedPercent);
385 statistics.add(new HTML(")"));
386 treeHeader.add(statistics);
387 treeHeader.setCellHorizontalAlignment(statistics, HasHorizontalAlignment.ALIGN_LEFT);
388 trees.add(treeHeader);
390 trees.add(folderTreeView);
391 trees.add(groupTreeView);
392 // Add the left and right panels to the split panel.
393 splitPanel.setLeftWidget(trees);
394 splitPanel.setRightWidget(inner);
395 splitPanel.setSplitPosition("35%");
396 splitPanel.setSize("100%", "100%");
397 splitPanel.addStyleName("pithos-splitPanel");
398 splitPanel.setWidth(contentWidth);
399 outer.add(splitPanel);
400 outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
403 statusPanel = new StatusPanel();
404 statusPanel.setWidth("100%");
405 outer.add(statusPanel);
406 outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
409 splitPanel.addStyleName("pithos-splitPanel-noframe");
411 // Hook the window resize event, so that we can adjust the UI.
412 Window.addResizeHandler(this);
413 // Clear out the window's built-in margin, because we want to take
414 // advantage of the entire client area.
415 Window.setMargin("0px");
416 // Finally, add the outer panel to the RootPanel, so that it will be
418 RootPanel.get().add(outer);
419 // Call the window resized handler to get the initial sizes setup. Doing
420 // this in a deferred command causes it to occur after all widgets'
421 // sizes have been computed by the browser.
422 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
425 public void execute() {
426 onWindowResized(Window.getClientHeight());
430 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
432 public void execute() {
433 fetchAccount(new Command() {
436 public void execute() {
437 if (!account.hasHomeContainer())
438 createHomeContainer(account, this);
439 else if (!account.hasTrashContainer())
440 createTrashContainer(this);
442 for (Folder f : account.getContainers())
443 if (f.getName().equals(Pithos.TRASH_CONTAINER)) {
447 folderTreeViewModel.initialize(account, new Command() {
450 public void execute() {
451 createMySharedTree();
454 groupTreeViewModel.initialize();
462 // Scheduler.get().scheduleDeferred(new Command() {
465 // public void execute() {
466 // displayError("lalala");
472 public void applyPermissions(Folder f) {
475 upload.setEnabled(false);
477 Boolean[] perms = f.getPermissions().get(username);
478 if (f.getOwner().equals(username) || (perms != null && perms[1] != null && perms[1])) {
479 upload.setEnabled(true);
482 upload.setEnabled(false);
486 upload.setEnabled(false);
489 @SuppressWarnings({ "rawtypes", "unchecked" })
490 public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
491 selectedTree = _selectedTree;
493 for (Composite c : treeViews)
494 if (c.equals(selectedTree))
495 c.addStyleName("cellTreeWidget-selectedTree");
497 c.removeStyleName("cellTreeWidget-selectedTree");
499 for (SingleSelectionModel s : selectionModels)
500 if (!s.equals(model))
501 s.setSelected(s.getSelectedObject(), false);
504 public void showFiles(final Folder f) {
505 Set<File> files = f.getFiles();
509 public void showFiles(Set<File> files) {
510 fileList.setFiles(new ArrayList<File>(files));
514 * Parse and store the user credentials to the appropriate fields.
516 private boolean parseUserCredentials() {
517 username = Window.Location.getParameter("user");
518 token = Window.Location.getParameter("token");
519 Configuration conf = (Configuration) GWT.create(Configuration.class);
520 if (username == null || username.length() == 0 || token == null || token.length() == 0) {
521 String cookie = conf.authCookie();
522 String auth = Cookies.getCookie(cookie);
527 if (auth.startsWith("\""))
528 auth = auth.substring(1);
529 if (auth.endsWith("\""))
530 auth = auth.substring(0, auth.length() - 1);
531 String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
532 if (authSplit.length != 2) {
536 username = authSplit[0];
537 token = authSplit[1];
541 Cookies.setCookie(conf.authCookie(), username + conf.cookieSeparator() + token, null, "", "/", false);
546 * Redirect the user to the login page for authentication.
548 protected void authenticateUser() {
549 Dictionary otherProperties = Dictionary.getDictionary("otherProperties");
550 Window.Location.assign(otherProperties.get("loginUrl"));
553 protected void fetchAccount(final Command callback) {
554 String path = "?format=json";
556 GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getApiPath(), username, path) {
558 public void onSuccess(AccountResource _result) {
560 if (callback != null)
565 public void onError(Throwable t) {
566 GWT.log("Error getting account", t);
568 if (t instanceof RestException)
569 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
571 displayError("System error fetching user data: " + t.getMessage());
575 protected void onUnauthorized(Response response) {
579 getAccount.setHeader("X-Auth-Token", token);
580 Scheduler.get().scheduleDeferred(getAccount);
583 public void updateStatistics() {
584 HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getApiPath(), username, "", account) {
587 public void onSuccess(AccountResource _result) {
592 public void onError(Throwable t) {
593 GWT.log("Error getting account", t);
595 if (t instanceof RestException)
596 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
598 displayError("System error fetching user data: " + t.getMessage());
602 protected void onUnauthorized(Response response) {
606 headAccount.setHeader("X-Auth-Token", token);
607 Scheduler.get().scheduleDeferred(headAccount);
610 protected void showStatistics() {
611 usedBytes.setHTML(String.valueOf(account.getFileSizeAsString()));
612 totalBytes.setHTML(String.valueOf(account.getQuotaAsString()));
613 NumberFormat nf = NumberFormat.getPercentFormat();
614 usedPercent.setHTML(nf.format(account.getUsedPercentage()));
617 protected void createHomeContainer(final AccountResource _account, final Command callback) {
618 String path = "/" + Pithos.HOME_CONTAINER;
619 PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
621 public void onSuccess(Resource result) {
622 if (!_account.hasTrashContainer())
623 createTrashContainer(callback);
625 fetchAccount(callback);
629 public void onError(Throwable t) {
630 GWT.log("Error creating pithos", t);
632 if (t instanceof RestException)
633 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
635 displayError("System error Error creating pithos: " + t.getMessage());
639 protected void onUnauthorized(Response response) {
643 createPithos.setHeader("X-Auth-Token", getToken());
644 Scheduler.get().scheduleDeferred(createPithos);
647 protected void createTrashContainer(final Command callback) {
648 String path = "/" + Pithos.TRASH_CONTAINER;
649 PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
651 public void onSuccess(Resource result) {
652 fetchAccount(callback);
656 public void onError(Throwable t) {
657 GWT.log("Error creating pithos", t);
659 if (t instanceof RestException)
660 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
662 displayError("System error Error creating pithos: " + t.getMessage());
666 protected void onUnauthorized(Response response) {
670 createPithos.setHeader("X-Auth-Token", getToken());
671 Scheduler.get().scheduleDeferred(createPithos);
675 * Creates an HTML fragment that places an image & caption together, for use
678 * @param imageProto an image prototype for an image
679 * @param caption the group caption
680 * @return the header HTML fragment
682 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
683 String captionHTML = "<table class='caption' cellpadding='0' "
684 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
685 + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'> "
686 + caption + "</b></td></tr></table>";
690 protected void onWindowResized(int height) {
691 // Adjust the split panel to take up the available room in the window.
692 int newHeight = height - splitPanel.getAbsoluteTop();
695 splitPanel.setHeight("" + newHeight);
696 inner.setHeight("" + newHeight);
700 public void onResize(ResizeEvent event) {
701 int height = event.getHeight();
702 onWindowResized(height);
706 * Display an error message.
708 * @param msg the message to display
710 public void displayError(String msg) {
711 messagePanel.displayError(msg);
715 * Display a warning message.
717 * @param msg the message to display
719 public void displayWarning(String msg) {
720 messagePanel.displayWarning(msg);
724 * Display an informational message.
726 * @param msg the message to display
728 public void displayInformation(String msg) {
729 messagePanel.displayInformation(msg);
733 * Retrieve the fileList.
735 * @return the fileList
737 public FileList getFileList() {
742 * Retrieve the topPanel.
744 * @return the topPanel
746 TopPanel getTopPanel() {
751 * Retrieve the clipboard.
753 * @return the clipboard
755 public Clipboard getClipboard() {
759 public StatusPanel getStatusPanel() {
763 public String getToken() {
767 public static native void preventIESelection() /*-{
768 $doc.body.onselectstart = function () { return false; };
771 public static native void enableIESelection() /*-{
772 if ($doc.body.onselectstart != null)
773 $doc.body.onselectstart = null;
777 * @return the absolute path of the API root URL
779 public String getApiPath() {
780 Configuration conf = (Configuration) GWT.create(Configuration.class);
781 return conf.apiPath();
785 * History support for folder navigation
786 * adds a new browser history entry
790 public void updateHistory(String key){
791 // Replace any whitespace of the initial string to "+"
792 // String result = key.replaceAll("\\s","+");
793 // Add a new browser history entry.
794 // History.newItem(result);
795 History.newItem(key);
798 public void deleteFolder(final Folder folder) {
799 String path = getApiPath() + folder.getOwner() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(folder.getPrefix()) + "&t=" + System.currentTimeMillis();
800 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
801 builder.setHeader("X-Auth-Token", getToken());
803 builder.sendRequest("", new RequestCallback() {
805 public void onResponseReceived(Request request, Response response) {
806 if (response.getStatusCode() == Response.SC_OK) {
807 JSONValue json = JSONParser.parseStrict(response.getText());
808 JSONArray array = json.isArray();
811 deleteObject(folder, i, array);
817 public void onError(Request request, Throwable exception) {
819 displayError("System error unable to delete folder: " + exception.getMessage());
823 catch (RequestException e) {
827 void deleteObject(final Folder folder, final int i, final JSONArray array) {
828 if (i < array.size()) {
829 JSONObject o = array.get(i).isObject();
830 if (o != null && !o.containsKey("subdir")) {
831 JSONString name = o.get("name").isString();
832 String path = "/" + folder.getContainer() + "/" + name.stringValue();
833 DeleteRequest delete = new DeleteRequest(getApiPath(), folder.getOwner(), URL.encode(path)) {
835 public void onSuccess(Resource result) {
836 deleteObject(folder, i + 1, array);
840 public void onError(Throwable t) {
843 displayError("System error unable to delete folder: " + t.getMessage());
847 protected void onUnauthorized(Response response) {
851 delete.setHeader("X-Auth-Token", getToken());
852 Scheduler.get().scheduleDeferred(delete);
854 else if (o != null) {
855 String subdir = o.get("subdir").isString().stringValue();
856 subdir = subdir.substring(0, subdir.length() - 1);
857 String path = getApiPath() + getUsername() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(subdir) + "&t=" + System.currentTimeMillis();
858 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
859 builder.setHeader("X-Auth-Token", getToken());
861 builder.sendRequest("", new RequestCallback() {
863 public void onResponseReceived(Request request, Response response) {
864 if (response.getStatusCode() == Response.SC_OK) {
865 JSONValue json = JSONParser.parseStrict(response.getText());
866 JSONArray array2 = json.isArray();
867 if (array2 != null) {
868 int l = array.size();
869 for (int j=0; j<array2.size(); j++) {
870 array.set(l++, array2.get(j));
873 deleteObject(folder, i + 1, array);
878 public void onError(Request request, Throwable exception) {
880 displayError("System error unable to delete folder: " + exception.getMessage());
884 catch (RequestException e) {
889 String path = folder.getUri();
890 DeleteRequest deleteFolder = new DeleteRequest(getApiPath(), getUsername(), URL.encode(path)) {
892 public void onSuccess(Resource result) {
893 updateFolder(folder.getParent(), true, new Command() {
896 public void execute() {
903 public void onError(Throwable t) {
906 if (t instanceof RestException) {
907 if (((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND)
908 displayError("Unable to delete folder: "+((RestException) t).getHttpStatusText());
913 displayError("System error unable to delete folder: " + t.getMessage());
917 protected void onUnauthorized(Response response) {
921 deleteFolder.setHeader("X-Auth-Token", getToken());
922 Scheduler.get().scheduleDeferred(deleteFolder);
926 public FolderTreeView getFolderTreeView() {
927 return folderTreeView;
930 public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
931 if (iter.hasNext()) {
932 File file = iter.next();
933 String path = targetUri + "/" + file.getName();
934 PutRequest copyFile = new PutRequest(getApiPath(), targetUsername, path) {
936 public void onSuccess(Resource result) {
937 copyFiles(iter, targetUsername, targetUri, callback);
941 public void onError(Throwable t) {
944 if (t instanceof RestException) {
945 displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
948 displayError("System error unable to copy file: "+t.getMessage());
952 protected void onUnauthorized(Response response) {
956 copyFile.setHeader("X-Auth-Token", getToken());
957 copyFile.setHeader("X-Copy-From", URL.encodePathSegment(file.getUri()));
958 if (!file.getOwner().equals(targetUsername))
959 copyFile.setHeader("X-Source-Account", URL.encodePathSegment(file.getOwner()));
960 copyFile.setHeader("Content-Type", file.getContentType());
961 Scheduler.get().scheduleDeferred(copyFile);
963 else if (callback != null) {
968 public void copySubfolders(final Iterator<Folder> iter, final String targetUsername, final String targetUri, final Command callback) {
969 if (iter.hasNext()) {
970 final Folder f = iter.next();
971 copyFolder(f, targetUsername, targetUri, new Command() {
974 public void execute() {
975 copySubfolders(iter, targetUsername, targetUri, callback);
979 else if (callback != null) {
984 public void copyFolder(final Folder f, final String targetUsername, final String targetUri, final Command callback) {
985 String path = targetUri + "/" + f.getName();
986 PutRequest createFolder = new PutRequest(getApiPath(), targetUsername, path) {
988 public void onSuccess(Resource result) {
989 GetRequest<Folder> getFolder = new GetRequest<Folder>(Folder.class, getApiPath(), f.getOwner(), "/" + f.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(f.getPrefix()), f) {
992 public void onSuccess(final Folder _f) {
993 Iterator<File> iter = _f.getFiles().iterator();
994 copyFiles(iter, targetUsername, targetUri + "/" + _f.getName(), new Command() {
996 public void execute() {
997 Iterator<Folder> iterf = _f.getSubfolders().iterator();
998 copySubfolders(iterf, targetUsername, targetUri + "/" + _f.getName(), callback);
1004 public void onError(Throwable t) {
1007 if (t instanceof RestException) {
1008 displayError("Unable to get folder: " + ((RestException) t).getHttpStatusText());
1011 displayError("System error getting folder: " + t.getMessage());
1015 protected void onUnauthorized(Response response) {
1019 getFolder.setHeader("X-Auth-Token", getToken());
1020 Scheduler.get().scheduleDeferred(getFolder);
1024 public void onError(Throwable t) {
1027 if (t instanceof RestException) {
1028 displayError("Unable to create folder: " + ((RestException) t).getHttpStatusText());
1031 displayError("System error creating folder: " + t.getMessage());
1035 protected void onUnauthorized(Response response) {
1039 createFolder.setHeader("X-Auth-Token", getToken());
1040 createFolder.setHeader("Accept", "*/*");
1041 createFolder.setHeader("Content-Length", "0");
1042 createFolder.setHeader("Content-Type", "application/folder");
1043 Scheduler.get().scheduleDeferred(createFolder);
1046 public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1047 selectionModels.add(model);
1050 public OtherSharedTreeView getOtherSharedTreeView() {
1051 return otherSharedTreeView;
1054 public void updateTrash(boolean showFiles, Command callback) {
1055 updateFolder(trash, showFiles, callback);
1058 public void updateGroupsNode() {
1059 groupTreeView.updateGroupNode(null);
1062 public void addGroup(String groupname) {
1063 Group newGroup = new Group(groupname);
1064 account.addGroup(newGroup);
1065 groupTreeView.updateGroupNode(null);
1068 public void removeGroup(Group group) {
1069 account.removeGroup(group);
1073 public TreeView getSelectedTree() {
1074 return selectedTree;
1077 public Folder getSelection() {
1078 return selectedTree.getSelection();
1081 public void showFolderStatistics(int folderFileCount) {
1082 numOfFiles.setHTML(String.valueOf(folderFileCount));
1085 public GroupTreeView getGroupTreeView() {
1086 return groupTreeView;
1089 public void sessionExpired() {
1090 new SessionExpiredDialog(this).center();
1093 public void updateRootFolder(Command callback) {
1094 updateFolder(account.getPithos(), false, callback);
1097 void createMySharedTree() {
1098 mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1099 mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1101 public void onSelectionChange(SelectionChangeEvent event) {
1102 if (mysharedTreeSelectionModel.getSelectedObject() != null) {
1103 deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1104 upload.setEnabled(false);
1105 updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1107 showRelevantToolbarButtons();
1110 selectionModels.add(mysharedTreeSelectionModel);
1111 mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1112 mysharedTreeViewModel.initialize(new Command() {
1115 public void execute() {
1116 mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1117 trees.insert(mysharedTreeView, 2);
1118 treeViews.add(mysharedTreeView);
1119 createOtherSharedTree();
1124 void createOtherSharedTree() {
1125 otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1126 otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1128 public void onSelectionChange(SelectionChangeEvent event) {
1129 if (otherSharedTreeSelectionModel.getSelectedObject() != null) {
1130 deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1131 otherSharedTreeView.addStyleName("cellTreeWidget-selectedTree");
1132 applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1133 updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true);
1135 showRelevantToolbarButtons();
1138 selectionModels.add(otherSharedTreeSelectionModel);
1139 otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1140 otherSharedTreeViewModel.initialize(new Command() {
1143 public void execute() {
1144 otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel);
1145 trees.insert(otherSharedTreeView, 3);
1146 treeViews.add(otherSharedTreeView);
1151 public native void log1(String message)/*-{
1152 $wnd.console.log(message);
1155 public String getErrorData() {
1157 return error.toString();
1161 public void setError(Throwable t) {
1165 public void showRelevantToolbarButtons() {
1166 toolbar.showRelevantButtons();
1169 public FileUploadDialog getFileUploadDialog() {
1170 if (fileUploadDialog == null)
1171 fileUploadDialog = new FileUploadDialog(this);
1172 return fileUploadDialog;
1175 public void hideUploadIndicator() {
1176 upload.removeStyleName("pithos-uploadButton-loading");
1177 upload.setTitle("");
1180 public void showUploadIndicator() {
1181 upload.addStyleName("pithos-uploadButton-loading");
1182 upload.setTitle("Upload in progress. Click for details.");
1185 public void scheduleFolderHeadCommand(final Folder folder, final Command callback) {
1186 HeadRequest<Folder> headFolder = new HeadRequest<Folder>(Folder.class, getApiPath(), folder.getOwner(), folder.getUri(), folder) {
1189 public void onSuccess(Folder _result) {
1190 if (callback != null)
1195 public void onError(Throwable t) {
1196 if (t instanceof RestException) {
1197 if (((RestException) t).getHttpStatusCode() == Response.SC_NOT_FOUND) {
1198 final String path = folder.getUri();
1199 PutRequest newFolder = new PutRequest(getApiPath(), folder.getOwner(), path) {
1201 public void onSuccess(Resource _result) {
1202 scheduleFolderHeadCommand(folder, callback);
1206 public void onError(Throwable _t) {
1209 if(_t instanceof RestException){
1210 displayError("Unable to create folder: " + ((RestException) _t).getHttpStatusText());
1213 displayError("System error creating folder: " + _t.getMessage());
1217 protected void onUnauthorized(Response response) {
1221 newFolder.setHeader("X-Auth-Token", getToken());
1222 newFolder.setHeader("Content-Type", "application/folder");
1223 newFolder.setHeader("Accept", "*/*");
1224 newFolder.setHeader("Content-Length", "0");
1225 Scheduler.get().scheduleDeferred(newFolder);
1228 displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
1231 displayError("System error heading folder: " + t.getMessage());
1233 GWT.log("Error heading folder", t);
1238 protected void onUnauthorized(Response response) {
1242 headFolder.setHeader("X-Auth-Token", getToken());
1243 Scheduler.get().scheduleDeferred(headFolder);
1246 public void scheduleFileHeadCommand(File f, final Command callback) {
1247 HeadRequest<File> headFile = new HeadRequest<File>(File.class, getApiPath(), f.getOwner(), f.getUri(), f) {
1250 public void onSuccess(File _result) {
1251 if (callback != null)
1256 public void onError(Throwable t) {
1257 GWT.log("Error heading file", t);
1259 if (t instanceof RestException)
1260 displayError("Error heading file: " + ((RestException) t).getHttpStatusText());
1262 displayError("System error heading file: " + t.getMessage());
1266 protected void onUnauthorized(Response response) {
1270 headFile.setHeader("X-Auth-Token", getToken());
1271 Scheduler.get().scheduleDeferred(headFile);