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.http.client.URL;
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.user.client.Command;
87 import com.google.gwt.user.client.Cookies;
88 import com.google.gwt.user.client.Event;
89 import com.google.gwt.user.client.History;
90 import com.google.gwt.user.client.Window;
91 import com.google.gwt.user.client.ui.AbstractImagePrototype;
92 import com.google.gwt.user.client.ui.Button;
93 import com.google.gwt.user.client.ui.HTML;
94 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
95 import com.google.gwt.user.client.ui.HasVerticalAlignment;
96 import com.google.gwt.user.client.ui.HorizontalPanel;
97 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
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 List<Tag> getAllTags() {
148 List<Tag> tagList = new ArrayList<Tag>();
149 for (Folder f : account.getContainers()) {
150 for (String t : f.getTags()) {
151 tagList.add(new Tag(t));
157 public MysharedTreeView getMySharedTreeView() {
158 return mysharedTreeView;
162 * An aggregate image bundle that pulls together all the images for this
163 * application into a single bundle.
165 public interface Images extends TopPanel.Images, FileList.Images, ToolsMenu.Images {
167 @Source("gr/grnet/pithos/resources/document.png")
168 ImageResource folders();
170 @Source("gr/grnet/pithos/resources/advancedsettings.png")
171 ImageResource tools();
175 * The Application Clipboard implementation;
177 private Clipboard clipboard = new Clipboard();
180 * The top panel that contains the menu bar.
182 private TopPanel topPanel;
185 * The panel that contains the various system messages.
187 private MessagePanel messagePanel = new MessagePanel(Pithos.images);
190 * The bottom panel that contains the status bar.
192 private StatusPanel statusPanel = null;
195 * The file list widget.
197 private FileList fileList;
200 * The tab panel that occupies the right side of the screen.
202 private VerticalPanel inner = new VerticalPanel();
206 * The split panel that will contain the left and right panels.
208 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
211 * The currently selected item in the application, for use by the Edit menu
212 * commands. Potential types are Folder, File, User and Group.
214 private Object currentSelection;
216 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
218 private String username = null;
221 * The authentication token of the current user.
223 private String token;
227 SingleSelectionModel<Folder> folderTreeSelectionModel;
228 FolderTreeViewModel folderTreeViewModel;
229 FolderTreeView folderTreeView;
231 SingleSelectionModel<Folder> mysharedTreeSelectionModel;
232 MysharedTreeViewModel mysharedTreeViewModel;
233 MysharedTreeView mysharedTreeView = null;;
235 protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
236 OtherSharedTreeViewModel otherSharedTreeViewModel;
237 OtherSharedTreeView otherSharedTreeView = null;
239 GroupTreeViewModel groupTreeViewModel;
240 private GroupTreeView groupTreeView;
242 private TreeView selectedTree;
243 protected AccountResource account;
247 @SuppressWarnings("rawtypes") List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
251 private HTML totalFiles;
253 private HTML usedBytes;
255 private HTML totalBytes;
257 private HTML usedPercent;
259 private HTML numOfFiles;
261 private Button toolsButton;
264 public void onModuleLoad() {
265 if (parseUserCredentials())
269 private void initialize() {
270 VerticalPanel outer = new VerticalPanel();
271 outer.setWidth("100%");
273 topPanel = new TopPanel(this, Pithos.images);
274 topPanel.setWidth("100%");
277 messagePanel.setWidth("100%");
278 messagePanel.setVisible(false);
279 outer.add(messagePanel);
280 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
283 // Inner contains the various lists.
284 inner.sinkEvents(Event.ONCONTEXTMENU);
285 inner.setWidth("100%");
287 HorizontalPanel rightside = new HorizontalPanel();
288 rightside.addStyleName("pithos-rightSide");
289 rightside.setSpacing(5);
291 toolsButton = new Button(AbstractImagePrototype.create(images.tools()).getHTML());
292 toolsButton.addClickHandler(new ClickHandler() {
295 public void onClick(ClickEvent event) {
296 ToolsMenu menu = new ToolsMenu(Pithos.this, images, getSelectedTree(), getSelectedTree().getSelection(), getFileList().getSelectedFiles());
297 if (!menu.isEmpty()) {
298 menu.setPopupPosition(event.getClientX(), event.getClientY());
303 rightside.add(toolsButton);
304 rightside.setCellHorizontalAlignment(toolsButton, HasHorizontalAlignment.ALIGN_LEFT);
306 HorizontalPanel folderStatistics = new HorizontalPanel();
307 folderStatistics.addStyleName("pithos-folderStatistics");
308 numOfFiles = new HTML();
309 folderStatistics.add(numOfFiles);
310 HTML numOfFilesLabel = new HTML(" Files");
311 folderStatistics.add(numOfFilesLabel);
312 rightside.add(folderStatistics);
313 rightside.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
315 inner.add(rightside);
316 inner.setCellVerticalAlignment(rightside, HasVerticalAlignment.ALIGN_MIDDLE);
317 inner.setCellHeight(rightside, "60px");
319 folderTreeSelectionModel = new SingleSelectionModel<Folder>();
320 folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
322 public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
323 if (folderTreeSelectionModel.getSelectedObject() != null) {
324 deselectOthers(folderTreeView, folderTreeSelectionModel);
325 applyPermissions(folderTreeSelectionModel.getSelectedObject());
326 Folder f = folderTreeSelectionModel.getSelectedObject();
327 updateFolder(f, true, null);
331 selectionModels.add(folderTreeSelectionModel);
333 folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
334 folderTreeView = new FolderTreeView(folderTreeViewModel);
336 fileList = new FileList(this, images, folderTreeView);
339 groupTreeViewModel = new GroupTreeViewModel(this);
340 groupTreeView = new GroupTreeView(groupTreeViewModel);
342 trees = new VerticalPanel();
344 upload = new Button("Upload File", new ClickHandler() {
346 public void onClick(@SuppressWarnings("unused") ClickEvent event) {
347 new UploadFileCommand(Pithos.this, null, getSelection()).execute();
350 upload.addStyleName("pithos-uploadButton");
353 HorizontalPanel treeHeader = new HorizontalPanel();
354 treeHeader.addStyleName("pithos-treeHeader");
355 HorizontalPanel statistics = new HorizontalPanel();
356 statistics.add(new HTML("Total Objects: "));
357 totalFiles = new HTML();
358 statistics.add(totalFiles);
359 statistics.add(new HTML(" | Used: "));
360 usedBytes = new HTML();
361 statistics.add(usedBytes);
362 statistics.add(new HTML(" of "));
363 totalBytes = new HTML();
364 statistics.add(totalBytes);
365 statistics.add(new HTML(" ("));
366 usedPercent = new HTML();
367 statistics.add(usedPercent);
368 statistics.add(new HTML("%)"));
369 treeHeader.add(statistics);
370 trees.add(treeHeader);
372 trees.add(folderTreeView);
373 trees.add(groupTreeView);
374 // Add the left and right panels to the split panel.
375 splitPanel.setLeftWidget(trees);
376 splitPanel.setRightWidget(inner);
377 splitPanel.setSplitPosition("25%");
378 splitPanel.setSize("100%", "100%");
379 splitPanel.addStyleName("pithos-splitPanel");
380 outer.add(splitPanel);
382 statusPanel = new StatusPanel();
383 outer.add(statusPanel);
386 // Hook the window resize event, so that we can adjust the UI.
387 Window.addResizeHandler(this);
388 // Clear out the window's built-in margin, because we want to take
389 // advantage of the entire client area.
390 Window.setMargin("0px");
391 // Finally, add the outer panel to the RootPanel, so that it will be
393 RootPanel.get().add(outer);
394 // Call the window resized handler to get the initial sizes setup. Doing
395 // this in a deferred command causes it to occur after all widgets'
396 // sizes have been computed by the browser.
397 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
400 public void execute() {
401 onWindowResized(Window.getClientHeight());
405 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
407 public void execute() {
408 fetchAccount(new Command() {
411 public void execute() {
412 if (!account.hasHomeContainer())
413 createHomeContainer(account, this);
414 else if (!account.hasTrashContainer())
415 createTrashContainer(this);
417 for (Folder f : account.getContainers())
418 if (f.getName().equals(Pithos.TRASH_CONTAINER)) {
422 folderTreeViewModel.initialize(account);
423 groupTreeViewModel.initialize();
424 createMySharedTree();
433 public void applyPermissions(Folder f) {
436 upload.setEnabled(false);
438 Boolean[] perms = f.getPermissions().get(username);
439 if (f.getOwner().equals(username) || (perms != null && perms[1] != null && perms[1])) {
440 upload.setEnabled(true);
443 upload.setEnabled(false);
447 upload.setEnabled(false);
450 @SuppressWarnings({ "rawtypes", "unchecked" })
451 public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
452 selectedTree = _selectedTree;
453 for (SingleSelectionModel s : selectionModels)
454 if (!s.equals(model))
455 s.setSelected(s.getSelectedObject(), false);
458 public void showFiles(Folder f) {
459 Set<File> files = f.getFiles();
463 public void showFiles(Set<File> files) {
464 //Iterator<File> iter = files.iterator();
465 //fetchFile(iter, files);
466 fileList.setFiles(new ArrayList<File>(files));
469 protected void fetchFile(final Iterator<File> iter, final Set<File> files) {
470 if (iter.hasNext()) {
471 File file = iter.next();
472 String path = file.getUri() + "?format=json";
473 GetRequest<File> getFile = new GetRequest<File>(File.class, getApiPath(), username, path, file) {
475 public void onSuccess(@SuppressWarnings("unused") File _result) {
476 fetchFile(iter, files);
480 public void onError(Throwable t) {
481 GWT.log("Error getting file", t);
482 if (t instanceof RestException)
483 displayError("Error getting file: " + ((RestException) t).getHttpStatusText());
485 displayError("System error fetching file: " + t.getMessage());
489 protected void onUnauthorized(Response response) {
493 getFile.setHeader("X-Auth-Token", "0000");
494 Scheduler.get().scheduleDeferred(getFile);
497 fileList.setFiles(new ArrayList<File>(files));
501 * Parse and store the user credentials to the appropriate fields.
503 private boolean parseUserCredentials() {
504 username = Window.Location.getParameter("user");
505 token = Window.Location.getParameter("token");
506 Configuration conf = (Configuration) GWT.create(Configuration.class);
507 if (username == null || username.length() == 0 || token == null || token.length() == 0) {
508 String cookie = conf.authCookie();
509 String auth = Cookies.getCookie(cookie);
514 String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
515 if (authSplit.length != 2) {
519 username = authSplit[0];
520 token = authSplit[1];
523 Cookies.setCookie(conf.authCookie(), username + conf.cookieSeparator() + token);
528 * Redirect the user to the login page for authentication.
530 protected void authenticateUser() {
531 Configuration conf = (Configuration) GWT.create(Configuration.class);
532 Window.Location.assign(conf.loginUrl() + "?next=" + Window.Location.getHref());
535 protected void fetchAccount(final Command callback) {
536 String path = "?format=json";
538 GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getApiPath(), username, path) {
540 public void onSuccess(AccountResource _result) {
542 if (callback != null)
547 public void onError(Throwable t) {
548 GWT.log("Error getting account", t);
549 if (t instanceof RestException)
550 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
552 displayError("System error fetching user data: " + t.getMessage());
556 protected void onUnauthorized(Response response) {
560 getAccount.setHeader("X-Auth-Token", token);
561 Scheduler.get().scheduleDeferred(getAccount);
564 public void updateStatistics() {
565 HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getApiPath(), username, "", account) {
568 public void onSuccess(@SuppressWarnings("unused") AccountResource _result) {
573 public void onError(Throwable t) {
574 GWT.log("Error getting account", t);
575 if (t instanceof RestException)
576 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
578 displayError("System error fetching user data: " + t.getMessage());
582 protected void onUnauthorized(Response response) {
586 headAccount.setHeader("X-Auth-Token", token);
587 Scheduler.get().scheduleDeferred(headAccount);
590 protected void showStatistics() {
591 totalFiles.setHTML(String.valueOf(account.getNumberOfObjects()));
592 usedBytes.setHTML(String.valueOf(account.getFileSizeAsString()));
593 totalBytes.setHTML(String.valueOf(account.getQuotaAsString()));
594 usedPercent.setHTML(String.valueOf(account.getUsedPercentage()));
597 protected void createHomeContainer(final AccountResource _account, final Command callback) {
598 String path = "/" + Pithos.HOME_CONTAINER;
599 PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
601 public void onSuccess(@SuppressWarnings("unused") Resource result) {
602 if (!_account.hasTrashContainer())
603 createTrashContainer(callback);
605 fetchAccount(callback);
609 public void onError(Throwable t) {
610 GWT.log("Error creating pithos", t);
611 if (t instanceof RestException)
612 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
614 displayError("System error Error creating pithos: " + t.getMessage());
618 protected void onUnauthorized(Response response) {
622 createPithos.setHeader("X-Auth-Token", getToken());
623 Scheduler.get().scheduleDeferred(createPithos);
626 protected void createTrashContainer(final Command callback) {
627 String path = "/" + Pithos.TRASH_CONTAINER;
628 PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
630 public void onSuccess(@SuppressWarnings("unused") Resource result) {
631 fetchAccount(callback);
635 public void onError(Throwable t) {
636 GWT.log("Error creating pithos", t);
637 if (t instanceof RestException)
638 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
640 displayError("System error Error creating pithos: " + t.getMessage());
644 protected void onUnauthorized(Response response) {
648 createPithos.setHeader("X-Auth-Token", getToken());
649 Scheduler.get().scheduleDeferred(createPithos);
653 * Creates an HTML fragment that places an image & caption together, for use
656 * @param imageProto an image prototype for an image
657 * @param caption the group caption
658 * @return the header HTML fragment
660 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
661 String captionHTML = "<table class='caption' cellpadding='0' "
662 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
663 + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'> "
664 + caption + "</b></td></tr></table>";
668 protected void onWindowResized(int height) {
669 // Adjust the split panel to take up the available room in the window.
670 int newHeight = height - splitPanel.getAbsoluteTop() - 60;
673 splitPanel.setHeight("" + newHeight);
674 inner.setHeight("" + newHeight);
678 public void onResize(ResizeEvent event) {
679 int height = event.getHeight();
680 onWindowResized(height);
684 * Display an error message.
686 * @param msg the message to display
688 public void displayError(String msg) {
689 messagePanel.displayError(msg);
693 * Display a warning message.
695 * @param msg the message to display
697 public void displayWarning(String msg) {
698 messagePanel.displayWarning(msg);
702 * Display an informational message.
704 * @param msg the message to display
706 public void displayInformation(String msg) {
707 messagePanel.displayInformation(msg);
711 * Retrieve the fileList.
713 * @return the fileList
715 public FileList getFileList() {
720 * Retrieve the topPanel.
722 * @return the topPanel
724 TopPanel getTopPanel() {
729 * Retrieve the clipboard.
731 * @return the clipboard
733 public Clipboard getClipboard() {
737 public StatusPanel getStatusPanel() {
741 public String getToken() {
745 public static native void preventIESelection() /*-{
746 $doc.body.onselectstart = function () { return false; };
749 public static native void enableIESelection() /*-{
750 if ($doc.body.onselectstart != null)
751 $doc.body.onselectstart = null;
755 * @return the absolute path of the API root URL
757 public String getApiPath() {
758 Configuration conf = (Configuration) GWT.create(Configuration.class);
759 return conf.apiPath();
763 * History support for folder navigation
764 * adds a new browser history entry
768 public void updateHistory(String key){
769 // Replace any whitespace of the initial string to "+"
770 // String result = key.replaceAll("\\s","+");
771 // Add a new browser history entry.
772 // History.newItem(result);
773 History.newItem(key);
776 public void deleteFolder(final Folder folder) {
777 String path = getApiPath() + folder.getOwner() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(folder.getPrefix()) + "&t=" + System.currentTimeMillis();
778 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
779 builder.setHeader("X-Auth-Token", getToken());
781 builder.sendRequest("", new RequestCallback() {
783 public void onResponseReceived(@SuppressWarnings("unused") Request request, Response response) {
784 if (response.getStatusCode() == Response.SC_OK) {
785 JSONValue json = JSONParser.parseStrict(response.getText());
786 JSONArray array = json.isArray();
789 deleteObject(folder, i, array);
795 public void onError(@SuppressWarnings("unused") Request request, Throwable exception) {
796 displayError("System error unable to delete folder: " + exception.getMessage());
800 catch (RequestException e) {
804 void deleteObject(final Folder folder, final int i, final JSONArray array) {
805 if (i < array.size()) {
806 JSONObject o = array.get(i).isObject();
807 if (o != null && !o.containsKey("subdir")) {
808 JSONString name = o.get("name").isString();
809 String path = "/" + folder.getContainer() + "/" + name.stringValue();
810 DeleteRequest delete = new DeleteRequest(getApiPath(), folder.getOwner(), path) {
812 public void onSuccess(@SuppressWarnings("unused") Resource result) {
813 deleteObject(folder, i + 1, array);
817 public void onError(Throwable t) {
819 displayError("System error unable to delete folder: " + t.getMessage());
823 protected void onUnauthorized(Response response) {
827 delete.setHeader("X-Auth-Token", getToken());
828 Scheduler.get().scheduleDeferred(delete);
830 else if (o != null) {
831 String subdir = o.get("subdir").isString().stringValue();
832 subdir = subdir.substring(0, subdir.length() - 1);
833 String path = getApiPath() + getUsername() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(subdir) + "&t=" + System.currentTimeMillis();
834 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
835 builder.setHeader("X-Auth-Token", getToken());
837 builder.sendRequest("", new RequestCallback() {
839 public void onResponseReceived(@SuppressWarnings("unused") Request request, Response response) {
840 if (response.getStatusCode() == Response.SC_OK) {
841 JSONValue json = JSONParser.parseStrict(response.getText());
842 JSONArray array2 = json.isArray();
843 if (array2 != null) {
844 int l = array.size();
845 for (int j=0; j<array2.size(); j++) {
846 array.set(l++, array2.get(j));
849 deleteObject(folder, i + 1, array);
854 public void onError(@SuppressWarnings("unused") Request request, Throwable exception) {
855 displayError("System error unable to delete folder: " + exception.getMessage());
859 catch (RequestException e) {
864 String path = folder.getUri();
865 DeleteRequest deleteFolder = new DeleteRequest(getApiPath(), getUsername(), path) {
867 public void onSuccess(@SuppressWarnings("unused") Resource result) {
868 updateFolder(folder.getParent(), true, new Command() {
871 public void execute() {
878 public void onError(Throwable t) {
880 if (t instanceof RestException) {
881 if (((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND)
882 displayError("Unable to delete folder: "+((RestException) t).getHttpStatusText());
887 displayError("System error unable to delete folder: " + t.getMessage());
891 protected void onUnauthorized(Response response) {
895 deleteFolder.setHeader("X-Auth-Token", getToken());
896 Scheduler.get().scheduleDeferred(deleteFolder);
900 public FolderTreeView getFolderTreeView() {
901 return folderTreeView;
904 public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
905 if (iter.hasNext()) {
906 File file = iter.next();
907 String path = targetUri + "/" + file.getName();
908 PutRequest copyFile = new PutRequest(getApiPath(), targetUsername, path) {
910 public void onSuccess(@SuppressWarnings("unused") Resource result) {
911 copyFiles(iter, targetUsername, targetUri, callback);
915 public void onError(Throwable t) {
917 if (t instanceof RestException) {
918 displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
921 displayError("System error unable to copy file: "+t.getMessage());
925 protected void onUnauthorized(Response response) {
929 copyFile.setHeader("X-Auth-Token", getToken());
930 copyFile.setHeader("X-Copy-From", file.getUri());
931 if (!file.getOwner().equals(targetUsername))
932 copyFile.setHeader("X-Source-Account", file.getOwner());
933 Scheduler.get().scheduleDeferred(copyFile);
935 else if (callback != null) {
940 public void copySubfolders(final Iterator<Folder> iter, final String targetUsername, final String targetUri, final Command callback) {
941 if (iter.hasNext()) {
942 final Folder f = iter.next();
943 copyFolder(f, targetUsername, targetUri, new Command() {
946 public void execute() {
947 copySubfolders(iter, targetUsername, targetUri, callback);
951 else if (callback != null) {
956 public void copyFolder(final Folder f, final String targetUsername, final String targetUri, final Command callback) {
957 String path = targetUri + "/" + f.getName();
958 PutRequest createFolder = new PutRequest(getApiPath(), targetUsername, path) {
960 public void onSuccess(@SuppressWarnings("unused") Resource result) {
961 GetRequest<Folder> getFolder = new GetRequest<Folder>(Folder.class, getApiPath(), f.getOwner(), "/" + f.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(f.getPrefix()), f) {
964 public void onSuccess(final Folder _f) {
965 Iterator<File> iter = _f.getFiles().iterator();
966 copyFiles(iter, targetUsername, targetUri + "/" + _f.getName(), new Command() {
968 public void execute() {
969 Iterator<Folder> iterf = _f.getSubfolders().iterator();
970 copySubfolders(iterf, targetUsername, targetUri + "/" + _f.getName(), callback);
976 public void onError(Throwable t) {
978 if (t instanceof RestException) {
979 displayError("Unable to get folder: " + ((RestException) t).getHttpStatusText());
982 displayError("System error getting folder: " + t.getMessage());
986 protected void onUnauthorized(Response response) {
990 getFolder.setHeader("X-Auth-Token", getToken());
991 Scheduler.get().scheduleDeferred(getFolder);
995 public void onError(Throwable t) {
997 if (t instanceof RestException) {
998 displayError("Unable to create folder: " + ((RestException) t).getHttpStatusText());
1001 displayError("System error creating folder: " + t.getMessage());
1005 protected void onUnauthorized(Response response) {
1009 createFolder.setHeader("X-Auth-Token", getToken());
1010 createFolder.setHeader("Accept", "*/*");
1011 createFolder.setHeader("Content-Length", "0");
1012 createFolder.setHeader("Content-Type", "application/folder");
1013 Scheduler.get().scheduleDeferred(createFolder);
1016 public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1017 selectionModels.add(model);
1020 public OtherSharedTreeView getOtherSharedTreeView() {
1021 return otherSharedTreeView;
1024 public void updateTrash(boolean showFiles, Command callback) {
1025 updateFolder(trash, showFiles, callback);
1028 public void updateGroupsNode() {
1029 groupTreeView.updateGroupNode(null);
1032 public void addGroup(String groupname) {
1033 Group newGroup = new Group(groupname);
1034 account.addGroup(newGroup);
1035 groupTreeView.updateGroupNode(null);
1038 public void removeGroup(Group group) {
1039 account.removeGroup(group);
1043 public TreeView getSelectedTree() {
1044 return selectedTree;
1047 public Folder getSelection() {
1048 return selectedTree.getSelection();
1051 public void showFolderStatistics(int folderFileCount) {
1052 numOfFiles.setHTML(String.valueOf(folderFileCount));
1055 public GroupTreeView getGroupTreeView() {
1056 return groupTreeView;
1059 public void sessionExpired() {
1060 new SessionExpiredDialog(this).center();
1063 public void updateRootFolder(Command callback) {
1064 updateFolder(account.getPithos(), false, callback);
1067 void createMySharedTree() {
1068 mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1069 mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1071 public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
1072 if (mysharedTreeSelectionModel.getSelectedObject() != null) {
1073 deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1074 upload.setEnabled(false);
1075 updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1079 selectionModels.add(mysharedTreeSelectionModel);
1080 mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1081 mysharedTreeViewModel.initialize(new Command() {
1084 public void execute() {
1085 mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1086 trees.insert(mysharedTreeView, 3);
1087 createOtherSharedTree();
1092 void createOtherSharedTree() {
1093 otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1094 otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1096 public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
1097 if (otherSharedTreeSelectionModel.getSelectedObject() != null) {
1098 deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1099 applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1100 updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true);
1104 selectionModels.add(otherSharedTreeSelectionModel);
1105 otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1106 otherSharedTreeViewModel.initialize(new Command() {
1109 public void execute() {
1110 otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel);
1111 trees.insert(otherSharedTreeView, 4);