2 * Copyright 2011 GRNET S.A. All rights reserved.
4 * Redistribution and use in source and binary forms, with or
5 * without modification, are permitted provided that the following
8 * 1. Redistributions of source code must retain the above
9 * copyright notice, this list of conditions and the following
12 * 2. Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following
14 * disclaimer in the documentation and/or other materials
15 * provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
18 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
21 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
24 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 * POSSIBILITY OF SUCH DAMAGE.
30 * The views and conclusions contained in the software and
31 * documentation are those of the authors and should not be
32 * interpreted as representing official policies, either expressed
33 * or implied, of GRNET S.A.
35 package gr.grnet.pithos.web.client;
37 import 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;
57 import gr.grnet.pithos.web.client.tagtree.TagTreeView;
58 import gr.grnet.pithos.web.client.tagtree.TagTreeViewModel;
60 import java.util.ArrayList;
61 import java.util.HashMap;
62 import java.util.Iterator;
63 import java.util.List;
66 import com.google.gwt.core.client.EntryPoint;
67 import com.google.gwt.core.client.GWT;
68 import com.google.gwt.core.client.Scheduler;
69 import com.google.gwt.core.client.Scheduler.ScheduledCommand;
70 import com.google.gwt.event.dom.client.ClickEvent;
71 import com.google.gwt.event.dom.client.ClickHandler;
72 import com.google.gwt.event.logical.shared.ResizeEvent;
73 import com.google.gwt.event.logical.shared.ResizeHandler;
74 import com.google.gwt.http.client.Request;
75 import com.google.gwt.http.client.RequestBuilder;
76 import com.google.gwt.http.client.RequestCallback;
77 import com.google.gwt.http.client.RequestException;
78 import com.google.gwt.http.client.Response;
79 import com.google.gwt.json.client.JSONArray;
80 import com.google.gwt.json.client.JSONObject;
81 import com.google.gwt.json.client.JSONParser;
82 import com.google.gwt.json.client.JSONString;
83 import com.google.gwt.json.client.JSONValue;
84 import com.google.gwt.resources.client.ImageResource;
85 import com.google.gwt.user.client.Command;
86 import com.google.gwt.user.client.Cookies;
87 import com.google.gwt.user.client.Event;
88 import com.google.gwt.user.client.History;
89 import com.google.gwt.user.client.Window;
90 import com.google.gwt.user.client.ui.AbstractImagePrototype;
91 import com.google.gwt.user.client.ui.Button;
92 import com.google.gwt.user.client.ui.HTML;
93 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
94 import com.google.gwt.user.client.ui.HasVerticalAlignment;
95 import com.google.gwt.user.client.ui.HorizontalPanel;
96 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
97 import com.google.gwt.user.client.ui.Image;
98 import com.google.gwt.user.client.ui.RootPanel;
99 import com.google.gwt.user.client.ui.VerticalPanel;
100 import com.google.gwt.view.client.SelectionChangeEvent;
101 import com.google.gwt.view.client.SelectionChangeEvent.Handler;
102 import com.google.gwt.view.client.SingleSelectionModel;
105 * Entry point classes define <code>onModuleLoad()</code>.
107 public class Pithos implements EntryPoint, ResizeHandler {
109 public static final String HOME_CONTAINER = "pithos";
111 public static final String TRASH_CONTAINER = "trash";
114 * Instantiate an application-level image bundle. This object will provide
115 * programmatic access to all the images needed by widgets.
117 static Images images = (Images) GWT.create(Images.class);
119 public String getUsername() {
123 public void setAccount(AccountResource acct) {
127 public AccountResource getAccount() {
131 public void updateFolder(Folder f, boolean showfiles, Command callback) {
132 folderTreeView.updateFolder(f, showfiles, callback);
135 public void updateGroupNode(Group group) {
136 groupTreeView.updateGroupNode(group);
139 public void updateSharedFolder(Folder f, boolean showfiles) {
140 mysharedTreeView.updateFolder(f, showfiles);
143 public void updateOtherSharedFolder(Folder f, boolean showfiles) {
144 otherSharedTreeView.updateFolder(f, showfiles);
147 public void updateTag(Tag t) {
148 tagTreeView.updateTag(t);
151 public void updateTags() {
152 tagTreeViewModel.initialize(getAllTags());
155 public List<Tag> getAllTags() {
156 List<Tag> tagList = new ArrayList<Tag>();
157 for (Folder f : account.getContainers()) {
158 for (String t : f.getTags()) {
159 tagList.add(new Tag(t));
165 public MysharedTreeView getMySharedTreeView() {
166 return mysharedTreeView;
170 * An aggregate image bundle that pulls together all the images for this
171 * application into a single bundle.
173 public interface Images extends TopPanel.Images, FileList.Images, ToolsMenu.Images {
175 @Source("gr/grnet/pithos/resources/document.png")
176 ImageResource folders();
178 @Source("gr/grnet/pithos/resources/edit_group_22.png")
179 ImageResource groups();
181 @Source("gr/grnet/pithos/resources/advancedsettings.png")
182 ImageResource tools();
186 * The Application Clipboard implementation;
188 private Clipboard clipboard = new Clipboard();
191 * The top panel that contains the menu bar.
193 private TopPanel topPanel;
196 * The panel that contains the various system messages.
198 private MessagePanel messagePanel = new MessagePanel(Pithos.images);
201 * The bottom panel that contains the status bar.
203 private StatusPanel statusPanel = null;
206 * The file list widget.
208 private FileList fileList;
211 * The tab panel that occupies the right side of the screen.
213 private VerticalPanel inner = new VerticalPanel();
217 * The split panel that will contain the left and right panels.
219 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
222 * The currently selected item in the application, for use by the Edit menu
223 * commands. Potential types are Folder, File, User and Group.
225 private Object currentSelection;
229 * The WebDAV password of the current user
231 private String webDAVPassword;
233 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
235 private String username = null;
238 * The authentication token of the current user.
240 private String token;
242 SingleSelectionModel<Folder> folderTreeSelectionModel;
243 FolderTreeViewModel folderTreeViewModel;
244 FolderTreeView folderTreeView;
246 SingleSelectionModel<Folder> mysharedTreeSelectionModel;
247 private MysharedTreeViewModel mysharedTreeViewModel;
248 MysharedTreeView mysharedTreeView;
250 protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
251 private OtherSharedTreeViewModel otherSharedTreeViewModel;
252 OtherSharedTreeView otherSharedTreeView;
254 protected SingleSelectionModel<Tag> tagTreeSelectionModel;
255 private TagTreeViewModel tagTreeViewModel;
256 private TagTreeView tagTreeView;
258 GroupTreeViewModel groupTreeViewModel;
259 private GroupTreeView groupTreeView;
261 private TreeView selectedTree;
262 protected AccountResource account;
266 @SuppressWarnings("rawtypes")
267 private List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
271 private HTML totalFiles;
273 private HTML usedBytes;
275 private HTML totalBytes;
277 private HTML usedPercent;
279 private HTML numOfFiles;
282 public void onModuleLoad() {
283 if (parseUserCredentials())
287 private void initialize() {
288 VerticalPanel outer = new VerticalPanel();
289 outer.setWidth("100%");
291 topPanel = new TopPanel(this, Pithos.images);
292 topPanel.setWidth("100%");
295 messagePanel.setWidth("100%");
296 messagePanel.setVisible(false);
297 outer.add(messagePanel);
298 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
301 // Inner contains the various lists.
302 inner.sinkEvents(Event.ONCONTEXTMENU);
303 inner.setWidth("100%");
305 HorizontalPanel rightside = new HorizontalPanel();
306 rightside.addStyleName("pithos-rightSide");
307 rightside.setSpacing(5);
309 Image toolsButton = AbstractImagePrototype.create(images.tools()).createImage();
310 toolsButton.addClickHandler(new ClickHandler() {
313 public void onClick(ClickEvent event) {
314 ToolsMenu menu = new ToolsMenu(Pithos.this, images, getSelectedTree(), getSelectedTree().getSelection(), getFileList().getSelectedFiles());
315 menu.setPopupPosition(event.getClientX(), event.getClientY());
319 rightside.add(toolsButton);
320 rightside.setCellHorizontalAlignment(toolsButton, HasHorizontalAlignment.ALIGN_LEFT);
322 HorizontalPanel folderStatistics = new HorizontalPanel();
323 folderStatistics.addStyleName("pithos-folderStatistics");
324 numOfFiles = new HTML();
325 folderStatistics.add(numOfFiles);
326 HTML numOfFilesLabel = new HTML(" Files");
327 folderStatistics.add(numOfFilesLabel);
328 rightside.add(folderStatistics);
329 rightside.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
331 inner.add(rightside);
332 inner.setCellVerticalAlignment(rightside, HasVerticalAlignment.ALIGN_MIDDLE);
333 inner.setCellHeight(rightside, "60px");
335 folderTreeSelectionModel = new SingleSelectionModel<Folder>();
336 folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
338 public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
339 if (folderTreeSelectionModel.getSelectedObject() != null) {
340 deselectOthers(folderTreeView, folderTreeSelectionModel);
341 applyPermissions(folderTreeSelectionModel.getSelectedObject());
342 Folder f = folderTreeSelectionModel.getSelectedObject();
343 updateFolder(f, true, null);
347 selectionModels.add(folderTreeSelectionModel);
349 folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
350 folderTreeView = new FolderTreeView(folderTreeViewModel);
352 fileList = new FileList(this, images, folderTreeView);
355 mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
356 mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
358 public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
359 if (mysharedTreeSelectionModel.getSelectedObject() != null) {
360 deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
361 upload.setEnabled(false);
362 updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
366 selectionModels.add(mysharedTreeSelectionModel);
367 mysharedTreeViewModel = new MysharedTreeViewModel(this, mysharedTreeSelectionModel);
368 mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
370 otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
371 otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
373 public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
374 if (otherSharedTreeSelectionModel.getSelectedObject() != null) {
375 deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
376 applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
377 updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true);
381 selectionModels.add(otherSharedTreeSelectionModel);
382 otherSharedTreeViewModel = new OtherSharedTreeViewModel(this, otherSharedTreeSelectionModel);
383 otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel);
385 groupTreeViewModel = new GroupTreeViewModel(this);
386 groupTreeView = new GroupTreeView(groupTreeViewModel);
388 VerticalPanel trees = new VerticalPanel();
390 upload = new Button("Upload File", new ClickHandler() {
392 public void onClick(@SuppressWarnings("unused") ClickEvent event) {
393 new UploadFileCommand(Pithos.this, null, getSelection()).execute();
396 upload.addStyleName("pithos-uploadButton");
399 HorizontalPanel treeHeader = new HorizontalPanel();
400 treeHeader.addStyleName("pithos-treeHeader");
401 HorizontalPanel statistics = new HorizontalPanel();
402 statistics.add(new HTML("Total Objects: "));
403 totalFiles = new HTML();
404 statistics.add(totalFiles);
405 statistics.add(new HTML(" | Used: "));
406 usedBytes = new HTML();
407 statistics.add(usedBytes);
408 statistics.add(new HTML(" of "));
409 totalBytes = new HTML();
410 statistics.add(totalBytes);
411 statistics.add(new HTML(" ("));
412 usedPercent = new HTML();
413 statistics.add(usedPercent);
414 statistics.add(new HTML("%)"));
415 treeHeader.add(statistics);
416 trees.add(treeHeader);
418 trees.add(folderTreeView);
419 trees.add(mysharedTreeView);
420 trees.add(otherSharedTreeView);
421 // trees.add(tagTreeView);
422 trees.add(groupTreeView);
423 // Add the left and right panels to the split panel.
424 splitPanel.setLeftWidget(trees);
425 splitPanel.setRightWidget(inner);
426 splitPanel.setSplitPosition("25%");
427 splitPanel.setSize("100%", "100%");
428 splitPanel.addStyleName("pithos-splitPanel");
429 outer.add(splitPanel);
431 statusPanel = new StatusPanel();
432 outer.add(statusPanel);
435 // Hook the window resize event, so that we can adjust the UI.
436 Window.addResizeHandler(this);
437 // Clear out the window's built-in margin, because we want to take
438 // advantage of the entire client area.
439 Window.setMargin("0px");
440 // Finally, add the outer panel to the RootPanel, so that it will be
442 RootPanel.get().add(outer);
443 // Call the window resized handler to get the initial sizes setup. Doing
444 // this in a deferred command causes it to occur after all widgets'
445 // sizes have been computed by the browser.
446 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
449 public void execute() {
450 onWindowResized(Window.getClientHeight());
454 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
456 public void execute() {
457 fetchAccount(new Command() {
460 public void execute() {
461 if (!account.hasHomeContainer())
462 createHomeContainer(account, this);
463 else if (!account.hasTrashContainer())
464 createTrashContainer(this);
466 for (Folder f : account.getContainers())
467 if (f.getName().equals(Pithos.TRASH_CONTAINER)) {
471 folderTreeViewModel.initialize(account);
472 groupTreeViewModel.initialize();
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;
501 for (SingleSelectionModel s : selectionModels)
502 if (!s.equals(model))
503 s.setSelected(s.getSelectedObject(), false);
506 public void showFiles(Folder f) {
507 Set<File> files = f.getFiles();
511 public void showFiles(Set<File> files) {
512 //Iterator<File> iter = files.iterator();
513 //fetchFile(iter, files);
514 fileList.setFiles(new ArrayList<File>(files));
517 protected void fetchFile(final Iterator<File> iter, final Set<File> files) {
518 if (iter.hasNext()) {
519 File file = iter.next();
520 String path = file.getUri() + "?format=json";
521 GetRequest<File> getFile = new GetRequest<File>(File.class, getApiPath(), username, path, file) {
523 public void onSuccess(@SuppressWarnings("unused") File _result) {
524 fetchFile(iter, files);
528 public void onError(Throwable t) {
529 GWT.log("Error getting file", t);
530 if (t instanceof RestException)
531 displayError("Error getting file: " + ((RestException) t).getHttpStatusText());
533 displayError("System error fetching file: " + t.getMessage());
536 getFile.setHeader("X-Auth-Token", "0000");
537 Scheduler.get().scheduleDeferred(getFile);
540 fileList.setFiles(new ArrayList<File>(files));
544 * Parse and store the user credentials to the appropriate fields.
546 private boolean parseUserCredentials() {
547 username = Window.Location.getParameter("user");
548 token = Window.Location.getParameter("token");
549 Configuration conf = (Configuration) GWT.create(Configuration.class);
550 if (username == null || username.length() == 0 || token == null || token.length() == 0) {
551 String cookie = conf.authCookie();
552 String auth = Cookies.getCookie(cookie);
557 String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
558 if (authSplit.length != 2) {
562 username = authSplit[0];
563 token = authSplit[1];
566 Cookies.setCookie(conf.authCookie(), username + conf.cookieSeparator() + token);
571 * Redirect the user to the login page for authentication.
573 protected void authenticateUser() {
574 Configuration conf = (Configuration) GWT.create(Configuration.class);
575 Window.Location.assign(conf.loginUrl() + "?next=" + 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);
592 if (t instanceof RestException)
593 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
595 displayError("System error fetching user data: " + t.getMessage());
598 getAccount.setHeader("X-Auth-Token", token);
599 Scheduler.get().scheduleDeferred(getAccount);
602 public void updateStatistics() {
603 HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getApiPath(), username, "", account) {
606 public void onSuccess(@SuppressWarnings("unused") AccountResource _result) {
611 public void onError(Throwable t) {
612 GWT.log("Error getting account", t);
613 if (t instanceof RestException)
614 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
616 displayError("System error fetching user data: " + t.getMessage());
619 headAccount.setHeader("X-Auth-Token", token);
620 Scheduler.get().scheduleDeferred(headAccount);
623 protected void showStatistics() {
624 totalFiles.setHTML(String.valueOf(account.getNumberOfObjects()));
625 usedBytes.setHTML(String.valueOf(account.getFileSizeAsString()));
626 totalBytes.setHTML(String.valueOf(account.getQuotaAsString()));
627 usedPercent.setHTML(String.valueOf(account.getUsedPercentage()));
630 protected void createHomeContainer(final AccountResource _account, final Command callback) {
631 String path = "/" + Pithos.HOME_CONTAINER;
632 PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
634 public void onSuccess(@SuppressWarnings("unused") Resource result) {
635 if (!_account.hasTrashContainer())
636 createTrashContainer(callback);
638 fetchAccount(callback);
642 public void onError(Throwable t) {
643 GWT.log("Error creating pithos", t);
644 if (t instanceof RestException)
645 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
647 displayError("System error Error creating pithos: " + t.getMessage());
650 createPithos.setHeader("X-Auth-Token", getToken());
651 Scheduler.get().scheduleDeferred(createPithos);
654 protected void createTrashContainer(final Command callback) {
655 String path = "/" + Pithos.TRASH_CONTAINER;
656 PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
658 public void onSuccess(@SuppressWarnings("unused") Resource result) {
659 fetchAccount(callback);
663 public void onError(Throwable t) {
664 GWT.log("Error creating pithos", t);
665 if (t instanceof RestException)
666 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
668 displayError("System error Error creating pithos: " + t.getMessage());
671 createPithos.setHeader("X-Auth-Token", getToken());
672 Scheduler.get().scheduleDeferred(createPithos);
676 * Creates an HTML fragment that places an image & caption together, for use
679 * @param imageProto an image prototype for an image
680 * @param caption the group caption
681 * @return the header HTML fragment
683 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
684 String captionHTML = "<table class='caption' cellpadding='0' "
685 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
686 + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'> "
687 + caption + "</b></td></tr></table>";
691 protected void onWindowResized(int height) {
692 // Adjust the split panel to take up the available room in the window.
693 int newHeight = height - splitPanel.getAbsoluteTop() - 60;
696 splitPanel.setHeight("" + newHeight);
697 inner.setHeight("" + newHeight);
701 public void onResize(ResizeEvent event) {
702 int height = event.getHeight();
703 onWindowResized(height);
707 * Display an error message.
709 * @param msg the message to display
711 public void displayError(String msg) {
712 messagePanel.displayError(msg);
716 * Display a warning message.
718 * @param msg the message to display
720 public void displayWarning(String msg) {
721 messagePanel.displayWarning(msg);
725 * Display an informational message.
727 * @param msg the message to display
729 public void displayInformation(String msg) {
730 messagePanel.displayInformation(msg);
734 * Retrieve the fileList.
736 * @return the fileList
738 public FileList getFileList() {
743 * Retrieve the topPanel.
745 * @return the topPanel
747 TopPanel getTopPanel() {
752 * Retrieve the clipboard.
754 * @return the clipboard
756 public Clipboard getClipboard() {
760 public StatusPanel getStatusPanel() {
764 public String getToken() {
768 public String getWebDAVPassword() {
769 return webDAVPassword;
772 public static native void preventIESelection() /*-{
773 $doc.body.onselectstart = function () { return false; };
776 public static native void enableIESelection() /*-{
777 if ($doc.body.onselectstart != null)
778 $doc.body.onselectstart = null;
782 * @return the absolute path of the API root URL
784 public String getApiPath() {
785 Configuration conf = (Configuration) GWT.create(Configuration.class);
786 return conf.apiPath();
790 * History support for folder navigation
791 * adds a new browser history entry
795 public void updateHistory(String key){
796 // Replace any whitespace of the initial string to "+"
797 // String result = key.replaceAll("\\s","+");
798 // Add a new browser history entry.
799 // History.newItem(result);
800 History.newItem(key);
803 public void deleteFolder(final Folder folder) {
804 String path = getApiPath() + folder.getOwner() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + folder.getPrefix();
805 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
806 builder.setHeader("If-Modified-Since", "0");
807 builder.setHeader("X-Auth-Token", getToken());
809 builder.sendRequest("", new RequestCallback() {
811 public void onResponseReceived(@SuppressWarnings("unused") Request request, Response response) {
812 if (response.getStatusCode() == Response.SC_OK) {
813 JSONValue json = JSONParser.parseStrict(response.getText());
814 JSONArray array = json.isArray();
817 deleteObject(folder, i, array);
823 public void onError(@SuppressWarnings("unused") Request request, Throwable exception) {
824 displayError("System error unable to delete folder: " + exception.getMessage());
828 catch (RequestException e) {
832 void deleteObject(final Folder folder, final int i, final JSONArray array) {
833 if (i < array.size()) {
834 JSONObject o = array.get(i).isObject();
835 if (o != null && !o.containsKey("subdir")) {
836 JSONString name = o.get("name").isString();
837 String path = "/" + folder.getContainer() + "/" + name.stringValue();
838 DeleteRequest delete = new DeleteRequest(getApiPath(), folder.getOwner(), path) {
840 public void onSuccess(@SuppressWarnings("unused") Resource result) {
841 deleteObject(folder, i + 1, array);
845 public void onError(Throwable t) {
847 displayError("System error unable to delete folder: " + t.getMessage());
850 delete.setHeader("X-Auth-Token", getToken());
851 Scheduler.get().scheduleDeferred(delete);
853 else if (o != null) {
854 String subdir = o.get("subdir").isString().stringValue();
855 subdir = subdir.substring(0, subdir.length() - 1);
856 String path = getApiPath() + getUsername() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + subdir;
857 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
858 builder.setHeader("If-Modified-Since", "0");
859 builder.setHeader("X-Auth-Token", getToken());
861 builder.sendRequest("", new RequestCallback() {
863 public void onResponseReceived(@SuppressWarnings("unused") 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(@SuppressWarnings("unused") Request request, Throwable exception) {
879 displayError("System error unable to delete folder: " + exception.getMessage());
883 catch (RequestException e) {
888 String path = folder.getUri();
889 DeleteRequest deleteFolder = new DeleteRequest(getApiPath(), getUsername(), path) {
891 public void onSuccess(@SuppressWarnings("unused") Resource result) {
892 updateFolder(folder.getParent(), true, new Command() {
895 public void execute() {
902 public void onError(Throwable t) {
904 if (t instanceof RestException) {
905 if (((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND)
906 displayError("Unable to delete folder: "+((RestException) t).getHttpStatusText());
911 displayError("System error unable to delete folder: " + t.getMessage());
914 deleteFolder.setHeader("X-Auth-Token", getToken());
915 Scheduler.get().scheduleDeferred(deleteFolder);
919 public FolderTreeView getFolderTreeView() {
920 return folderTreeView;
923 public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
924 if (iter.hasNext()) {
925 File file = iter.next();
926 String path = targetUri + "/" + file.getName();
927 PutRequest copyFile = new PutRequest(getApiPath(), targetUsername, path) {
929 public void onSuccess(@SuppressWarnings("unused") Resource result) {
930 copyFiles(iter, targetUsername, targetUri, callback);
934 public void onError(Throwable t) {
936 if (t instanceof RestException) {
937 displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
940 displayError("System error unable to copy file: "+t.getMessage());
943 copyFile.setHeader("X-Auth-Token", getToken());
944 copyFile.setHeader("X-Copy-From", file.getUri());
945 Scheduler.get().scheduleDeferred(copyFile);
947 else if (callback != null) {
952 public void copySubfolders(final Iterator<Folder> iter, final String targetUsername, final String targetUri, final Command callback) {
953 if (iter.hasNext()) {
954 final Folder f = iter.next();
955 copyFolder(f, targetUsername, targetUri, new Command() {
958 public void execute() {
959 copySubfolders(iter, targetUsername, targetUri, callback);
963 else if (callback != null) {
968 public void copyFolder(final Folder f, final String targetUsername, final String targetUri, final Command callback) {
969 String path = targetUri + "/" + f.getName();
970 PutRequest createFolder = new PutRequest(getApiPath(), targetUsername, path) {
972 public void onSuccess(@SuppressWarnings("unused") Resource result) {
973 GetRequest<Folder> getFolder = new GetRequest<Folder>(Folder.class, getApiPath(), f.getOwner(), "/" + f.getContainer() + "?format=json&delimiter=/&prefix=" + f.getPrefix(), f) {
976 public void onSuccess(final Folder _f) {
977 Iterator<File> iter = _f.getFiles().iterator();
978 copyFiles(iter, targetUsername, targetUri + "/" + _f.getName(), new Command() {
980 public void execute() {
981 Iterator<Folder> iterf = _f.getSubfolders().iterator();
982 copySubfolders(iterf, targetUsername, targetUri + "/" + _f.getName(), callback);
988 public void onError(Throwable t) {
990 if (t instanceof RestException) {
991 displayError("Unable to get folder: " + ((RestException) t).getHttpStatusText());
994 displayError("System error getting folder: " + t.getMessage());
997 getFolder.setHeader("X-Auth-Token", getToken());
998 Scheduler.get().scheduleDeferred(getFolder);
1002 public void onError(Throwable t) {
1004 if (t instanceof RestException) {
1005 displayError("Unable to create folder: " + ((RestException) t).getHttpStatusText());
1008 displayError("System error creating folder: " + t.getMessage());
1011 createFolder.setHeader("X-Auth-Token", getToken());
1012 createFolder.setHeader("Accept", "*/*");
1013 createFolder.setHeader("Content-Length", "0");
1014 createFolder.setHeader("Content-Type", "application/folder");
1015 Scheduler.get().scheduleDeferred(createFolder);
1018 public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1019 selectionModels.add(model);
1022 public OtherSharedTreeView getOtherSharedTreeView() {
1023 return otherSharedTreeView;
1026 public void updateTrash(boolean showFiles, Command callback) {
1027 updateFolder(trash, showFiles, callback);
1030 public void updateGroupsNode() {
1031 groupTreeView.updateGroupNode(null);
1034 public void addGroup(String groupname) {
1035 Group newGroup = new Group(groupname);
1036 account.addGroup(newGroup);
1037 groupTreeView.updateGroupNode(null);
1040 public void removeGroup(Group group) {
1041 account.removeGroup(group);
1045 public TreeView getSelectedTree() {
1046 return selectedTree;
1049 public Folder getSelection() {
1050 return selectedTree.getSelection();
1053 public void showFolderStatistics(int folderFileCount) {
1054 numOfFiles.setHTML(String.valueOf(folderFileCount));