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.i18n.client.NumberFormat;
81 import com.google.gwt.json.client.JSONArray;
82 import com.google.gwt.json.client.JSONObject;
83 import com.google.gwt.json.client.JSONParser;
84 import com.google.gwt.json.client.JSONString;
85 import com.google.gwt.json.client.JSONValue;
86 import com.google.gwt.resources.client.ImageResource;
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.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 updateSharedFolder(Folder f, boolean showfiles) {
141 mysharedTreeView.updateFolder(f, showfiles);
144 public void updateOtherSharedFolder(Folder f, boolean showfiles) {
145 otherSharedTreeView.updateFolder(f, showfiles);
148 public List<Tag> getAllTags() {
149 List<Tag> tagList = new ArrayList<Tag>();
150 for (Folder f : account.getContainers()) {
151 for (String t : f.getTags()) {
152 tagList.add(new Tag(t));
158 public MysharedTreeView getMySharedTreeView() {
159 return mysharedTreeView;
163 * An aggregate image bundle that pulls together all the images for this
164 * application into a single bundle.
166 public interface Images extends TopPanel.Images, FileList.Images, ToolsMenu.Images {
168 @Source("gr/grnet/pithos/resources/document.png")
169 ImageResource folders();
171 @Source("gr/grnet/pithos/resources/advancedsettings.png")
172 ImageResource tools();
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(Pithos.images);
191 * The bottom panel that contains the status bar.
193 private StatusPanel statusPanel = null;
196 * The file list widget.
198 private FileList fileList;
201 * The tab panel that occupies the right side of the screen.
203 private VerticalPanel inner = new VerticalPanel();
207 * The split panel that will contain the left and right panels.
209 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
212 * The currently selected item in the application, for use by the Edit menu
213 * commands. Potential types are Folder, File, User and Group.
215 private Object currentSelection;
217 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
219 private String username = null;
222 * The authentication token of the current user.
224 private String token;
228 SingleSelectionModel<Folder> folderTreeSelectionModel;
229 FolderTreeViewModel folderTreeViewModel;
230 FolderTreeView folderTreeView;
232 SingleSelectionModel<Folder> mysharedTreeSelectionModel;
233 MysharedTreeViewModel mysharedTreeViewModel;
234 MysharedTreeView mysharedTreeView = null;;
236 protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
237 OtherSharedTreeViewModel otherSharedTreeViewModel;
238 OtherSharedTreeView otherSharedTreeView = null;
240 GroupTreeViewModel groupTreeViewModel;
241 private GroupTreeView groupTreeView;
243 private TreeView selectedTree;
244 protected AccountResource account;
248 @SuppressWarnings("rawtypes") List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
252 private HTML totalFiles;
254 private HTML usedBytes;
256 private HTML totalBytes;
258 private HTML usedPercent;
260 private HTML numOfFiles;
262 private Button toolsButton;
265 public void onModuleLoad() {
266 if (parseUserCredentials())
270 private void initialize() {
271 VerticalPanel outer = new VerticalPanel();
272 outer.setWidth("100%");
274 topPanel = new TopPanel(this, Pithos.images);
275 topPanel.setWidth("100%");
277 outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
279 messagePanel.setWidth("75%");
280 messagePanel.setVisible(false);
281 outer.add(messagePanel);
282 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
285 // Inner contains the various lists.
286 inner.sinkEvents(Event.ONCONTEXTMENU);
287 inner.setWidth("100%");
289 HorizontalPanel rightside = new HorizontalPanel();
290 rightside.addStyleName("pithos-rightSide");
291 rightside.setSpacing(5);
293 toolsButton = new Button(AbstractImagePrototype.create(images.tools()).getHTML());
294 toolsButton.addClickHandler(new ClickHandler() {
297 public void onClick(ClickEvent event) {
298 ToolsMenu menu = new ToolsMenu(Pithos.this, images, getSelectedTree(), getSelectedTree().getSelection(), getFileList().getSelectedFiles());
299 if (!menu.isEmpty()) {
300 menu.setPopupPosition(event.getClientX(), event.getClientY());
305 rightside.add(toolsButton);
306 rightside.setCellHorizontalAlignment(toolsButton, HasHorizontalAlignment.ALIGN_LEFT);
308 HorizontalPanel folderStatistics = new HorizontalPanel();
309 folderStatistics.addStyleName("pithos-folderStatistics");
310 numOfFiles = new HTML();
311 folderStatistics.add(numOfFiles);
312 HTML numOfFilesLabel = new HTML(" Files");
313 folderStatistics.add(numOfFilesLabel);
314 rightside.add(folderStatistics);
315 rightside.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
317 inner.add(rightside);
318 inner.setCellVerticalAlignment(rightside, HasVerticalAlignment.ALIGN_MIDDLE);
319 inner.setCellHeight(rightside, "60px");
321 folderTreeSelectionModel = new SingleSelectionModel<Folder>();
322 folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
324 public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
325 if (folderTreeSelectionModel.getSelectedObject() != null) {
326 deselectOthers(folderTreeView, folderTreeSelectionModel);
327 applyPermissions(folderTreeSelectionModel.getSelectedObject());
328 Folder f = folderTreeSelectionModel.getSelectedObject();
329 updateFolder(f, true, null);
333 selectionModels.add(folderTreeSelectionModel);
335 folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
336 folderTreeView = new FolderTreeView(folderTreeViewModel);
338 fileList = new FileList(this, images, folderTreeView);
341 groupTreeViewModel = new GroupTreeViewModel(this);
342 groupTreeView = new GroupTreeView(groupTreeViewModel);
344 trees = new VerticalPanel();
345 trees.setWidth("100%");
347 VerticalPanel uploadButtonPanel = new VerticalPanel();
348 upload = new Button("Upload File", new ClickHandler() {
350 public void onClick(@SuppressWarnings("unused") ClickEvent event) {
351 new UploadFileCommand(Pithos.this, null, getSelection()).execute();
354 uploadButtonPanel.add(upload);
355 uploadButtonPanel.setWidth("100%");
356 uploadButtonPanel.setHeight("60px");
357 uploadButtonPanel.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_CENTER);
358 uploadButtonPanel.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
359 upload.addStyleName("pithos-uploadButton");
360 trees.add(uploadButtonPanel);
362 HorizontalPanel treeHeader = new HorizontalPanel();
363 treeHeader.addStyleName("pithos-treeHeader");
364 treeHeader.setWidth("100%");
365 treeHeader.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
366 HorizontalPanel statistics = new HorizontalPanel();
367 statistics.add(new HTML("Total Objects: "));
368 totalFiles = new HTML();
369 statistics.add(totalFiles);
370 statistics.add(new HTML(" | Used: "));
371 usedBytes = new HTML();
372 statistics.add(usedBytes);
373 statistics.add(new HTML(" of "));
374 totalBytes = new HTML();
375 statistics.add(totalBytes);
376 statistics.add(new HTML(" ("));
377 usedPercent = new HTML();
378 statistics.add(usedPercent);
379 statistics.add(new HTML(")"));
380 treeHeader.add(statistics);
381 treeHeader.setCellHorizontalAlignment(statistics, HasHorizontalAlignment.ALIGN_LEFT);
382 trees.add(treeHeader);
384 trees.add(folderTreeView);
385 trees.add(groupTreeView);
386 // Add the left and right panels to the split panel.
387 splitPanel.setLeftWidget(trees);
388 splitPanel.setRightWidget(inner);
389 splitPanel.setSplitPosition("35%");
390 splitPanel.setSize("100%", "100%");
391 splitPanel.addStyleName("pithos-splitPanel");
392 splitPanel.setWidth("75%");
393 outer.add(splitPanel);
394 outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
396 statusPanel = new StatusPanel();
397 statusPanel.setWidth("100%");
398 outer.add(statusPanel);
399 outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
401 // Hook the window resize event, so that we can adjust the UI.
402 Window.addResizeHandler(this);
403 // Clear out the window's built-in margin, because we want to take
404 // advantage of the entire client area.
405 Window.setMargin("0px");
406 // Finally, add the outer panel to the RootPanel, so that it will be
408 RootPanel.get().add(outer);
409 // Call the window resized handler to get the initial sizes setup. Doing
410 // this in a deferred command causes it to occur after all widgets'
411 // sizes have been computed by the browser.
412 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
415 public void execute() {
416 onWindowResized(Window.getClientHeight());
420 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
422 public void execute() {
423 fetchAccount(new Command() {
426 public void execute() {
427 if (!account.hasHomeContainer())
428 createHomeContainer(account, this);
429 else if (!account.hasTrashContainer())
430 createTrashContainer(this);
432 for (Folder f : account.getContainers())
433 if (f.getName().equals(Pithos.TRASH_CONTAINER)) {
437 folderTreeViewModel.initialize(account, new Command() {
440 public void execute() {
441 createMySharedTree();
444 groupTreeViewModel.initialize();
453 public void applyPermissions(Folder f) {
456 upload.setEnabled(false);
458 Boolean[] perms = f.getPermissions().get(username);
459 if (f.getOwner().equals(username) || (perms != null && perms[1] != null && perms[1])) {
460 upload.setEnabled(true);
463 upload.setEnabled(false);
467 upload.setEnabled(false);
470 @SuppressWarnings({ "rawtypes", "unchecked" })
471 public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
472 selectedTree = _selectedTree;
473 for (SingleSelectionModel s : selectionModels)
474 if (!s.equals(model))
475 s.setSelected(s.getSelectedObject(), false);
478 public void showFiles(Folder f) {
479 Set<File> files = f.getFiles();
483 public void showFiles(Set<File> files) {
484 //Iterator<File> iter = files.iterator();
485 //fetchFile(iter, files);
486 fileList.setFiles(new ArrayList<File>(files));
489 protected void fetchFile(final Iterator<File> iter, final Set<File> files) {
490 if (iter.hasNext()) {
491 File file = iter.next();
492 String path = file.getUri() + "?format=json";
493 GetRequest<File> getFile = new GetRequest<File>(File.class, getApiPath(), username, path, file) {
495 public void onSuccess(@SuppressWarnings("unused") File _result) {
496 fetchFile(iter, files);
500 public void onError(Throwable t) {
501 GWT.log("Error getting file", t);
502 if (t instanceof RestException)
503 displayError("Error getting file: " + ((RestException) t).getHttpStatusText());
505 displayError("System error fetching file: " + t.getMessage());
509 protected void onUnauthorized(Response response) {
513 getFile.setHeader("X-Auth-Token", "0000");
514 Scheduler.get().scheduleDeferred(getFile);
517 fileList.setFiles(new ArrayList<File>(files));
521 * Parse and store the user credentials to the appropriate fields.
523 private boolean parseUserCredentials() {
524 username = Window.Location.getParameter("user");
525 token = Window.Location.getParameter("token");
526 Configuration conf = (Configuration) GWT.create(Configuration.class);
527 if (username == null || username.length() == 0 || token == null || token.length() == 0) {
528 String cookie = conf.authCookie();
529 String auth = Cookies.getCookie(cookie);
534 String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
535 if (authSplit.length != 2) {
539 username = authSplit[0];
540 token = authSplit[1];
543 Cookies.setCookie(conf.authCookie(), username + conf.cookieSeparator() + token);
548 * Redirect the user to the login page for authentication.
550 protected void authenticateUser() {
551 Configuration conf = (Configuration) GWT.create(Configuration.class);
552 Window.Location.assign(conf.loginUrl() + "?next=" + Window.Location.getHref());
555 protected void fetchAccount(final Command callback) {
556 String path = "?format=json";
558 GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getApiPath(), username, path) {
560 public void onSuccess(AccountResource _result) {
562 if (callback != null)
567 public void onError(Throwable t) {
568 GWT.log("Error getting account", t);
569 if (t instanceof RestException)
570 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
572 displayError("System error fetching user data: " + t.getMessage());
576 protected void onUnauthorized(Response response) {
580 getAccount.setHeader("X-Auth-Token", token);
581 Scheduler.get().scheduleDeferred(getAccount);
584 public void updateStatistics() {
585 HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getApiPath(), username, "", account) {
588 public void onSuccess(@SuppressWarnings("unused") AccountResource _result) {
593 public void onError(Throwable t) {
594 GWT.log("Error getting account", t);
595 if (t instanceof RestException)
596 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
598 displayError("System error fetching user data: " + t.getMessage());
602 protected void onUnauthorized(Response response) {
606 headAccount.setHeader("X-Auth-Token", token);
607 Scheduler.get().scheduleDeferred(headAccount);
610 protected void showStatistics() {
611 totalFiles.setHTML(String.valueOf(account.getNumberOfObjects()));
612 usedBytes.setHTML(String.valueOf(account.getFileSizeAsString()));
613 totalBytes.setHTML(String.valueOf(account.getQuotaAsString()));
614 NumberFormat nf = NumberFormat.getPercentFormat();
615 usedPercent.setHTML(nf.format(account.getUsedPercentage()));
618 protected void createHomeContainer(final AccountResource _account, final Command callback) {
619 String path = "/" + Pithos.HOME_CONTAINER;
620 PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
622 public void onSuccess(@SuppressWarnings("unused") Resource result) {
623 if (!_account.hasTrashContainer())
624 createTrashContainer(callback);
626 fetchAccount(callback);
630 public void onError(Throwable t) {
631 GWT.log("Error creating pithos", t);
632 if (t instanceof RestException)
633 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
635 displayError("System error Error creating pithos: " + t.getMessage());
639 protected void onUnauthorized(Response response) {
643 createPithos.setHeader("X-Auth-Token", getToken());
644 Scheduler.get().scheduleDeferred(createPithos);
647 protected void createTrashContainer(final Command callback) {
648 String path = "/" + Pithos.TRASH_CONTAINER;
649 PutRequest createPithos = new PutRequest(getApiPath(), getUsername(), path) {
651 public void onSuccess(@SuppressWarnings("unused") Resource result) {
652 fetchAccount(callback);
656 public void onError(Throwable t) {
657 GWT.log("Error creating pithos", t);
658 if (t instanceof RestException)
659 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
661 displayError("System error Error creating pithos: " + t.getMessage());
665 protected void onUnauthorized(Response response) {
669 createPithos.setHeader("X-Auth-Token", getToken());
670 Scheduler.get().scheduleDeferred(createPithos);
674 * Creates an HTML fragment that places an image & caption together, for use
677 * @param imageProto an image prototype for an image
678 * @param caption the group caption
679 * @return the header HTML fragment
681 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
682 String captionHTML = "<table class='caption' cellpadding='0' "
683 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
684 + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'> "
685 + caption + "</b></td></tr></table>";
689 protected void onWindowResized(int height) {
690 // Adjust the split panel to take up the available room in the window.
691 int newHeight = height - splitPanel.getAbsoluteTop() - 60;
694 splitPanel.setHeight("" + newHeight);
695 inner.setHeight("" + newHeight);
699 public void onResize(ResizeEvent event) {
700 int height = event.getHeight();
701 onWindowResized(height);
705 * Display an error message.
707 * @param msg the message to display
709 public void displayError(String msg) {
710 messagePanel.displayError(msg);
714 * Display a warning message.
716 * @param msg the message to display
718 public void displayWarning(String msg) {
719 messagePanel.displayWarning(msg);
723 * Display an informational message.
725 * @param msg the message to display
727 public void displayInformation(String msg) {
728 messagePanel.displayInformation(msg);
732 * Retrieve the fileList.
734 * @return the fileList
736 public FileList getFileList() {
741 * Retrieve the topPanel.
743 * @return the topPanel
745 TopPanel getTopPanel() {
750 * Retrieve the clipboard.
752 * @return the clipboard
754 public Clipboard getClipboard() {
758 public StatusPanel getStatusPanel() {
762 public String getToken() {
766 public static native void preventIESelection() /*-{
767 $doc.body.onselectstart = function () { return false; };
770 public static native void enableIESelection() /*-{
771 if ($doc.body.onselectstart != null)
772 $doc.body.onselectstart = null;
776 * @return the absolute path of the API root URL
778 public String getApiPath() {
779 Configuration conf = (Configuration) GWT.create(Configuration.class);
780 return conf.apiPath();
784 * History support for folder navigation
785 * adds a new browser history entry
789 public void updateHistory(String key){
790 // Replace any whitespace of the initial string to "+"
791 // String result = key.replaceAll("\\s","+");
792 // Add a new browser history entry.
793 // History.newItem(result);
794 History.newItem(key);
797 public void deleteFolder(final Folder folder) {
798 String path = getApiPath() + folder.getOwner() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(folder.getPrefix()) + "&t=" + System.currentTimeMillis();
799 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
800 builder.setHeader("X-Auth-Token", getToken());
802 builder.sendRequest("", new RequestCallback() {
804 public void onResponseReceived(@SuppressWarnings("unused") Request request, Response response) {
805 if (response.getStatusCode() == Response.SC_OK) {
806 JSONValue json = JSONParser.parseStrict(response.getText());
807 JSONArray array = json.isArray();
810 deleteObject(folder, i, array);
816 public void onError(@SuppressWarnings("unused") Request request, Throwable exception) {
817 displayError("System error unable to delete folder: " + exception.getMessage());
821 catch (RequestException e) {
825 void deleteObject(final Folder folder, final int i, final JSONArray array) {
826 if (i < array.size()) {
827 JSONObject o = array.get(i).isObject();
828 if (o != null && !o.containsKey("subdir")) {
829 JSONString name = o.get("name").isString();
830 String path = "/" + folder.getContainer() + "/" + name.stringValue();
831 DeleteRequest delete = new DeleteRequest(getApiPath(), folder.getOwner(), path) {
833 public void onSuccess(@SuppressWarnings("unused") Resource result) {
834 deleteObject(folder, i + 1, array);
838 public void onError(Throwable t) {
840 displayError("System error unable to delete folder: " + t.getMessage());
844 protected void onUnauthorized(Response response) {
848 delete.setHeader("X-Auth-Token", getToken());
849 Scheduler.get().scheduleDeferred(delete);
851 else if (o != null) {
852 String subdir = o.get("subdir").isString().stringValue();
853 subdir = subdir.substring(0, subdir.length() - 1);
854 String path = getApiPath() + getUsername() + "/" + folder.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(subdir) + "&t=" + System.currentTimeMillis();
855 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
856 builder.setHeader("X-Auth-Token", getToken());
858 builder.sendRequest("", new RequestCallback() {
860 public void onResponseReceived(@SuppressWarnings("unused") Request request, Response response) {
861 if (response.getStatusCode() == Response.SC_OK) {
862 JSONValue json = JSONParser.parseStrict(response.getText());
863 JSONArray array2 = json.isArray();
864 if (array2 != null) {
865 int l = array.size();
866 for (int j=0; j<array2.size(); j++) {
867 array.set(l++, array2.get(j));
870 deleteObject(folder, i + 1, array);
875 public void onError(@SuppressWarnings("unused") Request request, Throwable exception) {
876 displayError("System error unable to delete folder: " + exception.getMessage());
880 catch (RequestException e) {
885 String path = folder.getUri();
886 DeleteRequest deleteFolder = new DeleteRequest(getApiPath(), getUsername(), path) {
888 public void onSuccess(@SuppressWarnings("unused") Resource result) {
889 // folderTreeSelectionModel.setSelected(folder.getParent(), true);
890 updateFolder(folder.getParent(), true, new Command() {
893 public void execute() {
900 public void onError(Throwable t) {
902 if (t instanceof RestException) {
903 if (((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND)
904 displayError("Unable to delete folder: "+((RestException) t).getHttpStatusText());
909 displayError("System error unable to delete folder: " + t.getMessage());
913 protected void onUnauthorized(Response response) {
917 deleteFolder.setHeader("X-Auth-Token", getToken());
918 Scheduler.get().scheduleDeferred(deleteFolder);
922 public FolderTreeView getFolderTreeView() {
923 return folderTreeView;
926 public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
927 if (iter.hasNext()) {
928 File file = iter.next();
929 String path = targetUri + "/" + file.getName();
930 PutRequest copyFile = new PutRequest(getApiPath(), targetUsername, path) {
932 public void onSuccess(@SuppressWarnings("unused") Resource result) {
933 copyFiles(iter, targetUsername, targetUri, callback);
937 public void onError(Throwable t) {
939 if (t instanceof RestException) {
940 displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
943 displayError("System error unable to copy file: "+t.getMessage());
947 protected void onUnauthorized(Response response) {
951 copyFile.setHeader("X-Auth-Token", getToken());
952 copyFile.setHeader("X-Copy-From", file.getUri());
953 if (!file.getOwner().equals(targetUsername))
954 copyFile.setHeader("X-Source-Account", file.getOwner());
955 Scheduler.get().scheduleDeferred(copyFile);
957 else if (callback != null) {
962 public void copySubfolders(final Iterator<Folder> iter, final String targetUsername, final String targetUri, final Command callback) {
963 if (iter.hasNext()) {
964 final Folder f = iter.next();
965 copyFolder(f, targetUsername, targetUri, new Command() {
968 public void execute() {
969 copySubfolders(iter, targetUsername, targetUri, callback);
973 else if (callback != null) {
978 public void copyFolder(final Folder f, final String targetUsername, final String targetUri, final Command callback) {
979 String path = targetUri + "/" + f.getName();
980 PutRequest createFolder = new PutRequest(getApiPath(), targetUsername, path) {
982 public void onSuccess(@SuppressWarnings("unused") Resource result) {
983 GetRequest<Folder> getFolder = new GetRequest<Folder>(Folder.class, getApiPath(), f.getOwner(), "/" + f.getContainer() + "?format=json&delimiter=/&prefix=" + URL.encodeQueryString(f.getPrefix()), f) {
986 public void onSuccess(final Folder _f) {
987 Iterator<File> iter = _f.getFiles().iterator();
988 copyFiles(iter, targetUsername, targetUri + "/" + _f.getName(), new Command() {
990 public void execute() {
991 Iterator<Folder> iterf = _f.getSubfolders().iterator();
992 copySubfolders(iterf, targetUsername, targetUri + "/" + _f.getName(), callback);
998 public void onError(Throwable t) {
1000 if (t instanceof RestException) {
1001 displayError("Unable to get folder: " + ((RestException) t).getHttpStatusText());
1004 displayError("System error getting folder: " + t.getMessage());
1008 protected void onUnauthorized(Response response) {
1012 getFolder.setHeader("X-Auth-Token", getToken());
1013 Scheduler.get().scheduleDeferred(getFolder);
1017 public void onError(Throwable t) {
1019 if (t instanceof RestException) {
1020 displayError("Unable to create folder: " + ((RestException) t).getHttpStatusText());
1023 displayError("System error creating folder: " + t.getMessage());
1027 protected void onUnauthorized(Response response) {
1031 createFolder.setHeader("X-Auth-Token", getToken());
1032 createFolder.setHeader("Accept", "*/*");
1033 createFolder.setHeader("Content-Length", "0");
1034 createFolder.setHeader("Content-Type", "application/folder");
1035 Scheduler.get().scheduleDeferred(createFolder);
1038 public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1039 selectionModels.add(model);
1042 public OtherSharedTreeView getOtherSharedTreeView() {
1043 return otherSharedTreeView;
1046 public void updateTrash(boolean showFiles, Command callback) {
1047 updateFolder(trash, showFiles, callback);
1050 public void updateGroupsNode() {
1051 groupTreeView.updateGroupNode(null);
1054 public void addGroup(String groupname) {
1055 Group newGroup = new Group(groupname);
1056 account.addGroup(newGroup);
1057 groupTreeView.updateGroupNode(null);
1060 public void removeGroup(Group group) {
1061 account.removeGroup(group);
1065 public TreeView getSelectedTree() {
1066 return selectedTree;
1069 public Folder getSelection() {
1070 return selectedTree.getSelection();
1073 public void showFolderStatistics(int folderFileCount) {
1074 numOfFiles.setHTML(String.valueOf(folderFileCount));
1077 public GroupTreeView getGroupTreeView() {
1078 return groupTreeView;
1081 public void sessionExpired() {
1082 new SessionExpiredDialog(this).center();
1085 public void updateRootFolder(Command callback) {
1086 updateFolder(account.getPithos(), false, callback);
1089 void createMySharedTree() {
1090 mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1091 mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1093 public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
1094 if (mysharedTreeSelectionModel.getSelectedObject() != null) {
1095 deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1096 upload.setEnabled(false);
1097 updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1101 selectionModels.add(mysharedTreeSelectionModel);
1102 mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1103 mysharedTreeViewModel.initialize(new Command() {
1106 public void execute() {
1107 mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1108 trees.insert(mysharedTreeView, 3);
1109 createOtherSharedTree();
1114 void createOtherSharedTree() {
1115 otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1116 otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1118 public void onSelectionChange(@SuppressWarnings("unused") SelectionChangeEvent event) {
1119 if (otherSharedTreeSelectionModel.getSelectedObject() != null) {
1120 deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1121 applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1122 updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true);
1126 selectionModels.add(otherSharedTreeSelectionModel);
1127 otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1128 otherSharedTreeViewModel.initialize(new Command() {
1131 public void execute() {
1132 otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel);
1133 trees.insert(otherSharedTreeView, 4);
1138 public void logoff() {
1139 Configuration conf = (Configuration) GWT.create(Configuration.class);
1140 Cookies.removeCookie(conf.authCookie());
1141 Cookies.removeCookie(conf.authTokenCookie(), "/");
1142 for (String s: Cookies.getCookieNames())
1143 if (s.startsWith(conf.shibSessionCookiePrefix()))
1144 Cookies.removeCookie(s, "/");
1145 Window.Location.assign(Window.Location.getPath());