2 * Copyright 2011-2012 GRNET S.A. All rights reserved.
4 * Redistribution and use in source and binary forms, with or
5 * without modification, are permitted provided that the following
8 * 1. Redistributions of source code must retain the above
9 * copyright notice, this list of conditions and the following
12 * 2. Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following
14 * disclaimer in the documentation and/or other materials
15 * provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
18 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
21 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
24 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 * POSSIBILITY OF SUCH DAMAGE.
30 * The views and conclusions contained in the software and
31 * documentation are those of the authors and should not be
32 * interpreted as representing official policies, either expressed
33 * or implied, of GRNET S.A.
35 package gr.grnet.pithos.web.client;
37 import gr.grnet.pithos.web.client.commands.UploadFileCommand;
38 import gr.grnet.pithos.web.client.foldertree.AccountResource;
39 import gr.grnet.pithos.web.client.foldertree.File;
40 import gr.grnet.pithos.web.client.foldertree.Folder;
41 import gr.grnet.pithos.web.client.foldertree.FolderTreeView;
42 import gr.grnet.pithos.web.client.foldertree.FolderTreeViewModel;
43 import gr.grnet.pithos.web.client.foldertree.Resource;
44 import gr.grnet.pithos.web.client.grouptree.Group;
45 import gr.grnet.pithos.web.client.grouptree.GroupTreeView;
46 import gr.grnet.pithos.web.client.grouptree.GroupTreeViewModel;
47 import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeView;
48 import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeViewModel;
49 import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeView;
50 import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeViewModel;
51 import gr.grnet.pithos.web.client.rest.DeleteRequest;
52 import gr.grnet.pithos.web.client.rest.GetRequest;
53 import gr.grnet.pithos.web.client.rest.HeadRequest;
54 import gr.grnet.pithos.web.client.rest.PutRequest;
55 import gr.grnet.pithos.web.client.rest.RestException;
57 import java.util.ArrayList;
58 import java.util.HashMap;
59 import java.util.Iterator;
60 import java.util.List;
63 import com.google.gwt.core.client.EntryPoint;
64 import com.google.gwt.core.client.GWT;
65 import com.google.gwt.core.client.Scheduler;
66 import com.google.gwt.core.client.Scheduler.RepeatingCommand;
67 import com.google.gwt.core.client.Scheduler.ScheduledCommand;
68 import com.google.gwt.event.dom.client.ClickEvent;
69 import com.google.gwt.event.dom.client.ClickHandler;
70 import com.google.gwt.event.logical.shared.ResizeEvent;
71 import com.google.gwt.event.logical.shared.ResizeHandler;
72 import com.google.gwt.http.client.Request;
73 import com.google.gwt.http.client.RequestBuilder;
74 import com.google.gwt.http.client.RequestCallback;
75 import com.google.gwt.http.client.RequestException;
76 import com.google.gwt.http.client.Response;
77 import com.google.gwt.http.client.URL;
78 import com.google.gwt.i18n.client.Dictionary;
79 import com.google.gwt.i18n.client.NumberFormat;
80 import com.google.gwt.json.client.JSONArray;
81 import com.google.gwt.json.client.JSONObject;
82 import com.google.gwt.json.client.JSONParser;
83 import com.google.gwt.json.client.JSONString;
84 import com.google.gwt.json.client.JSONValue;
85 import com.google.gwt.resources.client.ImageResource;
86 import com.google.gwt.resources.client.ImageResource.ImageOptions;
87 import com.google.gwt.user.client.Command;
88 import com.google.gwt.user.client.Cookies;
89 import com.google.gwt.user.client.Event;
90 import com.google.gwt.user.client.History;
91 import com.google.gwt.user.client.Window;
92 import com.google.gwt.user.client.ui.AbstractImagePrototype;
93 import com.google.gwt.user.client.ui.Button;
94 import com.google.gwt.user.client.ui.Composite;
95 import com.google.gwt.user.client.ui.HTML;
96 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
97 import com.google.gwt.user.client.ui.HasVerticalAlignment;
98 import com.google.gwt.user.client.ui.HorizontalPanel;
99 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
100 import com.google.gwt.user.client.ui.RootPanel;
101 import com.google.gwt.user.client.ui.VerticalPanel;
102 import com.google.gwt.view.client.SelectionChangeEvent;
103 import com.google.gwt.view.client.SelectionChangeEvent.Handler;
104 import com.google.gwt.view.client.SingleSelectionModel;
107 * Entry point classes define <code>onModuleLoad()</code>.
109 public class Pithos implements EntryPoint, ResizeHandler {
111 public static final String HOME_CONTAINER = "pithos";
113 public static final String TRASH_CONTAINER = "trash";
115 public static final Configuration config = GWT.create(Configuration.class);
118 * Instantiate an application-level image bundle. This object will provide
119 * programmatic access to all the images needed by widgets.
121 static Images images = (Images) GWT.create(Images.class);
123 public String getUsername() {
127 public void setAccount(AccountResource acct) {
131 public AccountResource getAccount() {
135 public void updateFolder(Folder f, boolean showfiles, Command callback, final boolean openParent) {
136 folderTreeView.updateFolder(f, showfiles, callback, openParent);
139 public void updateGroupNode(Group group) {
140 groupTreeView.updateGroupNode(group);
143 public void updateMySharedRoot() {
144 mysharedTreeView.updateRoot();
147 public void updateSharedFolder(Folder f, boolean showfiles) {
148 mysharedTreeView.updateFolder(f, showfiles);
151 public void updateOtherSharedFolder(Folder f, boolean showfiles) {
152 otherSharedTreeView.updateFolder(f, showfiles);
155 public MysharedTreeView getMySharedTreeView() {
156 return mysharedTreeView;
160 * An aggregate image bundle that pulls together all the images for this
161 * application into a single bundle.
163 public interface Images extends TopPanel.Images, FileList.Images, ToolsMenu.Images {
165 @Source("gr/grnet/pithos/resources/document.png")
166 ImageResource folders();
168 @Source("gr/grnet/pithos/resources/advancedsettings.png")
169 @ImageOptions(width=32, height=32)
170 ImageResource tools();
173 private Throwable error;
176 * The Application Clipboard implementation;
178 private Clipboard clipboard = new Clipboard();
181 * The top panel that contains the menu bar.
183 private TopPanel topPanel;
186 * The panel that contains the various system messages.
188 private MessagePanel messagePanel = new MessagePanel(this, Pithos.images);
191 * The bottom panel that contains the status bar.
193 private StatusPanel statusPanel = null;
196 * The file list widget.
198 private FileList fileList;
201 * The tab panel that occupies the right side of the screen.
203 private VerticalPanel inner = new VerticalPanel();
207 * The split panel that will contain the left and right panels.
209 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
212 * The currently selected item in the application, for use by the Edit menu
213 * commands. Potential types are Folder, File, User and Group.
215 private Object currentSelection;
217 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
219 private String username = null;
222 * The authentication token of the current user.
224 private String token;
228 SingleSelectionModel<Folder> folderTreeSelectionModel;
229 FolderTreeViewModel folderTreeViewModel;
230 FolderTreeView folderTreeView;
232 SingleSelectionModel<Folder> mysharedTreeSelectionModel;
233 MysharedTreeViewModel mysharedTreeViewModel;
234 MysharedTreeView mysharedTreeView = null;;
236 protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
237 OtherSharedTreeViewModel otherSharedTreeViewModel;
238 OtherSharedTreeView otherSharedTreeView = null;
240 GroupTreeViewModel groupTreeViewModel;
241 GroupTreeView groupTreeView;
243 TreeView selectedTree;
244 protected AccountResource account;
248 List<Composite> treeViews = new ArrayList<Composite>();
250 @SuppressWarnings("rawtypes") List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
254 private HTML usedBytes;
256 private HTML totalBytes;
258 private HTML usedPercent;
260 private HTML numOfFiles;
262 private Toolbar toolbar;
264 private FileUploadDialog fileUploadDialog;
267 public void onModuleLoad() {
268 if (parseUserCredentials())
272 private void initialize() {
273 boolean bareContent = Window.Location.getParameter("noframe") != null;
274 String contentWidth = bareContent ? "100%" : "75%";
276 VerticalPanel outer = new VerticalPanel();
277 outer.setWidth("100%");
279 outer.addStyleName("pithos-outer");
283 topPanel = new TopPanel(this, Pithos.images);
284 topPanel.setWidth("100%");
286 outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
289 messagePanel.setVisible(false);
290 outer.add(messagePanel);
291 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
292 outer.setCellVerticalAlignment(messagePanel, HasVerticalAlignment.ALIGN_MIDDLE);
294 HorizontalPanel header = new HorizontalPanel();
295 header.addStyleName("pithos-header");
296 header.setWidth(contentWidth);
298 header.addStyleName("pithos-header-noframe");
299 upload = new Button("Upload", new ClickHandler() {
301 public void onClick(ClickEvent event) {
302 if (getSelection() != null)
303 new UploadFileCommand(Pithos.this, null, getSelection()).execute();
306 upload.addStyleName("pithos-uploadButton");
308 header.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_LEFT);
309 header.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
311 toolbar = new Toolbar(this);
313 header.setCellHorizontalAlignment(toolbar, HasHorizontalAlignment.ALIGN_CENTER);
314 header.setCellVerticalAlignment(toolbar, HasVerticalAlignment.ALIGN_MIDDLE);
316 HorizontalPanel folderStatistics = new HorizontalPanel();
317 folderStatistics.addStyleName("pithos-folderStatistics");
318 numOfFiles = new HTML();
319 folderStatistics.add(numOfFiles);
320 folderStatistics.setCellVerticalAlignment(numOfFiles, HasVerticalAlignment.ALIGN_MIDDLE);
321 HTML numOfFilesLabel = new HTML(" Files");
322 folderStatistics.add(numOfFilesLabel);
323 folderStatistics.setCellVerticalAlignment(numOfFilesLabel, HasVerticalAlignment.ALIGN_MIDDLE);
324 header.add(folderStatistics);
325 header.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
326 header.setCellVerticalAlignment(folderStatistics, HasVerticalAlignment.ALIGN_MIDDLE);
327 header.setCellWidth(folderStatistics, "40px");
329 outer.setCellHorizontalAlignment(header, HasHorizontalAlignment.ALIGN_CENTER);
330 // Inner contains the various lists.nner
331 inner.sinkEvents(Event.ONCONTEXTMENU);
332 inner.setWidth("100%");
334 folderTreeSelectionModel = new SingleSelectionModel<Folder>();
335 folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
337 public void onSelectionChange(SelectionChangeEvent event) {
338 if (folderTreeSelectionModel.getSelectedObject() != null) {
339 deselectOthers(folderTreeView, folderTreeSelectionModel);
340 applyPermissions(folderTreeSelectionModel.getSelectedObject());
341 Folder f = folderTreeSelectionModel.getSelectedObject();
342 updateFolder(f, true, new Command() {
345 public void execute() {
349 showRelevantToolbarButtons();
352 if (getSelectedTree().equals(folderTreeView))
353 setSelectedTree(null);
354 if (getSelectedTree() == null)
355 showRelevantToolbarButtons();
359 selectionModels.add(folderTreeSelectionModel);
361 folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
362 folderTreeView = new FolderTreeView(folderTreeViewModel);
363 treeViews.add(folderTreeView);
365 fileList = new FileList(this, images, folderTreeView);
368 trees = new VerticalPanel();
369 trees.setWidth("100%");
371 trees.add(folderTreeView);
373 HorizontalPanel separator = new HorizontalPanel();
374 separator.addStyleName("pithos-statisticsSeparator");
375 trees.add(separator);
377 HorizontalPanel statistics = new HorizontalPanel();
378 statistics.addStyleName("pithos-statistics");
379 statistics.add(new HTML("Used: "));
380 usedBytes = new HTML();
381 statistics.add(usedBytes);
382 statistics.add(new HTML(" of "));
383 totalBytes = new HTML();
384 statistics.add(totalBytes);
385 statistics.add(new HTML(" ("));
386 usedPercent = new HTML();
387 statistics.add(usedPercent);
388 statistics.add(new HTML(")"));
389 trees.add(statistics);
391 // Add the left and right panels to the split panel.
392 splitPanel.setLeftWidget(trees);
393 splitPanel.setRightWidget(inner);
394 splitPanel.setSplitPosition("219px");
395 splitPanel.setSize("100%", "100%");
396 splitPanel.addStyleName("pithos-splitPanel");
397 splitPanel.setWidth(contentWidth);
398 outer.add(splitPanel);
399 outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
402 statusPanel = new StatusPanel();
403 statusPanel.setWidth("100%");
404 outer.add(statusPanel);
405 outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
408 splitPanel.addStyleName("pithos-splitPanel-noframe");
410 // Hook the window resize event, so that we can adjust the UI.
411 Window.addResizeHandler(this);
412 // Clear out the window's built-in margin, because we want to take
413 // advantage of the entire client area.
414 Window.setMargin("0px");
415 // Finally, add the outer panel to the RootPanel, so that it will be
417 RootPanel.get().add(outer);
418 // Call the window resized handler to get the initial sizes setup. Doing
419 // this in a deferred command causes it to occur after all widgets'
420 // sizes have been computed by the browser.
421 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
424 public void execute() {
425 onWindowResized(Window.getClientHeight());
429 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
431 public void execute() {
432 fetchAccount(new Command() {
435 public void execute() {
436 if (!account.hasHomeContainer())
437 createHomeContainer(account, this);
438 else if (!account.hasTrashContainer())
439 createTrashContainer(this);
441 for (Folder f : account.getContainers())
442 if (f.getName().equals(Pithos.TRASH_CONTAINER)) {
446 folderTreeViewModel.initialize(account, new Command() {
449 public void execute() {
450 createMySharedTree();
453 groupTreeViewModel = new GroupTreeViewModel(Pithos.this);
454 groupTreeView = new GroupTreeView(groupTreeViewModel);
455 treeViews.add(groupTreeView);
456 trees.add(groupTreeView);
464 Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {
467 public boolean execute() {
468 Folder f = getSelection();
470 if (getSelectedTree().equals(folderTreeView))
471 updateFolder(f, true, null, false);
472 else if (getSelectedTree().equals(mysharedTreeView))
473 updateSharedFolder(f, true);
480 public void applyPermissions(Folder f) {
483 upload.setEnabled(false);
485 Boolean[] perms = f.getPermissions().get(username);
486 if (f.getOwner().equals(username) || (perms != null && perms[1] != null && perms[1])) {
487 upload.setEnabled(true);
490 upload.setEnabled(false);
494 upload.setEnabled(false);
497 @SuppressWarnings({ "rawtypes", "unchecked" })
498 public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
499 selectedTree = _selectedTree;
501 for (Composite c : treeViews)
502 if (c.equals(selectedTree))
503 c.addStyleName("cellTreeWidget-selectedTree");
505 c.removeStyleName("cellTreeWidget-selectedTree");
507 for (SingleSelectionModel s : selectionModels)
508 if (!s.equals(model) && s.getSelectedObject() != null)
509 s.setSelected(s.getSelectedObject(), false);
512 public void showFiles(final Folder f) {
513 Set<File> files = f.getFiles();
517 public void showFiles(Set<File> files) {
518 fileList.setFiles(new ArrayList<File>(files));
522 * Parse and store the user credentials to the appropriate fields.
524 private boolean parseUserCredentials() {
525 Configuration conf = (Configuration) GWT.create(Configuration.class);
526 Dictionary otherProperties = Dictionary.getDictionary("otherProperties");
527 String cookie = otherProperties.get("authCookie");
528 String auth = Cookies.getCookie(cookie);
533 if (auth.startsWith("\""))
534 auth = auth.substring(1);
535 if (auth.endsWith("\""))
536 auth = auth.substring(0, auth.length() - 1);
537 String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
538 if (authSplit.length != 2) {
542 username = authSplit[0];
543 token = authSplit[1];
545 String gotoUrl = Window.Location.getParameter("goto");
546 if (gotoUrl != null && gotoUrl.length() > 0) {
547 Window.Location.assign(gotoUrl);
554 * Redirect the user to the login page for authentication.
556 protected void authenticateUser() {
557 Dictionary otherProperties = Dictionary.getDictionary("otherProperties");
558 Window.Location.assign(otherProperties.get("loginUrl") + Window.Location.getHref());
561 protected void fetchAccount(final Command callback) {
562 String path = "?format=json";
564 GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getApiPath(), username, path) {
566 public void onSuccess(AccountResource _result) {
568 if (callback != null)
573 public void onError(Throwable t) {
574 GWT.log("Error getting account", t);
576 if (t instanceof RestException)
577 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
579 displayError("System error fetching user data: " + t.getMessage());
583 protected void onUnauthorized(Response response) {
587 getAccount.setHeader("X-Auth-Token", token);
588 Scheduler.get().scheduleDeferred(getAccount);
591 public void updateStatistics() {
592 HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getApiPath(), username, "", account) {
595 public void onSuccess(AccountResource _result) {
600 public void onError(Throwable t) {
601 GWT.log("Error getting account", t);
603 if (t instanceof RestException)
604 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
606 displayError("System error fetching user data: " + t.getMessage());
610 protected void onUnauthorized(Response response) {
614 headAccount.setHeader("X-Auth-Token", token);
615 Scheduler.get().scheduleDeferred(headAccount);
618 protected void showStatistics() {
619 usedBytes.setHTML(String.valueOf(account.getFileSizeAsString()));
620 totalBytes.setHTML(String.valueOf(account.getQuotaAsString()));
621 NumberFormat nf = NumberFormat.getPercentFormat();
622 usedPercent.setHTML(nf.format(account.getUsedPercentage()));
625 protected void createHomeContainer(final AccountResource _account, final Command callback) {
626 String path = "/" + Pithos.HOME_CONTAINER;
627 PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
629 public void onSuccess(Resource result) {
630 if (!_account.hasTrashContainer())
631 createTrashContainer(callback);
633 fetchAccount(callback);
637 public void onError(Throwable t) {
638 GWT.log("Error creating pithos", t);
640 if (t instanceof RestException)
641 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
643 displayError("System error Error creating pithos: " + t.getMessage());
647 protected void onUnauthorized(Response response) {
651 createPithos.setHeader("X-Auth-Token", getToken());
652 Scheduler.get().scheduleDeferred(createPithos);
655 protected void createTrashContainer(final Command callback) {
656 String path = "/" + Pithos.TRASH_CONTAINER;
657 PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
659 public void onSuccess(Resource result) {
660 fetchAccount(callback);
664 public void onError(Throwable t) {
665 GWT.log("Error creating pithos", t);
667 if (t instanceof RestException)
668 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
670 displayError("System error Error creating pithos: " + t.getMessage());
674 protected void onUnauthorized(Response response) {
678 createPithos.setHeader("X-Auth-Token", getToken());
679 Scheduler.get().scheduleDeferred(createPithos);
683 * Creates an HTML fragment that places an image & caption together, for use
686 * @param imageProto an image prototype for an image
687 * @param caption the group caption
688 * @return the header HTML fragment
690 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
691 String captionHTML = "<table class='caption' cellpadding='0' "
692 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
693 + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'> "
694 + caption + "</b></td></tr></table>";
698 protected void onWindowResized(int height) {
699 // Adjust the split panel to take up the available room in the window.
700 int newHeight = height - splitPanel.getAbsoluteTop();
703 splitPanel.setHeight("" + newHeight);
704 inner.setHeight("" + newHeight);
708 public void onResize(ResizeEvent event) {
709 int height = event.getHeight();
710 onWindowResized(height);
714 * Display an error message.
716 * @param msg the message to display
718 public void displayError(String msg) {
719 messagePanel.displayError(msg);
723 * Display a warning message.
725 * @param msg the message to display
727 public void displayWarning(String msg) {
728 messagePanel.displayWarning(msg);
732 * Display an informational message.
734 * @param msg the message to display
736 public void displayInformation(String msg) {
737 messagePanel.displayInformation(msg);
741 * Retrieve the fileList.
743 * @return the fileList
745 public FileList getFileList() {
750 * Retrieve the topPanel.
752 * @return the topPanel
754 TopPanel getTopPanel() {
759 * Retrieve the clipboard.
761 * @return the clipboard
763 public Clipboard getClipboard() {
767 public StatusPanel getStatusPanel() {
771 public String getToken() {
775 public static native void preventIESelection() /*-{
776 $doc.body.onselectstart = function () { return false; };
779 public static native void enableIESelection() /*-{
780 if ($doc.body.onselectstart != null)
781 $doc.body.onselectstart = null;
785 * @return the absolute path of the API root URL
787 public String getApiPath() {
788 Configuration conf = (Configuration) GWT.create(Configuration.class);
789 return conf.apiPath();
793 * History support for folder navigation
794 * adds a new browser history entry
798 public void updateHistory(String key){
799 // Replace any whitespace of the initial string to "+"
800 // String result = key.replaceAll("\\s","+");
801 // Add a new browser history entry.
802 // History.newItem(result);
803 History.newItem(key);
806 public void deleteFolder(final Folder folder, final Command callback) {
807 String path = getApiPath() + folder.getOwner() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(folder.getPrefix()) + "&t=" + System.currentTimeMillis();
808 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
809 builder.setHeader("X-Auth-Token", getToken());
811 builder.sendRequest("", new RequestCallback() {
813 public void onResponseReceived(Request request, Response response) {
814 if (response.getStatusCode() == Response.SC_OK) {
815 JSONValue json = JSONParser.parseStrict(response.getText());
816 JSONArray array = json.isArray();
819 deleteObject(folder, i, array, callback);
825 public void onError(Request request, Throwable exception) {
827 displayError("System error unable to delete folder: " + exception.getMessage());
831 catch (RequestException e) {
835 void deleteObject(final Folder folder, final int i, final JSONArray array, final Command callback) {
836 if (i < array.size()) {
837 JSONObject o = array.get(i).isObject();
838 if (o != null && !o.containsKey("subdir")) {
839 JSONString name = o.get("name").isString();
840 String path = "/" + folder.getContainer() + "/" + name.stringValue();
841 DeleteRequest delete = new DeleteRequest(getApiPath(), folder.getOwner(), URL.encode(path)) {
843 public void onSuccess(Resource result) {
844 deleteObject(folder, i + 1, array, callback);
848 public void onError(Throwable t) {
851 displayError("System error unable to delete folder: " + t.getMessage());
855 protected void onUnauthorized(Response response) {
859 delete.setHeader("X-Auth-Token", getToken());
860 Scheduler.get().scheduleDeferred(delete);
862 else if (o != null) {
863 String subdir = o.get("subdir").isString().stringValue();
864 subdir = subdir.substring(0, subdir.length() - 1);
865 String path = getApiPath() + getUsername() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(subdir) + "&t=" + System.currentTimeMillis();
866 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
867 builder.setHeader("X-Auth-Token", getToken());
869 builder.sendRequest("", new RequestCallback() {
871 public void onResponseReceived(Request request, Response response) {
872 if (response.getStatusCode() == Response.SC_OK) {
873 JSONValue json = JSONParser.parseStrict(response.getText());
874 JSONArray array2 = json.isArray();
875 if (array2 != null) {
876 int l = array.size();
877 for (int j=0; j<array2.size(); j++) {
878 array.set(l++, array2.get(j));
881 deleteObject(folder, i + 1, array, callback);
886 public void onError(Request request, Throwable exception) {
888 displayError("System error unable to delete folder: " + exception.getMessage());
892 catch (RequestException e) {
897 String path = folder.getUri();
898 DeleteRequest deleteFolder = new DeleteRequest(getApiPath(), getUsername(), URL.encode(path)) {
900 public void onSuccess(Resource result) {
901 updateFolder(folder.getParent(), true, new Command() {
904 public void execute() {
905 folderTreeSelectionModel.setSelected(folder.getParent(), true);
907 if (callback != null)
914 public void onError(Throwable t) {
917 if (t instanceof RestException) {
918 if (((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND)
919 displayError("Unable to delete folder: "+((RestException) t).getHttpStatusText());
924 displayError("System error unable to delete folder: " + t.getMessage());
928 protected void onUnauthorized(Response response) {
932 deleteFolder.setHeader("X-Auth-Token", getToken());
933 Scheduler.get().scheduleDeferred(deleteFolder);
937 public FolderTreeView getFolderTreeView() {
938 return folderTreeView;
941 public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
942 if (iter.hasNext()) {
943 File file = iter.next();
944 String path = targetUri + "/" + file.getName();
945 PutRequest copyFile = new PutRequest(getApiPath(), targetUsername, path) {
947 public void onSuccess(Resource result) {
948 copyFiles(iter, targetUsername, targetUri, callback);
952 public void onError(Throwable t) {
955 if (t instanceof RestException) {
956 displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
959 displayError("System error unable to copy file: "+t.getMessage());
963 protected void onUnauthorized(Response response) {
967 copyFile.setHeader("X-Auth-Token", getToken());
968 copyFile.setHeader("X-Copy-From", URL.encodePathSegment(file.getUri()));
969 if (!file.getOwner().equals(targetUsername))
970 copyFile.setHeader("X-Source-Account", URL.encodePathSegment(file.getOwner()));
971 copyFile.setHeader("Content-Type", file.getContentType());
972 Scheduler.get().scheduleDeferred(copyFile);
974 else if (callback != null) {
979 public void copySubfolders(final Iterator<Folder> iter, final String targetUsername, final String targetUri, final Command callback) {
980 if (iter.hasNext()) {
981 final Folder f = iter.next();
982 copyFolder(f, targetUsername, targetUri, new Command() {
985 public void execute() {
986 copySubfolders(iter, targetUsername, targetUri, callback);
990 else if (callback != null) {
995 public void copyFolder(final Folder f, final String targetUsername, final String targetUri, final Command callback) {
996 String path = targetUri + "/" + f.getName();
997 PutRequest createFolder = new PutRequest(getApiPath(), targetUsername, path) {
999 public void onSuccess(Resource result) {
1000 GetRequest<Folder> getFolder = new GetRequest<Folder>(Folder.class, getApiPath(), f.getOwner(), "/" + f.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(f.getPrefix()), f) {
1003 public void onSuccess(final Folder _f) {
1004 Iterator<File> iter = _f.getFiles().iterator();
1005 copyFiles(iter, targetUsername, targetUri + "/" + _f.getName(), new Command() {
1007 public void execute() {
1008 Iterator<Folder> iterf = _f.getSubfolders().iterator();
1009 copySubfolders(iterf, targetUsername, targetUri + "/" + _f.getName(), callback);
1015 public void onError(Throwable t) {
1018 if (t instanceof RestException) {
1019 displayError("Unable to get folder: " + ((RestException) t).getHttpStatusText());
1022 displayError("System error getting folder: " + t.getMessage());
1026 protected void onUnauthorized(Response response) {
1030 getFolder.setHeader("X-Auth-Token", getToken());
1031 Scheduler.get().scheduleDeferred(getFolder);
1035 public void onError(Throwable t) {
1038 if (t instanceof RestException) {
1039 displayError("Unable to create folder: " + ((RestException) t).getHttpStatusText());
1042 displayError("System error creating folder: " + t.getMessage());
1046 protected void onUnauthorized(Response response) {
1050 createFolder.setHeader("X-Auth-Token", getToken());
1051 createFolder.setHeader("Accept", "*/*");
1052 createFolder.setHeader("Content-Length", "0");
1053 createFolder.setHeader("Content-Type", "application/folder");
1054 Scheduler.get().scheduleDeferred(createFolder);
1057 public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1058 selectionModels.add(model);
1061 public OtherSharedTreeView getOtherSharedTreeView() {
1062 return otherSharedTreeView;
1065 public void updateTrash(boolean showFiles, Command callback) {
1066 updateFolder(trash, showFiles, callback, true);
1069 public void updateGroupsNode() {
1070 groupTreeView.updateGroupNode(null);
1073 public void addGroup(String groupname) {
1074 Group newGroup = new Group(groupname);
1075 account.addGroup(newGroup);
1076 groupTreeView.updateGroupNode(null);
1079 public void removeGroup(Group group) {
1080 account.removeGroup(group);
1084 public TreeView getSelectedTree() {
1085 return selectedTree;
1088 public void setSelectedTree(TreeView selected) {
1089 selectedTree = selected;
1092 public Folder getSelection() {
1093 return selectedTree.getSelection();
1096 public void showFolderStatistics(int folderFileCount) {
1097 numOfFiles.setHTML(String.valueOf(folderFileCount));
1100 public GroupTreeView getGroupTreeView() {
1101 return groupTreeView;
1104 public void sessionExpired() {
1105 new SessionExpiredDialog(this).center();
1108 public void updateRootFolder(Command callback) {
1109 updateFolder(account.getPithos(), false, callback, true);
1112 void createMySharedTree() {
1113 mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1114 mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1116 public void onSelectionChange(SelectionChangeEvent event) {
1117 if (mysharedTreeSelectionModel.getSelectedObject() != null) {
1118 deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1119 upload.setEnabled(false);
1120 updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1121 showRelevantToolbarButtons();
1124 if (getSelectedTree().equals(mysharedTreeView))
1125 setSelectedTree(null);
1126 if (getSelectedTree() == null)
1127 showRelevantToolbarButtons();
1131 selectionModels.add(mysharedTreeSelectionModel);
1132 mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1133 mysharedTreeViewModel.initialize(new Command() {
1136 public void execute() {
1137 mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1138 trees.insert(mysharedTreeView, 3);
1139 treeViews.add(mysharedTreeView);
1140 createOtherSharedTree();
1145 void createOtherSharedTree() {
1146 otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1147 otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1149 public void onSelectionChange(SelectionChangeEvent event) {
1150 if (otherSharedTreeSelectionModel.getSelectedObject() != null) {
1151 deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1152 otherSharedTreeView.addStyleName("cellTreeWidget-selectedTree");
1153 applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1154 updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true);
1155 showRelevantToolbarButtons();
1158 if (getSelectedTree().equals(otherSharedTreeView))
1159 setSelectedTree(null);
1160 if (getSelectedTree() == null)
1161 showRelevantToolbarButtons();
1165 selectionModels.add(otherSharedTreeSelectionModel);
1166 otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1167 otherSharedTreeViewModel.initialize(new Command() {
1170 public void execute() {
1171 otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel);
1172 trees.insert(otherSharedTreeView, 3);
1173 treeViews.add(otherSharedTreeView);
1178 public native void log1(String message)/*-{
1179 $wnd.console.log(message);
1182 public String getErrorData() {
1184 return error.toString();
1188 public void setError(Throwable t) {
1192 public void showRelevantToolbarButtons() {
1193 toolbar.showRelevantButtons();
1196 public FileUploadDialog getFileUploadDialog() {
1197 if (fileUploadDialog == null)
1198 fileUploadDialog = new FileUploadDialog(this);
1199 return fileUploadDialog;
1202 public void hideUploadIndicator() {
1203 upload.removeStyleName("pithos-uploadButton-loading");
1204 upload.setTitle("");
1207 public void showUploadIndicator() {
1208 upload.addStyleName("pithos-uploadButton-loading");
1209 upload.setTitle("Upload in progress. Click for details.");
1212 public void scheduleFolderHeadCommand(final Folder folder, final Command callback) {
1213 if (folder == null) {
1214 if (callback != null)
1218 HeadRequest<Folder> headFolder = new HeadRequest<Folder>(Folder.class, getApiPath(), folder.getOwner(), folder.getUri(), folder) {
1221 public void onSuccess(Folder _result) {
1222 if (callback != null)
1227 public void onError(Throwable t) {
1228 if (t instanceof RestException) {
1229 if (((RestException) t).getHttpStatusCode() == Response.SC_NOT_FOUND) {
1230 final String path = folder.getUri();
1231 PutRequest newFolder = new PutRequest(getApiPath(), folder.getOwner(), path) {
1233 public void onSuccess(Resource _result) {
1234 scheduleFolderHeadCommand(folder, callback);
1238 public void onError(Throwable _t) {
1241 if(_t instanceof RestException){
1242 displayError("Unable to create folder: " + ((RestException) _t).getHttpStatusText());
1245 displayError("System error creating folder: " + _t.getMessage());
1249 protected void onUnauthorized(Response response) {
1253 newFolder.setHeader("X-Auth-Token", getToken());
1254 newFolder.setHeader("Content-Type", "application/folder");
1255 newFolder.setHeader("Accept", "*/*");
1256 newFolder.setHeader("Content-Length", "0");
1257 Scheduler.get().scheduleDeferred(newFolder);
1260 displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
1263 displayError("System error heading folder: " + t.getMessage());
1265 GWT.log("Error heading folder", t);
1270 protected void onUnauthorized(Response response) {
1274 headFolder.setHeader("X-Auth-Token", getToken());
1275 Scheduler.get().scheduleDeferred(headFolder);
1279 public void scheduleFileHeadCommand(File f, final Command callback) {
1280 HeadRequest<File> headFile = new HeadRequest<File>(File.class, getApiPath(), f.getOwner(), f.getUri(), f) {
1283 public void onSuccess(File _result) {
1284 if (callback != null)
1289 public void onError(Throwable t) {
1290 GWT.log("Error heading file", t);
1292 if (t instanceof RestException)
1293 displayError("Error heading file: " + ((RestException) t).getHttpStatusText());
1295 displayError("System error heading file: " + t.getMessage());
1299 protected void onUnauthorized(Response response) {
1303 headFile.setHeader("X-Auth-Token", getToken());
1304 Scheduler.get().scheduleDeferred(headFile);