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;
58 import java.util.ArrayList;
59 import java.util.HashMap;
60 import java.util.Iterator;
61 import java.util.List;
64 import com.google.gwt.core.client.EntryPoint;
65 import com.google.gwt.core.client.GWT;
66 import com.google.gwt.core.client.Scheduler;
67 import com.google.gwt.core.client.Scheduler.ScheduledCommand;
68 import com.google.gwt.event.dom.client.ClickEvent;
69 import com.google.gwt.event.dom.client.ClickHandler;
70 import com.google.gwt.event.logical.shared.ResizeEvent;
71 import com.google.gwt.event.logical.shared.ResizeHandler;
72 import com.google.gwt.http.client.Request;
73 import com.google.gwt.http.client.RequestBuilder;
74 import com.google.gwt.http.client.RequestCallback;
75 import com.google.gwt.http.client.RequestException;
76 import com.google.gwt.http.client.Response;
77 import com.google.gwt.http.client.URL;
78 import com.google.gwt.i18n.client.NumberFormat;
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.resources.client.ImageResource.ImageOptions;
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.Composite;
94 import com.google.gwt.user.client.ui.HTML;
95 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
96 import com.google.gwt.user.client.ui.HasVerticalAlignment;
97 import com.google.gwt.user.client.ui.HorizontalPanel;
98 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
99 import com.google.gwt.user.client.ui.RootPanel;
100 import com.google.gwt.user.client.ui.VerticalPanel;
101 import com.google.gwt.view.client.SelectionChangeEvent;
102 import com.google.gwt.view.client.SelectionChangeEvent.Handler;
103 import com.google.gwt.view.client.SingleSelectionModel;
106 * Entry point classes define <code>onModuleLoad()</code>.
108 public class Pithos implements EntryPoint, ResizeHandler {
110 public static final String HOME_CONTAINER = "pithos";
112 public static final String TRASH_CONTAINER = "trash";
115 * Instantiate an application-level image bundle. This object will provide
116 * programmatic access to all the images needed by widgets.
118 static Images images = (Images) GWT.create(Images.class);
120 public String getUsername() {
124 public void setAccount(AccountResource acct) {
128 public AccountResource getAccount() {
132 public void updateFolder(Folder f, boolean showfiles, Command callback) {
133 folderTreeView.updateFolder(f, showfiles, callback);
136 public void updateGroupNode(Group group) {
137 groupTreeView.updateGroupNode(group);
140 public void updateMySharedRoot() {
141 mysharedTreeView.updateRoot();
144 public void updateSharedFolder(Folder f, boolean showfiles) {
145 mysharedTreeView.updateFolder(f, showfiles);
148 public void updateOtherSharedFolder(Folder f, boolean showfiles) {
149 otherSharedTreeView.updateFolder(f, showfiles);
152 public List<Tag> getAllTags() {
153 List<Tag> tagList = new ArrayList<Tag>();
154 for (Folder f : account.getContainers()) {
155 for (String t : f.getTags()) {
156 tagList.add(new Tag(t));
162 public MysharedTreeView getMySharedTreeView() {
163 return mysharedTreeView;
167 * An aggregate image bundle that pulls together all the images for this
168 * application into a single bundle.
170 public interface Images extends TopPanel.Images, FileList.Images, ToolsMenu.Images {
172 @Source("gr/grnet/pithos/resources/document.png")
173 ImageResource folders();
175 @Source("gr/grnet/pithos/resources/advancedsettings.png")
176 @ImageOptions(width=32, height=32)
177 ImageResource tools();
180 private Throwable error;
183 * The Application Clipboard implementation;
185 private Clipboard clipboard = new Clipboard();
188 * The top panel that contains the menu bar.
190 private TopPanel topPanel;
193 * The panel that contains the various system messages.
195 private MessagePanel messagePanel = new MessagePanel(this, Pithos.images);
198 * The bottom panel that contains the status bar.
200 private StatusPanel statusPanel = null;
203 * The file list widget.
205 private FileList fileList;
208 * The tab panel that occupies the right side of the screen.
210 private VerticalPanel inner = new VerticalPanel();
214 * The split panel that will contain the left and right panels.
216 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
219 * The currently selected item in the application, for use by the Edit menu
220 * commands. Potential types are Folder, File, User and Group.
222 private Object currentSelection;
224 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
226 private String username = null;
229 * The authentication token of the current user.
231 private String token;
235 SingleSelectionModel<Folder> folderTreeSelectionModel;
236 FolderTreeViewModel folderTreeViewModel;
237 FolderTreeView folderTreeView;
239 SingleSelectionModel<Folder> mysharedTreeSelectionModel;
240 MysharedTreeViewModel mysharedTreeViewModel;
241 MysharedTreeView mysharedTreeView = null;;
243 protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
244 OtherSharedTreeViewModel otherSharedTreeViewModel;
245 OtherSharedTreeView otherSharedTreeView = null;
247 GroupTreeViewModel groupTreeViewModel;
248 private GroupTreeView groupTreeView;
250 TreeView selectedTree;
251 protected AccountResource account;
255 List<Composite> treeViews = new ArrayList<Composite>();
257 @SuppressWarnings("rawtypes") List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
261 private HTML usedBytes;
263 private HTML totalBytes;
265 private HTML usedPercent;
267 private HTML numOfFiles;
269 private Toolbar toolbar;
272 public void onModuleLoad() {
273 if (parseUserCredentials())
277 private void initialize() {
278 boolean bareContent = Window.Location.getParameter("noframe") != null;
279 String contentWidth = bareContent ? "100%" : "75%";
281 VerticalPanel outer = new VerticalPanel();
282 outer.setWidth("100%");
284 outer.addStyleName("pithos-outer");
288 topPanel = new TopPanel(this, Pithos.images);
289 topPanel.setWidth("100%");
291 outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
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 File", new ClickHandler() {
301 public void onClick(ClickEvent event) {
302 new UploadFileCommand(Pithos.this, null, getSelection()).execute();
305 upload.addStyleName("pithos-uploadButton");
307 header.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_LEFT);
308 header.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
310 messagePanel.setVisible(false);
311 header.add(messagePanel);
312 header.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
313 header.setCellVerticalAlignment(messagePanel, HasVerticalAlignment.ALIGN_MIDDLE);
315 toolbar = new Toolbar(this);
317 header.setCellHorizontalAlignment(toolbar, HasHorizontalAlignment.ALIGN_CENTER);
318 header.setCellVerticalAlignment(toolbar, HasVerticalAlignment.ALIGN_MIDDLE);
320 HorizontalPanel folderStatistics = new HorizontalPanel();
321 folderStatistics.addStyleName("pithos-folderStatistics");
322 numOfFiles = new HTML();
323 folderStatistics.add(numOfFiles);
324 folderStatistics.setCellVerticalAlignment(numOfFiles, HasVerticalAlignment.ALIGN_MIDDLE);
325 HTML numOfFilesLabel = new HTML(" Files");
326 folderStatistics.add(numOfFilesLabel);
327 folderStatistics.setCellVerticalAlignment(numOfFilesLabel, HasVerticalAlignment.ALIGN_MIDDLE);
328 header.add(folderStatistics);
329 header.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
330 header.setCellVerticalAlignment(folderStatistics, HasVerticalAlignment.ALIGN_MIDDLE);
331 header.setCellWidth(folderStatistics, "40px");
333 outer.setCellHorizontalAlignment(header, HasHorizontalAlignment.ALIGN_CENTER);
334 // Inner contains the various lists.nner
335 inner.sinkEvents(Event.ONCONTEXTMENU);
336 inner.setWidth("100%");
338 folderTreeSelectionModel = new SingleSelectionModel<Folder>();
339 folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
341 public void onSelectionChange(SelectionChangeEvent event) {
342 if (folderTreeSelectionModel.getSelectedObject() != null) {
343 deselectOthers(folderTreeView, folderTreeSelectionModel);
344 applyPermissions(folderTreeSelectionModel.getSelectedObject());
345 Folder f = folderTreeSelectionModel.getSelectedObject();
346 updateFolder(f, true, new Command() {
349 public void execute() {
354 showRelevantToolbarButtons();
357 selectionModels.add(folderTreeSelectionModel);
359 folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
360 folderTreeView = new FolderTreeView(folderTreeViewModel);
361 treeViews.add(folderTreeView);
363 fileList = new FileList(this, images, folderTreeView);
366 groupTreeViewModel = new GroupTreeViewModel(this);
367 groupTreeView = new GroupTreeView(groupTreeViewModel);
368 treeViews.add(groupTreeView);
370 trees = new VerticalPanel();
371 trees.setWidth("100%");
374 HorizontalPanel treeHeader = new HorizontalPanel();
375 treeHeader.addStyleName("pithos-treeHeader");
376 treeHeader.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
377 treeHeader.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
378 HorizontalPanel statistics = new HorizontalPanel();
379 statistics.addStyleName("pithos-statistics");
380 statistics.add(new HTML("Used: "));
381 usedBytes = new HTML();
382 statistics.add(usedBytes);
383 statistics.add(new HTML(" of "));
384 totalBytes = new HTML();
385 statistics.add(totalBytes);
386 statistics.add(new HTML(" ("));
387 usedPercent = new HTML();
388 statistics.add(usedPercent);
389 statistics.add(new HTML(")"));
390 treeHeader.add(statistics);
391 treeHeader.setCellHorizontalAlignment(statistics, HasHorizontalAlignment.ALIGN_LEFT);
392 trees.add(treeHeader);
394 trees.add(folderTreeView);
395 trees.add(groupTreeView);
396 // Add the left and right panels to the split panel.
397 splitPanel.setLeftWidget(trees);
398 splitPanel.setRightWidget(inner);
399 splitPanel.setSplitPosition("35%");
400 splitPanel.setSize("100%", "100%");
401 splitPanel.addStyleName("pithos-splitPanel");
402 splitPanel.setWidth(contentWidth);
403 outer.add(splitPanel);
404 outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
407 statusPanel = new StatusPanel();
408 statusPanel.setWidth("100%");
409 outer.add(statusPanel);
410 outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
413 splitPanel.addStyleName("pithos-splitPanel-noframe");
415 // Hook the window resize event, so that we can adjust the UI.
416 Window.addResizeHandler(this);
417 // Clear out the window's built-in margin, because we want to take
418 // advantage of the entire client area.
419 Window.setMargin("0px");
420 // Finally, add the outer panel to the RootPanel, so that it will be
422 RootPanel.get().add(outer);
423 // Call the window resized handler to get the initial sizes setup. Doing
424 // this in a deferred command causes it to occur after all widgets'
425 // sizes have been computed by the browser.
426 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
429 public void execute() {
430 onWindowResized(Window.getClientHeight());
434 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
436 public void execute() {
437 fetchAccount(new Command() {
440 public void execute() {
441 if (!account.hasHomeContainer())
442 createHomeContainer(account, this);
443 else if (!account.hasTrashContainer())
444 createTrashContainer(this);
446 for (Folder f : account.getContainers())
447 if (f.getName().equals(Pithos.TRASH_CONTAINER)) {
451 folderTreeViewModel.initialize(account, new Command() {
454 public void execute() {
455 createMySharedTree();
458 groupTreeViewModel.initialize();
466 // Scheduler.get().scheduleDeferred(new Command() {
469 // public void execute() {
470 // displayError("lalala");
476 public void applyPermissions(Folder f) {
479 upload.setEnabled(false);
481 Boolean[] perms = f.getPermissions().get(username);
482 if (f.getOwner().equals(username) || (perms != null && perms[1] != null && perms[1])) {
483 upload.setEnabled(true);
486 upload.setEnabled(false);
490 upload.setEnabled(false);
493 @SuppressWarnings({ "rawtypes", "unchecked" })
494 public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
495 selectedTree = _selectedTree;
497 for (Composite c : treeViews)
498 if (c.equals(selectedTree))
499 c.addStyleName("cellTreeWidget-selectedTree");
501 c.removeStyleName("cellTreeWidget-selectedTree");
503 for (SingleSelectionModel s : selectionModels)
504 if (!s.equals(model))
505 s.setSelected(s.getSelectedObject(), false);
508 public void showFiles(final Folder f) {
509 Set<File> files = f.getFiles();
513 public void showFiles(Set<File> 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(File _result) {
524 fetchFile(iter, files);
528 public void onError(Throwable t) {
529 GWT.log("Error getting file", t);
531 if (t instanceof RestException)
532 displayError("Error getting file: " + ((RestException) t).getHttpStatusText());
534 displayError("System error fetching file: " + t.getMessage());
538 protected void onUnauthorized(Response response) {
542 getFile.setHeader("X-Auth-Token", "0000");
543 Scheduler.get().scheduleDeferred(getFile);
546 fileList.setFiles(new ArrayList<File>(files));
550 * Parse and store the user credentials to the appropriate fields.
552 private boolean parseUserCredentials() {
553 username = Window.Location.getParameter("user");
554 token = Window.Location.getParameter("token");
555 Configuration conf = (Configuration) GWT.create(Configuration.class);
556 if (username == null || username.length() == 0 || token == null || token.length() == 0) {
557 String cookie = conf.authCookie();
558 String auth = Cookies.getCookie(cookie);
563 if (auth.startsWith("\""))
564 auth = auth.substring(1);
565 if (auth.endsWith("\""))
566 auth = auth.substring(0, auth.length() - 1);
567 String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
568 if (authSplit.length != 2) {
572 username = authSplit[0];
573 token = authSplit[1];
577 Cookies.setCookie(conf.authCookie(), username + conf.cookieSeparator() + token, null, "", "/", false);
582 * Redirect the user to the login page for authentication.
584 protected void authenticateUser() {
585 Configuration conf = (Configuration) GWT.create(Configuration.class);
586 Window.Location.assign(conf.loginUrl() + "?next=" + Window.Location.getHref());
589 protected void fetchAccount(final Command callback) {
590 String path = "?format=json";
592 GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getApiPath(), username, path) {
594 public void onSuccess(AccountResource _result) {
596 if (callback != null)
601 public void onError(Throwable t) {
602 GWT.log("Error getting account", t);
604 if (t instanceof RestException)
605 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
607 displayError("System error fetching user data: " + t.getMessage());
611 protected void onUnauthorized(Response response) {
615 getAccount.setHeader("X-Auth-Token", token);
616 Scheduler.get().scheduleDeferred(getAccount);
619 public void updateStatistics() {
620 HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getApiPath(), username, "", account) {
623 public void onSuccess(AccountResource _result) {
628 public void onError(Throwable t) {
629 GWT.log("Error getting account", t);
631 if (t instanceof RestException)
632 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
634 displayError("System error fetching user data: " + t.getMessage());
638 protected void onUnauthorized(Response response) {
642 headAccount.setHeader("X-Auth-Token", token);
643 Scheduler.get().scheduleDeferred(headAccount);
646 protected void showStatistics() {
647 usedBytes.setHTML(String.valueOf(account.getFileSizeAsString()));
648 totalBytes.setHTML(String.valueOf(account.getQuotaAsString()));
649 NumberFormat nf = NumberFormat.getPercentFormat();
650 usedPercent.setHTML(nf.format(account.getUsedPercentage()));
653 protected void createHomeContainer(final AccountResource _account, final Command callback) {
654 String path = "/" + Pithos.HOME_CONTAINER;
655 PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
657 public void onSuccess(Resource result) {
658 if (!_account.hasTrashContainer())
659 createTrashContainer(callback);
661 fetchAccount(callback);
665 public void onError(Throwable t) {
666 GWT.log("Error creating pithos", t);
668 if (t instanceof RestException)
669 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
671 displayError("System error Error creating pithos: " + t.getMessage());
675 protected void onUnauthorized(Response response) {
679 createPithos.setHeader("X-Auth-Token", getToken());
680 Scheduler.get().scheduleDeferred(createPithos);
683 protected void createTrashContainer(final Command callback) {
684 String path = "/" + Pithos.TRASH_CONTAINER;
685 PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
687 public void onSuccess(Resource result) {
688 fetchAccount(callback);
692 public void onError(Throwable t) {
693 GWT.log("Error creating pithos", t);
695 if (t instanceof RestException)
696 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
698 displayError("System error Error creating pithos: " + t.getMessage());
702 protected void onUnauthorized(Response response) {
706 createPithos.setHeader("X-Auth-Token", getToken());
707 Scheduler.get().scheduleDeferred(createPithos);
711 * Creates an HTML fragment that places an image & caption together, for use
714 * @param imageProto an image prototype for an image
715 * @param caption the group caption
716 * @return the header HTML fragment
718 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
719 String captionHTML = "<table class='caption' cellpadding='0' "
720 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
721 + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'> "
722 + caption + "</b></td></tr></table>";
726 protected void onWindowResized(int height) {
727 // Adjust the split panel to take up the available room in the window.
728 int newHeight = height - splitPanel.getAbsoluteTop();
731 splitPanel.setHeight("" + newHeight);
732 inner.setHeight("" + newHeight);
736 public void onResize(ResizeEvent event) {
737 int height = event.getHeight();
738 onWindowResized(height);
742 * Display an error message.
744 * @param msg the message to display
746 public void displayError(String msg) {
747 messagePanel.displayError(msg);
751 * Display a warning message.
753 * @param msg the message to display
755 public void displayWarning(String msg) {
756 messagePanel.displayWarning(msg);
760 * Display an informational message.
762 * @param msg the message to display
764 public void displayInformation(String msg) {
765 messagePanel.displayInformation(msg);
769 * Retrieve the fileList.
771 * @return the fileList
773 public FileList getFileList() {
778 * Retrieve the topPanel.
780 * @return the topPanel
782 TopPanel getTopPanel() {
787 * Retrieve the clipboard.
789 * @return the clipboard
791 public Clipboard getClipboard() {
795 public StatusPanel getStatusPanel() {
799 public String getToken() {
803 public static native void preventIESelection() /*-{
804 $doc.body.onselectstart = function () { return false; };
807 public static native void enableIESelection() /*-{
808 if ($doc.body.onselectstart != null)
809 $doc.body.onselectstart = null;
813 * @return the absolute path of the API root URL
815 public String getApiPath() {
816 Configuration conf = (Configuration) GWT.create(Configuration.class);
817 return conf.apiPath();
821 * History support for folder navigation
822 * adds a new browser history entry
826 public void updateHistory(String key){
827 // Replace any whitespace of the initial string to "+"
828 // String result = key.replaceAll("\\s","+");
829 // Add a new browser history entry.
830 // History.newItem(result);
831 History.newItem(key);
834 public void deleteFolder(final Folder folder) {
835 String path = getApiPath() + folder.getOwner() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(folder.getPrefix()) + "&t=" + System.currentTimeMillis();
836 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
837 builder.setHeader("X-Auth-Token", getToken());
839 builder.sendRequest("", new RequestCallback() {
841 public void onResponseReceived(Request request, Response response) {
842 if (response.getStatusCode() == Response.SC_OK) {
843 JSONValue json = JSONParser.parseStrict(response.getText());
844 JSONArray array = json.isArray();
847 deleteObject(folder, i, array);
853 public void onError(Request request, Throwable exception) {
855 displayError("System error unable to delete folder: " + exception.getMessage());
859 catch (RequestException e) {
863 void deleteObject(final Folder folder, final int i, final JSONArray array) {
864 if (i < array.size()) {
865 JSONObject o = array.get(i).isObject();
866 if (o != null && !o.containsKey("subdir")) {
867 JSONString name = o.get("name").isString();
868 String path = "/" + folder.getContainer() + "/" + name.stringValue();
869 DeleteRequest delete = new DeleteRequest(getApiPath(), folder.getOwner(), path) {
871 public void onSuccess(Resource result) {
872 deleteObject(folder, i + 1, array);
876 public void onError(Throwable t) {
879 displayError("System error unable to delete folder: " + t.getMessage());
883 protected void onUnauthorized(Response response) {
887 delete.setHeader("X-Auth-Token", getToken());
888 Scheduler.get().scheduleDeferred(delete);
890 else if (o != null) {
891 String subdir = o.get("subdir").isString().stringValue();
892 subdir = subdir.substring(0, subdir.length() - 1);
893 String path = getApiPath() + getUsername() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(subdir) + "&t=" + System.currentTimeMillis();
894 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
895 builder.setHeader("X-Auth-Token", getToken());
897 builder.sendRequest("", new RequestCallback() {
899 public void onResponseReceived(Request request, Response response) {
900 if (response.getStatusCode() == Response.SC_OK) {
901 JSONValue json = JSONParser.parseStrict(response.getText());
902 JSONArray array2 = json.isArray();
903 if (array2 != null) {
904 int l = array.size();
905 for (int j=0; j<array2.size(); j++) {
906 array.set(l++, array2.get(j));
909 deleteObject(folder, i + 1, array);
914 public void onError(Request request, Throwable exception) {
916 displayError("System error unable to delete folder: " + exception.getMessage());
920 catch (RequestException e) {
925 String path = folder.getUri();
926 DeleteRequest deleteFolder = new DeleteRequest(getApiPath(), getUsername(), path) {
928 public void onSuccess(Resource result) {
929 updateFolder(folder.getParent(), true, new Command() {
932 public void execute() {
939 public void onError(Throwable t) {
942 if (t instanceof RestException) {
943 if (((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND)
944 displayError("Unable to delete folder: "+((RestException) t).getHttpStatusText());
949 displayError("System error unable to delete folder: " + t.getMessage());
953 protected void onUnauthorized(Response response) {
957 deleteFolder.setHeader("X-Auth-Token", getToken());
958 Scheduler.get().scheduleDeferred(deleteFolder);
962 public FolderTreeView getFolderTreeView() {
963 return folderTreeView;
966 public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
967 if (iter.hasNext()) {
968 File file = iter.next();
969 String path = targetUri + "/" + file.getName();
970 PutRequest copyFile = new PutRequest(getApiPath(), targetUsername, path) {
972 public void onSuccess(Resource result) {
973 copyFiles(iter, targetUsername, targetUri, callback);
977 public void onError(Throwable t) {
980 if (t instanceof RestException) {
981 displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
984 displayError("System error unable to copy file: "+t.getMessage());
988 protected void onUnauthorized(Response response) {
992 copyFile.setHeader("X-Auth-Token", getToken());
993 copyFile.setHeader("X-Copy-From", URL.encodePathSegment(file.getUri()));
994 if (!file.getOwner().equals(targetUsername))
995 copyFile.setHeader("X-Source-Account", URL.encodePathSegment(file.getOwner()));
996 copyFile.setHeader("Content-Type", file.getContentType());
997 Scheduler.get().scheduleDeferred(copyFile);
999 else if (callback != null) {
1004 public void copySubfolders(final Iterator<Folder> iter, final String targetUsername, final String targetUri, final Command callback) {
1005 if (iter.hasNext()) {
1006 final Folder f = iter.next();
1007 copyFolder(f, targetUsername, targetUri, new Command() {
1010 public void execute() {
1011 copySubfolders(iter, targetUsername, targetUri, callback);
1015 else if (callback != null) {
1020 public void copyFolder(final Folder f, final String targetUsername, final String targetUri, final Command callback) {
1021 String path = targetUri + "/" + f.getName();
1022 PutRequest createFolder = new PutRequest(getApiPath(), targetUsername, path) {
1024 public void onSuccess(Resource result) {
1025 GetRequest<Folder> getFolder = new GetRequest<Folder>(Folder.class, getApiPath(), f.getOwner(), "/" + f.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(f.getPrefix()), f) {
1028 public void onSuccess(final Folder _f) {
1029 Iterator<File> iter = _f.getFiles().iterator();
1030 copyFiles(iter, targetUsername, targetUri + "/" + _f.getName(), new Command() {
1032 public void execute() {
1033 Iterator<Folder> iterf = _f.getSubfolders().iterator();
1034 copySubfolders(iterf, targetUsername, targetUri + "/" + _f.getName(), callback);
1040 public void onError(Throwable t) {
1043 if (t instanceof RestException) {
1044 displayError("Unable to get folder: " + ((RestException) t).getHttpStatusText());
1047 displayError("System error getting folder: " + t.getMessage());
1051 protected void onUnauthorized(Response response) {
1055 getFolder.setHeader("X-Auth-Token", getToken());
1056 Scheduler.get().scheduleDeferred(getFolder);
1060 public void onError(Throwable t) {
1063 if (t instanceof RestException) {
1064 displayError("Unable to create folder: " + ((RestException) t).getHttpStatusText());
1067 displayError("System error creating folder: " + t.getMessage());
1071 protected void onUnauthorized(Response response) {
1075 createFolder.setHeader("X-Auth-Token", getToken());
1076 createFolder.setHeader("Accept", "*/*");
1077 createFolder.setHeader("Content-Length", "0");
1078 createFolder.setHeader("Content-Type", "application/folder");
1079 Scheduler.get().scheduleDeferred(createFolder);
1082 public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1083 selectionModels.add(model);
1086 public OtherSharedTreeView getOtherSharedTreeView() {
1087 return otherSharedTreeView;
1090 public void updateTrash(boolean showFiles, Command callback) {
1091 updateFolder(trash, showFiles, callback);
1094 public void updateGroupsNode() {
1095 groupTreeView.updateGroupNode(null);
1098 public void addGroup(String groupname) {
1099 Group newGroup = new Group(groupname);
1100 account.addGroup(newGroup);
1101 groupTreeView.updateGroupNode(null);
1104 public void removeGroup(Group group) {
1105 account.removeGroup(group);
1109 public TreeView getSelectedTree() {
1110 return selectedTree;
1113 public Folder getSelection() {
1114 return selectedTree.getSelection();
1117 public void showFolderStatistics(int folderFileCount) {
1118 numOfFiles.setHTML(String.valueOf(folderFileCount));
1121 public GroupTreeView getGroupTreeView() {
1122 return groupTreeView;
1125 public void sessionExpired() {
1126 new SessionExpiredDialog(this).center();
1129 public void updateRootFolder(Command callback) {
1130 updateFolder(account.getPithos(), false, callback);
1133 void createMySharedTree() {
1134 mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1135 mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1137 public void onSelectionChange(SelectionChangeEvent event) {
1138 if (mysharedTreeSelectionModel.getSelectedObject() != null) {
1139 deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1140 upload.setEnabled(false);
1141 updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1143 showRelevantToolbarButtons();
1146 selectionModels.add(mysharedTreeSelectionModel);
1147 mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1148 mysharedTreeViewModel.initialize(new Command() {
1151 public void execute() {
1152 mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1153 trees.insert(mysharedTreeView, 2);
1154 treeViews.add(mysharedTreeView);
1155 createOtherSharedTree();
1160 void createOtherSharedTree() {
1161 otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1162 otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1164 public void onSelectionChange(SelectionChangeEvent event) {
1165 if (otherSharedTreeSelectionModel.getSelectedObject() != null) {
1166 deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1167 otherSharedTreeView.addStyleName("cellTreeWidget-selectedTree");
1168 applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1169 updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true);
1171 showRelevantToolbarButtons();
1174 selectionModels.add(otherSharedTreeSelectionModel);
1175 otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1176 otherSharedTreeViewModel.initialize(new Command() {
1179 public void execute() {
1180 otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel);
1181 trees.insert(otherSharedTreeView, 3);
1182 treeViews.add(otherSharedTreeView);
1187 public void logoff() {
1188 Configuration conf = (Configuration) GWT.create(Configuration.class);
1189 Cookies.removeCookie(conf.authCookie(), "/");
1190 Cookies.removeCookie(conf.authTokenCookie(), "/");
1191 for (String s: Cookies.getCookieNames())
1192 if (s.startsWith(conf.shibSessionCookiePrefix()))
1193 Cookies.removeCookie(s, "/");
1194 Window.Location.assign(Window.Location.getPath());
1197 public String getErrorData() {
1199 return error.toString();
1203 public void setError(Throwable t) {
1207 public void showRelevantToolbarButtons() {
1208 toolbar.showRelevantButtons();