2 * Copyright 2011-2013 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 com.google.gwt.core.client.EntryPoint;
38 import com.google.gwt.core.client.GWT;
39 import com.google.gwt.core.client.JsArrayString;
40 import com.google.gwt.core.client.Scheduler;
41 import com.google.gwt.core.client.Scheduler.RepeatingCommand;
42 import com.google.gwt.core.client.Scheduler.ScheduledCommand;
43 import com.google.gwt.event.dom.client.ClickEvent;
44 import com.google.gwt.event.dom.client.ClickHandler;
45 import com.google.gwt.event.logical.shared.ResizeEvent;
46 import com.google.gwt.event.logical.shared.ResizeHandler;
47 import com.google.gwt.http.client.Response;
48 import com.google.gwt.http.client.URL;
49 import com.google.gwt.i18n.client.DateTimeFormat;
50 import com.google.gwt.i18n.client.Dictionary;
51 import com.google.gwt.i18n.client.TimeZone;
52 import com.google.gwt.resources.client.ClientBundle;
53 import com.google.gwt.resources.client.CssResource;
54 import com.google.gwt.resources.client.ImageResource;
55 import com.google.gwt.resources.client.ImageResource.ImageOptions;
56 import com.google.gwt.user.client.*;
57 import com.google.gwt.user.client.ui.*;
58 import com.google.gwt.view.client.SelectionChangeEvent;
59 import com.google.gwt.view.client.SelectionChangeEvent.Handler;
60 import com.google.gwt.view.client.SingleSelectionModel;
61 import gr.grnet.pithos.web.client.catalog.UpdateUserCatalogs;
62 import gr.grnet.pithos.web.client.catalog.UserCatalogs;
63 import gr.grnet.pithos.web.client.commands.UploadFileCommand;
64 import gr.grnet.pithos.web.client.foldertree.*;
65 import gr.grnet.pithos.web.client.grouptree.Group;
66 import gr.grnet.pithos.web.client.grouptree.GroupTreeView;
67 import gr.grnet.pithos.web.client.grouptree.GroupTreeViewModel;
68 import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeView;
69 import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeViewModel;
70 import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeView;
71 import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeViewModel;
72 import gr.grnet.pithos.web.client.rest.*;
73 import org.apache.http.HttpStatus;
78 * Entry point classes define <code>onModuleLoad()</code>.
80 public class Pithos implements EntryPoint, ResizeHandler {
82 public static final Configuration config = GWT.create(Configuration.class);
84 public interface Style extends CssResource {
85 String commandAnchor();
89 @ClassName("gwt-HTML")
94 String uploadAlertLink();
96 String uploadAlertProgress();
98 String uploadAlertPercent();
100 String uploadAlertClose();
103 public interface Resources extends ClientBundle {
104 @Source("Pithos.css")
107 @Source("gr/grnet/pithos/resources/close-popup.png")
108 ImageResource closePopup();
111 public static Resources resources = GWT.create(Resources.class);
114 * Instantiate an application-level image bundle. This object will provide
115 * programmatic access to all the images needed by widgets.
117 static Images images = (Images) GWT.create(Images.class);
119 public String getUserID() {
123 public UserCatalogs getUserCatalogs() {
127 public String getCurrentUserDisplayNameOrID() {
128 final String displayName = userCatalogs.getDisplayName(getUserID());
129 return displayName == null ? getUserID() : displayName;
132 public boolean hasDisplayNameForUserID(String userID) {
133 return userCatalogs.getDisplayName(userID) != null;
136 public boolean hasIDForUserDisplayName(String userDisplayName) {
137 return userCatalogs.getID(userDisplayName) != null;
140 public String getDisplayNameForUserID(String userID) {
141 return userCatalogs.getDisplayName(userID);
144 public String getIDForUserDisplayName(String userDisplayName) {
145 return userCatalogs.getID(userDisplayName);
148 public List<String> getDisplayNamesForUserIDs(List<String> userIDs) {
149 if(userIDs == null) {
150 userIDs = new ArrayList<String>();
152 final List<String> userDisplayNames = new ArrayList<String>();
153 for(String userID : userIDs) {
154 final String displayName = getDisplayNameForUserID(userID);
155 userDisplayNames.add(displayName);
158 return userDisplayNames;
161 public List<String> filterUserIDsWithUnknownDisplayName(Collection<String> userIDs) {
162 if(userIDs == null) {
163 userIDs = new ArrayList<String>();
165 final List<String> filtered = new ArrayList<String>();
166 for(String userID : userIDs) {
167 if(!this.userCatalogs.hasID(userID)) {
168 filtered.add(userID);
174 public void setAccount(AccountResource acct) {
178 public AccountResource getAccount() {
182 public void updateFolder(Folder f, boolean showfiles, Command callback, final boolean openParent) {
183 folderTreeView.updateFolder(f, showfiles, callback, openParent);
186 public void updateGroupNode(Group group) {
187 groupTreeView.updateGroupNode(group);
190 public void updateMySharedRoot() {
191 mysharedTreeView.updateRoot();
194 public void updateSharedFolder(Folder f, boolean showfiles, Command callback) {
195 mysharedTreeView.updateFolder(f, showfiles, callback);
198 public void updateSharedFolder(Folder f, boolean showfiles) {
199 updateSharedFolder(f, showfiles, null);
202 public void updateOtherSharedFolder(Folder f, boolean showfiles, Command callback) {
203 otherSharedTreeView.updateFolder(f, showfiles, callback);
206 public MysharedTreeView getMySharedTreeView() {
207 return mysharedTreeView;
211 * An aggregate image bundle that pulls together all the images for this
212 * application into a single bundle.
214 public interface Images extends TopPanel.Images, FileList.Images, ToolsMenu.Images {
216 @Source("gr/grnet/pithos/resources/document.png")
217 ImageResource folders();
219 @Source("gr/grnet/pithos/resources/advancedsettings.png")
220 @ImageOptions(width = 32, height = 32)
221 ImageResource tools();
224 private Throwable error;
227 * The Application Clipboard implementation;
229 private Clipboard clipboard = new Clipboard();
232 * The top panel that contains the menu bar.
234 private TopPanel topPanel;
237 * The panel that contains the various system messages.
239 private MessagePanel messagePanel = new MessagePanel(this, Pithos.images);
242 * The bottom panel that contains the status bar.
244 StatusPanel statusPanel = null;
247 * The file list widget.
249 private FileList fileList;
252 * The tab panel that occupies the right side of the screen.
254 private VerticalPanel inner = new VerticalPanel();
258 * The split panel that will contain the left and right panels.
260 private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
263 * The currently selected item in the application, for use by the Edit menu
264 * commands. Potential types are Folder, File, User and Group.
266 private Object currentSelection;
268 public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
271 * The ID that uniquely identifies the user in Pithos+.
272 * Currently this is a UUID. It used to be the user's email.
274 private String userID = null;
277 * Hold mappings from user UUIDs to emails and vice-versa.
279 private UserCatalogs userCatalogs = new UserCatalogs();
282 * The authentication token of the current user.
284 private String userToken;
288 SingleSelectionModel<Folder> folderTreeSelectionModel;
289 FolderTreeViewModel folderTreeViewModel;
290 FolderTreeView folderTreeView;
292 SingleSelectionModel<Folder> mysharedTreeSelectionModel;
293 MysharedTreeViewModel mysharedTreeViewModel;
294 MysharedTreeView mysharedTreeView = null;
296 protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
297 OtherSharedTreeViewModel otherSharedTreeViewModel;
298 OtherSharedTreeView otherSharedTreeView = null;
300 GroupTreeViewModel groupTreeViewModel;
301 GroupTreeView groupTreeView;
303 TreeView selectedTree;
304 protected AccountResource account;
308 List<Composite> treeViews = new ArrayList<Composite>();
310 @SuppressWarnings("rawtypes")
311 List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
313 public Button upload;
315 private HTML numOfFiles;
317 private Toolbar toolbar;
319 private FileUploadDialog fileUploadDialog = new FileUploadDialog(this);
321 UploadAlert uploadAlert;
326 public void onModuleLoad() {
327 if(parseUserCredentials()) {
332 static native void __ConsoleLog(String message) /*-{
334 console.log(message);
339 public static void LOG(Object ...args) {
341 final StringBuilder sb = new StringBuilder();
342 for(Object arg : args) {
345 if(sb.length() > 0) {
346 __ConsoleLog(sb.toString());
351 private void initialize() {
352 lastModified = new Date(); //Initialize if-modified-since value with now.
353 resources.pithosCss().ensureInjected();
354 boolean bareContent = Window.Location.getParameter("noframe") != null;
355 String contentWidth = bareContent ? Const.PERCENT_100 : "75%";
357 VerticalPanel outer = new VerticalPanel();
358 outer.setWidth(Const.PERCENT_100);
360 outer.addStyleName("pithos-outer");
364 topPanel = new TopPanel(this, Pithos.images);
365 topPanel.setWidth(Const.PERCENT_100);
367 outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
370 messagePanel.setVisible(false);
371 outer.add(messagePanel);
372 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
373 outer.setCellVerticalAlignment(messagePanel, HasVerticalAlignment.ALIGN_MIDDLE);
375 HorizontalPanel header = new HorizontalPanel();
376 header.addStyleName("pithos-header");
377 header.setWidth(contentWidth);
379 header.addStyleName("pithos-header-noframe");
381 upload = new Button("Upload", new ClickHandler() {
383 public void onClick(ClickEvent event) {
384 if(getSelection() != null) {
385 new UploadFileCommand(Pithos.this, null, getSelection()).execute();
389 upload.addStyleName("pithos-uploadButton");
391 header.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_LEFT);
392 header.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
394 toolbar = new Toolbar(this);
396 header.setCellHorizontalAlignment(toolbar, HasHorizontalAlignment.ALIGN_CENTER);
397 header.setCellVerticalAlignment(toolbar, HasVerticalAlignment.ALIGN_MIDDLE);
399 HorizontalPanel folderStatistics = new HorizontalPanel();
400 folderStatistics.addStyleName("pithos-folderStatistics");
401 numOfFiles = new HTML();
402 folderStatistics.add(numOfFiles);
403 folderStatistics.setCellVerticalAlignment(numOfFiles, HasVerticalAlignment.ALIGN_MIDDLE);
404 HTML numOfFilesLabel = new HTML(" Files");
405 folderStatistics.add(numOfFilesLabel);
406 folderStatistics.setCellVerticalAlignment(numOfFilesLabel, HasVerticalAlignment.ALIGN_MIDDLE);
407 header.add(folderStatistics);
408 header.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
409 header.setCellVerticalAlignment(folderStatistics, HasVerticalAlignment.ALIGN_MIDDLE);
410 header.setCellWidth(folderStatistics, "40px");
412 outer.setCellHorizontalAlignment(header, HasHorizontalAlignment.ALIGN_CENTER);
413 // Inner contains the various lists
414 inner.sinkEvents(Event.ONCONTEXTMENU);
415 inner.setWidth(Const.PERCENT_100);
417 folderTreeSelectionModel = new SingleSelectionModel<Folder>();
418 folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
420 public void onSelectionChange(SelectionChangeEvent event) {
421 if(folderTreeSelectionModel.getSelectedObject() != null) {
422 deselectOthers(folderTreeView, folderTreeSelectionModel);
423 applyPermissions(folderTreeSelectionModel.getSelectedObject());
424 Folder f = folderTreeSelectionModel.getSelectedObject();
425 updateFolder(f, true, new Command() {
428 public void execute() {
432 showRelevantToolbarButtons();
435 if(getSelectedTree().equals(folderTreeView)) {
436 setSelectedTree(null);
438 if(getSelectedTree() == null) {
439 showRelevantToolbarButtons();
444 selectionModels.add(folderTreeSelectionModel);
446 folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
447 folderTreeView = new FolderTreeView(folderTreeViewModel);
448 treeViews.add(folderTreeView);
450 fileList = new FileList(this, images);
453 trees = new VerticalPanel();
454 trees.setWidth(Const.PERCENT_100);
456 // Add the left and right panels to the split panel.
457 splitPanel.setLeftWidget(trees);
458 FlowPanel right = new FlowPanel();
459 right.getElement().setId("rightPanel");
461 splitPanel.setRightWidget(right);
462 splitPanel.setSplitPosition("219px");
463 splitPanel.setSize(Const.PERCENT_100, Const.PERCENT_100);
464 splitPanel.addStyleName("pithos-splitPanel");
465 splitPanel.setWidth(contentWidth);
466 outer.add(splitPanel);
467 outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
470 statusPanel = new StatusPanel();
471 statusPanel.setWidth(Const.PERCENT_100);
472 outer.add(statusPanel);
473 outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
476 splitPanel.addStyleName("pithos-splitPanel-noframe");
479 // Hook the window resize event, so that we can adjust the UI.
480 Window.addResizeHandler(this);
481 // Clear out the window's built-in margin, because we want to take
482 // advantage of the entire client area.
483 Window.setMargin("0px");
484 // Finally, add the outer panel to the RootPanel, so that it will be
486 RootPanel.get().add(outer);
487 // Call the window resized handler to get the initial sizes setup. Doing
488 // this in a deferred command causes it to occur after all widgets'
489 // sizes have been computed by the browser.
490 Scheduler.get().scheduleIncremental(new RepeatingCommand() {
493 public boolean execute() {
494 if(!isCloudbarReady()) {
497 onWindowResized(Window.getClientHeight());
502 Scheduler.get().scheduleDeferred(new ScheduledCommand() {
504 public void execute() {
505 LOG("Pithos::initialize() Calling Pithos::fetchAccount()");
506 fetchAccount(new Command() {
509 public void execute() {
510 if(!account.hasHomeContainer()) {
511 createHomeContainer(account, this);
513 else if(!account.hasTrashContainer()) {
514 createTrashContainer(this);
517 for(Folder f : account.getContainers()) {
518 if(f.getName().equals(Const.TRASH_CONTAINER)) {
523 trees.add(folderTreeView);
524 folderTreeViewModel.initialize(account, new Command() {
527 public void execute() {
528 createMySharedTree();
532 HorizontalPanel separator = new HorizontalPanel();
533 separator.addStyleName("pithos-statisticsSeparator");
534 separator.add(new HTML(""));
535 trees.add(separator);
537 groupTreeViewModel = new GroupTreeViewModel(Pithos.this);
538 groupTreeView = new GroupTreeView(groupTreeViewModel);
539 treeViews.add(groupTreeView);
540 trees.add(groupTreeView);
541 folderTreeView.showStatistics(account);
549 public void scheduleResfresh() {
550 Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {
553 public boolean execute() {
554 final Folder f = getSelection();
559 HeadRequest<Folder> head = new HeadRequest<Folder>(Folder.class, getApiPath(), f.getOwnerID(), "/" + f.getContainer()) {
562 public void onSuccess(Folder _result) {
563 lastModified = new Date();
564 if(getSelectedTree().equals(folderTreeView)) {
565 updateFolder(f, true, new Command() {
568 public void execute() {
574 else if(getSelectedTree().equals(mysharedTreeView)) {
575 updateSharedFolder(f, true, new Command() {
578 public void execute() {
589 public void onError(Throwable t) {
590 if(t instanceof RestException && ((RestException) t).getHttpStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
593 else if(retries >= MAX_RETRIES) {
594 GWT.log("Error heading folder", t);
596 if(t instanceof RestException) {
597 displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
600 displayError("System error heading folder: " + t.getMessage());
604 GWT.log("Retry " + retries);
605 Scheduler.get().scheduleDeferred(this);
610 protected void onUnauthorized(Response response) {
611 if(retries >= MAX_RETRIES) {
616 Scheduler.get().scheduleDeferred(this);
620 head.setHeader(Const.X_AUTH_TOKEN, getUserToken());
621 head.setHeader(Const.IF_MODIFIED_SINCE, DateTimeFormat.getFormat(Const.DATE_FORMAT_1).format(lastModified, TimeZone.createTimeZone(0)) + " GMT");
622 Scheduler.get().scheduleDeferred(head);
629 public void applyPermissions(Folder f) {
632 upload.setEnabled(false);
636 Boolean[] perms = f.getPermissions().get(userID);
637 if(f.getOwnerID().equals(userID) || (perms != null && perms[1] != null && perms[1])) {
638 upload.setEnabled(true);
642 upload.setEnabled(false);
648 upload.setEnabled(false);
653 @SuppressWarnings({"rawtypes", "unchecked"})
654 public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
655 selectedTree = _selectedTree;
657 for(SingleSelectionModel s : selectionModels) {
658 if(!s.equals(model) && s.getSelectedObject() != null) {
659 s.setSelected(s.getSelectedObject(), false);
664 public void showFiles(final Folder f) {
665 Set<File> files = f.getFiles();
669 public void showFiles(Set<File> files) {
670 fileList.setFiles(new ArrayList<File>(files));
674 * Parse and store the user credentials to the appropriate fields.
676 private boolean parseUserCredentials() {
677 Configuration conf = (Configuration) GWT.create(Configuration.class);
678 Dictionary otherProperties = Dictionary.getDictionary(Const.OTHER_PROPERTIES);
679 String cookie = otherProperties.get(Const.AUTH_COOKIE);
680 String auth = Cookies.getCookie(cookie);
685 if(auth.startsWith("\"")) {
686 auth = auth.substring(1);
688 if(auth.endsWith("\"")) {
689 auth = auth.substring(0, auth.length() - 1);
691 String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
692 if(authSplit.length != 2) {
696 userID = authSplit[0];
697 userToken = authSplit[1];
699 String gotoUrl = Window.Location.getParameter("goto");
700 if(gotoUrl != null && gotoUrl.length() > 0) {
701 Window.Location.assign(gotoUrl);
708 * Redirect the user to the login page for authentication.
710 protected void authenticateUser() {
711 Dictionary otherProperties = Dictionary.getDictionary(Const.OTHER_PROPERTIES);
712 Window.Location.assign(otherProperties.get(Const.LOGIN_URL) + Window.Location.getHref());
715 public void fetchAccount(final Command callback) {
716 String path = "?format=json";
718 GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getApiPath(), userID, path) {
720 public void onSuccess(AccountResource accountResource) {
721 account = accountResource;
722 if(callback != null) {
726 final List<String> memberIDs = new ArrayList<String>();
727 final List<Group> groups = account.getGroups();
728 for(Group group : groups) {
729 memberIDs.addAll(group.getMemberIDs());
731 memberIDs.add(Pithos.this.getUserID());
733 final List<String> theUnknown = Pithos.this.filterUserIDsWithUnknownDisplayName(memberIDs);
734 // Initialize the user catalog
735 new UpdateUserCatalogs(Pithos.this, theUnknown).scheduleDeferred();
736 LOG("Called new UpdateUserCatalogs(Pithos.this, theUnknown).scheduleDeferred();");
740 public void onError(Throwable t) {
741 GWT.log("Error getting account", t);
743 if(t instanceof RestException) {
744 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
747 displayError("System error fetching user data: " + t.getMessage());
752 protected void onUnauthorized(Response response) {
756 getAccount.setHeader(Const.X_AUTH_TOKEN, userToken);
757 Scheduler.get().scheduleDeferred(getAccount);
760 public void updateStatistics() {
761 HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getApiPath(), userID, "", account) {
764 public void onSuccess(AccountResource _result) {
765 folderTreeView.showStatistics(account);
769 public void onError(Throwable t) {
770 GWT.log("Error getting account", t);
772 if(t instanceof RestException) {
773 displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
776 displayError("System error fetching user data: " + t.getMessage());
781 protected void onUnauthorized(Response response) {
785 headAccount.setHeader(Const.X_AUTH_TOKEN, userToken);
786 Scheduler.get().scheduleDeferred(headAccount);
789 protected void createHomeContainer(final AccountResource _account, final Command callback) {
790 String path = "/" + Const.HOME_CONTAINER;
791 PutRequest createPithos = new PutRequest(getApiPath(), getUserID(), path) {
793 public void onSuccess(Resource result) {
794 if(!_account.hasTrashContainer()) {
795 createTrashContainer(callback);
798 fetchAccount(callback);
803 public void onError(Throwable t) {
804 GWT.log("Error creating pithos", t);
806 if(t instanceof RestException) {
807 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
810 displayError("System error Error creating pithos: " + t.getMessage());
815 protected void onUnauthorized(Response response) {
819 createPithos.setHeader(Const.X_AUTH_TOKEN, getUserToken());
820 Scheduler.get().scheduleDeferred(createPithos);
823 protected void createTrashContainer(final Command callback) {
824 String path = "/" + Const.TRASH_CONTAINER;
825 PutRequest createPithos = new PutRequest(getApiPath(), getUserID(), path) {
827 public void onSuccess(Resource result) {
828 fetchAccount(callback);
832 public void onError(Throwable t) {
833 GWT.log("Error creating pithos", t);
835 if(t instanceof RestException) {
836 displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
839 displayError("System error Error creating pithos: " + t.getMessage());
844 protected void onUnauthorized(Response response) {
848 createPithos.setHeader(Const.X_AUTH_TOKEN, getUserToken());
849 Scheduler.get().scheduleDeferred(createPithos);
853 * Creates an HTML fragment that places an image & caption together, for use
856 * @param imageProto an image prototype for an image
857 * @param caption the group caption
858 * @return the header HTML fragment
860 private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
861 String captionHTML = "<table class='caption' cellpadding='0' "
862 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
863 + "</td><td id =" + caption + " class='rcaption'><b style='white-space:nowrap'> "
864 + caption + "</b></td></tr></table>";
868 protected void onWindowResized(int height) {
869 // Adjust the split panel to take up the available room in the window.
870 int newHeight = height - splitPanel.getAbsoluteTop() - 153;
874 splitPanel.setHeight("" + newHeight);
875 inner.setHeight("" + newHeight);
878 native boolean isCloudbarReady()/*-{
879 if ($wnd.$("div.cloudbar") && $wnd.$("div.cloudbar").height() > 0)
885 public void onResize(ResizeEvent event) {
886 int height = event.getHeight();
887 onWindowResized(height);
891 * Display an error message.
893 * @param msg the message to display
895 public void displayError(String msg) {
896 messagePanel.displayError(msg);
897 onWindowResized(Window.getClientHeight());
901 * Display a warning message.
903 * @param msg the message to display
905 public void displayWarning(String msg) {
906 messagePanel.displayWarning(msg);
907 onWindowResized(Window.getClientHeight());
911 * Display an informational message.
913 * @param msg the message to display
915 public void displayInformation(String msg) {
916 messagePanel.displayInformation(msg);
917 onWindowResized(Window.getClientHeight());
921 * Retrieve the fileList.
923 * @return the fileList
925 public FileList getFileList() {
930 * Retrieve the topPanel.
932 * @return the topPanel
934 TopPanel getTopPanel() {
939 * Retrieve the clipboard.
941 * @return the clipboard
943 public Clipboard getClipboard() {
947 public StatusPanel getStatusPanel() {
951 public String getUserToken() {
955 public static native void preventIESelection() /*-{
956 $doc.body.onselectstart = function () {
961 public static native void enableIESelection() /*-{
962 if ($doc.body.onselectstart != null)
963 $doc.body.onselectstart = null;
967 * @return the absolute path of the API root URL
969 public String getApiPath() {
970 Configuration conf = (Configuration) GWT.create(Configuration.class);
971 return conf.apiPath();
975 * History support for folder navigation
976 * adds a new browser history entry
980 public void updateHistory(String key) {
981 // Replace any whitespace of the initial string to "+"
982 // String result = key.replaceAll("\\s","+");
983 // Add a new browser history entry.
984 // History.newItem(result);
985 History.newItem(key);
988 public void deleteFolder(final Folder folder, final Command callback) {
989 final PleaseWaitPopup pwp = new PleaseWaitPopup();
991 String path = "/" + folder.getContainer() + "/" + folder.getPrefix() + "?delimiter=/" + "&t=" + System.currentTimeMillis();
992 DeleteRequest deleteFolder = new DeleteRequest(getApiPath(), folder.getOwnerID(), path) {
995 protected void onUnauthorized(Response response) {
1001 public void onSuccess(Resource result) {
1002 updateFolder(folder.getParent(), true, new Command() {
1005 public void execute() {
1006 folderTreeSelectionModel.setSelected(folder.getParent(), true);
1008 if(callback != null) {
1017 public void onError(Throwable t) {
1020 if(t instanceof RestException) {
1021 if(((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND) {
1022 displayError("Unable to delete folder: " + ((RestException) t).getHttpStatusText());
1029 displayError("System error unable to delete folder: " + t.getMessage());
1034 deleteFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1035 Scheduler.get().scheduleDeferred(deleteFolder);
1038 public FolderTreeView getFolderTreeView() {
1039 return folderTreeView;
1042 public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
1043 if(iter.hasNext()) {
1044 File file = iter.next();
1045 String path = targetUri + "/" + file.getName();
1046 PutRequest copyFile = new PutRequest(getApiPath(), targetUsername, path) {
1048 public void onSuccess(Resource result) {
1049 copyFiles(iter, targetUsername, targetUri, callback);
1053 public void onError(Throwable t) {
1056 if(t instanceof RestException) {
1057 displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
1060 displayError("System error unable to copy file: " + t.getMessage());
1065 protected void onUnauthorized(Response response) {
1069 copyFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1070 copyFile.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(file.getUri()));
1071 if(!file.getOwnerID().equals(targetUsername)) {
1072 copyFile.setHeader(Const.X_SOURCE_ACCOUNT, URL.encodePathSegment(file.getOwnerID()));
1074 copyFile.setHeader(Const.CONTENT_TYPE, file.getContentType());
1075 Scheduler.get().scheduleDeferred(copyFile);
1077 else if(callback != null) {
1082 public void copyFolder(final Folder f, final String targetUsername, final String targetUri, boolean move, final Command callback) {
1083 String path = targetUri + "?delimiter=/";
1084 PutRequest copyFolder = new PutRequest(getApiPath(), targetUsername, path) {
1086 public void onSuccess(Resource result) {
1087 if(callback != null) {
1093 public void onError(Throwable t) {
1096 if(t instanceof RestException) {
1097 displayError("Unable to copy folder: " + ((RestException) t).getHttpStatusText());
1100 displayError("System error copying folder: " + t.getMessage());
1105 protected void onUnauthorized(Response response) {
1109 copyFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1110 copyFolder.setHeader(Const.ACCEPT, "*/*");
1111 copyFolder.setHeader(Const.CONTENT_LENGTH, "0");
1112 copyFolder.setHeader(Const.CONTENT_TYPE, "application/directory");
1113 if(!f.getOwnerID().equals(targetUsername)) {
1114 copyFolder.setHeader(Const.X_SOURCE_ACCOUNT, f.getOwnerID());
1117 copyFolder.setHeader(Const.X_MOVE_FROM, URL.encodePathSegment(f.getUri()));
1120 copyFolder.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(f.getUri()));
1122 Scheduler.get().scheduleDeferred(copyFolder);
1125 public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1126 selectionModels.add(model);
1129 public OtherSharedTreeView getOtherSharedTreeView() {
1130 return otherSharedTreeView;
1133 public void updateTrash(boolean showFiles, Command callback) {
1134 updateFolder(trash, showFiles, callback, true);
1137 public void updateGroupsNode() {
1138 groupTreeView.updateGroupNode(null);
1141 public Group addGroup(String groupname) {
1142 Group newGroup = new Group(groupname);
1143 account.addGroup(newGroup);
1144 groupTreeView.updateGroupNode(null);
1148 public void removeGroup(Group group) {
1149 account.removeGroup(group);
1153 public TreeView getSelectedTree() {
1154 return selectedTree;
1157 public void setSelectedTree(TreeView selected) {
1158 selectedTree = selected;
1161 public Folder getSelection() {
1162 if(selectedTree != null) {
1163 return selectedTree.getSelection();
1168 public void showFolderStatistics(int folderFileCount) {
1169 numOfFiles.setHTML(String.valueOf(folderFileCount));
1172 public GroupTreeView getGroupTreeView() {
1173 return groupTreeView;
1176 public void sessionExpired() {
1177 new SessionExpiredDialog(this).center();
1180 public void updateRootFolder(Command callback) {
1181 updateFolder(account.getPithos(), false, callback, true);
1184 void createMySharedTree() {
1185 LOG("Pithos::createMySharedTree()");
1186 mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1187 mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1189 public void onSelectionChange(SelectionChangeEvent event) {
1190 if(mysharedTreeSelectionModel.getSelectedObject() != null) {
1191 deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1192 upload.setEnabled(false);
1193 disableUploadArea();
1194 updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1195 showRelevantToolbarButtons();
1198 if(getSelectedTree().equals(mysharedTreeView)) {
1199 setSelectedTree(null);
1201 if(getSelectedTree() == null) {
1202 showRelevantToolbarButtons();
1207 selectionModels.add(mysharedTreeSelectionModel);
1208 mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1209 mysharedTreeViewModel.initialize(new Command() {
1212 public void execute() {
1213 mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1214 trees.insert(mysharedTreeView, 2);
1215 treeViews.add(mysharedTreeView);
1216 createOtherSharedTree();
1221 void createOtherSharedTree() {
1222 LOG("Pithos::createOtherSharedTree()");
1223 otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1224 otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1226 public void onSelectionChange(SelectionChangeEvent event) {
1227 if(otherSharedTreeSelectionModel.getSelectedObject() != null) {
1228 deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1229 applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1230 updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true, null);
1231 showRelevantToolbarButtons();
1234 if(getSelectedTree().equals(otherSharedTreeView)) {
1235 setSelectedTree(null);
1237 if(getSelectedTree() == null) {
1238 showRelevantToolbarButtons();
1243 selectionModels.add(otherSharedTreeSelectionModel);
1244 otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1245 LOG("Pithos::createOtherSharedTree(), initializing otherSharedTreeViewModel with a callback");
1246 otherSharedTreeViewModel.initialize(new Command() {
1248 public void execute() {
1249 otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel);
1250 trees.insert(otherSharedTreeView, 1);
1251 treeViews.add(otherSharedTreeView);
1257 public String getErrorData() {
1258 final StringBuilder sb = new StringBuilder();
1259 final String NL = Const.NL;
1260 Throwable t = this.error;
1262 sb.append(t.toString());
1264 StackTraceElement[] traces = t.getStackTrace();
1265 for(StackTraceElement trace : traces) {
1267 sb.append(trace.getClassName());
1269 sb.append(trace.getMethodName());
1270 sb.append("() at ");
1271 sb.append(trace.getFileName());
1273 sb.append(trace.getLineNumber());
1280 return sb.toString();
1283 public void setError(Throwable t) {
1287 public void showRelevantToolbarButtons() {
1288 toolbar.showRelevantButtons();
1291 public FileUploadDialog getFileUploadDialog() {
1292 if(fileUploadDialog == null) {
1293 fileUploadDialog = new FileUploadDialog(this);
1295 return fileUploadDialog;
1298 public void hideUploadIndicator() {
1299 upload.removeStyleName("pithos-uploadButton-loading");
1300 upload.setTitle("");
1303 public void showUploadIndicator() {
1304 upload.addStyleName("pithos-uploadButton-loading");
1305 upload.setTitle("Upload in progress. Click for details.");
1308 public void scheduleFolderHeadCommand(final Folder folder, final Command callback) {
1309 if(folder == null) {
1310 if(callback != null) {
1315 HeadRequest<Folder> headFolder = new HeadRequest<Folder>(Folder.class, getApiPath(), folder.getOwnerID(), folder.getUri(), folder) {
1318 public void onSuccess(Folder _result) {
1319 if(callback != null) {
1325 public void onError(Throwable t) {
1326 if(t instanceof RestException) {
1327 if(((RestException) t).getHttpStatusCode() == Response.SC_NOT_FOUND) {
1328 final String path = folder.getUri();
1329 PutRequest newFolder = new PutRequest(getApiPath(), folder.getOwnerID(), path) {
1331 public void onSuccess(Resource _result) {
1332 scheduleFolderHeadCommand(folder, callback);
1336 public void onError(Throwable _t) {
1339 if(_t instanceof RestException) {
1340 displayError("Unable to create folder: " + ((RestException) _t).getHttpStatusText());
1343 displayError("System error creating folder: " + _t.getMessage());
1348 protected void onUnauthorized(Response response) {
1352 newFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1353 newFolder.setHeader(Const.CONTENT_TYPE, "application/folder");
1354 newFolder.setHeader(Const.ACCEPT, "*/*");
1355 newFolder.setHeader(Const.CONTENT_LENGTH, "0");
1356 Scheduler.get().scheduleDeferred(newFolder);
1358 else if(((RestException) t).getHttpStatusCode() == Response.SC_FORBIDDEN) {
1362 displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
1366 displayError("System error heading folder: " + t.getMessage());
1369 GWT.log("Error heading folder", t);
1374 protected void onUnauthorized(Response response) {
1378 headFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1379 Scheduler.get().scheduleDeferred(headFolder);
1383 public void scheduleFileHeadCommand(File f, final Command callback) {
1384 HeadRequest<File> headFile = new HeadRequest<File>(File.class, getApiPath(), f.getOwnerID(), f.getUri(), f) {
1387 public void onSuccess(File _result) {
1388 if(callback != null) {
1394 public void onError(Throwable t) {
1395 GWT.log("Error heading file", t);
1397 if(t instanceof RestException) {
1398 displayError("Error heading file: " + ((RestException) t).getHttpStatusText());
1401 displayError("System error heading file: " + t.getMessage());
1406 protected void onUnauthorized(Response response) {
1410 headFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1411 Scheduler.get().scheduleDeferred(headFile);
1414 public boolean isMySharedSelected() {
1415 return getSelectedTree().equals(getMySharedTreeView());
1418 private Folder getUploadFolder() {
1419 if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1420 return getSelection();
1425 private void updateUploadFolder() {
1426 updateUploadFolder(null);
1429 private void updateUploadFolder(final JsArrayString urls) {
1430 if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1431 Folder f = getSelection();
1432 if(getSelectedTree().equals(getFolderTreeView())) {
1433 updateFolder(f, true, new Command() {
1436 public void execute() {
1439 selectUploadedFiles(urls);
1445 updateOtherSharedFolder(f, true, null);
1450 public native void disableUploadArea() /*-{
1451 var uploader = $wnd.$("#uploader").pluploadQueue();
1452 var dropElm = $wnd.document.getElementById('rightPanel');
1453 $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1456 public native void enableUploadArea() /*-{
1457 var uploader = $wnd.$("#uploader").pluploadQueue();
1458 var dropElm = $wnd.document.getElementById('rightPanel');
1459 $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1460 if (uploader.runtime == 'html5') {
1461 uploader.settings.drop_element = 'rightPanel';
1462 uploader.trigger('PostInit');
1466 public void showUploadAlert(int nOfFiles) {
1467 if(uploadAlert == null) {
1468 uploadAlert = new UploadAlert(this, nOfFiles);
1470 if(!uploadAlert.isShowing()) {
1471 uploadAlert.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
1474 public void setPosition(int offsetWidth, int offsetHeight) {
1475 uploadAlert.setPopupPosition((Window.getClientWidth() - offsetWidth) / 2, statusPanel.getAbsoluteTop() - offsetHeight);
1479 uploadAlert.setNumOfFiles(nOfFiles);
1482 public void hideUploadAlert() {
1483 if(uploadAlert != null && uploadAlert.isShowing()) {
1488 public void selectUploadedFiles(JsArrayString urls) {
1489 List<String> selectedUrls = new ArrayList<String>();
1490 for(int i = 0; i < urls.length(); i++) {
1491 selectedUrls.add(urls.get(i));
1493 fileList.selectByUrl(selectedUrls);
1496 public void emptyContainer(final Folder container) {
1497 String path = "/" + container.getName() + "?delimiter=/";
1498 DeleteRequest delete = new DeleteRequest(getApiPath(), getUserID(), path) {
1501 protected void onUnauthorized(Response response) {
1506 public void onSuccess(Resource result) {
1507 updateFolder(container, true, null, true);
1511 public void onError(Throwable t) {
1512 GWT.log("Error deleting trash", t);
1514 if(t instanceof RestException) {
1515 displayError("Error deleting trash: " + ((RestException) t).getHttpStatusText());
1518 displayError("System error deleting trash: " + t.getMessage());
1522 delete.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1523 Scheduler.get().scheduleDeferred(delete);