From 40f4088413bb39220fcec3eaf9044171f6ef49f7 Mon Sep 17 00:00:00 2001 From: Francesco Mangiacrapa Date: Fri, 13 Sep 2019 14:48:26 +0000 Subject: [PATCH] merged with private version at 181504 git-svn-id: http://svn.d4science-ii.research-infrastructures.eu/gcube/trunk/portlets/user/workspace-tree-widget@181670 82a268e6-3cf1-43bd-a215-b396298e98cf --- distro/changelog.xml | 201 +- pom.xml | 91 +- .../client/AppControllerExplorer.java | 376 +- .../client/event/FilterScopeEvent.java | 29 - .../client/event/FilterScopeEventHandler.java | 7 - .../workspace/client/event/LoadTreeEvent.java | 52 + .../client/event/LoadTreeEventHandler.java | 21 + .../client/event/OpenReportsEvent.java | 35 - .../client/event/OpenReportsEventHandler.java | 7 - .../interfaces/GXTFolderItemTypeEnum.java | 6 +- .../TreeAppControllerInterface.java | 4 +- .../model/ExtendedInfoContactModel.java | 2 +- .../workspace/client/resources/Resources.java | 4 - .../client/rpc/GWTWorkspaceService.java | 164 +- .../client/rpc/GWTWorkspaceServiceAsync.java | 168 +- .../client/view/sharing/DialogPermission.java | 1 - .../view/sharing/DialogShareFolder.java | 1 - .../client/view/smartfolder/SmartButton.java | 142 - .../view/smartfolder/SmartFolderPanel.java | 203 - .../client/view/tree/ContextMenuTree.java | 8 - .../client/workspace/GWTWorkspaceFolder.java | 54 +- .../server/DownloadPublicLinkServlet.java | 5 +- .../workspace/server/DownloadServlet.java | 69 +- .../server/FileNotVersionedException.java | 5 - .../workspace/server/GWTWorkspaceBuilder.java | 2457 ------------- .../server/GWTWorkspaceServiceImpl.java | 3255 +++++++---------- .../user/workspace/server/ImageServlet.java | 84 +- .../server/NoGcubeItemTypeException.java | 2 - .../workspace/server/ReusableInputStream.java | 94 + .../notifications/NotificationsProducer.java | 695 ---- .../notifications/NotificationsUtil.java | 252 -- .../NotificationMapperToStorageHub.java | 37 +- .../NotificationStorageHubUtil.java | 130 +- .../NotificationsProducerToStorageHub.java | 95 +- .../PortalUrlGroupGatewayProperty.java | 5 +- .../PropertyFileNotFoundException.java | 9 + .../reader/ApplicationProfileReader.java | 14 +- ...solverReaderParameterForResolverIndex.java | 5 +- .../tostoragehub/BuildServiceURLUtil.java | 74 + .../server/tostoragehub/FormatterUtil.java | 118 + .../ObjectStorageHubToWorkpaceMapper.java | 205 +- .../StorageHubToWorkpaceConverter.java | 495 ++- .../server/util/AclTypeComparator.java | 106 - .../server/util/AllowedMimeTypeToInline.java | 5 +- .../DifferenceBetweenInfoContactModel.java | 4 - .../server/util/HttpRequestUtil.java | 5 +- .../server/util/MimeTypeUtility.java | 5 +- .../workspace/server/util/StringUtil.java | 5 +- .../server/util/ThumbnailGenerator.java | 12 +- .../workspace/server/util/UrlEncoderUtil.java | 11 +- .../user/workspace/server/util/UserUtil.java | 47 +- .../server/util/WorkspaceEventCollector.java | 47 - .../user/workspace/server/util/WsUtil.java | 211 +- .../resource/PropertySpecialFolderReader.java | 5 +- .../server/util/scope/ScopeUtilFilter.java | 42 +- .../user/workspace/shared/ListContact.java | 43 + .../WsExtensionToMimeTypeMap.properties | 1 + .../WsMimeTypeToExtensionMap.properties | 1 + .../user/workspace/CreateSharedFolder.java | 172 +- .../portlets/user/workspace/DeleteTest.java | 467 +-- .../DephtVisitDonwloadFilesTester.java | 406 +- .../user/workspace/DonwloadServletTest.java | 222 +- .../user/workspace/GcubeProperties.java | 105 +- .../portlets/user/workspace/ItemCreate.java | 475 +-- .../portlets/user/workspace/ItemRetrieve.java | 367 +- .../user/workspace/PublicLinkTest.java | 277 +- .../user/workspace/SearchTextTest.java | 155 +- .../portlets/user/workspace/ShareFolder.java | 153 +- .../user/workspace/SinglePublicLinkTest.java | 413 ++- .../user/workspace/SizeRetrieving.java | 191 +- .../user/workspace/SmartFolderTest.java | 275 +- .../portlets/user/workspace/TestSync.java | 409 +-- .../portlets/user/workspace/TestWithTime.java | 153 +- .../user/workspace/UploadServletTest.java | 275 +- .../workspace/UploadServletTestToken.java | 233 +- .../user/workspace/UriResolverReaderRR.java | 474 ++- 76 files changed, 5865 insertions(+), 9588 deletions(-) delete mode 100644 src/main/java/org/gcube/portlets/user/workspace/client/event/FilterScopeEvent.java delete mode 100644 src/main/java/org/gcube/portlets/user/workspace/client/event/FilterScopeEventHandler.java create mode 100644 src/main/java/org/gcube/portlets/user/workspace/client/event/LoadTreeEvent.java create mode 100644 src/main/java/org/gcube/portlets/user/workspace/client/event/LoadTreeEventHandler.java delete mode 100644 src/main/java/org/gcube/portlets/user/workspace/client/event/OpenReportsEvent.java delete mode 100644 src/main/java/org/gcube/portlets/user/workspace/client/event/OpenReportsEventHandler.java delete mode 100644 src/main/java/org/gcube/portlets/user/workspace/client/view/smartfolder/SmartButton.java delete mode 100644 src/main/java/org/gcube/portlets/user/workspace/client/view/smartfolder/SmartFolderPanel.java delete mode 100644 src/main/java/org/gcube/portlets/user/workspace/server/GWTWorkspaceBuilder.java create mode 100644 src/main/java/org/gcube/portlets/user/workspace/server/ReusableInputStream.java delete mode 100644 src/main/java/org/gcube/portlets/user/workspace/server/notifications/NotificationsProducer.java delete mode 100644 src/main/java/org/gcube/portlets/user/workspace/server/notifications/NotificationsUtil.java create mode 100644 src/main/java/org/gcube/portlets/user/workspace/server/tostoragehub/BuildServiceURLUtil.java create mode 100644 src/main/java/org/gcube/portlets/user/workspace/server/tostoragehub/FormatterUtil.java delete mode 100644 src/main/java/org/gcube/portlets/user/workspace/server/util/AclTypeComparator.java delete mode 100644 src/main/java/org/gcube/portlets/user/workspace/server/util/WorkspaceEventCollector.java create mode 100644 src/main/java/org/gcube/portlets/user/workspace/shared/ListContact.java diff --git a/distro/changelog.xml b/distro/changelog.xml index 4f0b7e1..459d0c5 100644 --- a/distro/changelog.xml +++ b/distro/changelog.xml @@ -1,12 +1,13 @@ - - Added support to workspace users discovery by VREs [ticket: - #17169] - Updated the list of classes shared with sharing widget - component + + [Task #17226] Workspace and Workspace Tree: migrate HL remaining methods to SHUB + + Updated the list of classes shared with sharing widget component - [Task #17135] Workspace: assign the file extension during the download @@ -15,13 +16,15 @@ shared folder - [Task #17018] Move some methods to SHUB due to backward compatibility broken between SHUB and HL - Updated to StorageHub [ticket: #13226] [Support #16430] fixed @@ -29,7 +32,8 @@ should be managed by dedicated message on WS-side - Updated regular expression to validate Folder and File names @@ -39,7 +43,8 @@ [Task #13106] Provide public links for versioned files - [Task #12521] Migrate the tree view @@ -65,7 +70,8 @@ [Incident #12922] Workspace get link not working - [Task #12489] Migrate delete operation to StorageHub @@ -73,65 +79,76 @@ Switchboard service discovery - [Task #12089] Migrate to workspace-uploader 2.0 [Release #12006] Removed Send to - [Project Activity #11690] Integrated with Task Executor Widget - Managed case of Exception in order to avoid failure on checkItemLocked - [Task #11127] Porting to new ws-thredds engine [Feature #11325] Workspace: add New URL feature in the context menu of right pane - Issue #10831, Workspace download folder tomcat temp occupation issue - Feature #9760: WS-Thredds synch folder integration - Incident #9676: fixed. Removed check on get sub-folder public link when operation is performed by an administrator - Added regex in order to remove list of chars when renaming or creating new item. It is different for folder and item name - [Feature #5207] Integrate Image Preview Widget - Quick fix to set folder as public Updated messages to history including version of file if it is present - Removed no longer used dependency: accesslogger [Feature #7006] File Versioning @@ -141,7 +158,8 @@ [Task #7382] Added a quick fix to 'Edit Permissions' 'Edit Permissions' can be performed by Administrators - Added a loader on share window when contacts are loading from server @@ -150,12 +168,14 @@ external servlets - Removed message box shown in case of failure on getAllContatcs - [Feature #5873] Remove ASL Session from the Workspace and its components @@ -164,7 +184,8 @@ access is granted for owner or admin - [Feature #2335] Added "Get Folder Link" facility [Incident #4878] Fixed: Workspace tree not displaying user's @@ -181,33 +202,39 @@ [Bug #5218] Fixed return to the Workspace root Folder - [Feature #4128] Migration to Liferay 6.2 Data Catalogue publishing supported - Integrated with new workspace uploader Bug fixed: Css for Dialog Cancel multiple files - Added icons for: .odt, .ods, .ott, .odg, .odp - [Feature #1925] Added, new public link format: http://host/storageID [Feature #1298] Update public link generation - Bug Fixing - #1804; #1808; #1822; #1333 - [Feature #124] Remove a user from shared folder [Feature #1259] Enhancement to workspace item history @@ -220,7 +247,8 @@ [Bug: #1459] Fixed: get link disabled - [Bug #718] Fixed breadcrumb path [Bug #546] Fixed bug @@ -231,7 +259,8 @@ after an delete multiple - [Feature #129] Porting to HL 2.0 @@ -239,12 +268,14 @@ complete link - Integrated with Contact Edit Permissions - Added user storage usage @@ -252,14 +283,16 @@ shared folder - Support Ticket #813: Broken Breadcrumb for long path Ticket #3053: Load current ACL stored to Shared Folder - #2798 Sharing Panel usability improved @@ -267,7 +300,8 @@ https://support.social.isti.cnr.it/ticket/126 - Added Trash: https://issue.imarine.research-infrastructures.eu/ticket/2497 @@ -276,7 +310,8 @@ 3.2) - Fixed: https://support.d4science.research-infrastructures.eu/ticket/843 @@ -285,12 +320,14 @@ https://issue.imarine.research-infrastructures.eu/ticket/282 - Management of My Special Folder Added change permissions to VRE shared folder - #2634 Workspace: support for setting permissions over shared folders @@ -300,18 +337,21 @@ session validation - Changed several labels into Logger - #Ticket 2223. This project was enhancements to gwt 2.5.1 GCF dependency was removed - Provide support for public link, Related ticket: #1993 @@ -320,20 +360,23 @@ Fixed bug on shared links, Ticket #630 - Provide support for share link, Related ticket: #1504 Edit description on sharing, Related ticket: #1822 Bugs fixed, Related Tickets: #628, #633, #630 - Provide support for accounting, related ticket: #1752 Enable notification for file upload in shared folder, related ticket: #1732 - Workspace portlet was enhanced to meet the requests coming from the User Community @@ -342,20 +385,23 @@ #1497, #1536 - #1247 The workspace tree was mavenized #230, #205 The Workspace environment now supports the sharing of folder between users - Old Send Message removed, added support for new mail sender Bug fixed: upload file/archive - #216 New version of Workspace Tree is developed using the GXT framework @@ -363,38 +409,45 @@ #216 New tree is asynchronous #216 Reviews tree GUI and adding new features - #1740: ICIS / Download csv / added extension .xlw - #1555: WorkflowTemplate and WorkflowReport required in Workspace Portlet - Synch with others changes in HomeLibrary GWT 2.2.0 - Removed Workspace and Basket type, replaced with folder option Synch with others changes in HomeLibrary - Added more checks on GWT model construction - Enabled details panel for Report, ReportTemplate and AquaMapsItem workspace items - #36: ICIS / Workspace / Upload an archive Merged ThumbnailServlet and ImageServlet @@ -402,13 +455,15 @@ link not working - Ported to GWT 2.0 Updated project structure to WebPortlet Update to LifeRay portal - #424: Workspace code refactoring an enanchement refactored code @@ -417,35 +472,43 @@ Report Template - gcube release 1.7.0 - gcube release 1.6.0 - gcube release 1.5.0 - gcube release - gcube release 1.2.2 - gcube release 1.2.0 - gcube release 1.2.0 rc1 - first release diff --git a/pom.xml b/pom.xml index 94ccb47..624ba7d 100644 --- a/pom.xml +++ b/pom.xml @@ -131,20 +131,6 @@ ws-thredds-sync-widget [1.0.0-SNAPSHOT, 2.0.0-SNAPSHOT) compile - - - home-library-model - org.gcube.common - - - home-library-jcr - org.gcube.common - - - home-library - org.gcube.common - - @@ -192,34 +178,41 @@ [2.0.0-SNAPSHOT, 3.0.0-SNAPSHOT) + + org.apache.tika + tika-core + 1.21 + compile + + - - org.gcube.common - home-library-model - provided - - - org.gcube.common - home-library-jcr - provided - - - asm-debug-all - org.ow2.asm - - - - - org.gcube.common - home-library - provided - - - asm-all - asm - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + org.gcube.portlets.widgets @@ -269,20 +262,14 @@ commons-io - - - log4j - log4j - - - org.slf4j - slf4j-log4j12 - runtime - org.slf4j slf4j-api - runtime + + + + org.slf4j + slf4j-log4j12 diff --git a/src/main/java/org/gcube/portlets/user/workspace/client/AppControllerExplorer.java b/src/main/java/org/gcube/portlets/user/workspace/client/AppControllerExplorer.java index 8bf832f..5347f49 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/client/AppControllerExplorer.java +++ b/src/main/java/org/gcube/portlets/user/workspace/client/AppControllerExplorer.java @@ -48,8 +48,6 @@ import org.gcube.portlets.user.workspace.client.event.FileDownloadEvent.Download import org.gcube.portlets.user.workspace.client.event.FileDownloadEventHandler; import org.gcube.portlets.user.workspace.client.event.FileUploadEvent; import org.gcube.portlets.user.workspace.client.event.FileUploadEventHandler; -import org.gcube.portlets.user.workspace.client.event.FilterScopeEvent; -import org.gcube.portlets.user.workspace.client.event.FilterScopeEventHandler; import org.gcube.portlets.user.workspace.client.event.GetFolderLinkEvent; import org.gcube.portlets.user.workspace.client.event.GetFolderLinkEventHandler; import org.gcube.portlets.user.workspace.client.event.GetInfoEvent; @@ -61,12 +59,12 @@ import org.gcube.portlets.user.workspace.client.event.GetSharedLinkEventHandler; import org.gcube.portlets.user.workspace.client.event.ImagePreviewEvent; import org.gcube.portlets.user.workspace.client.event.ImagePreviewEventHandler; import org.gcube.portlets.user.workspace.client.event.LoadFolderEvent; +import org.gcube.portlets.user.workspace.client.event.LoadTreeEvent; +import org.gcube.portlets.user.workspace.client.event.LoadTreeEventHandler; import org.gcube.portlets.user.workspace.client.event.MoveItemsEvent; import org.gcube.portlets.user.workspace.client.event.MoveItemsEventHandler; import org.gcube.portlets.user.workspace.client.event.OpenContextMenuTreeEvent; import org.gcube.portlets.user.workspace.client.event.OpenContextMenuTreeEventHandler; -import org.gcube.portlets.user.workspace.client.event.OpenReportsEvent; -import org.gcube.portlets.user.workspace.client.event.OpenReportsEventHandler; import org.gcube.portlets.user.workspace.client.event.OpenUrlEvent; import org.gcube.portlets.user.workspace.client.event.OpenUrlEventHandler; import org.gcube.portlets.user.workspace.client.event.PublishOnDataCatalogueEvent; @@ -101,8 +99,6 @@ import org.gcube.portlets.user.workspace.client.event.VRESettingPermissionEvent; import org.gcube.portlets.user.workspace.client.event.VRESettingPermissionEventHandler; import org.gcube.portlets.user.workspace.client.event.VersioningHistoryShowEvent; import org.gcube.portlets.user.workspace.client.event.VersioningHistoryShowEventHandler; -import org.gcube.portlets.user.workspace.client.event.WebDavUrlEvent; -import org.gcube.portlets.user.workspace.client.event.WebDavUrlEventHandler; import org.gcube.portlets.user.workspace.client.interfaces.EventsTypeEnum; import org.gcube.portlets.user.workspace.client.interfaces.GXTFolderItemTypeEnum; import org.gcube.portlets.user.workspace.client.interfaces.GuiEventInterface; @@ -110,7 +106,6 @@ import org.gcube.portlets.user.workspace.client.interfaces.SubscriberInterface; import org.gcube.portlets.user.workspace.client.interfaces.TreeAppControllerInterface; import org.gcube.portlets.user.workspace.client.model.FileModel; import org.gcube.portlets.user.workspace.client.model.FolderModel; -import org.gcube.portlets.user.workspace.client.model.SmartFolderModel; import org.gcube.portlets.user.workspace.client.model.SubTree; import org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService; import org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceServiceAsync; @@ -128,7 +123,6 @@ import org.gcube.portlets.user.workspace.client.view.windows.DialogGetLink; import org.gcube.portlets.user.workspace.client.view.windows.DialogGetLink.Link_Type; import org.gcube.portlets.user.workspace.client.view.windows.DialogShareLink; import org.gcube.portlets.user.workspace.client.view.windows.DialogText; -import org.gcube.portlets.user.workspace.client.view.windows.DialogWebDavUrl; import org.gcube.portlets.user.workspace.client.view.windows.ImagesPreviewController; import org.gcube.portlets.user.workspace.client.view.windows.InfoDisplayMessage; import org.gcube.portlets.user.workspace.client.view.windows.MessageBoxAlert; @@ -191,11 +185,11 @@ import com.google.gwt.user.client.ui.HasWidgets; /** * The Class AppControllerExplorer. * - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * May 15, 2017 + * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it May 15, 2017 */ public class AppControllerExplorer implements EventHandler, TreeAppControllerInterface { + private static final String METHOD_IS_NO_LONGER_USED = "method is no longer used"; public static final GWTWorkspaceServiceAsync rpcWorkspaceService = (GWTWorkspaceServiceAsync) GWT .create(GWTWorkspaceService.class); private ExplorerPanel explorerPanel; @@ -540,7 +534,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt // IF NOT CANCELLED String clickedButton = be.getButtonClicked().getItemId(); if (clickedButton.equals(Dialog.YES)) { - GWT.log("Calling unSharedFolderByFolderSharedId for id: " + folderIdentification); + GWT.log("Calling unSharedFolderByFolderSharedId for id: "+folderIdentification); explorerPanel.getAsycTreePanel().mask(ConstantsExplorer.UNSHARING, ConstantsExplorer.LOADINGSTYLE); WorkspaceSharingServiceAsync.INSTANCE.unSharedFolderByFolderSharedId( @@ -887,40 +881,6 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt } }); - eventBus.addHandler(WebDavUrlEvent.TYPE, new WebDavUrlEventHandler() { - - @Override - public void onClickWebDavUrl(WebDavUrlEvent webDavUrlEvent) { - - String itemIdentifier = webDavUrlEvent.getItemIdentifier(); - if (itemIdentifier == null) - itemIdentifier = explorerPanel.getAsycTreePanel().getRootItem().getIdentifier(); - - rpcWorkspaceService.getUrlWebDav(itemIdentifier, new AsyncCallback() { - - @Override - public void onFailure(Throwable caught) { - new MessageBoxAlert("Error", - ConstantsExplorer.SERVER_ERROR + " viewing WebDAV url" + ConstantsExplorer.TRY_AGAIN, - null); - } - - @Override - public void onSuccess(String url) { - // new MessageBoxInfo(ConstantsExplorer.URL_WEBDAV, - // url); - DialogWebDavUrl diag = new DialogWebDavUrl( - ConstantsExplorer.URL_WEBDAV + ": " + ConstantsExplorer.TITLEACCESSWEBDAV, "", url); - diag.selectTxt(); - - } - - }); - - } - - }); - eventBus.addHandler(GetShareLinkEvent.TYPE, new GetSharedLinkEventHandler() { @Override @@ -1009,15 +969,6 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt } }); - // eventBus.addHandler(CopyItemsEvent.TYPE, new CopyItemsEventHandler() - // { - // - // @Override - // public void onCopyItems(CopyItemsEvent copytemEvent) { - // notifySubscriber(copytemEvent); - // } - // }); - eventBus.addHandler(CopyItemsEvent.TYPE, new CopyItemsEventHandler() { @Override @@ -1164,11 +1115,6 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt eventBus.fireEvent(new RefreshFolderEvent(folderDestionationInTree, true, false, false)); - // if(folderDestionationInTree!=null) - // moveItemsEvent.setTreeRefreshable(true); - // else - // moveItemsEvent.setTreeRefreshable(false); - moveItemsEvent.setTreeRefreshable(false); // forcing // grid // refresh @@ -1202,56 +1148,6 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt navigator.addWorkspaceExplorerSelectNotificationListener(listener); navigator.show(); - // break; - - // case COPY: - // - // rpcWorkspaceService.copyItems(pasteItemEvent.getIds(), - // pasteItemEvent.getFolderDestinationId(), new - // AsyncCallback() { - // - // @Override - // public void onFailure(Throwable caught) { - // - // if(caught instanceof SessionExpiredException){ - // GWT.log("Session expired"); - // eventBus.fireEvent(new SessionExpiredEvent()); - // return; - // } - // - // new MessageBoxAlert("Error", caught.getMessage(), null); - // - // eventBus.fireEvent(new - // RefreshFolderEvent(explorerPanel.getAsycTreePanel().getFileModelByIdentifier(pasteItemEvent.getFolderDestinationId()), - // false, true, false)); - // - // notifySubscriber(pasteItemEvent); - // } - // - // @Override - // public void onSuccess(Boolean result) { - // - // FileModel fileInTree = - // explorerPanel.getAsycTreePanel().getFileModelByIdentifier(pasteItemEvent.getFolderDestinationId()); - // if(result) - // eventBus.fireEvent(new RefreshFolderEvent(fileInTree, false, - // false, false)); - // - // if(fileInTree!=null) - // pasteItemEvent.setTreeRefreshable(true); - // else - // pasteItemEvent.setTreeRefreshable(false); - // - // notifySubscriber(pasteItemEvent); - // } - // - // }); - - // break; - - // default: - // - // } } }); @@ -1263,28 +1159,19 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt } }); - eventBus.addHandler(FilterScopeEvent.TYPE, new FilterScopeEventHandler() { + eventBus.addHandler(LoadTreeEvent.TYPE, new LoadTreeEventHandler() { @Override - public void onClickScopeFilter(FilterScopeEvent filterScopeEvent) { - - explorerPanel.getAsycTreePanel().setSearch(false); // SET IS - // SEARCH - // FALSE - - doChangeScope(filterScopeEvent.getScopeId()); - - } - - private void doChangeScope(String scopeId) { - - explorerPanel.getAsycTreePanel().loadRootItem(selectRootItem); // RELOAD - // ROOT - // BY - // SCOPE - + public void doLoadTree(LoadTreeEvent loadtreeEvent) { + selectRootItem = loadtreeEvent.isSelectRoot(); + //SET IS SEARCH TO FALSE + explorerPanel.getAsycTreePanel().setSearch(false); + // RELOAD TREE ROOT + explorerPanel.getAsycTreePanel().loadRootItem(selectRootItem); } }); + + eventBus.addHandler(AccountingHistoryEvent.TYPE, new AccountingHistoryEventHandler() { @@ -1545,42 +1432,8 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt } private void doDeleteSmartFolder(DeleteSmartFolderEvent deleteSmartFolderEvent) { - final String smartIdentifier = deleteSmartFolderEvent.getSmartIdentifier(); - final String smartName = deleteSmartFolderEvent.getSmartName(); - - MessageBoxConfirm mbc = new MessageBoxConfirm(ConstantsExplorer.MESSAGE_DELETE, - ConstantsExplorer.MESSAGE_CONFIRM_DELETE_SMART_FOLDER + " " + smartName + "?"); - mbc.getMessageBoxConfirm().addCallback(new Listener() { - - public void handleEvent(MessageBoxEvent be) { - - // eventBus.fireEvent(new DeleteItemEvent(sel)); - - // IF NOT CANCELLED - String clickedButton = be.getButtonClicked().getItemId(); - if (clickedButton.equals(Dialog.YES)) { - - rpcWorkspaceService.removeSmartFolder(smartIdentifier, smartName, - new AsyncCallback() { - - @Override - public void onSuccess(Boolean result) { - - } - - @Override - public void onFailure(Throwable caught) { - // explorerPanel.getAsycTreePanel().unmask(); - new MessageBoxAlert("Error", - ConstantsExplorer.SERVER_ERROR + " deleting smart folder.", null); - explorerPanel.getAsycTreePanel().removeAllAndRecoveryRoot(); - - } - }); - - } - } - }); + + Window.alert("The method 'doDeleteSmartFolder' " +METHOD_IS_NO_LONGER_USED); } }); @@ -1593,46 +1446,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt } private void doSaveSmartFolder(final AddSmartFolderEvent saveSmartFolderEvent) { - - final String query = saveSmartFolderEvent.getSearchText(); - final String parentId = saveSmartFolderEvent.getParentId(); - - final DialogAddFolderAndSmart dialogAddSmartFolder = new DialogAddFolderAndSmart("", - AddType.SMARTFOLDER); - - dialogAddSmartFolder.getButtonById(Dialog.OK).addListener(Events.Select, new Listener() { - - @Override - public void handleEvent(BaseEvent be) { - - if (dialogAddSmartFolder.isValidForm()) - - rpcWorkspaceService.createSmartFolder(dialogAddSmartFolder.getName(), - dialogAddSmartFolder.getDescription(), query, parentId, - new AsyncCallback() { - - @Override - public void onFailure(Throwable caught) { - explorerPanel.getAsycTreePanel().unmask(); - if (caught instanceof SessionExpiredException) { - GWT.log("Session expired"); - eventBus.fireEvent(new SessionExpiredEvent()); - return; - } - new MessageBoxAlert("Error", - ConstantsExplorer.SERVER_ERROR + " saving smart folder.", null); - explorerPanel.getAsycTreePanel().removeAllAndRecoveryRoot(); - - } - - @Override - public void onSuccess(SmartFolderModel smart) { - - } - }); - } - - }); + Window.alert("The method 'doSaveSmartFolder' " +METHOD_IS_NO_LONGER_USED); } }); @@ -1686,11 +1500,10 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt eventBus.fireEvent(new SessionExpiredEvent()); return; } - - if (caught instanceof SHUBOperationNotAllowedException) { - MessageBox.info("Operation not allowed...", caught.getMessage(), null) - .show(); - } else { + + if(caught instanceof SHUBOperationNotAllowedException) { + MessageBox.info("Operation not allowed...", caught.getMessage(), null).show(); + }else { new MessageBoxAlert("Error", caught.getMessage(), null); } explorerPanel.getAsycTreePanel().removeAllAndRecoveryRoot(); @@ -1750,16 +1563,15 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt @Override public void onFailure(Throwable caught) { - + explorerPanel.getAsycTreePanel().unmask(); - - if (caught instanceof SHUBOperationNotAllowedException) { - MessageBox.info("Operation not allowed...", caught.getMessage(), null) - .show(); - } else { + + if(caught instanceof SHUBOperationNotAllowedException) { + MessageBox.info("Operation not allowed...", caught.getMessage(), null).show(); + }else { new MessageBoxAlert("Error", caught.getMessage(), null); } - + explorerPanel.getAsycTreePanel().removeAllAndRecoveryRoot(); } @@ -1945,16 +1757,14 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt } new MessageBoxAlert("Error", caught.getMessage() + ".", null); - + // System.out.println(caught.getMessage()); - // explorerPanel.getAsycTreePanel().reloadTreeLevelAndExpandFolder( - // event.getTargetParentFileModel().getIdentifier(), - // false); - // explorerPanel.getAsycTreePanel().reloadTreeLevelAndExpandFolder( - // event.getFileSourceModel().getParentFileModel().getIdentifier(), - // true); - - // FXING THE ISSUE #16665 +// explorerPanel.getAsycTreePanel().reloadTreeLevelAndExpandFolder( +// event.getTargetParentFileModel().getIdentifier(), false); +// explorerPanel.getAsycTreePanel().reloadTreeLevelAndExpandFolder( +// event.getFileSourceModel().getParentFileModel().getIdentifier(), true); + + //FXING THE ISSUE #16665 explorerPanel.getAsycTreePanel().removeAllAndRecoveryRoot(); } @@ -1965,7 +1775,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt if (result.getError() != null) { new MessageBoxAlert("Error", result.getError(), null); - // FXING THE ISSUE #16665 + //FXING THE ISSUE #16665 explorerPanel.getAsycTreePanel().removeAllAndRecoveryRoot(); } @@ -2121,97 +1931,6 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt } }); - - eventBus.addHandler(OpenReportsEvent.TYPE, new OpenReportsEventHandler() { - - @Override - public void onClickOpenReports(OpenReportsEvent openReportsEvent) { - - if (openReportsEvent.getSourceFileModel().getGXTFolderItemType() - .equals(GXTFolderItemTypeEnum.REPORT_TEMPLATE)) - doClickOpenReportTemplate(openReportsEvent); - else - doClickOpenReport(openReportsEvent); - - } - - public void doClickOpenReport(OpenReportsEvent openReportsEvent) { - - final NewBrowserWindow newBrowserWindow = NewBrowserWindow.open("", "_self", ""); - - rpcWorkspaceService.getURLFromApplicationProfile(openReportsEvent.getSourceFileModel().getIdentifier(), - new AsyncCallback() { - - @Override - public void onFailure(Throwable caught) { - new MessageBoxAlert("Error", ConstantsExplorer.SERVER_ERROR - + " getting application profile - attribute idreport", null); - - } - - @Override - public void onSuccess(String url) { - - if (url == null || url.isEmpty()) { - String currentUrl = portalURL(); - int last = currentUrl.lastIndexOf("/"); - String reportUrl = currentUrl.substring(0, last + 1) - + ConstantsExplorer.REPORTGENERATION; - // new WindowOpenUrl(reportUrl, "_self", - // ""); - newBrowserWindow.setUrl(reportUrl); - } else { - String reportUrl = url; - // new WindowOpenUrl(reportUrl, "_self", - // ""); - newBrowserWindow.setUrl(reportUrl); - } - } - }); - - } - - private void doClickOpenReportTemplate(OpenReportsEvent openReportTemplateEvent) { - - final NewBrowserWindow newBrowserWindow = NewBrowserWindow.open("", "_self", ""); - - rpcWorkspaceService.getURLFromApplicationProfile( - openReportTemplateEvent.getSourceFileModel().getIdentifier(), new AsyncCallback() { - - @Override - public void onFailure(Throwable caught) { - new MessageBoxAlert("Error", ConstantsExplorer.SERVER_ERROR - + " getting application profile - attribute idreport", null); - - } - - @Override - public void onSuccess(String url) { - - if (url == null || url.isEmpty()) { - String currentUrl = portalURL(); - int last = currentUrl.lastIndexOf("/"); - String templateUrl = currentUrl.substring(0, last + 1) - + ConstantsExplorer.TEMPLATECREATION; - // Log.trace("Url: "+templateUrl); - GWT.log("currentUrl " + currentUrl); - GWT.log("reportUrl " + templateUrl); - newBrowserWindow.setUrl(templateUrl); - // new WindowOpenUrl(templateUrl, "_self", - // ""); - } else { - - String templateUrl = url; - newBrowserWindow.setUrl(templateUrl); - // new WindowOpenUrl(templateUrl, "_self", - // ""); - } - - } - }); - } - }); - } /** @@ -2733,7 +2452,7 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt MultiDragConstants.SHARE_WITH_RIGHT_LIST = "New Administrator/s"; final MultiDragWorkspaceContactAdmin multiDragContactAdmin = new MultiDragWorkspaceContactAdmin( - file.getIdentifier()); + file.getIdentifier()); final Dialog multidrag = multiDragContactAdmin.getDialogMultiDragContact(); multidrag.getButtonById(Dialog.OK).addListener(Events.Select, new Listener() { @@ -3145,17 +2864,18 @@ public class AppControllerExplorer implements EventHandler, TreeAppControllerInt @Override public void findItemAndSelectItemInTree(String itemIdentifier) { - FileModel fileModel = this.explorerPanel.getAsycTreePanel().getFileModelByIdentifier(itemIdentifier); - - if (fileModel == null) { // Loading item by RPC - - loadItemFromWorkspace(itemIdentifier); - } - - else { - - selectItemInTree(itemIdentifier); - } +// FileModel fileModel = this.explorerPanel.getAsycTreePanel().getFileModelByIdentifier(itemIdentifier); +// +// if (fileModel == null) { // Loading item by RPC +// +// loadItemFromWorkspace(itemIdentifier); +// } +// +// else { +// +// selectItemInTree(itemIdentifier); +// } + Window.alert("the method findItemAndSelectItemInTree is no longer used"); } /** diff --git a/src/main/java/org/gcube/portlets/user/workspace/client/event/FilterScopeEvent.java b/src/main/java/org/gcube/portlets/user/workspace/client/event/FilterScopeEvent.java deleted file mode 100644 index e98ef73..0000000 --- a/src/main/java/org/gcube/portlets/user/workspace/client/event/FilterScopeEvent.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.gcube.portlets.user.workspace.client.event; - -import com.google.gwt.event.shared.GwtEvent; - -public class FilterScopeEvent extends GwtEvent { - public static Type TYPE = new Type(); - private String scopeId; - - - public FilterScopeEvent(String scopeId) { - this.scopeId = scopeId; - } - - @Override - public Type getAssociatedType() { - // TODO Auto-generated method stub - return TYPE; - } - - @Override - protected void dispatch(FilterScopeEventHandler handler) { - handler.onClickScopeFilter(this); - - } - - public String getScopeId() { - return scopeId; - } -} diff --git a/src/main/java/org/gcube/portlets/user/workspace/client/event/FilterScopeEventHandler.java b/src/main/java/org/gcube/portlets/user/workspace/client/event/FilterScopeEventHandler.java deleted file mode 100644 index 9042c76..0000000 --- a/src/main/java/org/gcube/portlets/user/workspace/client/event/FilterScopeEventHandler.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.gcube.portlets.user.workspace.client.event; - -import com.google.gwt.event.shared.EventHandler; - -public interface FilterScopeEventHandler extends EventHandler { - void onClickScopeFilter(FilterScopeEvent filterScopeEvent); -} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/workspace/client/event/LoadTreeEvent.java b/src/main/java/org/gcube/portlets/user/workspace/client/event/LoadTreeEvent.java new file mode 100644 index 0000000..ff1482f --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/workspace/client/event/LoadTreeEvent.java @@ -0,0 +1,52 @@ +package org.gcube.portlets.user.workspace.client.event; + +import com.google.gwt.event.shared.GwtEvent; + + +/** + * The Class LoadTreeEvent. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * + * Jul 31, 2019 + */ +public class LoadTreeEvent extends GwtEvent { + public static Type TYPE = new Type(); + private boolean selectRoot; + + /** + * Instantiates a new load tree event. + * + * @param selectRoot the select root + */ + public LoadTreeEvent(boolean selectRoot) { + this.selectRoot = selectRoot; + } + + /* (non-Javadoc) + * @see com.google.gwt.event.shared.GwtEvent#getAssociatedType() + */ + @Override + public Type getAssociatedType() { + // TODO Auto-generated method stub + return TYPE; + } + + /* (non-Javadoc) + * @see com.google.gwt.event.shared.GwtEvent#dispatch(com.google.gwt.event.shared.EventHandler) + */ + @Override + protected void dispatch(LoadTreeEventHandler handler) { + handler.doLoadTree(this); + + } + + /** + * Checks if is select root. + * + * @return true, if is select root + */ + public boolean isSelectRoot() { + return selectRoot; + } +} diff --git a/src/main/java/org/gcube/portlets/user/workspace/client/event/LoadTreeEventHandler.java b/src/main/java/org/gcube/portlets/user/workspace/client/event/LoadTreeEventHandler.java new file mode 100644 index 0000000..312e872 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/workspace/client/event/LoadTreeEventHandler.java @@ -0,0 +1,21 @@ +package org.gcube.portlets.user.workspace.client.event; + +import com.google.gwt.event.shared.EventHandler; + + +/** + * The Interface LoadTreeEventHandler. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * + * Jul 31, 2019 + */ +public interface LoadTreeEventHandler extends EventHandler { + + /** + * Do load tree. + * + * @param loadTreeEvent the load tree event + */ + void doLoadTree(LoadTreeEvent loadTreeEvent); +} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/workspace/client/event/OpenReportsEvent.java b/src/main/java/org/gcube/portlets/user/workspace/client/event/OpenReportsEvent.java deleted file mode 100644 index 31e4eed..0000000 --- a/src/main/java/org/gcube/portlets/user/workspace/client/event/OpenReportsEvent.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.gcube.portlets.user.workspace.client.event; - -import org.gcube.portlets.user.workspace.client.model.FileModel; - -import com.google.gwt.event.shared.GwtEvent; - -/** - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * - */ -public class OpenReportsEvent extends GwtEvent { - public static Type TYPE = new Type(); - - private FileModel sourceFileModel = null; //Report template - - public OpenReportsEvent(FileModel fileSourceModel) { - this.sourceFileModel = fileSourceModel; - } - - @Override - public Type getAssociatedType() { - // TODO Auto-generated method stub - return TYPE; - } - - @Override - protected void dispatch(OpenReportsEventHandler handler) { - handler.onClickOpenReports(this); - - } - - public FileModel getSourceFileModel() { - return sourceFileModel; - } -} diff --git a/src/main/java/org/gcube/portlets/user/workspace/client/event/OpenReportsEventHandler.java b/src/main/java/org/gcube/portlets/user/workspace/client/event/OpenReportsEventHandler.java deleted file mode 100644 index 88931d9..0000000 --- a/src/main/java/org/gcube/portlets/user/workspace/client/event/OpenReportsEventHandler.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.gcube.portlets.user.workspace.client.event; - -import com.google.gwt.event.shared.EventHandler; - -public interface OpenReportsEventHandler extends EventHandler { - void onClickOpenReports(OpenReportsEvent openReportTemplateEvent); -} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/workspace/client/interfaces/GXTFolderItemTypeEnum.java b/src/main/java/org/gcube/portlets/user/workspace/client/interfaces/GXTFolderItemTypeEnum.java index effe5c7..45e59a5 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/client/interfaces/GXTFolderItemTypeEnum.java +++ b/src/main/java/org/gcube/portlets/user/workspace/client/interfaces/GXTFolderItemTypeEnum.java @@ -12,9 +12,9 @@ public enum GXTFolderItemTypeEnum implements Serializable { EXTERNAL_PDF_FILE("External PDF File"), EXTERNAL_URL("External Url"), EXTERNAL_RESOURCE_LINK("Exteranl Resource Link"), - QUERY("Query"), - REPORT("Report"), - REPORT_TEMPLATE("Report Template"), +// QUERY("Query"), +// REPORT("Report"), +// REPORT_TEMPLATE("Report Template"), TIME_SERIES("Time Series"), DOCUMENT("Document"), IMAGE_DOCUMENT("Image Document"), diff --git a/src/main/java/org/gcube/portlets/user/workspace/client/interfaces/TreeAppControllerInterface.java b/src/main/java/org/gcube/portlets/user/workspace/client/interfaces/TreeAppControllerInterface.java index 3fa96d1..37412c1 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/client/interfaces/TreeAppControllerInterface.java +++ b/src/main/java/org/gcube/portlets/user/workspace/client/interfaces/TreeAppControllerInterface.java @@ -22,7 +22,9 @@ public interface TreeAppControllerInterface { boolean reloadFolderChildren(String itemIdentifier); List getListParentsByIdentifierFromTree(String itemIdentifier); void setVisualizationType(VisualizationType type); - void findItemAndSelectItemInTree(String itemIdentifier); + + void findItemAndSelectItemInTree(String itemIdentifier); //this method is no longer used + void expandFolder(String itemIdentifier); void searching(boolean isSearch); void selectRootItem(); diff --git a/src/main/java/org/gcube/portlets/user/workspace/client/model/ExtendedInfoContactModel.java b/src/main/java/org/gcube/portlets/user/workspace/client/model/ExtendedInfoContactModel.java index 411ce45..4eb3a73 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/client/model/ExtendedInfoContactModel.java +++ b/src/main/java/org/gcube/portlets/user/workspace/client/model/ExtendedInfoContactModel.java @@ -23,7 +23,7 @@ public class ExtendedInfoContactModel extends InfoContactModel { public ExtendedInfoContactModel() {} - public ExtendedInfoContactModel(String id, String login, String fullName, String emailDomain,boolean isGroup) { + public ExtendedInfoContactModel(String id, String login, String fullName, String emailDomain, boolean isGroup) { super(id, login, fullName, emailDomain, isGroup); } diff --git a/src/main/java/org/gcube/portlets/user/workspace/client/resources/Resources.java b/src/main/java/org/gcube/portlets/user/workspace/client/resources/Resources.java index 17ca923..930e967 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/client/resources/Resources.java +++ b/src/main/java/org/gcube/portlets/user/workspace/client/resources/Resources.java @@ -1455,10 +1455,6 @@ public class Resources { // return Resources.getIconTable(); }else if(itemType.equals(GXTFolderItemTypeEnum.TIME_SERIES)){ return Resources.getIconTimeSeries(); - }else if(itemType.equals(GXTFolderItemTypeEnum.REPORT)){ - return Resources.getIconReport(); - }else if(itemType.equals(GXTFolderItemTypeEnum.REPORT_TEMPLATE)){ - return Resources.getIconReportTemplate(); }else if(itemType.equals(GXTFolderItemTypeEnum.URL_DOCUMENT)){ return Resources.getIconLink(); }else if(itemType.equals(GXTFolderItemTypeEnum.EXTERNAL_RESOURCE_LINK)){ diff --git a/src/main/java/org/gcube/portlets/user/workspace/client/rpc/GWTWorkspaceService.java b/src/main/java/org/gcube/portlets/user/workspace/client/rpc/GWTWorkspaceService.java index e5469f3..6062f13 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/client/rpc/GWTWorkspaceService.java +++ b/src/main/java/org/gcube/portlets/user/workspace/client/rpc/GWTWorkspaceService.java @@ -5,15 +5,12 @@ import java.util.Date; import java.util.List; import java.util.Map; -import org.gcube.portlets.user.workspace.client.interfaces.GXTCategorySmartFolder; import org.gcube.portlets.user.workspace.client.model.FileGridModel; import org.gcube.portlets.user.workspace.client.model.FileModel; import org.gcube.portlets.user.workspace.client.model.FileTrashedModel; import org.gcube.portlets.user.workspace.client.model.FileVersionModel; import org.gcube.portlets.user.workspace.client.model.FolderModel; import org.gcube.portlets.user.workspace.client.model.GcubeVRE; -import org.gcube.portlets.user.workspace.client.model.ScopeModel; -import org.gcube.portlets.user.workspace.client.model.SmartFolderModel; import org.gcube.portlets.user.workspace.client.model.SubTree; import org.gcube.portlets.user.workspace.client.workspace.GWTWorkspaceItem; import org.gcube.portlets.user.workspace.shared.GarbageItem; @@ -77,15 +74,6 @@ public interface GWTWorkspaceService extends RemoteService { */ public FolderModel getRootForTree() throws Exception; - /** - * Gets the all scope. - * - * @return the all scope - * @throws Exception - * the exception - */ - public List getAllScope() throws Exception; - /** * Gets the folder children. * @@ -139,53 +127,53 @@ public interface GWTWorkspaceService extends RemoteService { */ public ArrayList getChildrenSubTreeToRootByIdentifier(String itemIdentifier) throws Exception; - /** - * Gets the smart folder results by category. - * - * @param category - * the category - * @return the smart folder results by category - * @throws Exception - * the exception - */ - List getSmartFolderResultsByCategory(GXTCategorySmartFolder category) throws Exception; +// /** +// * Gets the smart folder results by category. +// * +// * @param category +// * the category +// * @return the smart folder results by category +// * @throws Exception +// * the exception +// */ +// List getSmartFolderResultsByCategory(GXTCategorySmartFolder category) throws Exception; - /** - * Creates the smart folder. - * - * @param name - * the name - * @param description - * the description - * @param query - * the query - * @param parentId - * the parent id - * @return the smart folder model - * @throws Exception - * the exception - */ - SmartFolderModel createSmartFolder(String name, String description, String query, String parentId) throws Exception; +// /** +// * Creates the smart folder. +// * +// * @param name +// * the name +// * @param description +// * the description +// * @param query +// * the query +// * @param parentId +// * the parent id +// * @return the smart folder model +// * @throws Exception +// * the exception +// */ +// SmartFolderModel createSmartFolder(String name, String description, String query, String parentId) throws Exception; - /** - * Gets the smart folder results by id. - * - * @param folderId - * the folder id - * @return the smart folder results by id - * @throws Exception - * the exception - */ - public List getSmartFolderResultsById(String folderId) throws Exception; +// /** +// * Gets the smart folder results by id. +// * +// * @param folderId +// * the folder id +// * @return the smart folder results by id +// * @throws Exception +// * the exception +// */ +// public List getSmartFolderResultsById(String folderId) throws Exception; - /** - * Gets the all smart folders. - * - * @return the all smart folders - * @throws Exception - * the exception - */ - public List getAllSmartFolders() throws Exception; +// /** +// * Gets the all smart folders. +// * +// * @return the all smart folders +// * @throws Exception +// * the exception +// */ +// public List getAllSmartFolders() throws Exception; /** * Gets the image by id. @@ -285,60 +273,6 @@ public interface GWTWorkspaceService extends RemoteService { * the exception */ public Boolean renameItem(String itemId, String newName, String oldName) throws Exception; - - /** - * Removes the smart folder. - * - * @param itemId - * the item id - * @param name - * the name - * @return the boolean - * @throws Exception - * the exception - */ - public Boolean removeSmartFolder(String itemId, String name) throws Exception; - - /** - * Gets the url web dav. - * - * @param itemId - * the item id - * @return the url web dav - * @throws Exception - * the exception - */ - public String getUrlWebDav(String itemId) throws Exception; - - /** - * Send to by id. - * - * @param listContactsId - * the list contacts id - * @param listAttachmentsId - * the list attachments id - * @param subject - * the subject - * @param text - * the text - * @return true, if successful - * @throws Exception - * the exception - */ - public boolean sendToById(List listContactsId, List listAttachmentsId, String subject, String text) - throws Exception; - - /** - * Gets the time series by id. - * - * @param identifier - * the identifier - * @return the time series by id - * @throws Exception - * the exception - */ - public GWTWorkspaceItem getTimeSeriesById(String identifier) throws Exception; - /** @@ -355,16 +289,6 @@ public interface GWTWorkspaceService extends RemoteService { public List getListParentsByItemIdentifier(String itemIdentifier, boolean includeItemAsParent) throws Exception; - /** - * Gets the URL from application profile. - * - * @param oid - * the oid - * @return the URL from application profile - * @throws Exception - * the exception - */ - public String getURLFromApplicationProfile(String oid) throws Exception; /** * Item exists in workpace folder. diff --git a/src/main/java/org/gcube/portlets/user/workspace/client/rpc/GWTWorkspaceServiceAsync.java b/src/main/java/org/gcube/portlets/user/workspace/client/rpc/GWTWorkspaceServiceAsync.java index 0cd4928..20cfb21 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/client/rpc/GWTWorkspaceServiceAsync.java +++ b/src/main/java/org/gcube/portlets/user/workspace/client/rpc/GWTWorkspaceServiceAsync.java @@ -8,15 +8,12 @@ import java.util.Date; import java.util.List; import java.util.Map; -import org.gcube.portlets.user.workspace.client.interfaces.GXTCategorySmartFolder; import org.gcube.portlets.user.workspace.client.model.FileGridModel; import org.gcube.portlets.user.workspace.client.model.FileModel; import org.gcube.portlets.user.workspace.client.model.FileTrashedModel; import org.gcube.portlets.user.workspace.client.model.FileVersionModel; import org.gcube.portlets.user.workspace.client.model.FolderModel; import org.gcube.portlets.user.workspace.client.model.GcubeVRE; -import org.gcube.portlets.user.workspace.client.model.ScopeModel; -import org.gcube.portlets.user.workspace.client.model.SmartFolderModel; import org.gcube.portlets.user.workspace.client.model.SubTree; import org.gcube.portlets.user.workspace.client.workspace.GWTWorkspaceItem; import org.gcube.portlets.user.workspace.shared.GarbageItem; @@ -135,50 +132,50 @@ public interface GWTWorkspaceServiceAsync { */ void getItemsBySearchName(String text, String folderId, AsyncCallback> callback); - /** - * Gets the smart folder results by category. - * - * @param category - * the category - * @param callback - * the callback - */ - void getSmartFolderResultsByCategory(GXTCategorySmartFolder category, AsyncCallback> callback); +// /** +// * Gets the smart folder results by category. +// * +// * @param category +// * the category +// * @param callback +// * the callback +// */ +// void getSmartFolderResultsByCategory(GXTCategorySmartFolder category, AsyncCallback> callback); - /** - * Creates the smart folder. - * - * @param name - * the name - * @param description - * the description - * @param query - * the query - * @param parentId - * the parent id - * @param callback - * the callback - */ - void createSmartFolder(String name, String description, String query, String parentId, - AsyncCallback callback); +// /** +// * Creates the smart folder. +// * +// * @param name +// * the name +// * @param description +// * the description +// * @param query +// * the query +// * @param parentId +// * the parent id +// * @param callback +// * the callback +// */ +// void createSmartFolder(String name, String description, String query, String parentId, +// AsyncCallback callback); - /** - * Gets the smart folder results by id. - * - * @param folderId - * the folder id - * @param callback - * the callback - */ - void getSmartFolderResultsById(String folderId, AsyncCallback> callback); +// /** +// * Gets the smart folder results by id. +// * +// * @param folderId +// * the folder id +// * @param callback +// * the callback +// */ +// void getSmartFolderResultsById(String folderId, AsyncCallback> callback); - /** - * Gets the all smart folders. - * - * @param callback - * the callback - */ - void getAllSmartFolders(AsyncCallback> callback); +// /** +// * Gets the all smart folders. +// * +// * @param callback +// * the callback +// */ +// void getAllSmartFolders(AsyncCallback> callback); /** * Gets the image by id. @@ -239,62 +236,25 @@ public interface GWTWorkspaceServiceAsync { */ void setValueInSession(String name, String value, AsyncCallback callback); - /** - * Removes the smart folder. - * - * @param itemId - * the item id - * @param name - * the name - * @param callback - * the callback - */ - void removeSmartFolder(String itemId, String name, AsyncCallback callback); +// /** +// * Removes the smart folder. +// * +// * @param itemId +// * the item id +// * @param name +// * the name +// * @param callback +// * the callback +// */ +// void removeSmartFolder(String itemId, String name, AsyncCallback callback); - /** - * Gets the all scope. - * - * @param callback - * the callback - */ - void getAllScope(AsyncCallback> callback); - - /** - * Send to by id. - * - * @param listContactsId - * the list contacts id - * @param listAttachmentsId - * the list attachments id - * @param subject - * the subject - * @param text - * the text - * @param callback - * the callback - */ - void sendToById(List listContactsId, List listAttachmentsId, String subject, String text, - AsyncCallback callback); - - /** - * Gets the url web dav. - * - * @param itemId - * the item id - * @param callback - * the callback - */ - void getUrlWebDav(String itemId, AsyncCallback callback); - - /** - * Gets the time series by id. - * - * @param identifier - * the identifier - * @param callback - * the callback - */ - void getTimeSeriesById(String identifier, AsyncCallback callback); +// /** +// * Gets the all scope. +// * +// * @param callback +// * the callback +// */ +// void getAllScope(AsyncCallback> callback); /** * Gets the list parents by item identifier. @@ -309,16 +269,6 @@ public interface GWTWorkspaceServiceAsync { void getListParentsByItemIdentifier(String itemIdentifier, boolean includeItemAsParent, AsyncCallback> callback); - /** - * Gets the URL from application profile. - * - * @param oid - * the oid - * @param callback - * the callback - */ - void getURLFromApplicationProfile(String oid, AsyncCallback callback); - /** * Item exists in workpace folder. * diff --git a/src/main/java/org/gcube/portlets/user/workspace/client/view/sharing/DialogPermission.java b/src/main/java/org/gcube/portlets/user/workspace/client/view/sharing/DialogPermission.java index 6c798a8..a76814f 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/client/view/sharing/DialogPermission.java +++ b/src/main/java/org/gcube/portlets/user/workspace/client/view/sharing/DialogPermission.java @@ -6,7 +6,6 @@ import org.gcube.portlets.user.workspace.client.AppControllerExplorer; import org.gcube.portlets.user.workspace.client.event.UpdatedVREPermissionEvent; import org.gcube.portlets.user.workspace.client.model.FileModel; import org.gcube.portlets.user.workspace.client.resources.Resources; - import org.gcube.portlets.user.workspace.client.view.windows.InfoDisplay; import org.gcube.portlets.user.workspace.client.view.windows.MessageBoxAlert; import org.gcube.portlets.widgets.workspacesharingwidget.client.permissions.PanelTogglePermission; diff --git a/src/main/java/org/gcube/portlets/user/workspace/client/view/sharing/DialogShareFolder.java b/src/main/java/org/gcube/portlets/user/workspace/client/view/sharing/DialogShareFolder.java index d448fd0..5fabaea 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/client/view/sharing/DialogShareFolder.java +++ b/src/main/java/org/gcube/portlets/user/workspace/client/view/sharing/DialogShareFolder.java @@ -6,7 +6,6 @@ import org.gcube.portlets.user.workspace.client.AppControllerExplorer; import org.gcube.portlets.user.workspace.client.ConstantsExplorer; import org.gcube.portlets.user.workspace.client.model.FileModel; import org.gcube.portlets.user.workspace.client.resources.Resources; - import org.gcube.portlets.user.workspace.client.view.windows.MessageBoxAlert; import org.gcube.portlets.widgets.workspacesharingwidget.client.permissions.PanelTogglePermission; import org.gcube.portlets.widgets.workspacesharingwidget.client.rpc.WorkspaceSharingServiceAsync; diff --git a/src/main/java/org/gcube/portlets/user/workspace/client/view/smartfolder/SmartButton.java b/src/main/java/org/gcube/portlets/user/workspace/client/view/smartfolder/SmartButton.java deleted file mode 100644 index 0f5fd32..0000000 --- a/src/main/java/org/gcube/portlets/user/workspace/client/view/smartfolder/SmartButton.java +++ /dev/null @@ -1,142 +0,0 @@ -package org.gcube.portlets.user.workspace.client.view.smartfolder; - -import org.gcube.portlets.user.workspace.client.AppControllerExplorer; -import org.gcube.portlets.user.workspace.client.event.DeleteSmartFolderEvent; -import org.gcube.portlets.user.workspace.client.resources.Resources; - -import com.extjs.gxt.ui.client.widget.Composite; -import com.extjs.gxt.ui.client.widget.HorizontalPanel; -import com.google.gwt.event.dom.client.ClickEvent; -import com.google.gwt.event.dom.client.ClickHandler; -import com.google.gwt.event.dom.client.MouseOutEvent; -import com.google.gwt.event.dom.client.MouseOutHandler; -import com.google.gwt.event.dom.client.MouseOverEvent; -import com.google.gwt.event.dom.client.MouseOverHandler; -import com.google.gwt.user.client.Command; -import com.google.gwt.user.client.ui.AbstractImagePrototype; -import com.google.gwt.user.client.ui.HTML; -import com.google.gwt.user.client.ui.Image; -/** - * - * @author Massimiliano Assante ISTI-CNR - * - * @version 1.0 May 14th 2012 - */ -public class SmartButton extends Composite { - - private final static String BASE_STYLE = "smartButton"; - - private boolean selected; - - private String caption; - - private HorizontalPanel myPanel = new HorizontalPanel(); - - private HTML text = new HTML(); - - private Command myCommand = null; - - private SmartFolderPanel caller; - - private Image delete = new Image(Resources.ICONS.close()); - - public SmartButton(String caption, AbstractImagePrototype img, SmartFolderPanel caller) { - super(); - selected = false; - this.caption = caption; - this.caller = caller; - super.setWidth(300); - text.setPixelSize(300, 30); - myPanel.setWidth("100%"); - - text.setHTML("
" + - "" + img.getHTML() + "" + - ""+ caption+"
"); - - myPanel.add(text); - - myPanel.setStyleName(BASE_STYLE); - initComponent(myPanel); - - text.addClickHandler(new ClickHandler() { - - @Override - public void onClick(ClickEvent event) { - selected = selected? false : true; - if (selected) { - myPanel.addStyleName(BASE_STYLE + "-selected"); - } else { - myPanel.removeStyleName(BASE_STYLE + "-selected"); - } - deselectOthers(); - if (myCommand != null) - myCommand.execute(); - } - }); - - } - - public SmartButton(String caption, AbstractImagePrototype img, SmartFolderPanel caller, boolean isDeletable) { - this(caption, img, caller); - - delete.getElement().getStyle().setOpacity(0.6); - delete.getElement().getStyle().setMarginTop(3, com.google.gwt.dom.client.Style.Unit.PX); - myPanel.add(delete); - delete.addClickHandler(new ClickHandler() { - @Override - public void onClick(ClickEvent event) { - deleteFolder(); - } - }); - - delete.addMouseOutHandler(new MouseOutHandler() { - @Override - public void onMouseOut(MouseOutEvent event) { - delete.getElement().getStyle().setOpacity(0.6); - } - }); - - delete.addMouseOverHandler(new MouseOverHandler() { - @Override - public void onMouseOver(MouseOverEvent event) { - delete.getElement().getStyle().setOpacity(0.9); - } - }); - } - - private void deleteFolder() { - AppControllerExplorer.getEventBus().fireEvent(new DeleteSmartFolderEvent(this.getId(), caption)); - } - - private void deselectOthers() { - caller.toggleOthers(this); - } - - public void setCommand(Command cmd) { - myCommand = cmd; - } - - /** - * Returns true if the button is pressed. - * - * @return the pressed state - */ - public boolean isSelected() { - return selected; - } - - /** - * Sets the current selected state. - * - * @param state true to set selected state - */ - protected void toggle(boolean state) { - this.selected = state; - if (selected) { - myPanel.addStyleName(BASE_STYLE + "-selected"); - } else { - myPanel.removeStyleName(BASE_STYLE + "-selected"); - } - } -} - diff --git a/src/main/java/org/gcube/portlets/user/workspace/client/view/smartfolder/SmartFolderPanel.java b/src/main/java/org/gcube/portlets/user/workspace/client/view/smartfolder/SmartFolderPanel.java deleted file mode 100644 index 70d8839..0000000 --- a/src/main/java/org/gcube/portlets/user/workspace/client/view/smartfolder/SmartFolderPanel.java +++ /dev/null @@ -1,203 +0,0 @@ -package org.gcube.portlets.user.workspace.client.view.smartfolder; - -import java.util.List; - -import org.gcube.portlets.user.workspace.client.AppControllerExplorer; -import org.gcube.portlets.user.workspace.client.ConstantsExplorer; -import org.gcube.portlets.user.workspace.client.event.SmartFolderSelectedEvent; -import org.gcube.portlets.user.workspace.client.interfaces.GXTCategorySmartFolder; -import org.gcube.portlets.user.workspace.client.model.SmartFolderModel; -import org.gcube.portlets.user.workspace.client.resources.Resources; -import org.gcube.portlets.user.workspace.client.view.windows.MessageBoxAlert; - -import com.extjs.gxt.ui.client.Style.Scroll; -import com.extjs.gxt.ui.client.widget.ContentPanel; -import com.extjs.gxt.ui.client.widget.LayoutContainer; -import com.google.gwt.core.client.GWT; -import com.google.gwt.user.client.Command; -import com.google.gwt.user.client.rpc.AsyncCallback; - -/** - * The Class SmartFolderPanel. - * - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * @author Massimiliano Assante ISTI-CNR - * @version 1.0 May 14th 2012 - */ - -public class SmartFolderPanel extends LayoutContainer { - - private ContentPanel cp; - private SmartButton buttDocuments = new SmartButton(GXTCategorySmartFolder.SMF_DOCUMENTS.getValue(), Resources.getIconDocuments(), this); - private SmartButton buttImages = new SmartButton(GXTCategorySmartFolder.SMF_IMAGES.getValue(), Resources.getIconImages(), this); - private SmartButton buttLinks = new SmartButton(GXTCategorySmartFolder.SMF_LINKS.getValue(), Resources.getIconLinks(), this); - private SmartButton buttPublicFolder = new SmartButton(GXTCategorySmartFolder.SMF_PUBLIC_FOLDERS.getValue(), Resources.getIconFolderPublic(), this); - - /** - * Instantiates a new smart folder panel. - */ - public SmartFolderPanel() { - this.cp = new ContentPanel(); - cp.setBodyBorder(false); - cp.setHeaderVisible(false); - cp.setScrollMode(Scroll.AUTO); - addListeners(); - add(cp); - } - - /** - * Reload panel smart folder. - */ - public void reloadPanelSmartFolder(){ - cp.removeAll(); - cp.add(buttDocuments); - cp.add(buttImages); - cp.add(buttLinks); - cp.add(buttPublicFolder); - cp.layout(); - addUserSmartFolder(); - - } - - /** - * Deselect all. - */ - public void deselectAll(){ - for (int i = 0; i < cp.getItemCount(); i++ ) - if (cp.getItem(i) instanceof SmartButton) { - SmartButton b = (SmartButton) cp.getItem(i); - b.toggle(false); - } - } - - /** - * Adds the user smart folder. - */ - private void addUserSmartFolder() { - AppControllerExplorer.rpcWorkspaceService.getAllSmartFolders(new AsyncCallback>() { - @Override - public void onSuccess(List result) { - loadSmartFolders(result); - } - @Override - public void onFailure(Throwable caught) { - new MessageBoxAlert("Error", ConstantsExplorer.SERVER_ERROR + " getting User's Smart Folders. " +ConstantsExplorer.TRY_AGAIN, null); - GWT.log("Error in load smart folder " + caught.getMessage()); - } - }); - - } - - /** - * Adds the listeners. - */ - private void addListeners() { - - buttImages.setCommand(new Command() { - @Override - public void execute() { - AppControllerExplorer.getEventBus().fireEvent(new SmartFolderSelectedEvent(GXTCategorySmartFolder.SMF_IMAGES)); - - } - }); - - buttLinks.setCommand(new Command() { - @Override - public void execute() { - AppControllerExplorer.getEventBus().fireEvent(new SmartFolderSelectedEvent(GXTCategorySmartFolder.SMF_LINKS)); - } - }); - - - buttDocuments.setCommand(new Command() { - @Override - public void execute() { - AppControllerExplorer.getEventBus().fireEvent(new SmartFolderSelectedEvent(GXTCategorySmartFolder.SMF_DOCUMENTS)); - } - }); - - buttPublicFolder.setCommand(new Command() { - - @Override - public void execute() { - - AppControllerExplorer.getEventBus().fireEvent(new SmartFolderSelectedEvent(GXTCategorySmartFolder.SMF_PUBLIC_FOLDERS)); - } - }); - } - - /** - * Load smart folders. - * - * @param result the result - */ - public void loadSmartFolders(List result) { - if (result != null && result.size() > 0) { - for (SmartFolderModel smart : result) { - loadSmartFolder(smart); - } - cp.layout(); - } - } - - - /** - * Load smart folder. - * - * @param smart the smart - */ - public void loadSmartFolder(final SmartFolderModel smart) { - - SmartButton userSmartFolder = new SmartButton(smart.getName(), Resources.getIconStar(), this, true); - userSmartFolder.setId(smart.getIdentifier()); - userSmartFolder.setCommand(new Command() { - @Override - public void execute() { - AppControllerExplorer.getEventBus().fireEvent(new SmartFolderSelectedEvent(smart.getIdentifier(), smart.getName(), null)); - } - }); - cp.add(userSmartFolder); - cp.layout(); - } - - /** - * Sets the size smart panel. - * - * @param width the width - * @param height the height - */ - public void setSizeSmartPanel(int width, int height) { - cp.setSize(width, height); - } - - /** - * Removes the smart folder. - * - * @param smartIdentifier the smart identifier - */ - public void removeSmartFolder(String smartIdentifier) { - cp.remove(cp.getItemByItemId(smartIdentifier)); - cp.layout(true); - } - - /** - * Un pressed all toogle. - */ - public void unPressedAllToogle(){ - deselectAll(); - } - - /** - * Toggle others. - * - * @param button the button - */ - public void toggleOthers(SmartButton button){ - for (int i = 0; i < cp.getItemCount(); i++ ) - if (cp.getItem(i) instanceof SmartButton) { - SmartButton b = (SmartButton) cp.getItem(i); - if (! b.equals(button)) - b.toggle(false); - } - } -} diff --git a/src/main/java/org/gcube/portlets/user/workspace/client/view/tree/ContextMenuTree.java b/src/main/java/org/gcube/portlets/user/workspace/client/view/tree/ContextMenuTree.java index 4d19c32..a58a43d 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/client/view/tree/ContextMenuTree.java +++ b/src/main/java/org/gcube/portlets/user/workspace/client/view/tree/ContextMenuTree.java @@ -941,14 +941,6 @@ public class ContextMenuTree { contextMenu.getItemByItemId(WorkspaceOperation.PUBLISH_ON_DATA_CATALOGUE.getId()).setVisible(true); contextMenu.getItemByItemId(WorkspaceOperation.COPY.getId()).setVisible(true); break; - case REPORT_TEMPLATE: - //contextMenu.getItemByItemId(WorkspaceOperation.OPEN_REPORT_TEMPLATE.getId()).setVisible(true); - break; - case REPORT: - //contextMenu.getItemByItemId(WorkspaceOperation.OPEN_REPORT.getId()).setVisible(true); - break; - case QUERY: - break; case TIME_SERIES: break; // case AQUAMAPS_ITEM: diff --git a/src/main/java/org/gcube/portlets/user/workspace/client/workspace/GWTWorkspaceFolder.java b/src/main/java/org/gcube/portlets/user/workspace/client/workspace/GWTWorkspaceFolder.java index efe9b26..faf02af 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/client/workspace/GWTWorkspaceFolder.java +++ b/src/main/java/org/gcube/portlets/user/workspace/client/workspace/GWTWorkspaceFolder.java @@ -12,8 +12,11 @@ import com.google.gwt.user.client.rpc.IsSerializable; /** - * @author Federico De Faveri defaveriAtisti.cnr.it + * The Class GWTWorkspaceFolder. * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * + * Jul 17, 2019 */ public class GWTWorkspaceFolder extends GWTWorkspaceItem implements IsSerializable { @@ -25,9 +28,26 @@ public class GWTWorkspaceFolder extends GWTWorkspaceItem implements IsSerializab protected boolean isShared = false; + /** + * Instantiates a new GWT workspace folder. + */ protected GWTWorkspaceFolder() { } + /** + * Instantiates a new GWT workspace folder. + * + * @param id the id + * @param name the name + * @param description the description + * @param owner the owner + * @param creationTime the creation time + * @param properties the properties + * @param lastModificationTime the last modification time + * @param lastAction the last action + * @param parent the parent + * @param children the children + */ public GWTWorkspaceFolder(String id, String name, String description, String owner, Date creationTime, GWTProperties properties, Date lastModificationTime, GWTWorkspaceItemAction lastAction, GWTWorkspaceFolder parent, List children) { @@ -37,21 +57,33 @@ public class GWTWorkspaceFolder extends GWTWorkspaceItem implements IsSerializab } + /* (non-Javadoc) + * @see org.gcube.portlets.user.workspace.client.workspace.GWTWorkspaceItem#getChildren() + */ public List getChildren(){ return children; } + /* (non-Javadoc) + * @see org.gcube.portlets.user.workspace.client.workspace.GWTWorkspaceItem#getType() + */ public GWTWorkspaceItemType getType() { return GWTWorkspaceItemType.FOLDER; } + /* (non-Javadoc) + * @see org.gcube.portlets.user.workspace.client.workspace.GWTWorkspaceItem#getItemDescription() + */ @Override public GWTItemDescription getItemDescription() { return getType(); } + /* (non-Javadoc) + * @see org.gcube.portlets.user.workspace.client.workspace.GWTWorkspaceItem#getIconClass() + */ @Override public String getIconClass() { @@ -62,21 +94,39 @@ public class GWTWorkspaceFolder extends GWTWorkspaceItem implements IsSerializab else return TREE_ROOT_ICON; } + /** + * Gets the enabled operations. + * + * @return the enabled operations + */ public List getEnabledOperations(){ return null; } + /** + * Adds the child. + * + * @param child the child + * @throws WrongItemTypeException the wrong item type exception + */ protected void addChild(GWTWorkspaceItem child) throws WrongItemTypeException { children.add( child); } + /** + * Removes the child. + * + * @param child the child + */ protected void removeChild(GWTWorkspaceItem child) { children.remove(child); } /** + * Checks if is shared. + * * @return the isShared */ public boolean isShared() { @@ -85,6 +135,8 @@ public class GWTWorkspaceFolder extends GWTWorkspaceItem implements IsSerializab /** + * Sets the shared. + * * @param isShared the isShared to set */ public void setShared(boolean isShared) { diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/DownloadPublicLinkServlet.java b/src/main/java/org/gcube/portlets/user/workspace/server/DownloadPublicLinkServlet.java index 45efa0e..6dcc720 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/DownloadPublicLinkServlet.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/DownloadPublicLinkServlet.java @@ -10,9 +10,10 @@ import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.log4j.Logger; import org.gcube.portlets.user.workspace.server.property.PortalUrlGroupGatewayProperty; import org.gcube.portlets.user.workspace.shared.HandlerResultMessage; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @@ -26,7 +27,7 @@ public class DownloadPublicLinkServlet extends HttpServlet{ private static final long serialVersionUID = -8423345575690165644L; - protected static Logger logger = Logger.getLogger(DownloadPublicLinkServlet.class); + protected static Logger logger = LoggerFactory.getLogger(DownloadPublicLinkServlet.class); /** * {@inheritDoc} diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/DownloadServlet.java b/src/main/java/org/gcube/portlets/user/workspace/server/DownloadServlet.java index 9f4801e..b884764 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/DownloadServlet.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/DownloadServlet.java @@ -3,10 +3,13 @@ */ package org.gcube.portlets.user.workspace.server; +import java.io.ByteArrayInputStream; +import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.StringReader; +import java.nio.file.Files; import java.util.List; import javax.servlet.ServletException; @@ -16,7 +19,6 @@ import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; -import org.apache.log4j.Logger; import org.gcube.common.portal.PortalContext; import org.gcube.common.storagehubwrapper.server.StorageHubWrapper; import org.gcube.common.storagehubwrapper.server.tohl.Workspace; @@ -27,6 +29,7 @@ import org.gcube.common.storagehubwrapper.shared.tohl.items.ImageFileItem; import org.gcube.common.storagehubwrapper.shared.tohl.items.ItemStreamDescriptor; import org.gcube.common.storagehubwrapper.shared.tohl.items.PDFFileItem; import org.gcube.common.storagehubwrapper.shared.tohl.items.URLFileItem; +import org.gcube.common.storagehubwrapper.shared.tohl.items.URLItem; import org.gcube.portlets.user.workspace.client.ConstantsExplorer; import org.gcube.portlets.user.workspace.server.property.PortalUrlGroupGatewayProperty; import org.gcube.portlets.user.workspace.server.util.AllowedMimeTypeToInline; @@ -35,6 +38,8 @@ import org.gcube.portlets.user.workspace.server.util.WsUtil; import org.gcube.portlets.user.workspace.shared.HandlerResultMessage; import org.gcube.portlets.user.workspace.shared.SessionExpiredException; import org.gcube.vomanagement.usermanagement.model.GCubeUser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @@ -48,7 +53,7 @@ public class DownloadServlet extends HttpServlet{ private static final long serialVersionUID = -8423345575690165644L; - protected static Logger logger = Logger.getLogger(DownloadServlet.class); + protected static Logger logger = LoggerFactory.getLogger(DownloadServlet.class); /** * {@inheritDoc} @@ -130,12 +135,43 @@ public class DownloadServlet extends HttpServlet{ } switch (item.getType()) { - - + case URL_ITEM: { + try{ + logger.info("Downloading "+item.getType()); + String urlValue = "URL not found"; + if(item instanceof URLItem) { + URLItem theURL = (URLItem) item; + urlValue = theURL.getValue()==null?"URL not found":theURL.getValue().toString(); + } + + StringBuilder build = new StringBuilder(); + build.append("#URL downloaded from D4Science, source filename: "+item.getName()); + build.append("\n"); + build.append(urlValue); + String fileContent = build.toString(); + logger.info("Writing file content: \n"+fileContent); + ByteArrayInputStream is = new ByteArrayInputStream(fileContent.getBytes()); + String contentDisposition = viewContent?"inline":"attachment"; + String urlMimeType = "text/uri-list"; + String itemName = MimeTypeUtility.getNameWithExtension(item.getName(), urlMimeType); + resp.setHeader("Content-Disposition", contentDisposition+"; filename=\"" + itemName + "\"" ); + resp.setContentType(urlMimeType); + + OutputStream out = resp.getOutputStream(); + IOUtils.copy(is, out); + is.close(); + out.close(); + return; + }catch (Exception e) { + logger.error("Error during downloading the item "+itemId,e); + handleError(urlRedirectOnError, req, resp, itemId, HttpServletResponse.SC_INTERNAL_SERVER_ERROR +": Error during data downloading: "+e.getMessage()); + return; + } + } case FOLDER: case SHARED_FOLDER: case VRE_FOLDER: - case SMART_FOLDER:{ + case SMART_FOLDER: { WorkspaceFolder workspaceFolder = (WorkspaceFolder) item; ItemStreamDescriptor descr; @@ -160,7 +196,7 @@ public class DownloadServlet extends HttpServlet{ OutputStream out = resp.getOutputStream(); InputStream is = descr.getStream(); - IOUtils.copy(descr.getStream(), out); + IOUtils.copy(is, out); is.close(); out.close(); @@ -251,7 +287,7 @@ public class DownloadServlet extends HttpServlet{ String contentDisposition = viewContent?"inline":"attachment"; resp.setHeader("Content-Disposition", contentDisposition+"; filename=\"" + itemName + "\"" ); resp.setContentType(urlMimeType); - resp = setContentLength(resp, externalUrl.getSize()); + //resp = setContentLength(resp, externalUrl.getSize()); //MODIFIED 22-05-2013 CLOSE STREAM OutputStream out = resp.getOutputStream(); @@ -509,6 +545,25 @@ public class DownloadServlet extends HttpServlet{ response.sendRedirect(response.encodeRedirectURL(requestUrl)); return; } + + /** + * Creates the temp file. + * + * @param fileName the file name + * @param extension the extension + * @param data the data + * @return the file + * @throws IOException Signals that an I/O exception has occurred. + */ + public static File createTempFile(String fileName, String extension, byte[] data) throws IOException { + // Since Java 1.7 Files and Path API simplify operations on files + java.nio.file.Path path = Files.createTempFile(fileName, extension); + File file = path.toFile(); + // writing sample data + Files.write(path, data); + logger.info("Created the Temp File: "+file.getAbsolutePath()); + return file; + } /** * Gets the request url. diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/FileNotVersionedException.java b/src/main/java/org/gcube/portlets/user/workspace/server/FileNotVersionedException.java index 2cc3f82..df8b30e 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/FileNotVersionedException.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/FileNotVersionedException.java @@ -12,13 +12,8 @@ package org.gcube.portlets.user.workspace.server; */ public class FileNotVersionedException extends Exception { - - /** - * - */ private static final long serialVersionUID = -954314398414781437L; - /** * Instantiates a new file not versioned exception. */ diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/GWTWorkspaceBuilder.java b/src/main/java/org/gcube/portlets/user/workspace/server/GWTWorkspaceBuilder.java deleted file mode 100644 index 1cc3a7e..0000000 --- a/src/main/java/org/gcube/portlets/user/workspace/server/GWTWorkspaceBuilder.java +++ /dev/null @@ -1,2457 +0,0 @@ -package org.gcube.portlets.user.workspace.server; - -import java.text.DecimalFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.UUID; -import java.util.concurrent.TimeUnit; - -import org.apache.log4j.Logger; -import org.gcube.common.homelibary.model.items.gcube.DocumentAlternativeLink; -import org.gcube.common.homelibary.model.items.gcube.DocumentMetadata; -import org.gcube.common.homelibary.model.items.gcube.DocumentPartLink; -import org.gcube.common.homelibary.model.items.type.NodeProperty; -import org.gcube.common.homelibary.model.items.type.WorkspaceItemType; -import org.gcube.common.homelibrary.home.User; -import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; -import org.gcube.common.homelibrary.home.workspace.Properties; -import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; -import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; -import org.gcube.common.homelibrary.home.workspace.WorkspaceSharedFolder; -import org.gcube.common.homelibrary.home.workspace.WorkspaceSmartFolder; -import org.gcube.common.homelibrary.home.workspace.accounting.AccountingEntry; -import org.gcube.common.homelibrary.home.workspace.accounting.AccountingEntryAdd; -import org.gcube.common.homelibrary.home.workspace.accounting.AccountingEntryCreate; -import org.gcube.common.homelibrary.home.workspace.accounting.AccountingEntryCut; -import org.gcube.common.homelibrary.home.workspace.accounting.AccountingEntryDisabledPublicAccess; -import org.gcube.common.homelibrary.home.workspace.accounting.AccountingEntryEnabledPublicAccess; -import org.gcube.common.homelibrary.home.workspace.accounting.AccountingEntryPaste; -import org.gcube.common.homelibrary.home.workspace.accounting.AccountingEntryRead; -import org.gcube.common.homelibrary.home.workspace.accounting.AccountingEntryRemoval; -import org.gcube.common.homelibrary.home.workspace.accounting.AccountingEntryRenaming; -import org.gcube.common.homelibrary.home.workspace.accounting.AccountingEntryRestore; -import org.gcube.common.homelibrary.home.workspace.accounting.AccountingEntryShare; -import org.gcube.common.homelibrary.home.workspace.accounting.AccountingEntryUnshare; -import org.gcube.common.homelibrary.home.workspace.accounting.AccountingEntryUpdate; -import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; -import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalFile; -import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalImage; -import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalPDFFile; -import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalUrl; -import org.gcube.common.homelibrary.home.workspace.folder.items.GCubeItem; -import org.gcube.common.homelibrary.home.workspace.search.SearchFolderItem; -import org.gcube.common.homelibrary.home.workspace.search.SearchItem; -import org.gcube.common.homelibrary.home.workspace.sharing.WorkspaceMessage; -import org.gcube.common.homelibrary.home.workspace.trash.WorkspaceTrashFolder; -import org.gcube.common.homelibrary.home.workspace.trash.WorkspaceTrashItem; -import org.gcube.common.homelibrary.home.workspace.usermanager.GCubeGroup; -import org.gcube.common.scope.api.ScopeProvider; -import org.gcube.common.storagehubwrapper.shared.ACLType; -import org.gcube.portal.wssynclibrary.shared.ItemNotSynched; -import org.gcube.portal.wssynclibrary.shared.thredds.Sync_Status; -import org.gcube.portal.wssynclibrary.thredds.WorkspaceThreddsSynchronize; -import org.gcube.portlets.user.workspace.client.ConstantsExplorer; -import org.gcube.portlets.user.workspace.client.interfaces.GXTCategorySmartFolder; -import org.gcube.portlets.user.workspace.client.interfaces.GXTFolderItemTypeEnum; -import org.gcube.portlets.user.workspace.client.model.FileDetailsModel; -import org.gcube.portlets.user.workspace.client.model.FileGridModel; -import org.gcube.portlets.user.workspace.client.model.FileModel; -import org.gcube.portlets.user.workspace.client.model.FileTrashedModel; -import org.gcube.portlets.user.workspace.client.model.FolderGridModel; -import org.gcube.portlets.user.workspace.client.model.FolderModel; -import org.gcube.portlets.user.workspace.client.model.MessageModel; -import org.gcube.portlets.user.workspace.client.model.ScopeModel; -import org.gcube.portlets.user.workspace.client.model.SmartFolderModel; -import org.gcube.portlets.user.workspace.client.util.ImageRequestType; -import org.gcube.portlets.user.workspace.client.workspace.GWTProperties; -import org.gcube.portlets.user.workspace.client.workspace.GWTWorkspaceFolder; -import org.gcube.portlets.user.workspace.client.workspace.GWTWorkspaceItem; -import org.gcube.portlets.user.workspace.client.workspace.GWTWorkspaceItemAction; -import org.gcube.portlets.user.workspace.client.workspace.folder.item.GWTExternalImage; -import org.gcube.portlets.user.workspace.client.workspace.folder.item.GWTExternalUrl; -import org.gcube.portlets.user.workspace.client.workspace.folder.item.gcube.GWTDocumentMetadata; -import org.gcube.portlets.user.workspace.client.workspace.folder.item.gcube.GWTImageDocument; -import org.gcube.portlets.user.workspace.client.workspace.folder.item.gcube.GWTUrlDocument; -import org.gcube.portlets.user.workspace.server.util.UserUtil; -import org.gcube.portlets.user.workspace.shared.accounting.GxtAccountingEntryType; -import org.gcube.portlets.user.workspace.shared.accounting.GxtAccountingField; -import org.gcube.portlets.widgets.workspacesharingwidget.shared.InfoContactModel; -import org.gcube.vomanagement.usermanagement.model.GCubeUser; - -import com.thoughtworks.xstream.XStream; - -// TODO: Auto-generated Javadoc -/** - * The Class GWTWorkspaceBuilder. - * - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * Nov 30, 2016 - */ -public class GWTWorkspaceBuilder { - - protected static final String IMAGE_SERVICE_URL = "ImageService"; - protected static Logger logger = Logger.getLogger(GWTWorkspaceBuilder.class); - private InfoContactModel userLogged; - private String scope; - protected static HashMap hashTestUser = null; - - /** - * Instantiates a new GWT workspace builder. - */ - public GWTWorkspaceBuilder() { - } - - /** - * Used in test mode. - * - * @return the hash test users - */ - public static HashMap getHashTestUsers() { - - if (hashTestUser == null) { - hashTestUser = new HashMap(); - - // USERS - hashTestUser.put("federico.defaveri", new InfoContactModel("federico.defaveri", "federico.defaveri", - "Federico de Faveri", "@isti.cnr.it", false)); - hashTestUser.put("antonio.gioia", - new InfoContactModel("antonio.gioia", "antonio.gioia", "Antonio Gioia", "@isti.cnr.it", false)); - hashTestUser.put("fabio.sinibaldi", new InfoContactModel("fabio.sinibaldi", "fabio.sinibaldi", - "Fabio Sinibaldi", "@isti.cnr.it", false)); - hashTestUser.put("pasquale.pagano", new InfoContactModel("pasquale.pagano", "pasquale.pagano", - "Pasquale Pagano", "@isti.cnr.it", false)); - hashTestUser.put("valentina.marioli", new InfoContactModel("valentina.marioli", "valentina.marioli", - "Valentina Marioli", "@isti.cnr.it", false)); - hashTestUser.put("roberto.cirillo", new InfoContactModel("roberto.cirillo", "roberto.cirillo", - "Roberto Cirillo", "@isti.cnr.it", false)); - hashTestUser.put("francesco.mangiacrapa", new InfoContactModel("francesco.mangiacrapa", - "francesco.mangiacrapa", "Francesco Mangiacrapa", "@isti.cnr.it", false)); - hashTestUser.put("massimiliano.assante", new InfoContactModel("massimiliano.assante", - "massimiliano.assante", "Massimiliano Assante", "@isti.cnr.it", false)); - - // try{ - // logger.info("Sleeping for testing..."); - // Thread.sleep(30000); - // logger.info("Alive again"); - // }catch(Exception e){ - // - // } - // GROUPS - // hashTestUser.put("/gcube/devsec/devVRE", new - // InfoContactModel("/gcube/devsec/devVRE", "/gcube/devsec/devVRE", - // "",true)); - // hashTestUser.put("/gcube/devsec/gcube-test-test", new - // InfoContactModel("/gcube/devsec/gcube-test-test", - // "/gcube/gcube-test-test", "",true)); - } - - return hashTestUser; - } - - /** - * utility method extract the @domain.com from an email address - * return @unknown-domain in case of no emails - */ - private String extractDomainFromEmail(String email) { - int index = email.indexOf('@'); - if (index > 0) - return email.substring(index); - else - return "@unknown-domain"; - } - - /** - * To date. - * - * @param calendar - * the calendar - * @return the date - */ - public static Date toDate(Calendar calendar) { - if (calendar == null) - return new Date(0); - return calendar.getTime(); - - } - - /** - * To date format to string. - * - * @param calendar - * the calendar - * @return the string - */ - protected String toDateFormatToString(Calendar calendar) { - - SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM, yyyy HH:mm:ss z"); - Date resultdate = getDate(calendar); - return dateFormat.format(resultdate); - } - - /** - * To date format. - * - * @param calendar - * the calendar - * @return the date - */ - protected Date toDateFormat(Calendar calendar) { - - SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM, yyyy HH:mm:ss z"); - Date resultdate = getDate(calendar); - try { - resultdate = dateFormat.parse(dateFormat.format(resultdate)); - } catch (ParseException e) { - e.printStackTrace(); - resultdate = new Date(0); - } - return resultdate; - } - - /** - * Gets the date. - * - * @param calendar - * the calendar - * @return the date - */ - private Date getDate(Calendar calendar) { - - Date resultdate = null; - - if (calendar == null) - resultdate = new Date(0); - else - resultdate = new Date(calendar.getTimeInMillis()); - - return resultdate; - - } - - /** - * Builds the gwt properties. - * - * @param metadata - * the metadata - * @return the GWT properties - * @throws InternalErrorException - * the internal error exception - */ - protected GWTProperties buildGWTProperties(Properties metadata) throws InternalErrorException { - // FIXME temp solution - // GWTProperties gwtProperties = new GWTProperties(metadata.getId(), - // metadata.getProperties()); - return new GWTProperties(); - } - - /** - * Builds the image url. - * - * @param id - * the id - * @param currentGroupId - * the current group id - * @param currUserId - * the curr user id - * @return the string - */ - protected String buildImageUrl(String id, String currentGroupId, String currUserId) { - return buildImageServiceUrl(id, ImageRequestType.IMAGE, currentGroupId, currUserId); - } - - /** - * Builds the thumbnail url. - * - * @param id - * the id - * @param currentGroupId - * the current group id - * @param currUserId - * the curr user id - * @return the string - */ - protected String buildThumbnailUrl(String id, String currentGroupId, String currUserId) { - return buildImageServiceUrl(id, ImageRequestType.THUMBNAIL, currentGroupId, currUserId); - } - - /** - * Builds the image service url. - * - * @param id - * the id - * @param requestType - * the request type - * @param currentGroupId - * the current group id read from PortalContext - * @param currUserId - * the curr user id - * @return the string - */ - protected String buildImageServiceUrl(String id, ImageRequestType requestType, String currentGroupId, - String currUserId) { - StringBuilder sb = new StringBuilder(); - sb.append(IMAGE_SERVICE_URL); - sb.append("?id="); - sb.append(id); - sb.append("&type="); - sb.append(requestType.toString()); - sb.append("&" + ConstantsExplorer.CURRENT_CONTEXT_ID + "="); - sb.append(currentGroupId); - // sb.append("&"+ConstantsExplorer.CURRENT_USER_ID+"="); - // sb.append(currUserId); - sb.append("&random="); - sb.append(UUID.randomUUID().toString()); - return sb.toString(); - } - - /** - * Builds the gwt workspace image. - * - * @param item - * the item - * @param isInteralImage - * the is interal image - * @param fullDetails - * the full details - * @param currentGroupId - * the current group id - * @param currentUserId - * the current user id - * @return the GWT workspace item - * @throws InternalErrorException - * the internal error exception - */ - @SuppressWarnings("unchecked") - protected GWTWorkspaceItem buildGWTWorkspaceImage(WorkspaceItem item, boolean isInteralImage, boolean fullDetails, - String currentGroupId, String currentUserId) throws InternalErrorException { - - GWTWorkspaceItem gwtImage; - - GWTProperties gwtProperties = buildGWTProperties(item.getProperties()); - // - if (isInteralImage) { - - GCubeItem image = (GCubeItem) item; // Cast OLD Image Document - - List links = (List) new XStream() - .fromXML(image.getProperties().getPropertyValue(NodeProperty.ALTERNATIVES.toString())); - List parts = (List) new XStream() - .fromXML(image.getProperties().getPropertyValue(NodeProperty.PARTS.toString())); - Map metadatas = (Map) new XStream() - .fromXML(image.getProperties().getPropertyValue(NodeProperty.METADATA.toString())); - Map gwtmetadatas = getMetadatas(metadatas, image.getId()); - - gwtImage = new GWTImageDocument(toDate(image.getCreationTime()), image.getId(), gwtProperties, - image.getName(), image.getOwner().getPortalLogin(), image.getDescription(), - toDate(image.getLastModificationTime()), - GWTWorkspaceItemAction.valueOf(image.getLastAction().toString()), null, - buildImageUrl(image.getId(), currentGroupId, currentUserId), - buildThumbnailUrl(image.getId(), currentGroupId, currentUserId), - Integer.parseInt(image.getProperties().getPropertyValue(NodeProperty.IMAGE_WIDTH.toString())), - Integer.parseInt(image.getProperties().getPropertyValue(NodeProperty.IMAGE_HEIGHT.toString())), - Integer.parseInt(image.getProperties().getPropertyValue(NodeProperty.THUMBNAIL_WIDTH.toString())), - Integer.parseInt(image.getProperties().getPropertyValue(NodeProperty.THUMBNAIL_HEIGHT.toString())), - -1, image.getLength(), image.getMimeType(), - image.getProperties().getPropertyValue(NodeProperty.OID.toString()), gwtmetadatas, - new LinkedHashMap(), - image.getProperties().getPropertyValue(NodeProperty.COLLECTION_NAME.toString()), links.size(), - parts.size()); - } - - else { - - ExternalImage image = (ExternalImage) item; // Cast External - // Document - - if (fullDetails) { - - gwtImage = new GWTExternalImage(toDate(image.getCreationTime()), image.getId(), gwtProperties, - image.getName(), image.getOwner().getPortalLogin(), image.getDescription(), - toDate(image.getLastModificationTime()), - GWTWorkspaceItemAction.valueOf(image.getLastAction().toString()), null, // parent - buildImageUrl(image.getId(), currentGroupId, currentUserId), - buildThumbnailUrl(image.getId(), currentGroupId, currentUserId), image.getWidth(), - image.getHeight(), image.getLength(), image.getThumbnailWidth(), image.getThumbnailHeight(), -1, - image.getMimeType()); - } else { - - gwtImage = new GWTExternalImage(image.getId(), image.getName(), - buildImageUrl(image.getId(), currentGroupId, currentUserId), - buildThumbnailUrl(image.getId(), currentGroupId, currentUserId), image.getWidth(), - image.getHeight(), image.getLength(), image.getThumbnailWidth(), image.getThumbnailHeight(), -1, - image.getMimeType()); - } - } - return gwtImage; - } - - /** - * Builds the gwt external url. - * - * @param url - * the url - * @param parent - * the parent - * @return the GWT external url - * @throws InternalErrorException - * the internal error exception - */ - protected GWTExternalUrl buildGWTExternalUrl(ExternalUrl url, GWTWorkspaceFolder parent) - throws InternalErrorException { - GWTProperties gwtProperties = buildGWTProperties(url.getProperties()); - GWTExternalUrl gwtUrl = new GWTExternalUrl(toDate(url.getCreationTime()), url.getId(), gwtProperties, - url.getName(), url.getOwner().getPortalLogin(), url.getDescription(), - toDate(url.getLastModificationTime()), GWTWorkspaceItemAction.valueOf(url.getLastAction().toString()), - parent, url.getLength(), url.getUrl()); - - return gwtUrl; - } - - /** - * Builds the gwt worspace url. - * - * @param item - * the item - * @param isInternalUrl - * the is internal url - * @param fullDetails - * the full details - * @return the GWT workspace item - * @throws InternalErrorException - * the internal error exception - */ - @SuppressWarnings("unchecked") - protected GWTWorkspaceItem buildGWTWorspaceUrl(WorkspaceItem item, boolean isInternalUrl, boolean fullDetails) - throws InternalErrorException { - - GWTWorkspaceItem gwtUrl = null; - GWTProperties gwtProperties = buildGWTProperties(item.getProperties()); - - if (isInternalUrl) { - - GCubeItem document = (GCubeItem) item; // Cast OLD UrlDocument - // UrlDocument document = (UrlDocument) item; //Cast - List links = (List) new XStream() - .fromXML(document.getProperties().getPropertyValue(NodeProperty.ALTERNATIVES.toString())); - List parts = (List) new XStream() - .fromXML(document.getProperties().getPropertyValue(NodeProperty.PARTS.toString())); - Map metadatas = (Map) new XStream() - .fromXML(document.getProperties().getPropertyValue(NodeProperty.METADATA.toString())); - Map gwtmetadatas = getMetadatas(metadatas, document.getId()); - - gwtUrl = new GWTUrlDocument(toDate(document.getCreationTime()), document.getId(), gwtProperties, - document.getName(), document.getOwner().getPortalLogin(), document.getDescription(), - toDate(document.getLastModificationTime()), - GWTWorkspaceItemAction.valueOf(document.getLastAction().toString()), null, document.getLength(), - document.getProperties().getPropertyValue(NodeProperty.OID.toString()), document.getMimeType(), - gwtmetadatas, new LinkedHashMap(), - document.getProperties().getPropertyValue(NodeProperty.COLLECTION_NAME.toString()), links.size(), - parts.size(), document.getProperties().getPropertyValue(NodeProperty.URL.toString())); - } else { - - ExternalUrl document = (ExternalUrl) item; // Cast - - if (fullDetails) { - gwtUrl = new GWTExternalUrl(toDate(document.getCreationTime()), document.getId(), gwtProperties, - document.getName(), document.getOwner().getPortalLogin(), document.getDescription(), - toDate(document.getLastModificationTime()), - GWTWorkspaceItemAction.valueOf(document.getLastAction().toString()), null, document.getLength(), - document.getUrl()); - } else - gwtUrl = new GWTExternalUrl(document.getUrl()); - } - return gwtUrl; - } - - /** - * Gets the metadatas. - * - * @param metadatas - * the metadatas - * @param documentId - * the document id - * @return the metadatas - */ - protected Map getMetadatas(Map metadatas, - String documentId) { - Map gwtmetadatas = new LinkedHashMap(); - - for (Entry metadata : metadatas.entrySet()) - gwtmetadatas.put(metadata.getKey(), getMetadata(metadata.getValue(), documentId)); - - return gwtmetadatas; - } - - /** - * Gets the metadata. - * - * @param metadata - * the metadata - * @param documentId - * the document id - * @return the metadata - */ - protected GWTDocumentMetadata getMetadata(DocumentMetadata metadata, String documentId) { - return new GWTDocumentMetadata(metadata.getSchemaName(), - "MetadataService?id=" + documentId + "&schema=" + metadata.getSchemaName() + "&type=" - + MetadataFormat.HTML, - "MetadataService?id=" + documentId + "&schema=" + metadata.getSchemaName() + "&type=" - + MetadataFormat.RAW_XML_AS_HTML, - "MetadataService?id=" + documentId + "&schema=" + metadata.getSchemaName() + "&type=" - + MetadataFormat.FORMATTED_XML); - } - - /** - * Builds the workspace file model root. - * - * @param workspaceRoot - * the workspace root - * @return the folder model - * @throws InternalErrorException - * the internal error exception - */ - public FolderModel buildWorkspaceFileModelRoot(WorkspaceFolder workspaceRoot) throws InternalErrorException { - - logger.trace("workspace id: " + workspaceRoot.getId()); - logger.trace("workspace name: " + workspaceRoot.getName()); - logger.trace("workspace path " + workspaceRoot.getPath()); - - FolderModel root = new FolderModel(workspaceRoot.getId(), workspaceRoot.getName(), null, true, - workspaceRoot.isShared(), false, workspaceRoot.isPublic()); - root.setIsRoot(true); - - return root; - } - - /** - * Builds the gxt list file model item. - * - * @param workspaceFolder - * the workspace folder - * @param parentFolderModel - * the parent folder model - * @return the list - * @throws InternalErrorException - * the internal error exception - */ - protected List buildGXTListFileModelItem(WorkspaceItem workspaceFolder, FileModel parentFolderModel) - throws InternalErrorException { - - List listFileModel = new ArrayList(); - - @SuppressWarnings("unchecked") - List listItems = (List) workspaceFolder.getChildren(); - - if (listItems != null) - logger.trace("HL return " + listItems.size() + " items, converting..."); - - // TEST TIME - // Long startTime = System.currentTimeMillis(); - // Long endTime = System.currentTimeMillis() - startTime; - // String time = String.format("%d msc %d sec", endTime, - // TimeUnit.MILLISECONDS.toSeconds(endTime)); - // logger.trace("tree getChildren() returning "+listItems.size()+" - // elements in " + time); - // startTime = System.currentTimeMillis(); - - for (WorkspaceItem item : listItems) { - if (item.isFolder()) { - logger.debug("item: " + item.getName() + "is root? " + item.isRoot()); - listFileModel.add(buildGXTFileModelItem(item, parentFolderModel)); - } - } - - // TEST TIME - // endTime = System.currentTimeMillis() - startTime; - // time = String.format("%d msc %d sec", endTime, - // TimeUnit.MILLISECONDS.toSeconds(endTime)); - // logger.trace("tree gxt objects getChildren() returning - // "+listItems.size()+" elements in " + time); - - return listFileModel; - - // return buildGXTListFileModelItem((WorkspaceItem) - // workspaceFolder.getChildren(), parentFolderModel); - } - - /** - * Builds the gxt list file model item for attachs. - * - * @param listWorspaceItems - * the list worspace items - * @return the list - * @throws InternalErrorException - * the internal error exception - */ - protected List buildGXTListFileModelItemForAttachs(List listWorspaceItems) - throws InternalErrorException { - - List listFileModel = new ArrayList(); - - for (WorkspaceItem item : listWorspaceItems) { - - FileModel fileModel = null; - - switch (item.getType()) { - - case FOLDER: - fileModel = new FolderModel(item.getId(), item.getName(), true, false); - fileModel.setType(GXTFolderItemTypeEnum.FOLDER.getLabel()); - break; - - case FOLDER_ITEM: - fileModel = new FileModel(item.getId(), item.getName(), false); - FolderItem folderItem = (FolderItem) item; - fileModel = setFolderItemType(fileModel, folderItem); - break; - - case SHARED_FOLDER: - - WorkspaceSharedFolder shared = (WorkspaceSharedFolder) item; - String name = shared.isVreFolder() ? shared.getDisplayName() : item.getName(); - - fileModel = new FolderModel(item.getId(), name, true, shared.isVreFolder()); - fileModel.setShared(true); - fileModel.setType(GXTFolderItemTypeEnum.FOLDER_SHARED.getLabel()); - - break; - default: - logger.error("gxt conversion return null for item " + item.getName()); - break; - } - - listFileModel.add(fileModel); - } - return listFileModel; - } - - /** - * Builds the gxt info contacts from portal logins. - * - * @param listPortalLogin - * the list portal login - * @return the list - */ - public static List buildGxtInfoContactsFromPortalLogins(List listPortalLogin) { - - List listContact = new ArrayList(); - - if (listPortalLogin != null && listPortalLogin.size() > 0) { - for (String portalLogin : listPortalLogin) - listContact.add(buildGxtInfoContactFromPortalLogin(portalLogin)); - } - - logger.debug("buildGxtInfoContactsFromPortalLogins return: " + listContact.size()); - return listContact; - } - - /** - * Builds the gxt info contact from portal login. - * - * @param portalLogin - * the portal login - * @return the info contact model - */ - public static InfoContactModel buildGxtInfoContactFromPortalLogin(String portalLogin) { - - if (portalLogin == null) { - logger.warn("portal login is null, return empty"); - portalLogin = ""; - } - - return new InfoContactModel(portalLogin, portalLogin, UserUtil.getUserFullName(portalLogin), "", false); - } - - /** - * Builds the gxt info contact from portal login test mode. - * - * @param listPortalLogin - * the list portal login - * @return the list - */ - public static List buildGxtInfoContactFromPortalLoginTestMode(List listPortalLogin) { - - List listContact = new ArrayList(); - - for (String portalLogin : listPortalLogin) - listContact.add(getHashTestUsers().get(portalLogin)); - - return listContact; - } - - /** - * Builds the gxt file model item. - * - * @param item - * the item - * @param parentFolderModel - * the parent folder model - * @return the file model - * @throws InternalErrorException - * the internal error exception - */ - protected FileModel buildGXTFileModelItem(WorkspaceItem item, FileModel parentFolderModel) - throws InternalErrorException { - // logger.debug("buildGXTFileModelItem: "+item.getName()); - - FileModel fileModel = null; - - /* - * if(parentFolderModel!=null) parentFolderModel = parentFolderModel; - */ - - switch (item.getType()) { - - case FOLDER: - boolean isPublic = ((WorkspaceFolder) item).isPublic(); - fileModel = new FolderModel(item.getId(), item.getName(), parentFolderModel, true, false, false, isPublic); - if (isPublic) - fileModel.setType(GXTFolderItemTypeEnum.FOLDER_PUBLIC.getLabel()); - else - fileModel.setType(GXTFolderItemTypeEnum.FOLDER.getLabel()); - - fileModel.setType(GXTFolderItemTypeEnum.FOLDER.getLabel()); - fileModel.setShareable(true); - fileModel.setDescription(item.getDescription()); - break; - - case FOLDER_ITEM: - - fileModel = new FileModel(item.getId(), item.getName(), parentFolderModel, false, false); - FolderItem folderItem = (FolderItem) item; - fileModel = setFolderItemType(fileModel, folderItem); - fileModel.setShareable(true); - break; - - case SHARED_FOLDER: - WorkspaceSharedFolder shared = (WorkspaceSharedFolder) item; - isPublic = ((WorkspaceFolder) shared).isPublic(); - String name = shared.isVreFolder() ? shared.getDisplayName() : item.getName(); - fileModel = new FolderModel(item.getId(), name, parentFolderModel, true, true, shared.isVreFolder(), - isPublic); - if (isPublic) - fileModel.setType(GXTFolderItemTypeEnum.FOLDER_SHARED_PUBLIC.toString()); - else - fileModel.setType(GXTFolderItemTypeEnum.FOLDER_SHARED.toString()); - - fileModel.setShareable(true); - fileModel.setDescription(item.getDescription()); - break; - - default: - logger.error("gxt conversion return null for item " + item.getName()); - break; - - } - - // SET SHARE POLICY - if (parentFolderModel != null && parentFolderModel.isShared()) { - fileModel.setShared(true); - fileModel.setShareable(false); // UPDATED TO CHANGE PERMISSIONS TO - // SHARED SUBFOLDERS - } else if (parentFolderModel == null && item.isShared()) { // ADDED TO - // FIX #1808 - fileModel.setShared(true); - if (item.getParent() != null && item.getParent().isShared()) - fileModel.setShareable(false); - } - - setSynchedThreddsStateFor(fileModel, scope, userLogged.getLogin()); - return fileModel; - } - - /** - * Builds the gxt list file grid model item for search. - * - * @param listSearchItems - * the list search items - * @return the list - * @throws Exception - * the exception - */ - public List buildGXTListFileGridModelItemForSearch(List listSearchItems) - throws Exception { - List listFileGridModel = new ArrayList(); - FileModel parentFileModel = null; - for (SearchItem item : listSearchItems) - listFileGridModel.add(buildGXTFileGridModelItemForSearch(item, parentFileModel)); - return listFileGridModel; - } - - /** - * Builds the gxt file grid model item for search. - * - * @param item - * the item - * @param parentFileModel - * the parent file model - * @return the file grid model - * @throws Exception - * the exception - */ - private FileGridModel buildGXTFileGridModelItemForSearch(SearchItem item, FileModel parentFileModel) - throws Exception { - - FileGridModel fileGridModel = null; - try { - - switch (item.getType()) { - - case FOLDER: - fileGridModel = new FolderGridModel(item.getId(), item.getName(), toDate(item.getLastModified()), - parentFileModel, -1, true, false, false, false); - fileGridModel.setType(GXTFolderItemTypeEnum.FOLDER.getLabel()); - fileGridModel.setShortcutCategory(GXTCategorySmartFolder.SMF_FOLDERS); - fileGridModel.setShareable(true); - break; - - case FOLDER_ITEM: - SearchFolderItem folderItem = (SearchFolderItem) item; - fileGridModel = new FileGridModel(item.getId(), item.getName(), toDate(item.getLastModified()), - parentFileModel, folderItem.getSize(), false, false); - fileGridModel = (FileGridModel) setFolderItemTypeForSearch(fileGridModel, folderItem); - break; - - case SHARED_FOLDER: - // ATTENTION: SEARCH ITEM IS NOT CASTABLE AT - // WorkspaceSharedFolder - fileGridModel = new FolderGridModel(item.getId(), item.getName(), toDate(item.getLastModified()), - parentFileModel, -1, true, true, item.isVreFolder(), false); - fileGridModel.setType(GXTFolderItemTypeEnum.FOLDER_SHARED.getLabel()); - fileGridModel.setShortcutCategory(GXTCategorySmartFolder.SMF_SHARED_FOLDERS); - fileGridModel.setShareable(true); - break; - - default: - logger.error("gxt conversion return null for item " + item.getName()); - break; - - } - - if (parentFileModel != null && parentFileModel.isShared()) { - fileGridModel.setShared(true); - fileGridModel.setShareable(false); // UPDATED TO CHANGE - // PERMISSIONS TO SHARED - // SUBFOLDERS - } - - // OWNER - if (item.isShared()) { // IS READ FROM HL ONLY IF THE ITEM IS SHARED - fileGridModel.setShared(true); // TEMPORARY SOLUTION: ADDED TO - // FIX WRONG TYPE - // SearchFolderItem - String portalLogin = item.getOwner(); // IS PORTAL LOGIN - if (portalLogin != null) { - fileGridModel.setOwnerFullName(UserUtil.getUserFullName(portalLogin)); - } - } else { - if (userLogged != null) - fileGridModel.setOwnerFullName(userLogged.getName()); - } - - setSynchedThreddsStateFor(fileGridModel, scope, userLogged.getLogin()); - return fileGridModel; - - } catch (Exception e) { - logger.error("An error occurred in buildGXTFileGridModelItemForSearch:", e); - throw new Exception(e); - } - } - - /** - * Builds the gxt list file grid model item. - * - * @param listWorkspaceItems - * the list workspace items - * @param parentFileModel - * the parent file model - * @return the list - * @throws InternalErrorException - * the internal error exception - */ - public List buildGXTListFileGridModelItem(List listWorkspaceItems, - FileModel parentFileModel) throws InternalErrorException { - - Long startTime = System.currentTimeMillis(); - List listFileGridModel = new ArrayList(); - - for (WorkspaceItem item : listWorkspaceItems) - listFileGridModel.add(buildGXTFileGridModelItem(item, parentFileModel)); - - Long endTime = System.currentTimeMillis() - startTime; - String time = String.format("%d msc %d sec", endTime, TimeUnit.MILLISECONDS.toSeconds(endTime)); - logger.trace("##GRID FILLING: gxt grid objects getChildren() returning " + listWorkspaceItems.size() - + " elements in " + time); - - return listFileGridModel; - } - - /** - * Builds the gxt file grid model item. - * - * @param item - * the item - * @param parentFileModel - * the parent file model - * @return the file grid model - * @throws InternalErrorException - * the internal error exception - */ - public FileGridModel buildGXTFileGridModelItem(WorkspaceItem item, FileModel parentFileModel) - throws InternalErrorException { - - FileGridModel fileGridModel = null; - - switch (item.getType()) { - - case FOLDER: - boolean isPublic = ((WorkspaceFolder) item).isPublic(); - fileGridModel = new FolderGridModel(item.getId(), item.getName(), toDate(item.getLastModificationTime()), - parentFileModel, -1, true, false, false, isPublic); - if (isPublic) - fileGridModel.setType(GXTFolderItemTypeEnum.FOLDER_PUBLIC.getLabel().toString()); - else - fileGridModel.setType(GXTFolderItemTypeEnum.FOLDER.getLabel().toString()); - - fileGridModel.setShortcutCategory(GXTCategorySmartFolder.SMF_FOLDERS); - fileGridModel.setShareable(true); - fileGridModel.setDescription(item.getDescription()); - break; - - case FOLDER_ITEM: - FolderItem folderItem = (FolderItem) item; - fileGridModel = new FileGridModel(item.getId(), item.getName(), toDate(item.getLastModificationTime()), - parentFileModel, folderItem.getLength(), false, false); - fileGridModel = (FileGridModel) setFolderItemType(fileGridModel, folderItem); - - // ADDING VERSION NAME - // if (folderItem instanceof ExternalFile){ - // - // ExternalFile extFile = (ExternalFile) folderItem; - // WorkspaceVersion version = extFile.getCurrentVersion(); - // fileGridModel.setVersionName(version!=null?version.getName():null); - // } - - break; - - case SHARED_FOLDER: - WorkspaceSharedFolder shared = (WorkspaceSharedFolder) item; - isPublic = ((WorkspaceFolder) shared).isPublic(); - String name = shared.isVreFolder() ? shared.getDisplayName() : item.getName(); - fileGridModel = new FolderGridModel(item.getId(), name, toDate(item.getLastModificationTime()), - parentFileModel, -1, true, true, shared.isVreFolder(), isPublic); - - if (isPublic) - fileGridModel.setType(GXTFolderItemTypeEnum.FOLDER_SHARED_PUBLIC.getLabel().toString()); - else - fileGridModel.setType(GXTFolderItemTypeEnum.FOLDER_SHARED.getLabel().toString()); - - fileGridModel.setShortcutCategory(GXTCategorySmartFolder.SMF_SHARED_FOLDERS); - fileGridModel.setShareable(true); - fileGridModel.setDescription(item.getDescription()); - break; - - default: - logger.error("gxt conversion return null for item " + item.getName()); - break; - - } - - if (parentFileModel != null && parentFileModel.isShared()) { - fileGridModel.setShared(true); - fileGridModel.setShareable(false); // UPDATED TO CHANGE PERMISSIONS - // TO SHARED SUBFOLDERS - } - - // OWNER - if (item.isShared()) { // IS READ FROM HL ONLY IF THE ITEM IS SHARED - fileGridModel.setShared(true); // NOT REMOVE IT IS IMPORTAT SEE - // #1459 - User owner = item.getOwner(); - if (owner != null) { - // System.out.println("++++reading owner"); - String portalLogin = owner.getPortalLogin(); - fileGridModel.setOwnerFullName(UserUtil.getUserFullName(portalLogin)); - } - } else { - if (userLogged != null) - // fileGridModel.setOwner(new - // InfoContactModel(userLogged.getId(), userLogged.getLogin(), - // userLogged.getName())); - fileGridModel.setOwnerFullName(userLogged.getName()); - } - - setSynchedThreddsStateFor(fileGridModel, scope, userLogged.getLogin()); - return fileGridModel; - } - - /** - * Sets the folder item type for search. - * - * @param fileModel - * the file model - * @param searchFolderItem - * the search folder item - * @return the file model - */ - protected FileModel setFolderItemTypeForSearch(FileModel fileModel, SearchFolderItem searchFolderItem) { - - if (searchFolderItem.getFolderItemType() == null) { - logger.trace("Search folder item type is null for " + searchFolderItem.getId() + " name: " - + searchFolderItem.getName()); - // FOR DEBUG - // System.out.println("Search folder item type is null for - // "+searchFolderItem.getId() + " name: - // "+searchFolderItem.getName()); - return fileModel; - } - - switch (searchFolderItem.getFolderItemType()) { - case EXTERNAL_IMAGE: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.EXTERNAL_IMAGE); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_IMAGES); - fileModel.setType(searchFolderItem.getMimeType()); - break; - case EXTERNAL_FILE: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.EXTERNAL_FILE); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_DOCUMENTS); - fileModel.setType(searchFolderItem.getMimeType()); - break; - case EXTERNAL_PDF_FILE: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.EXTERNAL_PDF_FILE); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_DOCUMENTS); - fileModel.setType(searchFolderItem.getMimeType()); - break; - case EXTERNAL_URL: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.EXTERNAL_URL); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_LINKS); - break; - case REPORT_TEMPLATE: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.REPORT_TEMPLATE); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_REPORTS); - break; - case REPORT: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.REPORT); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_REPORTS); - break; - case QUERY: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.QUERY); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_DOCUMENTS); - break; - case TIME_SERIES: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.TIME_SERIES); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_TIMESERIES); - break; - case PDF_DOCUMENT: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.PDF_DOCUMENT); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_DOCUMENTS); - break; - case IMAGE_DOCUMENT: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.IMAGE_DOCUMENT); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_IMAGES); - fileModel.setType(searchFolderItem.getMimeType()); - break; - case DOCUMENT: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.DOCUMENT); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_DOCUMENTS); - fileModel.setType(searchFolderItem.getMimeType()); - break; - case URL_DOCUMENT: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.URL_DOCUMENT); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_DOCUMENTS); - break; - case METADATA: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.METADATA); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_DOCUMENTS); - break; - case GCUBE_ITEM: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.GCUBE_ITEM); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_GCUBE_ITEMS); - break; - default: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.UNKNOWN_TYPE); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_UNKNOWN); - fileModel.setType(GXTFolderItemTypeEnum.UNKNOWN_TYPE.toString()); - break; - } - - return fileModel; - } - - /** - * Sets the folder item type. - * - * @param fileModel - * the file model - * @param worspaceFolderItem - * the worspace folder item - * @return the file model - */ - protected FileModel setFolderItemType(FileModel fileModel, FolderItem worspaceFolderItem) { - - switch (worspaceFolderItem.getFolderItemType()) { - case EXTERNAL_IMAGE: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.EXTERNAL_IMAGE); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_IMAGES); - ExternalImage extImage = (ExternalImage) worspaceFolderItem; - fileModel.setType(extImage.getMimeType()); - break; - case EXTERNAL_FILE: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.EXTERNAL_FILE); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_DOCUMENTS); - ExternalFile extFile = (ExternalFile) worspaceFolderItem; - fileModel.setType(extFile.getMimeType()); - break; - case EXTERNAL_PDF_FILE: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.EXTERNAL_PDF_FILE); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_DOCUMENTS); - ExternalPDFFile pdfExt = (ExternalPDFFile) worspaceFolderItem; - fileModel.setType(pdfExt.getMimeType()); - break; - case EXTERNAL_URL: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.EXTERNAL_URL); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_LINKS); - break; - case REPORT_TEMPLATE: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.REPORT_TEMPLATE); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_REPORTS); - break; - case REPORT: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.REPORT); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_REPORTS); - break; - case QUERY: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.QUERY); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_DOCUMENTS); - break; - case TIME_SERIES: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.TIME_SERIES); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_TIMESERIES); - break; - case PDF_DOCUMENT: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.PDF_DOCUMENT); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_DOCUMENTS); - break; - case IMAGE_DOCUMENT: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.IMAGE_DOCUMENT); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_IMAGES); - // ImageDocument imgDoc = (ImageDocument) worspaceFolderItem; - GCubeItem imgDoc = (GCubeItem) worspaceFolderItem; // Cast GCubeItem - try { - fileModel.setType(imgDoc.getMimeType()); - } catch (InternalErrorException e) { - logger.error( - "IMAGE_DOCUMENT InternalErrorException when getting MimeType on " + fileModel.getIdentifier()); - } - break; - case DOCUMENT: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.DOCUMENT); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_DOCUMENTS); - // Document doc = (Document) worspaceFolderItem; - GCubeItem doc = (GCubeItem) worspaceFolderItem; // Cast GCubeItem - try { - fileModel.setType(doc.getMimeType()); - } catch (InternalErrorException e) { - logger.error("DOCUMENT InternalErrorException when getting MimeType on " + fileModel.getIdentifier()); - } - break; - case URL_DOCUMENT: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.URL_DOCUMENT); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_DOCUMENTS); - break; - case METADATA: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.METADATA); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_DOCUMENTS); - break; - case GCUBE_ITEM: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.GCUBE_ITEM); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_GCUBE_ITEMS); - break; - default: - fileModel.setFolderItemType(GXTFolderItemTypeEnum.UNKNOWN_TYPE); - fileModel.setShortcutCategory(GXTCategorySmartFolder.SMF_UNKNOWN); - fileModel.setType(GXTFolderItemTypeEnum.UNKNOWN_TYPE.toString()); - break; - } - - return fileModel; - } - - /** - * Gets the public link for folder item. - * - * @param worspaceFolderItem - * the worspace folder item - * @return the publi link for folder item - * @throws InternalErrorException - * the internal error exception - */ - public String getPublicLinkForFolderItem(FolderItem worspaceFolderItem) throws InternalErrorException { - - if (worspaceFolderItem == null) - return ""; - - try { - switch (worspaceFolderItem.getFolderItemType()) { - case EXTERNAL_IMAGE: - return ((ExternalImage) worspaceFolderItem).getPublicLink(); - case EXTERNAL_FILE: - return ((ExternalFile) worspaceFolderItem).getPublicLink(); - case EXTERNAL_PDF_FILE: - return ((ExternalPDFFile) worspaceFolderItem).getPublicLink(); - case EXTERNAL_URL: - break; - case REPORT_TEMPLATE: - break; - case REPORT: - break; - case QUERY: - break; - case TIME_SERIES: - break; - case PDF_DOCUMENT: - break; - case IMAGE_DOCUMENT: - GCubeItem imgDoc = (GCubeItem) worspaceFolderItem; // Cast - // GCubeItem - return imgDoc.getPublicLink(false); - case DOCUMENT: - break; - case URL_DOCUMENT: - break; - case METADATA: - break; - default: - return ""; - } - - } catch (Exception e) { - logger.error("an error occurred when get public link for item: " + worspaceFolderItem.getName()); - return ""; - } - - return ""; - } - - /** - * Gets the storage id for folder item. - * - * @param worspaceFolderItem - * the worspace folder item - * @return the storage id for folder item - * @throws InternalErrorException - * the internal error exception - */ - public String getStorageIDForFolderItem(FolderItem worspaceFolderItem) throws InternalErrorException { - - if (worspaceFolderItem == null) - return ""; - - try { - switch (worspaceFolderItem.getFolderItemType()) { - case EXTERNAL_IMAGE: - return ((ExternalImage) worspaceFolderItem).getStorageID(); - case EXTERNAL_FILE: - return ((ExternalFile) worspaceFolderItem).getStorageID(); - case EXTERNAL_PDF_FILE: - return ((ExternalPDFFile) worspaceFolderItem).getStorageID(); - case EXTERNAL_URL: - break; - case REPORT_TEMPLATE: - break; - case REPORT: - break; - case QUERY: - break; - case TIME_SERIES: - break; - case PDF_DOCUMENT: - break; - case IMAGE_DOCUMENT: - GCubeItem imgDoc = (GCubeItem) worspaceFolderItem; // Cast - // GCubeItem - return imgDoc.getStorageID(); - case DOCUMENT: - break; - case URL_DOCUMENT: - break; - case METADATA: - break; - default: - return ""; - } - - } catch (Exception e) { - logger.error("an error occurred when get public link for item: " + worspaceFolderItem.getName()); - return ""; - } - - return ""; - } - - /** - * Builds the gxt folder model item. - * - * @param wsFolder - * the ws folder - * @param parent - * the parent - * @return the folder model - * @throws InternalErrorException - * the internal error exception - */ - public FolderModel buildGXTFolderModelItem(WorkspaceFolder wsFolder, FileModel parent) - throws InternalErrorException { - logger.debug("buildGXTFolderModelItem..."); - - String name = ""; - - // MANAGEMENT SHARED FOLDER NAME - if (wsFolder.isShared() && wsFolder.getType().equals(WorkspaceItemType.SHARED_FOLDER)) { - WorkspaceSharedFolder shared = (WorkspaceSharedFolder) wsFolder; - name = shared.isVreFolder() ? shared.getDisplayName() : wsFolder.getName(); - } else - name = wsFolder.getName(); - - // MANAGEMENT SPECIAL FOLDER - // if(wsFolder.getName().compareTo("MySpecialFolders")==0 && - // wsFolder.getParent()!=null && wsFolder.getParent().isRoot()){ - // WorkspaceSharedFolder shared = (WorkspaceSharedFolder) wsFolder; - // name = - // shared.isVreFolder()?shared.getDisplayName():wsFolder.getName(); - // }else - // name = wsFolder.getName(); - - FolderModel folder = new FolderModel(wsFolder.getId(), name, parent, true, wsFolder.isShared(), false, - wsFolder.isPublic()); - folder.setShareable(true); - folder.setDescription(wsFolder.getDescription()); - // folder.setOwner(wsFolder.getOwner()); - - if (parent != null && parent.isShared()) { - folder.setShared(true); - folder.setShareable(false); - } - - return folder; - } - - /** - * TODO ********TEMPORARY SOLUTION HL MUST MANAGE SPECIAL FOLDER AS - * WORKSPACESPECIALFOLDER**** REMOVE THIS METHOD AND ADDING INSTANCE OF AT - * buildGXTFolderModelItem. - * - * @param wsFolder - * the ws folder - * @param parent - * the parent - * @param specialFolderName - * the special folder name - * @return the folder model - * @throws InternalErrorException - * the internal error exception - */ - public FolderModel buildGXTFolderModelItemHandleSpecialFolder(WorkspaceFolder wsFolder, FileModel parent, - String specialFolderName) throws InternalErrorException { - - String name = ""; - - logger.debug("buildGXTFolderModelItemHandleSpecialFolder to folder: " + wsFolder.getName()); - // MANAGEMENT SHARED FOLDER NAME - if (wsFolder.isShared() && wsFolder.getType().equals(WorkspaceItemType.SHARED_FOLDER)) { - logger.debug("MANAGEMENT SHARED Folder name.."); - WorkspaceSharedFolder shared = (WorkspaceSharedFolder) wsFolder; - logger.debug("shared.isVreFolder(): " + shared.isVreFolder()); - name = shared.isVreFolder() ? shared.getDisplayName() : wsFolder.getName(); - - /* - * if(shared.isVreFolder()) - * logger.debug("shared.getDisplayName(): "+shared.getDisplayName()) - * ; - */ - // MANAGEMENT SPECIAL FOLDER - } else if (wsFolder.getName().compareTo(ConstantsExplorer.MY_SPECIAL_FOLDERS) == 0 - && wsFolder.getParent() != null && wsFolder.getParent().isRoot()) { - // MANAGEMENT SPECIAL FOLDER - logger.debug("MANAGEMENT SPECIAL FOLDER NAME REWRITING AS: " + specialFolderName); - if (specialFolderName != null && !specialFolderName.isEmpty()) - name = specialFolderName; - else - name = wsFolder.getName(); - } else { - logger.debug("MANAGEMENT Base Folder name.."); - name = wsFolder.getName(); - } - - logger.debug("Name is: " + name); - - FolderModel folder = new FolderModel(wsFolder.getId(), name, parent, true, wsFolder.isShared(), false, - wsFolder.isPublic()); - folder.setShareable(true); - folder.setIsRoot(wsFolder.isRoot()); - folder.setDescription(wsFolder.getDescription()); - // folder.setOwner(wsFolder.getOwner()); - - if (parent != null && parent.isShared()) { - folder.setShared(true); - folder.setShareable(false); - } - return folder; - } - - /** - * Builds the gwt workspace file details. - * - * @param wsItem - * the ws item - * @param item - * the item - * @return the file details model - * @throws InternalErrorException - * the internal error exception - */ - public FileDetailsModel buildGWTWorkspaceFileDetails(WorkspaceItem wsItem, FileModel item) - throws InternalErrorException { - - FileDetailsModel fileDetailsModel = new FileDetailsModel(wsItem.getId(), wsItem.getName(), wsItem.getPath(), - toDate(wsItem.getCreationTime()), item.getParentFileModel(), 0, // size - item.isDirectory(), wsItem.getDescription(), toDate(wsItem.getLastModificationTime()), - buildGXTInfoContactModel(wsItem.getOwner()), wsItem.isShared()); - - return fileDetailsModel; - } - - /** - * Gets the folder item type category. - * - * @param item - * the item - * @return the folder item type category - * @throws InternalErrorException - * the internal error exception - */ - protected GXTCategorySmartFolder getFolderItemTypeCategory(SearchItem item) throws InternalErrorException { - - switch (item.getType()) { - - case FOLDER: - - return GXTCategorySmartFolder.SMF_DOCUMENTS; - - case FOLDER_ITEM: - - SearchFolderItem folderItem = (SearchFolderItem) item; - switch (folderItem.getFolderItemType()) { - case EXTERNAL_IMAGE: - return GXTCategorySmartFolder.SMF_IMAGES; - case EXTERNAL_FILE: - return GXTCategorySmartFolder.SMF_DOCUMENTS; - case EXTERNAL_PDF_FILE: - return GXTCategorySmartFolder.SMF_DOCUMENTS; - case EXTERNAL_URL: - return GXTCategorySmartFolder.SMF_LINKS; - case REPORT_TEMPLATE: - return GXTCategorySmartFolder.SMF_REPORTS; - case REPORT: - return GXTCategorySmartFolder.SMF_REPORTS; - case QUERY: - return GXTCategorySmartFolder.SMF_DOCUMENTS; - case TIME_SERIES: - return GXTCategorySmartFolder.SMF_TIMESERIES; - case PDF_DOCUMENT: - return GXTCategorySmartFolder.SMF_DOCUMENTS; - case IMAGE_DOCUMENT: - return GXTCategorySmartFolder.SMF_IMAGES; - case DOCUMENT: - return GXTCategorySmartFolder.SMF_DOCUMENTS; - case URL_DOCUMENT: - return GXTCategorySmartFolder.SMF_DOCUMENTS; - case METADATA: - return GXTCategorySmartFolder.SMF_DOCUMENTS; - case GCUBE_ITEM: - return GXTCategorySmartFolder.SMF_GCUBE_ITEMS; - default: - return GXTCategorySmartFolder.SMF_UNKNOWN; - } - - default: - logger.error("gxt conversion return null for item " + item.getName()); - return GXTCategorySmartFolder.SMF_UNKNOWN; - } - - } - - /** - * Filter list file grid model item by category. - * - * @param listSearchItem - * the list search item - * @param category - * the category - * @return the list - * @throws Exception - * the exception - */ - public List filterListFileGridModelItemByCategory(List listSearchItem, - GXTCategorySmartFolder category) throws Exception { - - List filteredList = new ArrayList(); - logger.trace("filterListFileGridModelItemByCategory - Category:" + category + "listSearchItem size " - + listSearchItem.size()); - for (SearchItem searchItem : listSearchItem) { - logger.trace("wsItem: " + searchItem.getName()); - if (category.equals(getFolderItemTypeCategory(searchItem))) - filteredList.add(buildGXTFileGridModelItemForSearch(searchItem, null)); - } - return filteredList; - } - - /** - * Builds the gxt list smart folder model. - * - * @param listWorkspaceSmartFolder - * the list workspace smart folder - * @return the list - * @throws Exception - * the exception - */ - public List buildGXTListSmartFolderModel(List listWorkspaceSmartFolder) - throws Exception { - List listSmartFolder = new ArrayList(); - - for (WorkspaceSmartFolder workspaceFolder : listWorkspaceSmartFolder) - listSmartFolder.add(buildGXTSmartFolderModel(workspaceFolder, "")); - - return listSmartFolder; - } - - /** - * Builds the gxt smart folder model. - * - * @param wsFolder - * the ws folder - * @param query - * the query - * @return the smart folder model - * @throws Exception - * the exception - */ - public SmartFolderModel buildGXTSmartFolderModel(WorkspaceSmartFolder wsFolder, String query) throws Exception { - - SmartFolderModel smartFolderModel = new SmartFolderModel(wsFolder.getId(), wsFolder.getName(), query); - - logger.trace("in return SmartFolder: " + smartFolderModel.getIdentifier() + " " + smartFolderModel.getName() - + " " + smartFolderModel.getQuery()); - return smartFolderModel; - } - - /** - * Builds the gxt list scope model. - * - * @param listFilteredScopes - * the list filtered scopes - * @param mapPortalScopes - * the map portal scopes - * @return the list - */ - public List buildGXTListScopeModel(List listFilteredScopes, - Map mapPortalScopes) { - - List listScopeModel = new ArrayList(); - for (String scope : listFilteredScopes) - listScopeModel.add(new ScopeModel(mapPortalScopes.get(scope), scope)); - - return listScopeModel; - - } - - /** - * Builds the gxt list contacts model from user model. - * - * @param listUsers - * the list users - * @return the list - * @throws InternalErrorException - * the internal error exception - */ - public List buildGXTListContactsModelFromUserModel(List listUsers) - throws InternalErrorException { - - List listContactsModel = new ArrayList(); - - if (listUsers == null) - return listContactsModel; - - logger.trace("List size returned from Portal VO is: " + listUsers.size()); - - logger.trace("Building list contact model list user model"); - for (GCubeUser userModel : listUsers) { - String fullName = userModel.getFullname(); - - if (fullName != null && !fullName.isEmpty()) - listContactsModel.add(new InfoContactModel(userModel.getUserId() + "", userModel.getScreenName(), - fullName, extractDomainFromEmail(userModel.getEmail()), false)); - else - logger.trace("buildGXTListContactsModel is not returning user: " + userModel.getScreenName() - + "because name is null or empty"); - } - logger.trace("List contact model completed, return " + listContactsModel.size() + " contacts"); - - return listContactsModel; - } - - /** - * Builds the gxt list contacts model from gcube group. - * - * @param list - * the list - * @return the list - * @throws InternalErrorException - * the internal error exception - */ - public List buildGXTListContactsModelFromGcubeGroup(List list) - throws InternalErrorException { - - List listContactsModel = new ArrayList(); - - if (list == null) - return listContactsModel; - - logger.trace("List size returned from GcubeGroup is: " + list.size()); - - logger.trace("Building list contact model..."); - - for (GCubeGroup group : list) { - try { - String groupDN = group.getDisplayName(); - - if (groupDN == null || groupDN.isEmpty()) - groupDN = group.getName(); - - if (group.getName() == null || group.getName().isEmpty()) - logger.warn("Skipping group with null or empty name " + group); - else { - InfoContactModel contact = new InfoContactModel(group.getName(), group.getName(), groupDN, "", - true); - logger.trace("Adding group " + contact); - listContactsModel.add(contact); - } - } catch (InternalErrorException e) { - logger.warn("Dispaly name is not available to group " + group); - logger.warn("Adding get name property " + group.getName()); - - if (group.getName() == null || group.getName().isEmpty()) - logger.warn("Skipping group with null or empty name " + group); - else - listContactsModel - .add(new InfoContactModel(group.getName(), group.getName(), group.getName(), "", true)); - } - } - - logger.trace("List GCubeGroup contact model completed, return " + listContactsModel.size() + " contacts"); - - return listContactsModel; - } - - /** - * Builds the list login from contanct model. - * - * @param listContactsModel - * the list contacts model - * @return list of portal logins - * @throws InternalErrorException - * the internal error exception - */ - public List buildListLoginFromContanctModel(List listContactsModel) - throws InternalErrorException { - - List listPortalLogin = new ArrayList(); - - for (InfoContactModel contact : listContactsModel) { - listPortalLogin.add(contact.getLogin()); - - } - return listPortalLogin; - } - - /** - * Builds the gxt list message model for grid. - * - * @param listMessages - * the list messages - * @param typeMessages - * the type messages - * @return the list - * @throws InternalErrorException - * the internal error exception - */ - public List buildGXTListMessageModelForGrid(List listMessages, String typeMessages) - throws InternalErrorException { - - List listMessageModel = new ArrayList(); - - for (WorkspaceMessage mess : listMessages) { - List listAttachs = mess.getAttachments(); - List listAttachsNames = new ArrayList(); - - logger.trace("IN SERVER MESSAGE TYPE: " + typeMessages); - logger.trace("subject " + mess.getSubject()); - - if (listAttachs != null) { - for (WorkspaceItem attach : listAttachs) { - listAttachsNames.add(attach.getName()); - logger.trace("Received attach: " + attach.getName() + " " + attach.getId()); - } - } - - listMessageModel - .add(new MessageModel(mess.getId(), mess.getSubject(), buildGXTInfoContactModel(mess.getSender()), - toDate(mess.getSendTime()), listAttachsNames, typeMessages, mess.isRead())); - - } - return listMessageModel; - } - - /** - * Builds the gxt message model. - * - * @param mess - * the mess - * @param listWorkspaceItems - * the list workspace items - * @param messageType - * the message type - * @return the message model - * @throws InternalErrorException - * the internal error exception - */ - public MessageModel buildGXTMessageModel(WorkspaceMessage mess, List listWorkspaceItems, - String messageType) throws InternalErrorException { - - List listAttachs = buildGXTListFileModelItemForAttachs(listWorkspaceItems); - return new MessageModel(mess.getId(), mess.getSubject(), buildGXTInfoContactModel(mess.getSender()), - toDate(mess.getSendTime()), mess.getBody(), listAttachs, mess.getAddresses(), messageType, - mess.isRead()); - - } - - /** - * Builds the gxt info contact model. - * - * @param user - * the user - * @return InfoContactModel - * @throws InternalErrorException - * the internal error exception - */ - public InfoContactModel buildGXTInfoContactModel(User user) throws InternalErrorException { - - if (user != null) - return new InfoContactModel(user.getId(), user.getPortalLogin(), - UserUtil.getUserFullName(user.getPortalLogin()), "", false); - - return new InfoContactModel(); - } - - /** - * Builds the gxt accounting item. - * - * @param accoutings - * the accoutings - * @param gxtEntryType - * the gxt entry type - * @return the list - */ - public List buildGXTAccountingItem(List accoutings, - GxtAccountingEntryType gxtEntryType) { - - List listAccFields = new ArrayList(); - - if (accoutings != null) { - logger.trace("accoutings size " + accoutings.size() + ", converting..."); - - for (AccountingEntry accountingEntry : accoutings) { - - GxtAccountingField af = new GxtAccountingField(); - - InfoContactModel user = buildGxtInfoContactFromPortalLogin(accountingEntry.getUser()); - - af.setUser(user); - af.setDate(toDate(accountingEntry.getDate())); - - switch (accountingEntry.getEntryType()) { - - case CREATE: - - if (gxtEntryType == null || gxtEntryType.equals(GxtAccountingEntryType.ALL) - || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) - || gxtEntryType.equals(GxtAccountingEntryType.CREATE)) { - AccountingEntryCreate create = (AccountingEntryCreate) accountingEntry; - af.setOperation(GxtAccountingEntryType.CREATE); - - // af.setDescription(GxtAccountingEntryType.CREATE.getName() - // + " by "+user.getName()); - String msg = ""; - if (create.getItemName() == null || create.getItemName().isEmpty()) - msg = GxtAccountingEntryType.CREATE.getId() + " by " + user.getName(); - else { - - if (create.getVersion() == null) - msg = create.getItemName() + " " + GxtAccountingEntryType.CREATE.getName() + " by " - + user.getName(); - else - msg = create.getItemName() + " v. " + create.getVersion() + " " - + GxtAccountingEntryType.CREATE.getName() + " by " + user.getName(); - } - - af.setDescription(msg); - } - - break; - - case READ: - - if (gxtEntryType == null || gxtEntryType.equals(GxtAccountingEntryType.ALL) - || gxtEntryType.equals(GxtAccountingEntryType.READ)) { - - AccountingEntryRead read = (AccountingEntryRead) accountingEntry; - af.setOperation(GxtAccountingEntryType.READ); - af.setDescription(read.getItemName() + " " + GxtAccountingEntryType.READ.getName() + " by " - + user.getName()); - - String msg = ""; - if (read.getItemName() == null || read.getItemName().isEmpty()) - msg = GxtAccountingEntryType.READ.getId() + " by " + user.getName(); - else { - - if (read.getVersion() == null) - msg = read.getItemName() + " " + GxtAccountingEntryType.READ.getName() + " by " - + user.getName(); - else - msg = read.getItemName() + " v." + read.getVersion() + " " - + GxtAccountingEntryType.READ.getName() + " by " + user.getName(); - } - - af.setDescription(msg); - } - - break; - - case CUT: - - if (gxtEntryType == null || gxtEntryType.equals(GxtAccountingEntryType.ALL) - || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) - || gxtEntryType.equals(GxtAccountingEntryType.CUT)) { - - af.setOperation(GxtAccountingEntryType.CUT); - AccountingEntryCut cut = (AccountingEntryCut) accountingEntry; - - String msg = ""; - if (cut.getItemName() == null || cut.getItemName().isEmpty()) - msg = GxtAccountingEntryType.CUT.getName() + " by " + user.getName(); - else { - if (cut.getVersion() == null) - msg = cut.getItemName() + " " + GxtAccountingEntryType.CUT.getName() + " by " - + user.getName(); - else - msg = cut.getItemName() + " v." + cut.getVersion() + " " - + GxtAccountingEntryType.CUT.getName() + " by " + user.getName(); - } - - af.setDescription(msg); - } - - break; - - case PASTE: - - if (gxtEntryType == null || gxtEntryType.equals(GxtAccountingEntryType.ALL) - || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) - || gxtEntryType.equals(GxtAccountingEntryType.PASTE)) { - - af.setOperation(GxtAccountingEntryType.PASTE); - AccountingEntryPaste paste = (AccountingEntryPaste) accountingEntry; - - if (paste.getVersion() == null) - af.setDescription(GxtAccountingEntryType.PASTE.getName() + " from " + paste.getFromPath() - + " by " + user.getName()); - else - af.setDescription(GxtAccountingEntryType.PASTE.getName() + " v. " + paste.getVersion() - + " from " + paste.getFromPath() + " by " + user.getName()); - } - - break; - - case REMOVAL: - - if (gxtEntryType == null || gxtEntryType.equals(GxtAccountingEntryType.ALL) - || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) - || gxtEntryType.equals(GxtAccountingEntryType.REMOVE)) { - - af.setOperation(GxtAccountingEntryType.REMOVE); - AccountingEntryRemoval rem = (AccountingEntryRemoval) accountingEntry; - String msg = rem.getItemName() == null || rem.getItemName().isEmpty() ? "" - : rem.getItemName() + " "; - - if (rem.getVersion() == null) - msg += GxtAccountingEntryType.REMOVE.getName() + " by " + user.getName(); - else - msg += GxtAccountingEntryType.REMOVE.getName() + " v." + rem.getVersion() + " by " - + user.getName(); - - af.setDescription(msg); - } - break; - - case RENAMING: - - if (gxtEntryType == null || gxtEntryType.equals(GxtAccountingEntryType.ALL) - || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) - || gxtEntryType.equals(GxtAccountingEntryType.RENAME)) { - - af.setOperation(GxtAccountingEntryType.RENAME); - AccountingEntryRenaming ren = (AccountingEntryRenaming) accountingEntry; - String msg = ren.getOldItemName() == null || ren.getOldItemName().isEmpty() ? "" - : ren.getOldItemName() + " "; - if (ren.getVersion() == null) - msg += GxtAccountingEntryType.RENAME.getName() + " to " + ren.getNewItemName() + " by " - + user.getName(); - else - msg += " v." + ren.getVersion() + " " + GxtAccountingEntryType.RENAME.getName() + " to " - + ren.getNewItemName() + " by " + user.getName(); - - af.setDescription(msg); - } - break; - - case ADD: - - if (gxtEntryType == null || gxtEntryType.equals(GxtAccountingEntryType.ALL) - || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) - || gxtEntryType.equals(GxtAccountingEntryType.ADD)) { - - af.setOperation(GxtAccountingEntryType.ADD); - AccountingEntryAdd acc = (AccountingEntryAdd) accountingEntry; - String msg = acc.getItemName() == null || acc.getItemName().isEmpty() ? "" - : acc.getItemName() + " "; - if (acc.getVersion() == null) - msg += GxtAccountingEntryType.ADD.getName() + " by " + user.getName(); - else - msg += " v." + acc.getVersion() + " " + GxtAccountingEntryType.ADD.getName() + " by " - + user.getName(); - - af.setDescription(msg); - } - break; - - case UPDATE: - - if (gxtEntryType == null || gxtEntryType.equals(GxtAccountingEntryType.ALL) - || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) - || gxtEntryType.equals(GxtAccountingEntryType.UPDATE)) { - - af.setOperation(GxtAccountingEntryType.UPDATE); - AccountingEntryUpdate upd = (AccountingEntryUpdate) accountingEntry; - String msg = upd.getItemName() == null || upd.getItemName().isEmpty() ? "" - : upd.getItemName() + " "; - if (upd.getVersion() == null) - msg += GxtAccountingEntryType.UPDATE.getName() + " by " + user.getName(); - else - msg += " v." + upd.getVersion() + " " + GxtAccountingEntryType.UPDATE.getName() + " by " - + user.getName(); - - af.setDescription(msg); - } - break; - - case SHARE: - - if (gxtEntryType == null || gxtEntryType.equals(GxtAccountingEntryType.ALL) - || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) - || gxtEntryType.equals(GxtAccountingEntryType.SHARE)) { - - af.setOperation(GxtAccountingEntryType.SHARE); - - AccountingEntryShare acc = (AccountingEntryShare) accountingEntry; - - String msg = ""; - if (acc.getItemName() == null || acc.getItemName().isEmpty()) - msg = user.getName() + " " + GxtAccountingEntryType.SHARE.getName() + " workspace folder"; - else - msg = user.getName() + " " + GxtAccountingEntryType.SHARE.getName() + " workspace folder " - + acc.getItemName(); - - if (acc.getMembers() != null && acc.getMembers().size() > 0) - msg += " with " + UserUtil.separateFullNameToCommaForPortalLogin(acc.getMembers()); - - af.setDescription(msg); - } - break; - - case UNSHARE: - - if (gxtEntryType == null || gxtEntryType.equals(GxtAccountingEntryType.ALL) - || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) - || gxtEntryType.equals(GxtAccountingEntryType.UNSHARE)) { - - af.setOperation(GxtAccountingEntryType.UNSHARE); - AccountingEntryUnshare uns = (AccountingEntryUnshare) accountingEntry; - String msg = uns.getItemName() == null || uns.getItemName().isEmpty() ? "" - : uns.getItemName() + " "; - msg += GxtAccountingEntryType.UNSHARE.getName() + " by " + user.getName(); - af.setDescription(msg); - } - break; - - case RESTORE: - - if (gxtEntryType == null || gxtEntryType.equals(GxtAccountingEntryType.ALL) - || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) - || gxtEntryType.equals(GxtAccountingEntryType.RESTORE)) { - - af.setOperation(GxtAccountingEntryType.RESTORE); - AccountingEntryRestore acc = (AccountingEntryRestore) accountingEntry; - String msg = acc.getItemName() == null || acc.getItemName().isEmpty() ? "" - : acc.getItemName() + " "; - - if (acc.getVersion() == null) - msg += GxtAccountingEntryType.RESTORE.getName() + " by " + user.getName(); - else - msg += " v." + acc.getVersion() + " " + GxtAccountingEntryType.RESTORE.getName() + " by " - + user.getName(); - - af.setDescription(msg); - } - break; - - case DISABLED_PUBLIC_ACCESS: - - if (gxtEntryType == null || gxtEntryType.equals(GxtAccountingEntryType.ALL) - || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) - || gxtEntryType.equals(GxtAccountingEntryType.DISABLED_PUBLIC_ACCESS)) { - - af.setOperation(GxtAccountingEntryType.DISABLED_PUBLIC_ACCESS); - AccountingEntryDisabledPublicAccess acc = (AccountingEntryDisabledPublicAccess) accountingEntry; - String msg = acc.getItemName() == null || acc.getItemName().isEmpty() ? "" - : acc.getItemName() + " "; - msg += GxtAccountingEntryType.DISABLED_PUBLIC_ACCESS.getName() + " by " + user.getName(); - af.setDescription(msg); - } - - break; - - case ENABLED_PUBLIC_ACCESS: - - if (gxtEntryType == null || gxtEntryType.equals(GxtAccountingEntryType.ALL) - || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) - || gxtEntryType.equals(GxtAccountingEntryType.ENABLED_PUBLIC_ACCESS)) { - - af.setOperation(GxtAccountingEntryType.ENABLED_PUBLIC_ACCESS); - AccountingEntryEnabledPublicAccess acc = (AccountingEntryEnabledPublicAccess) accountingEntry; - String msg = acc.getItemName() == null || acc.getItemName().isEmpty() ? "" - : acc.getItemName() + " "; - msg += GxtAccountingEntryType.ENABLED_PUBLIC_ACCESS.getName() + " by " + user.getName(); - af.setDescription(msg); - } - - break; - - default: - - break; - - } - listAccFields.add(af); - } - } - logger.debug("get accounting readers converting completed - returning size " + listAccFields.size()); - - return listAccFields; - - } - - /** - * Builds the gxt accounting item from readers. - * - * @param readers - * the readers - * @return the list - */ - public List buildGXTAccountingItemFromReaders(List readers) { - - List listAccFields = new ArrayList(); - - if (readers != null) { - - for (AccountingEntryRead accReader : readers) { - - GxtAccountingField af = new GxtAccountingField(); - InfoContactModel user = buildGxtInfoContactFromPortalLogin(accReader.getUser()); - - af.setUser(user); - af.setDate(toDate(accReader.getDate())); - af.setOperation(GxtAccountingEntryType.READ); - - String msg = ""; - if (accReader.getItemName() == null || accReader.getItemName().isEmpty()) - msg = GxtAccountingEntryType.READ.getName() + " by " + user.getName(); - else - msg = accReader.getItemName() + " " + GxtAccountingEntryType.READ.getName() + " by " - + user.getName(); - - af.setDescription(msg); - listAccFields.add(af); - } - - } - - return listAccFields; - } - - /** - * Sets the contex info. - * - * @param infoContactModel - * the info contact model - * @param scope - * the scope - */ - public void setContexInfo(InfoContactModel infoContactModel, String scope) { - this.userLogged = infoContactModel; - this.scope = scope; - } - - /** - * Builds the gxt list trash content. - * - * @param trash - * the trash - * @return the list - * @throws Exception - * the exception - */ - public List buildGXTListTrashContent(WorkspaceTrashFolder trash) throws Exception { - List trashContent = trash.listTrashItems(); - - logger.info("Converting trash content, size is: " + trashContent.size()); - - List listFileModel = new ArrayList(); - - try { - - for (WorkspaceTrashItem trashedItem : trashContent) - try { - FileTrashedModel cti = buildGXTTrashModelItem(trashedItem); - listFileModel.add(cti); - } catch (Exception e) { - logger.warn("Error in server buildGXTListTrashContent, skipping conversion of trashedItem", e); - } - } catch (Exception e) { - logger.error("Error in server buildGXTListTrashContent", e); - String error = ConstantsExplorer.SERVER_ERROR + " get Trash content. " + e.getMessage(); - throw new Exception(error); - } - - logger.info("Returning trash content as FileTrashedModel, size is: " + trashContent.size()); - - return listFileModel; - - } - - /** - * Builds the gxt trash model item. - * - * @param trashedItem - * the trashed item - * @return the file trashed model - * @throws InternalErrorException - * the internal error exception - */ - public FileTrashedModel buildGXTTrashModelItem(WorkspaceTrashItem trashedItem) throws InternalErrorException { - - FileTrashedModel fileTrashModel = new FileTrashedModel(); - fileTrashModel.setName(trashedItem.getName()); - - fileTrashModel.setIdentifier(trashedItem.getId()); // TODO - - // SETTING PARENT - FileModel oldParent = new FileModel(trashedItem.getOriginalParentId(), "", true); - - fileTrashModel.setOrginalPath(trashedItem.getDeletedFrom()); - fileTrashModel.setParentFileModel(oldParent); - - // SETTING DELETED BY - InfoContactModel deleteUser = buildGxtInfoContactFromPortalLogin(trashedItem.getDeletedBy()); - fileTrashModel.setDeleteUser(deleteUser); - - // SETTING MIME TYPE - fileTrashModel.setType(trashedItem.getMimeType()); - - // SETTING IS DIRECTORY - fileTrashModel.setIsDirectory(trashedItem.isFolder()); - - // SETTING DELETE DATE - fileTrashModel.setDeleteDate(toDate(trashedItem.getDeletedTime())); - - fileTrashModel.setShared(false); - - logger.debug( - "Converting return trash item: " + fileTrashModel.getName() + " id: " + fileTrashModel.getIdentifier()); - - return fileTrashModel; - - } - - /** - * Builds the gxt trash model item by id. - * - * @param itemId - * the item id - * @param trash - * the trash - * @return the file trashed model - * @throws InternalErrorException - * the internal error exception - */ - public FileTrashedModel buildGXTTrashModelItemById(String itemId, WorkspaceTrashFolder trash) - throws InternalErrorException { - return null; - - } - - /** - * Gets the formatted html acl from ac ls. - * - * @param aclOwner - * the acl owner - * @return the formatted html of the ACLs - */ - public String getFormatHtmlACLFromACLs(Map> aclOwner) { - - String html = "
"; - - logger.trace("Formatting " + aclOwner.size() + " ACL/s"); - - for (ACLType type : aclOwner.keySet()) { - List listLogins = aclOwner.get(type); - - html += "" + type + ": "; - html += ""; - for (String login : listLogins) { - logger.trace("Adding login " + login); - String fullName = UserUtil.getUserFullName(login); - if (fullName != null && !fullName.isEmpty()) - html += fullName + "; "; - else - html += login + "; "; - } - html += "
"; - } - html += "
"; - - return html; - } - - /** - * returns dynamically the formated size. - * - * @param size - * the size - * @return the string - */ - public static String formatFileSize(long size) { - String formattedSize = null; - - double b = size; - double k = size / 1024.0; - double m = size / 1024.0 / 1024.0; - double g = size / 1024.0 / 1024.0 / 1024.0; - double t = size / 1024.0 / 1024.0 / 1024.0 / 1024.0; - - DecimalFormat dec = new DecimalFormat("0.00"); - - if (t > 1) { - formattedSize = dec.format(t).concat(" TB"); - } else if (g > 1) { - formattedSize = dec.format(g).concat(" GB"); - } else if (m > 1) { - formattedSize = dec.format(m).concat(" MB"); - } else if (k > 1) { - formattedSize = dec.format(k).concat(" KB"); - } else { - formattedSize = dec.format(b).concat(" Bytes"); - } - - return formattedSize; - } - - /** - * Gets the item description for type by id. - * - * @param item - * the item - * @return the item description for type by id - * @throws Exception - * the exception - */ - public String getItemDescriptionForTypeById(WorkspaceItem item) throws Exception { - - if (item == null) - throw new Exception("The item is null"); - - logger.info("Getting ItemDescriptionById: " + item.getId()); - - try { - - switch (item.getType()) { - - case FOLDER: { - WorkspaceFolder theFolder = (WorkspaceFolder) item; - return theFolder.getDescription(); - } - case SHARED_FOLDER: { - WorkspaceSharedFolder theFolder = (WorkspaceSharedFolder) item; - return theFolder.getDescription(); - } - - case SMART_FOLDER: { - WorkspaceSmartFolder theFolder = (WorkspaceSmartFolder) item; - return theFolder.getDescription(); - } - - case TRASH_FOLDER: { - WorkspaceTrashFolder theFolder = (WorkspaceTrashFolder) item; - return ""; - } - - case TRASH_ITEM: { - WorkspaceTrashItem tItem = (WorkspaceTrashItem) item; - return tItem.getDescription(); - } - - default: { // IS AN ITEM - return item.getDescription(); - } - } - - } catch (Exception e) { - logger.error("Error in server ItemDescriptionForTypeById: ", e); - String error = ConstantsExplorer.SERVER_ERROR + " getting description for item id: " + item.getId(); - throw new Exception(error); - } - } - - /** - * Gets the format html gcube item properties. - * - * @param item - * the item - * @return Format HTML. A DIV HTML containing gcube item properties. If item - * is a GcubeItem and contains properties return HTML, null - * otherwise - */ - public String getFormatHtmlGcubeItemProperties(WorkspaceItem item) { - - Map properties = getGcubeItemProperties(item); - - if (properties != null) { - - if (properties.size() == 0) { - try { - logger.warn("Gcube Item Properties not found for item: " + item.getId()); - } catch (InternalErrorException e) { - // SILENT - } - return null; - } - - String html = "
"; - - for (String key : properties.keySet()) { - String value = properties.get(key); - logger.trace("Getting property: [" + key + "," + properties.get(key) + "]"); - html += "" + key + ": "; - html += ""; - html += value; - html += "
"; - } - html += "
"; - - return html; - } - return null; - } - - /** - * Gets the gcube item properties. - * - * @param item - * the item - * @return the gcube item properties - */ - public Map getGcubeItemProperties(WorkspaceItem item) { - - if (item instanceof GCubeItem) { - GCubeItem gItem = (GCubeItem) item; - try { - if (gItem.getProperties() != null) { - Map map = gItem.getProperties().getProperties(); - HashMap properties = new HashMap(map.size()); // TO - // PREVENT - // GWT - // SERIALIZATION - // ERROR - for (String key : map.keySet()) - properties.put(key, map.get(key)); - - return properties; - } - } catch (InternalErrorException e) { - logger.error("Error in server getItemProperties: ", e); - return null; - } - } - return null; - } - - /** - * Sets the synched thredds state for. - * - * @param fileModel - * the file model - * @param scope - * the scope - * @param username - * the username - * @return the file model - */ - protected FileModel setSynchedThreddsStateFor(FileModel fileModel, String scope, String username) { - - try { - - if (fileModel.isDirectory()) { - ScopeProvider.instance.set(scope); - Sync_Status status = WorkspaceThreddsSynchronize.getInstance() - .getSynchedStatusFromItemProperty(fileModel.getIdentifier(), username); - fileModel.setSyncThreddsStatus(status); - } - - } catch (ItemNotSynched e) { - // silent - logger.trace("Item: " + fileModel.getIdentifier() + " name: " + fileModel.getName() + " is not synched"); - } catch (Exception e) { - logger.warn("It is not possible to get synched status for item: " + fileModel.getIdentifier()); - } - - return fileModel; - } - -} diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/GWTWorkspaceServiceImpl.java b/src/main/java/org/gcube/portlets/user/workspace/server/GWTWorkspaceServiceImpl.java index d3ea79f..8dc7d0c 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/GWTWorkspaceServiceImpl.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/GWTWorkspaceServiceImpl.java @@ -8,7 +8,6 @@ import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Calendar; -import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -18,59 +17,41 @@ import java.util.concurrent.TimeUnit; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; -import org.apache.log4j.Logger; import org.gcube.common.encryption.StringEncrypter; -import org.gcube.common.homelibary.model.items.type.FolderItemType; -import org.gcube.common.homelibary.model.items.type.WorkspaceItemType; -import org.gcube.common.homelibrary.home.Home; -import org.gcube.common.homelibrary.home.exceptions.HomeNotFoundException; -import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; -import org.gcube.common.homelibrary.home.workspace.Workspace; -import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; -import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; -import org.gcube.common.homelibrary.home.workspace.WorkspaceSharedFolder; -import org.gcube.common.homelibrary.home.workspace.WorkspaceSmartFolder; -import org.gcube.common.homelibrary.home.workspace.accounting.AccountingEntry; -import org.gcube.common.homelibrary.home.workspace.exceptions.InsufficientPrivilegesException; -import org.gcube.common.homelibrary.home.workspace.exceptions.ItemAlreadyExistException; -import org.gcube.common.homelibrary.home.workspace.exceptions.ItemNotFoundException; -import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException; -import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; -import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalFile; -import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalUrl; -import org.gcube.common.homelibrary.home.workspace.folder.items.GCubeItem; -import org.gcube.common.homelibrary.home.workspace.search.SearchItem; import org.gcube.common.portal.PortalContext; import org.gcube.common.resources.gcore.ServiceEndpoint; import org.gcube.common.scope.api.ScopeProvider; import org.gcube.common.storagehub.model.exceptions.UserNotAuthorizedException; +import org.gcube.common.storagehub.model.items.nodes.accounting.AccountEntry; import org.gcube.common.storagehubwrapper.server.StorageHubWrapper; import org.gcube.common.storagehubwrapper.shared.tohl.TrashedItem; import org.gcube.common.storagehubwrapper.shared.tohl.impl.WorkspaceFileVersion; +import org.gcube.common.storagehubwrapper.shared.tohl.items.ImageFileItem; +import org.gcube.common.storagehubwrapper.shared.tohl.items.PropertyMap; +import org.gcube.common.storagehubwrapper.shared.tohl.items.URLFileItem; +import org.gcube.common.storagehubwrapper.shared.tohl.items.URLItem; import org.gcube.portal.wssynclibrary.shared.ItemNotSynched; import org.gcube.portal.wssynclibrary.shared.WorkspaceFolderLocked; import org.gcube.portal.wssynclibrary.shared.thredds.Sync_Status; import org.gcube.portal.wssynclibrary.thredds.WorkspaceThreddsSynchronize; import org.gcube.portlets.user.urlshortener.UrlShortener; import org.gcube.portlets.user.workspace.client.ConstantsExplorer; -import org.gcube.portlets.user.workspace.client.interfaces.GXTCategorySmartFolder; import org.gcube.portlets.user.workspace.client.model.FileGridModel; import org.gcube.portlets.user.workspace.client.model.FileModel; import org.gcube.portlets.user.workspace.client.model.FileTrashedModel; import org.gcube.portlets.user.workspace.client.model.FileVersionModel; import org.gcube.portlets.user.workspace.client.model.FolderModel; import org.gcube.portlets.user.workspace.client.model.GcubeVRE; -import org.gcube.portlets.user.workspace.client.model.ScopeModel; -import org.gcube.portlets.user.workspace.client.model.SmartFolderModel; import org.gcube.portlets.user.workspace.client.model.SubTree; import org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService; import org.gcube.portlets.user.workspace.client.workspace.GWTWorkspaceItem; -import org.gcube.portlets.user.workspace.server.notifications.NotificationsProducer; -import org.gcube.portlets.user.workspace.server.notifications.NotificationsUtil; +import org.gcube.portlets.user.workspace.client.workspace.folder.item.GWTExternalUrl; import org.gcube.portlets.user.workspace.server.notifications.tostoragehub.NotificationStorageHubUtil; import org.gcube.portlets.user.workspace.server.notifications.tostoragehub.NotificationsProducerToStorageHub; import org.gcube.portlets.user.workspace.server.reader.ApplicationProfile; import org.gcube.portlets.user.workspace.server.reader.ApplicationProfileReader; +import org.gcube.portlets.user.workspace.server.tostoragehub.FormatterUtil; +import org.gcube.portlets.user.workspace.server.tostoragehub.ObjectStorageHubToWorkpaceMapper; import org.gcube.portlets.user.workspace.server.tostoragehub.StorageHubToWorkpaceConverter; import org.gcube.portlets.user.workspace.server.util.PortalContextInfo; import org.gcube.portlets.user.workspace.server.util.StringUtil; @@ -90,6 +71,7 @@ import org.gcube.portlets.user.workspace.shared.WorkspaceUserQuote; import org.gcube.portlets.user.workspace.shared.WorkspaceVersioningOperation; import org.gcube.portlets.user.workspace.shared.accounting.GxtAccountingEntryType; import org.gcube.portlets.user.workspace.shared.accounting.GxtAccountingField; +import org.gcube.portlets.widgets.workspacesharingwidget.server.notifications.NotificationsProducer; import org.gcube.portlets.widgets.workspacesharingwidget.shared.InfoContactModel; import org.gcube.resources.discovery.client.api.DiscoveryClient; import org.gcube.resources.discovery.client.queries.api.SimpleQuery; @@ -101,14 +83,19 @@ import org.gcube.vomanagement.usermanagement.impl.LiferayGroupManager; import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager; import org.gcube.vomanagement.usermanagement.model.GCubeGroup; import org.gcube.vomanagement.usermanagement.model.GCubeUser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import com.liferay.portal.service.UserLocalServiceUtil; + /** * The Class GWTWorkspaceServiceImpl. * - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * + * Aug 1, 2019 */ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWTWorkspaceService { @@ -117,31 +104,7 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT private static final long serialVersionUID = 2828885661214875589L; public static final String LAST_OPEN_FOLDER_ATTRIBUTE = "WORKSPACE.LAST_OPEN_FOLDER"; public static final String SELECTION_STATE_ATTRIBUTE = "WORKSPACE.SELECTION_STATE"; - protected Logger workspaceLogger = Logger.getLogger(GWTWorkspaceServiceImpl.class); - - /** - * Gets the GWT workspace builder. - * - * @return the GWT workspace builder - */ - protected GWTWorkspaceBuilder getGWTWorkspaceBuilder() { - return WsUtil.getGWTWorkspaceBuilder(this.getThreadLocalRequest()); - } - - /** - * Gets the workspace. - * - * @return Workspace - * @throws InternalErrorException Internal error - * @throws InternalErrorException Internal error - * @throws HomeNotFoundException Home not found error - * @throws WorkspaceFolderNotFoundException Folder not found error - */ - protected Workspace getWorkspace() - throws InternalErrorException, HomeNotFoundException, WorkspaceFolderNotFoundException, - org.gcube.common.storagehubwrapper.shared.tohl.exceptions.InternalErrorException { - return WsUtil.getWorkspace(this.getThreadLocalRequest()); - } + protected Logger workspaceLogger = LoggerFactory.getLogger(GWTWorkspaceServiceImpl.class); /** * Gets the notification producer. @@ -181,19 +144,6 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT return WsUtil.getUrlShortener(this.getThreadLocalRequest()); } - - - //TODO CHECK METHODS BEFORE - -// /** -// * Gets the uri resolver. -// * -// * @return the uri resolver -// */ -// protected UriResolverReaderParameterForResolverIndex getUriResolver() { -// return WsUtil.getUriResolver(this.getThreadLocalRequest()); -// } - /** * Gets the property special folder reader. * @@ -235,1618 +185,6 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT .info("Read special folder name: '" + sfReader.getSpecialFolderName() + "', from property file.."); return sfReader.getSpecialFolderName(); } - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getItemsBySearchName(java.lang.String) - */ - /** - * Gets the items by search name. - * - * @param text - * the text - * @param folderId - * the folder id - * @return the items by search name - * @throws Exception - * the exception - */ - @Override - public List getItemsBySearchName(String text, String folderId) throws Exception { - - //TODO MOVE TO SHUB - - try { - Workspace workspace = getWorkspace(); - if (folderId == null || folderId.isEmpty()) { - workspaceLogger.trace("searching folderId is null, settings root Id"); - folderId = workspace.getRoot().getId(); - } - - workspaceLogger.info("searching by name: " + text + " in " + folderId); - List listSearchItems = workspace.searchByName(text, folderId); - workspaceLogger.info("HL search returning " + listSearchItems.size() + " items"); - - workspaceLogger.info("Converting " + listSearchItems.size() + " items"); - GWTWorkspaceBuilder builder = getGWTWorkspaceBuilder(); - List listFileGridModels = new ArrayList(); - - listFileGridModels = builder.buildGXTListFileGridModelItemForSearch(listSearchItems); - workspaceLogger.info("Search objects converted, returning"); - - return listFileGridModels; - } catch (Exception e) { - workspaceLogger.error("Error in server During search retrieving", e); - // workspaceLogger.trace("Error in server During search retrieving " - // + e); - - // GWT can't serialize all exceptions - throw new Exception("Error during searching, please contact the support."); - } - } - - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getDetailsFile(org.gcube.portlets.user.workspace.client.model.FileModel) - */ - -// /** -// * Gets the details file. -// * -// * @param folder -// * the folder -// * @return the details file -// * @throws Exception -// * the exception -// */ -// @Override -// public FileDetailsModel getDetailsFile(FileModel folder) throws Exception { -// -// try { -// -// if (folder == null) -// throw new Exception("Folder is null"); -// -// workspaceLogger.trace("load file details: " + folder.getName()); -// Workspace workspace = getWorkspace(); -// WorkspaceItem wsItem = workspace.getItem(folder.getIdentifier()); -// GWTWorkspaceBuilder builder = getGWTWorkspaceBuilder(); -// -// return builder.buildGWTWorkspaceFileDetails(wsItem, folder); -// -// } catch (Exception e) { -// workspaceLogger.error("Error in load server file details", e); -// throw new Exception(e.getMessage()); -// } -// } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getChildrenSubTreeToRootByIdentifier(java.lang.String) - */ - /** - * Gets the children sub tree to root by identifier. - * - * @param itemIdentifier - * the item identifier - * @return the children sub tree to root by identifier - * @throws Exception - * the exception - */ - @Override - public ArrayList getChildrenSubTreeToRootByIdentifier(String itemIdentifier) throws Exception { - - ArrayList listSubTree = new ArrayList(); - - try { - - if (itemIdentifier == null) - throw new Exception(IDENTIFIER_IS_NULL); - - Workspace workspace = getWorkspace(); - workspaceLogger.trace("search itemId: " + itemIdentifier); - WorkspaceItem item = workspace.getItem(itemIdentifier); // get item - // from - // workspace - getListsChildrenByParent(listSubTree, item); - Collections.reverse(listSubTree); // reverse order of array - - // SET THE ROOT - int lenght = listSubTree.size(); - if (lenght > 0) { - FolderModel firstLevel = listSubTree.get(0).getParent(); // get - // root - workspaceLogger.trace("set: " + firstLevel.getName() + " as root"); - listSubTree.get(0).getParent().setIsRoot(true); - // IF IT CASE - REWRITE SPECIAL FOLDER NAME - if (lenght > 1) { - FolderModel wsFolder = listSubTree.get(1).getParent(); // get - // first - // child - String nameSpecialFolder = getNameForSpecialFolder(); - if (wsFolder.getName().compareTo(ConstantsExplorer.MY_SPECIAL_FOLDERS) == 0 - && firstLevel.isRoot()) { - // MANAGEMENT SPECIAL FOLDER - workspaceLogger - .debug("getChildrenSubTreeToRootByIdentifier MANAGEMENT SPECIAL FOLDER NAME REWRITING AS: " - + nameSpecialFolder); - if (nameSpecialFolder != null && !nameSpecialFolder.isEmpty()) - listSubTree.get(1).getParent().setName(nameSpecialFolder); - } - } - } - - workspaceLogger.trace("getChildrenSubTreeToRootByIdentifier returning list SubTree: " + listSubTree); - } catch (Exception e) { - workspaceLogger.error("Error in server find Item", e); - throw new Exception(e.getMessage()); - } - - return listSubTree; - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getSmartFolderResultsByCategory(java.lang.String) - */ - /** - * Gets the smart folder results by category. - * - * @param category - * the category - * @return the smart folder results by category - * @throws Exception - * the exception - */ - @Override - public List getSmartFolderResultsByCategory(GXTCategorySmartFolder category) throws Exception { - - try { - - Workspace workspace = getWorkspace(); - workspaceLogger.trace("get smart folder by category: " + category); - GWTWorkspaceBuilder builder = getGWTWorkspaceBuilder(); - List listWorkspaceItems = new ArrayList(); - - // Category IMAGES - if (category.equals(GXTCategorySmartFolder.SMF_IMAGES)) { - listWorkspaceItems = workspace.getFolderItems(FolderItemType.IMAGE_DOCUMENT, - FolderItemType.EXTERNAL_IMAGE); - // Category BIODIVERSITY - } else if (category.equals(GXTCategorySmartFolder.SMF_BIODIVERSITY)) { - // listWorkspaceItems = - // workspace.getFolderItems(FolderItemType.AQUAMAPS_ITEM); - // Category DOCUMENTS - } else if (category.equals(GXTCategorySmartFolder.SMF_DOCUMENTS)) { - - listWorkspaceItems = workspace.getFolderItems(FolderItemType.EXTERNAL_FILE, - FolderItemType.EXTERNAL_PDF_FILE, FolderItemType.QUERY, FolderItemType.PDF_DOCUMENT, - FolderItemType.METADATA, FolderItemType.DOCUMENT); - - // Category LINKS - } else if (category.equals(GXTCategorySmartFolder.SMF_LINKS)) { - // listWorkspaceItems = - // workspace.getFolderItems(FolderItemType.EXTERNAL_URL, - // FolderItemType.URL_DOCUMENT, - // FolderItemType.EXTERNAL_RESOURCE_LINK); - // Category REPORTS - } else if (category.equals(GXTCategorySmartFolder.SMF_REPORTS)) { - listWorkspaceItems = workspace.getFolderItems(FolderItemType.REPORT_TEMPLATE, FolderItemType.REPORT); - // Category TIME SERIES - } else if (category.equals(GXTCategorySmartFolder.SMF_TIMESERIES)) { - listWorkspaceItems = workspace.getFolderItems(FolderItemType.TIME_SERIES); - } else if (category.equals(GXTCategorySmartFolder.SMF_PUBLIC_FOLDERS)) { - List listFolder = workspace.getPublicFolders(); - if (listFolder == null || listFolder.isEmpty()) - return new ArrayList(); - return builder.buildGXTListFileGridModelItem(listFolder, null); - } else - new Exception("Smart folder category unknown"); - - return builder.filterListFileGridModelItemByCategory(listWorkspaceItems, category); - - } catch (Exception e) { - workspaceLogger.error("Error in server get smart folder by category", e); - throw new Exception(e.getMessage()); - } - - } - - /** - * Gets the lists children by parents. - * - * @param listSubTree - * the list sub tree - * @param parent - * the parent - * @return the lists children by parents - * @throws Exception - * the exception - */ - private void getListsChildrenByParent(ArrayList listSubTree, WorkspaceItem parent) throws Exception { - - if (parent == null) - return; - - if (!parent.isFolder()) { - workspaceLogger.warn("getListsChildrenByParent returning: " + parent.getName() + " is not a folder"); - return; - } - - workspaceLogger.trace("getListsChildrenByParent: " + parent.getName()); - GWTWorkspaceBuilder builder = getGWTWorkspaceBuilder(); - FolderModel parentModel = (FolderModel) builder.buildGXTFileModelItem(parent, null); // get - // folder - List childrenList = getFolderChildren(parentModel); // get - // children - SubTree subTree = new SubTree(parentModel, childrenList); - listSubTree.add(subTree); - getListsChildrenByParent(listSubTree, parent.getParent()); - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * createSmartFolder(java.lang.String, java.lang.String, java.lang.String) - */ - /** - * Creates the smart folder. - * - * @param name - * the name - * @param description - * the description - * @param query - * the query - * @param parentId - * the parent id - * @return the smart folder model - * @throws Exception - * the exception - */ - @Override - public SmartFolderModel createSmartFolder(String name, String description, String query, String parentId) - throws Exception { - - if (isSessionExpired()) - throw new SessionExpiredException(); - - try { - - Workspace workspace = getWorkspace(); - workspaceLogger.trace("create smart folder by name: " + name); - workspaceLogger.trace("description " + description); - workspaceLogger.trace("query " + query); - workspaceLogger.trace("parentId " + parentId); - - if (parentId == null || parentId.isEmpty()) { - workspaceLogger.trace("parent id is null using root id"); - parentId = workspace.getRoot().getId(); - } - - WorkspaceSmartFolder wsSmartFolder = workspace.createSmartFolder(name, description, query, parentId); // create - // Smart - // Folder - // from - // workspace - workspaceLogger.trace("create : " + wsSmartFolder.getName() + " id " + wsSmartFolder.getId()); - GWTWorkspaceBuilder builder = getGWTWorkspaceBuilder(); - return builder.buildGXTSmartFolderModel(wsSmartFolder, query); - - } catch (Exception e) { - workspaceLogger.error("Error in server create smart folder by name: ", e); - // workspaceLogger.trace("Error in server create smart folder by id - // " + e); - // GWT can't serialize all exceptions - throw new Exception(e.getMessage()); - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * removeSmartFolder(java.lang.String, java.lang.String) - */ - /** - * Removes the smart folder. - * - * @param itemId - * the item id - * @param name - * the name - * @return the boolean - * @throws Exception - * the exception - */ - @Override - public Boolean removeSmartFolder(String itemId, String name) throws Exception { - - if (itemId == null) - return null; - - try { - - Workspace workspace = getWorkspace(); - workspaceLogger.trace("remove smart folder by id: " + itemId); - workspace.removeItem(itemId); // remove Smart Folder from workspace - return true; - - } catch (Exception e) { - workspaceLogger.error("Error in remove smart folder by id: ", e); - throw new Exception(e.getMessage()); - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getAllSmartFolders() - */ - /** - * Gets the all smart folders. - * - * @return the all smart folders - * @throws Exception - * the exception - */ - @Override - public List getAllSmartFolders() throws Exception { - - try { - - Workspace workspace = getWorkspace(); - workspaceLogger.trace("get all smart folder"); - List listWorkspaceFolder = new ArrayList(); - listWorkspaceFolder = workspace.getAllSmartFolders(); // create - // Smart - // Folder - // from - // workspace - workspaceLogger.trace("list smart folders size" + listWorkspaceFolder.size()); - GWTWorkspaceBuilder builder = getGWTWorkspaceBuilder(); - return builder.buildGXTListSmartFolderModel(listWorkspaceFolder); - - } catch (Exception e) { - workspaceLogger.error("Error in server get all smart folder: ", e); - throw new Exception(e.getMessage()); - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getSmartFolderResultsById(java.lang.String) - */ - /** - * Gets the smart folder results by id. - * - * @param folderId - * the folder id - * @return the smart folder results by id - * @throws Exception - * the exception - */ - @Override - public List getSmartFolderResultsById(String folderId) throws Exception { - - if (folderId == null) - return null; - - try { - - Workspace workspace = getWorkspace(); - workspaceLogger.trace("get smart folder by id: " + folderId); - WorkspaceSmartFolder wsSmartFolder = workspace.getSmartFolder(folderId); // get - // Smart - // Folder - // from - // workspace - workspaceLogger.trace("wsFolder " + wsSmartFolder.getName()); - GWTWorkspaceBuilder builder = getGWTWorkspaceBuilder(); - - List searchItems = wsSmartFolder.getSearchItems(); - - if (searchItems != null) { - workspaceLogger.trace("smart folders size " + searchItems.size()); - return builder.buildGXTListFileGridModelItemForSearch((List) searchItems); - } else - return new ArrayList(); - - } catch (Exception e) { - workspaceLogger.error("Error in get server smart folder by id", e); - throw new Exception(e.getMessage()); - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getImageById(java.lang.String, boolean, boolean) - */ - /** - * Gets the image by id. - * - * @param identifier - * the identifier - * @param isInteralImage - * the is interal image - * @param fullDetails - * the full details - * @return the image by id - * @throws Exception - * the exception - */ - @Override - public GWTWorkspaceItem getImageById(String identifier, boolean isInteralImage, boolean fullDetails) - throws Exception { - - if (identifier == null) - return null; - - try { - - Workspace workspace = getWorkspace(); - workspaceLogger.trace("get image by id: " + identifier); - WorkspaceItem item = workspace.getItem(identifier); // get item from - // workspace - workspaceLogger.trace("item name " + item.getName()); - GWTWorkspaceBuilder builder = getGWTWorkspaceBuilder(); - PortalContextInfo context = WsUtil.getPortalContext(this.getThreadLocalRequest()); - GCubeUser user = PortalContext.getConfiguration().getCurrentUser(this.getThreadLocalRequest()); - return builder.buildGWTWorkspaceImage(item, isInteralImage, fullDetails, context.getCurrGroupId() + "", - user.getUserId() + ""); - - } catch (Exception e) { - workspaceLogger.error("Error in server get image by id", e); - throw new Exception(e.getMessage()); - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getTimeSeriesById(java.lang.String) - */ - /** - * Gets the time series by id. - * - * @param identifier - * the identifier - * @return the time series by id - * @throws Exception - * the exception - */ - @Override - @Deprecated - /** - * this method return always null - */ - public GWTWorkspaceItem getTimeSeriesById(String identifier) throws Exception { - - if (identifier == null) - return null; - - try { - - Workspace workspace = getWorkspace(); - workspaceLogger.trace("get timeseries by id: " + identifier); - WorkspaceItem item = workspace.getItem(identifier); // get item from - // workspace - workspaceLogger.trace("item name " + item.getName()); - GWTWorkspaceBuilder builder = getGWTWorkspaceBuilder(); - return null; - } catch (Exception e) { - workspaceLogger.error("Error in server get timeseries by id", e); - throw new Exception(e.getMessage()); - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getUrlById(java.lang.String, boolean, boolean) - */ - /** - * Gets the url by id. - * - * @param identifier - * the identifier - * @param isInternalUrl - * the is internal url - * @param fullDetails - * the full details - * @return the url by id - * @throws Exception - * the exception - */ - @Override - public GWTWorkspaceItem getUrlById(String identifier, boolean isInternalUrl, boolean fullDetails) throws Exception { - - try { - - if (identifier == null) - throw new Exception(IDENTIFIER_IS_NULL); - - Workspace workspace = getWorkspace(); - workspaceLogger.trace("get url by id: " + identifier); - WorkspaceItem item = workspace.getItem(identifier); // get item from - // workspace - workspaceLogger.trace("item name " + item.getName()); - GWTWorkspaceBuilder builder = getGWTWorkspaceBuilder(); - return builder.buildGWTWorspaceUrl(item, isInternalUrl, fullDetails); - - } catch (Exception e) { - workspaceLogger.error("Error in server get image by id ", e); - // workspaceLogger.trace("Error in server get image by id " + e); - // GWT can't serialize all exceptions - throw new Exception(e.getMessage()); - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * createExternalUrl(org.gcube.portlets.user.workspace.client.model. - * FileModel, java.lang.String, java.lang.String, java.lang.String) - */ - - /** - * Creates the external url. - * - * @param parentId - * the parent id - * @param name - * the name - * @param description - * the description - * @param url - * the url - * @return the file model - * @throws Exception - * the exception - */ - @Override - public FileModel createExternalUrl(String parentId, String name, String description, String url) throws Exception { - - try { - Workspace workspace = getWorkspace(); - - if (parentId == null) { - workspaceLogger.error("Error on creating url. Parent ID is null"); - throw new Exception("Parent ID is null"); - } - - checkItemLocked(parentId); - - workspaceLogger.trace("create url in parent id: " + parentId); - ExternalUrl ext = workspace.createExternalUrl(name, description, url, parentId); - WorkspaceItem parent = workspace.getItem(parentId); // get item from - // workspace - workspaceLogger.trace("parent name " + parent.getName()); - GWTWorkspaceBuilder builder = getGWTWorkspaceBuilder(); - - FolderModel parentFileModel = builder.buildGXTFolderModelItem((WorkspaceFolder) parent, null); - return builder.buildGXTFileModelItem(ext, parentFileModel); - - } catch (WorkspaceFolderLocked e1) { - throw new Exception(e1.getMessage()); - - } catch (Exception e) { - workspaceLogger.error("Error in server create url in parent id ", e); - // workspaceLogger.trace("Error in server create url in parent id " - // + e); - // GWT can't serialize all exceptions - throw new Exception(e.getMessage()); - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getURLFromApplicationProfile(java.lang.String) - */ - /** - * Gets the URL from application profile. - * - * @param oid - * the oid - * @return the URL from application profile - * @throws Exception - * the exception - */ - @Override - public String getURLFromApplicationProfile(String oid) throws Exception { - - throw new Exception("Operation not supported"); - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * setValueInSession(java.lang.String, java.lang.String) - */ - /** - * Sets the value in session. - * - * @param name - * the name - * @param value - * the value - * @throws Exception - * the exception - */ - @Override - public void setValueInSession(String name, String value) throws Exception { - - try { - this.getThreadLocalRequest().getSession().setAttribute(name, value); - workspaceLogger.trace("set value in session with name: " + name + ", value: " + value); - } catch (Exception e) { - workspaceLogger.error("setValueInSession", e); - throw new Exception(e.getMessage()); - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getAllScope() - */ - /** - * Gets the all scope. - * - * @return the all scope - * @throws Exception - * the exception - */ - @Override - public List getAllScope() throws Exception { - - try { - - Workspace workspace = getWorkspace(); - workspaceLogger.trace("get all scope"); - GWTWorkspaceBuilder builder = getGWTWorkspaceBuilder(); - ScopeUtilFilter scopeUtilFilter = getScopeUtilFilter(); - - Home home = workspace.getHome(); - if (home != null) { - List listIdFilterdScope = scopeUtilFilter.convertListScopeToPortlet(home.listScopes()); - return builder.buildGXTListScopeModel(listIdFilterdScope, scopeUtilFilter.getHashScopesFiltered()); - } else { - workspaceLogger.error("workspace.getHome() is null"); - throw new Exception("Sorry, an error occurred on getting all scope. Please try later"); - } - - } catch (Exception e) { - workspaceLogger.error("Error in server get all scope ", e); - e.printStackTrace(); - // workspaceLogger.trace("Error in server get all scope " + - // e.getMessage()); - // GWT can't serialize all exceptions - throw new Exception(e.getMessage()); - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * sendToById(java.util.List, java.util.List, java.lang.String, - * java.lang.String) - */ - /** - * Send to by id. - * - * @param listContactsId - * the list contacts id - * @param listAttachmentsId - * the list attachments id - * @param subject - * the subject - * @param body - * the body - * @return true, if successful - * @throws Exception - * the exception - */ - @Override - public boolean sendToById(List listContactsId, List listAttachmentsId, String subject, String body) - throws Exception { - - try { - - Workspace workspace = getWorkspace(); - // workspaceLogger.trace("######### SEND TO: "); - // workspaceLogger.trace("subject " + subject); - // workspaceLogger.trace("body " + body); - - // DEBUG - for (String contactId : listContactsId) - workspaceLogger.trace("contactId " + contactId); - // DEBUG - for (String id : listAttachmentsId) - workspaceLogger.trace("attachId " + id); - - workspace.getWorkspaceMessageManager().sendMessageToPortalLogins(subject, body, listAttachmentsId, - listContactsId); - return true; - - } catch (Exception e) { - workspaceLogger.error("Error in server sendTo ", e); - // GWT can't serialize all exceptions - throw new Exception(e.getMessage()); - } - - } - - /** - * Gets the list workspace item by id. - * - * @param workspace - * the workspace - * @param listItemsId - * the list items id - * @return the list workspace item by id - * @throws ItemNotFoundException - * the item not found exception - * @throws InternalErrorException - * the internal error exception - */ - private List getListWorkspaceItemById(Workspace workspace, List listItemsId) - throws ItemNotFoundException, InternalErrorException { - - List listWorkspaceItem = new ArrayList(); - - for (String itemId : listItemsId) { - - WorkspaceItem item = workspace.getItem(itemId); - workspaceLogger.trace("Attach name: " + item.getName()); - workspaceLogger.trace("Attach id: " + item.getId()); - listWorkspaceItem.add(workspace.getItem(itemId)); // get item from - // workspace - } - - return listWorkspaceItem; - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getUrlWebDav(java.lang.String) - */ - /** - * Gets the url web dav. - * - * @param itemId - * the item id - * @return the url web dav - * @throws Exception - * the exception - */ - @Override - public String getUrlWebDav(String itemId) throws Exception { - - try { - Workspace workspace = getWorkspace(); - workspaceLogger.trace("getWebDavUrl" + itemId); - return workspace.getUrlWebDav(); - - } catch (Exception e) { - workspaceLogger.error("Error in getNewFolderBulkCreator ", e); - // workspaceLogger.trace("Error in getNewFolderBulkCreator " + - // e.getMessage()); - throw new Exception(e.getMessage()); - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * itemExistsInWorkpaceFolder(java.lang.String, java.lang.String) - */ - /** - * Item exists in workpace folder. - * - * @param parentId - * the parent id - * @param itemName - * the item name - * @return the string - * @throws Exception - * the exception - */ - @Override - public String itemExistsInWorkpaceFolder(String parentId, String itemName) throws Exception { - - workspaceLogger.trace("get itemExistsInWorkpace by parentId: " + parentId); - System.out.println("get itemExistsInWorkpace by parentId: " + parentId); - - try { - - Workspace workspace = getWorkspace(); - WorkspaceItem wsItem = workspace.getItem(parentId); // GET PARENT - - if (wsItem.getType().equals(WorkspaceItemType.FOLDER) - || wsItem.getType().equals(WorkspaceItemType.SHARED_FOLDER)) { - - WorkspaceItem itemFound = workspace.find(itemName, parentId); - - if (itemFound == null) - return null; - - return itemFound.getId(); - } else - throw new Exception("Invalid Folder parent"); - - } catch (InternalErrorException e) { - return null; - } catch (ItemNotFoundException e) { - return null; - } catch (Exception e) { - String error = "an error occurred on search item in folder "; - workspaceLogger.error(error, e); - throw new Exception(e.getMessage()); - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getItemCreationDateById(java.lang.String) - */ - /** - * Gets the item creation date by id. - * - * @param itemId - * the item id - * @return the item creation date by id - * @throws Exception - * the exception - */ - @Override - public Date getItemCreationDateById(String itemId) throws Exception { - workspaceLogger.trace("get Item Creation Date By ItemId " + itemId); - try { - - Workspace workspace = getWorkspace(); - WorkspaceItem wsItem = workspace.getItem(itemId); - Calendar cl = wsItem.getCreationTime(); - - if (cl != null) - return cl.getTime(); - - return null; - - } catch (Exception e) { - workspaceLogger.error("get Item Creation Date By ItemId ", e); - throw new Exception(e.getMessage()); - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * loadSizeByItemId(java.lang.String) - */ - /** - * Load size by item id. - * - * @param itemId - * the item id - * @return the long - * @throws Exception - * the exception - */ - @Override - public Long loadSizeByItemId(String itemId) throws Exception { - - workspaceLogger.info("get Size By ItemId " + itemId); - try { - - Workspace workspace = getWorkspace(); - WorkspaceItem wsItem = workspace.getItem(itemId); - Long size = new Long(-1); - - if (wsItem instanceof FolderItem) { // ITEM - FolderItem folderItem = (FolderItem) wsItem; - size = new Long(folderItem.getLength()); - } else if (wsItem instanceof WorkspaceFolder) { // FOLDER - WorkspaceFolder theFolder = (WorkspaceFolder) wsItem; - size = theFolder.getSize(); - } else if (wsItem instanceof WorkspaceSharedFolder) { // SHARED - // FOLDER - WorkspaceSharedFolder theFolder = (WorkspaceSharedFolder) wsItem; - size = theFolder.getSize(); - } - workspaceLogger.info("returning size: " + size); - return size; - - } catch (Exception e) { - workspaceLogger.error("get Size By ItemId ", e); - throw new Exception(e.getMessage()); - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * loadLastModificationDateById(java.lang.String) - */ - /** - * Load last modification date by id. - * - * @param itemId - * the item id - * @return the date - * @throws Exception - * the exception - */ - @Override - public Date loadLastModificationDateById(String itemId) throws Exception { - - workspaceLogger.trace("get last modification date ItemId " + itemId); - try { - - Workspace workspace = getWorkspace(); - WorkspaceItem wsItem = workspace.getItem(itemId); - wsItem.getLastModificationTime().getTime(); - Date lastModification = null; - - if (wsItem.getLastModificationTime() != null) { - lastModification = wsItem.getLastModificationTime().getTime(); - } - - return lastModification; - - } catch (Exception e) { - workspaceLogger.error("get last modification date ItemId ", e); - throw new Exception(e.getMessage()); - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getParentByItemId(java.lang.String) - */ - /** - * Gets the parent by item id. - * - * @param identifier - * the identifier - * @return the parent by item id - * @throws Exception - * the exception - */ - @Override - public FileModel getParentByItemId(String identifier) throws Exception { - - workspaceLogger.trace("get Parent By Item Identifier " + identifier); - try { - - Workspace workspace = getWorkspace(); - WorkspaceItem wsItem = workspace.getItem(identifier); - workspaceLogger.trace("workspace retrieve item name: " + wsItem.getName()); - GWTWorkspaceBuilder builder = getGWTWorkspaceBuilder(); - - while (wsItem != null && wsItem.getParent() != null) { - - WorkspaceFolder wsFolder = wsItem.getParent(); - workspaceLogger.trace("parent was found " + wsFolder.getName() + " retuning"); - return builder.buildGXTFolderModelItem(wsFolder, null); - } - workspaceLogger.trace("parent not found - retuning"); - return null; - - } catch (Exception e) { - workspaceLogger.error("Error in get Parent By Item Identifier", e); - e.printStackTrace(); - throw new Exception(e.getMessage()); - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getAccountingReaders(java.lang.String) - */ - /** - * Gets the accounting readers. - * - * @param identifier - * the identifier - * @return the accounting readers - * @throws Exception - * the exception - */ - @Override - public List getAccountingReaders(String identifier) throws Exception { - - workspaceLogger.trace("get accounting readers " + identifier); - try { - - Workspace workspace = getWorkspace(); - WorkspaceItem wsItem = workspace.getItem(identifier); - GWTWorkspaceBuilder builder = getGWTWorkspaceBuilder(); - List listReaders = builder.buildGXTAccountingItemFromReaders(wsItem.getReaders()); - workspaceLogger.trace("get accounting readers - returning size " + listReaders.size()); - return listReaders; - - } catch (Exception e) { - workspaceLogger.error("Error get accounting readers ", e); - String error = ConstantsExplorer.SERVER_ERROR + " getting account. " + ConstantsExplorer.TRY_AGAIN; - throw new Exception(error); - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getAccountingHistory(java.lang.String) - */ - /** - * Gets the accounting history. - * - * @param identifier - * the identifier - * @return the accounting history - * @throws Exception - * the exception - */ - @Override - public List getAccountingHistory(String identifier) throws Exception { - - workspaceLogger.trace("get accounting history " + identifier); - try { - - Workspace workspace = getWorkspace(); - WorkspaceItem wsItem = workspace.getItem(identifier); - List accoutings = wsItem.getAccounting(); - GWTWorkspaceBuilder builder = getGWTWorkspaceBuilder(); - List listReaders = builder.buildGXTAccountingItem(accoutings, - GxtAccountingEntryType.ALL); - workspaceLogger.trace("get accounting readers - returning size " + listReaders.size()); - return listReaders; - - } catch (Exception e) { - workspaceLogger.error("Error get accounting readers ", e); - String error = ConstantsExplorer.SERVER_ERROR + " getting account. " + ConstantsExplorer.TRY_AGAIN; - throw new Exception(error); - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getShortUrl(java.lang.String) - */ - /** - * Gets the short url. - * - * @param longUrl - * the long url - * @return the short url - * @throws Exception - * the exception - */ - @Override - public String getShortUrl(String longUrl) throws Exception { - - workspaceLogger.trace("get short url for " + longUrl); - UrlShortener shortener = getUrlShortener(); - try { - - if (shortener != null && shortener.isAvailable()) - return shortener.shorten(longUrl); - - return longUrl; - - } catch (Exception e) { - workspaceLogger.error("Error get short url for ", e); - return null; - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getLinkForSendToSwitchBoard(java.lang.String) - */ - /** - * Gets the link for send to switch board. - * - * @param itemId - * the item id - * @return the link for send to switch board - * @throws Exception - * the exception - */ - @Override - public String getLinkForSendToSwitchBoard(String itemId) throws Exception { - String fallbackValue = ConstantsExplorer.CLARIN_SWITCHBOARD_ENDPOINT_FALLBACK; - String sbEndpoint = ""; - try { - sbEndpoint = getCLARINSwitchBoardEndpoint(); - } catch (Exception e) { - workspaceLogger.error( - "Could not find CLARINSwitchBoardEndpoint on IS, returning fallback value: " + fallbackValue); - sbEndpoint = fallbackValue; - } - String URI = getPublicLinkForFileItemId(itemId, false).getCompleteURL(); - workspaceLogger.debug("Got LinkForSendToSwitchBoard: " + URI + " encoding ..."); - String encodedURI = URLEncoder.encode(getPublicLinkForFileItemId(itemId, false).getCompleteURL(), "UTF-8"); - workspaceLogger.debug("LinkForSendToSwitchBoard: " + encodedURI + " encoded ..."); - return new StringBuilder(sbEndpoint).append(encodedURI).toString(); - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * isSessionExpired() - */ - /** - * Checks if is session expired. - * - * @return true, if is session expired - * @throws Exception - * the exception - */ - @Override - public boolean isSessionExpired() throws Exception { - return WsUtil.isSessionExpired(this.getThreadLocalRequest()); - } - - /** - * Checks if is within portal. - * - * @return true if you're running into the portal, false if in development - */ - private boolean isWithinPortal() { - try { - UserLocalServiceUtil.getService(); - return true; - } catch (Exception ex) { - workspaceLogger.trace("Development Mode ON"); - return false; - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getMyLogin() - */ - /** - * Gets the my login. - * - * @param currentPortletUrl - * the current portlet url - * @return the my login - */ - @Override - public UserBean getMyLogin(String currentPortletUrl) { - PortalContextInfo info = WsUtil.getPortalContext(this.getThreadLocalRequest()); - String username = info.getUsername(); - String email = info.getUserEmail(); - String firstName = "Testing"; - String lastName = "User"; - - if (isWithinPortal() && username != null) { - try { - LiferayUserManager l = new LiferayUserManager(); - GCubeUser user = l.getUserByUsername(username); - firstName = user.getFirstName(); - lastName = user.getLastName(); - email = user.getEmail(); - } catch (UserManagementSystemException e) { - workspaceLogger.error("UserManagementSystemException for username: " + username); - } catch (UserRetrievalFault e) { - workspaceLogger.error("UserRetrievalFault for username: " + username); - - } catch (Exception e) { - workspaceLogger.error("Error during getMyLogin for username: " + username, e); - } - - } - - UserBean us = new UserBean(username, firstName, lastName, email); - workspaceLogger.info("Returning myLogin: " + us); - - return us; - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getMyLogin() - */ - /** - * Gets the my first name. - * - * @return the my first name - */ - @Override - public String getMyFirstName() { - if (!isWithinPortal()) - return ""; - - PortalContextInfo info = WsUtil.getPortalContext(this.getThreadLocalRequest()); - String username = info.getUsername(); - String firstName = ""; - if (isWithinPortal() && username != null) { - try { - LiferayUserManager l = new LiferayUserManager(); - GCubeUser user = l.getUserByUsername(username); - workspaceLogger.info("My login first name is: " + user.getFirstName()); - firstName = user.getFirstName(); - } catch (UserManagementSystemException e) { - workspaceLogger.error("UserManagementSystemException for username: " + username); - } catch (UserRetrievalFault e) { - workspaceLogger.error("UserRetrievalFault for username: " + username); - } - - } - return firstName; - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getItemDescriptionById(java.lang.String) - */ - /** - * Gets the item description by id. - * - * @param identifier - * the identifier - * @return the item description by id - * @throws Exception - * the exception - */ - @Override - public String getItemDescriptionById(String identifier) throws Exception { - - workspaceLogger.info("Getting ItemDescriptionById: " + identifier); - if (identifier == null || identifier.isEmpty()) { - workspaceLogger.warn("Getting ItemDescriptionById identifier is null or empty, returning null"); - return null; - } - - try { - - Workspace workspace = getWorkspace(); - WorkspaceItem item = workspace.getItem(identifier); - GWTWorkspaceBuilder builder = getGWTWorkspaceBuilder(); - return builder.getItemDescriptionForTypeById(item); - - } catch (Exception e) { - workspaceLogger.error("Error in server ItemDescriptionById: ", e); - String error = ConstantsExplorer.SERVER_ERROR + " getting description for item id: " + identifier; - throw new Exception(error); - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getUserWorkspaceQuote() - */ - /** - * Gets the user workspace quote. - * - * @return the user workspace quote - * @throws Exception - * the exception - */ - @Override - public WorkspaceUserQuote getUserWorkspaceQuote() throws Exception { - try { - workspaceLogger.info("Getting UserWorkspaceQuote.."); - Workspace workspace = getWorkspace(); - long size = workspace.getDiskUsage(); - workspaceLogger.info("Root size is: " + size + " formatting.."); - String formatSize = GWTWorkspaceBuilder.formatFileSize(size); - long total = getUserWorkspaceTotalItems(); - - WorkspaceUserQuote quote = new WorkspaceUserQuote(); - quote.setDiskSpace(size); - quote.setDiskSpaceFormatted(formatSize); - quote.setTotalItems(total); - workspaceLogger.info("returning user quote: " + quote); - return quote; - } catch (Exception e) { - workspaceLogger.error("Error on UserWorkspaceQuote", e); - return null; - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getUserWorkspaceSize() - */ - /** - * Gets the user workspace size. - * - * @return the user workspace size - * @throws Exception - * the exception - */ - @Override - public String getUserWorkspaceSize() throws Exception { - try { - workspaceLogger.info("Getting workspace size.."); - Workspace workspace = getWorkspace(); - long size = workspace.getDiskUsage(); - // workspaceLogger.info("Root size is: "+size +" formatting.."); - String formatSize = GWTWorkspaceBuilder.formatFileSize(size); - workspaceLogger.info("returning workspace size: " + formatSize); - return formatSize; - } catch (Exception e) { - workspaceLogger.error("Error on UserWorkspaceSize", e); - String error = ConstantsExplorer.SERVER_ERROR + " getting disk usage"; - throw new Exception(error); - } - - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getUserWorkspaceTotalItems() - */ - /** - * Gets the user workspace total items. - * - * @return the user workspace total items - * @throws Exception - * the exception - */ - @Override - public long getUserWorkspaceTotalItems() throws Exception { - try { - workspaceLogger.info("Getting total items.."); - Workspace workspace = getWorkspace(); - long size = workspace.getTotalItems(); - workspaceLogger.info("returning total items value: " + size); - return size; - } catch (Exception e) { - workspaceLogger.error("Error on UserWorkspaceSize", e); - String error = ConstantsExplorer.SERVER_ERROR + " getting total items"; - throw new Exception(error); - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * loadGcubeItemProperties(java.lang.String) - */ - /** - * Load gcube item properties. - * - * @param itemId - * the item id - * @return the map - * @throws Exception - * the exception - */ - @Override - public Map loadGcubeItemProperties(String itemId) throws Exception { - workspaceLogger.info("Getting GcubeItemProperties for itemId: " + itemId); - if (itemId == null || itemId.isEmpty()) { - workspaceLogger.warn("Getting GcubeItemProperties identifier is null or empty, returning null"); - return null; - } - - try { - Workspace workspace = getWorkspace(); - WorkspaceItem item = workspace.getItem(itemId); - GWTWorkspaceBuilder builder = getGWTWorkspaceBuilder(); - Map mapProperties = builder.getGcubeItemProperties(item); - if (mapProperties != null) - workspaceLogger.info("Returning " + mapProperties.size() + " properties"); - else - workspaceLogger.info("Returning null properties"); - - return mapProperties; - } catch (Exception e) { - workspaceLogger.error("Error in server GcubeItemProperties: ", e); - String error = ConstantsExplorer.SERVER_ERROR + " getting gcube item properties for item id: " + itemId; - throw new Exception(error); - } - } - - /** - * Gets the HTML gcube item properties. - * - * @param itemId - * the item id - * @return The Gcube Item Properties in HTML format if itemId is a GcubeItem - * and contains properties, null otherwise - * @throws Exception - * the exception - */ - @Override - public String getHTMLGcubeItemProperties(String itemId) throws Exception { - workspaceLogger.info("Getting FormattedGcubeItemProperties for itemId: " + itemId); - if (itemId == null || itemId.isEmpty()) { - workspaceLogger.warn("Getting FormattedGcubeItemProperties identifier is null or empty, returning null"); - return null; - } - - try { - - Workspace workspace = getWorkspace(); - WorkspaceItem item = workspace.getItem(itemId); - GWTWorkspaceBuilder builder = getGWTWorkspaceBuilder(); - return builder.getFormatHtmlGcubeItemProperties(item); - - } catch (Exception e) { - workspaceLogger.error("Error in server FormattedGcubeItemProperties: ", e); - String error = ConstantsExplorer.SERVER_ERROR + " getting gcube item properties for item id: " + itemId; - throw new Exception(error); - } - } - - /** - * Sets the gcube item properties. - * - * @param itemId - * the item id - * @param properties - * the properties - * @throws Exception - * the exception - */ - @Override - public void setGcubeItemProperties(String itemId, Map properties) throws Exception { - workspaceLogger.info("Set GcubeItemProperties for itemId: " + itemId); - if (itemId == null || itemId.isEmpty()) { - workspaceLogger.warn("Set GcubeItemProperties, identifier is null or empty, returning null"); - throw new Exception("The item id is null or empty"); - } - - try { - - Workspace workspace = getWorkspace(); - WorkspaceItem item = workspace.getItem(itemId); - if (item instanceof GCubeItem) { - workspaceLogger.info("Adding " + properties.size() + " properties to GCubeItem: " + itemId); - GCubeItem gItem = (GCubeItem) item; - for (String key : properties.keySet()) { - // ADD PROPERTIES - workspaceLogger.trace("Adding property: [" + key + "," + properties.get(key) + "]"); - gItem.getProperties().addProperty(key, properties.get(key)); - } - gItem.getProperties().update(); - } else - throw new NoGcubeItemTypeException("The item is not a Gcube Item"); - - } catch (NoGcubeItemTypeException e) { - workspaceLogger.error("Error in server FormattedGcubeItemProperties: ", e); - throw new Exception(e.getMessage()); - } catch (Exception e) { - workspaceLogger.error("Error in server FormattedGcubeItemProperties: ", e); - String error = ConstantsExplorer.SERVER_ERROR + " setting gcube item properties for item id: " + itemId; - throw new Exception(error); - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * markFolderAsPublicForFolderItemId(java.lang.String, boolean) - */ - /** - * Mark folder as public for folder item id. - * - * @param itemId - * the item id - * @param setPublic - * the set public - * @return the public link - * @throws SessionExpiredException - * the session expired exception - * @throws Exception - * the exception - */ - @Override - public PublicLink markFolderAsPublicForFolderItemId(String itemId, boolean setPublic) - throws SessionExpiredException, Exception { - - if (isSessionExpired()) - throw new SessionExpiredException(); - - try { - Workspace workspace = getWorkspace(); - WorkspaceItem item = workspace.getItem(itemId); - if (item instanceof WorkspaceFolder) { - WorkspaceFolder folder = (WorkspaceFolder) item; - - if (setPublic) { - if (!folder.isPublic()) - folder.setPublic(true); - - String folderId = item.getId(); - workspaceLogger.info("HL returning folder link id: " + folderId); - ApplicationProfileReader apReader = new ApplicationProfileReader("Workspace-Explorer-App", - "org.gcube.portlets.user.workspaceexplorerapp.server.WorkspaceExplorerAppServiceImpl"); - ApplicationProfile ap = apReader.readProfileFromInfrastrucure(); - - String encriptedFId = StringEncrypter.getEncrypter().encrypt(folderId); - workspaceLogger.info("Encrypted folder Id: " + encriptedFId); - String encodedFId = StringUtil.base64EncodeStringURLSafe(encriptedFId); - workspaceLogger.info("Encoded in Base 64: " + encodedFId); - workspaceLogger.info("Application profile returning url: " + ap.getUrl()); - String folderLink = ap.getUrl() + "?folderId=" + encodedFId; - String shortURL = null; - try { - shortURL = getShortUrl(folderLink); - shortURL = shortURL != null ? shortURL : "not available"; - } catch (Exception e) { - workspaceLogger.warn("Short url error, skipping"); - shortURL = "not available"; - } - return new PublicLink(folderLink, shortURL); - } else { - folder.setPublic(false); - return null; - } - } else - throw new NoGcubeItemTypeException("The item is not a Gcube Item"); - - } catch (NoGcubeItemTypeException e) { - workspaceLogger.error("Error in server: ", e); - throw new Exception(e.getMessage()); - } catch (InsufficientPrivilegesException e) { - workspaceLogger.error("Error in server: ", e); - throw new Exception(e.getMessage()); - } catch (Exception e) { - workspaceLogger.error("Error in server markFolderAsPublicForFolderItemId: ", e); - String error = ConstantsExplorer.SERVER_ERROR + " reading Folder Link for id: " + itemId; - throw new Exception(error); - } - } /** * Gets the servlet context path. @@ -1881,238 +219,7 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT return url.toString(); } - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * performOperationOnVersionedFile(java.lang.String, java.util.List, - * org.gcube.portlets.user.workspace.shared.WorkspaceVersioningOperation) - */ - /** - * Perform operation on versioned file. - * - * @param fileId - * the file id - * @param olderVersionIDs - * the older version i ds - * @param operation - * the operation - * @return the list - * @throws Exception - * the exception - */ - @Override - public List performOperationOnVersionedFile(String fileId, List olderVersionIDs, - WorkspaceVersioningOperation operation) throws Exception { - - if (fileId == null || olderVersionIDs == null || olderVersionIDs.size() == 0) - throw new Exception("File Versioned is null"); - - workspaceLogger - .info("File Id: " + fileId + ", Ids Version: " + olderVersionIDs + " perform operation: " + operation); - - try { - - Workspace workspace = getWorkspace(); - WorkspaceItem fileHL = workspace.getItem(fileId); - if (fileHL instanceof ExternalFile) { - ExternalFile extFile = (ExternalFile) fileHL; - - switch (operation) { - - case DOWNLOAD: { - // IMPLEMENTED CLIENT-SIDE - break; - } - - case DELETE_ALL_OLDER_VERSIONS: { - // MUST BE OPTIMIZED HL-SIDE - for (String olderVersionId : olderVersionIDs) { - extFile.removeVersion(olderVersionId); - workspaceLogger.info("Version " + olderVersionId + " of file id: " + fileId + " removed"); - } - return getVersionHistory(fileId); - } - - // case RESTORE: { - // for (String olderVersionId : olderVersionIDs) { - // extFile.restoreVersion(olderVersionId); - // workspaceLogger.info("Version "+olderVersionId +" of file id: - // "+fileId+" restored"); - // } - // return getVersionHistory(fileId); - // - // } - - case REFRESH: { - return getVersionHistory(fileId); - } - - case DELETE_PERMANENTLY: { - for (String olderVersionId : olderVersionIDs) { - extFile.removeVersion(olderVersionId); - workspaceLogger.info("Version " + olderVersionId + " of file id: " + fileId + " removed"); - } - return getVersionHistory(fileId); - } - - default: { - - break; - } - } - - return getVersionHistory(fileId); - - } else - throw new FileNotVersionedException("Selected file is not versioned"); - - } catch (Exception e) { - - if (e instanceof FileNotVersionedException) - throw new Exception(e.getMessage()); - - if (e instanceof InsufficientPrivilegesException) - throw new Exception(e.getMessage()); - - workspaceLogger.error("Error in server during perform operation on versioning on file id: " + fileId, e); - String error = ConstantsExplorer.SERVER_ERROR + " updating versioning of file id: " + fileId; - throw new Exception(error); - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getImagesForFolder(java.lang.String, java.lang.String) - */ - /** - * Gets the images for folder. - * - * @param folderId - * the folder id - * @param currentImageId - * the current image id - * @return the images for folder - * @throws Exception - * the exception - */ - @Override - public List getImagesForFolder(String folderId, String currentImageId) throws Exception { - - if (folderId == null) - return null; - - try { - - Workspace workspace = getWorkspace(); - workspaceLogger.debug("get images for folder id: " + folderId); - WorkspaceItem item = workspace.getItem(folderId); // get item from - // workspace - List images = new ArrayList(); - - if (item.isFolder()) { - WorkspaceFolder folder = (WorkspaceFolder) item; - GWTWorkspaceBuilder builder = getGWTWorkspaceBuilder(); - PortalContextInfo context = WsUtil.getPortalContext(this.getThreadLocalRequest()); - GCubeUser user = PortalContext.getConfiguration().getCurrentUser(this.getThreadLocalRequest()); - List children = folder.getChildren(); - - for (WorkspaceItem workspaceItem : children) { - boolean foundCurrentImage = false; - if (workspaceItem.getType().compareTo(WorkspaceItemType.FOLDER_ITEM) == 0) { - FolderItem file = (FolderItem) workspaceItem; - GWTWorkspaceItem image = null; - switch (file.getFolderItemType()) { - case EXTERNAL_IMAGE: - image = builder.buildGWTWorkspaceImage(workspaceItem, false, false, - context.getCurrGroupId() + "", user.getUserId() + ""); - image.setId(workspaceItem.getId()); - break; - case IMAGE_DOCUMENT: - image = builder.buildGWTWorkspaceImage(workspaceItem, true, false, - context.getCurrGroupId() + "", user.getUserId() + ""); - image.setId(workspaceItem.getId()); - break; - default: - break; - } - - if (image != null) { - if (!foundCurrentImage && image.getId().compareTo(currentImageId) == 0) { - workspaceLogger.debug( - "It is current thumbnail adding to list as first element: " + image.getName()); - images.add(0, image); - foundCurrentImage = true; - } else { - workspaceLogger.debug("Adding thumbnail name to list: " + image.getName()); - images.add(image); - } - } - } - } - } - - workspaceLogger.info("Returning " + images.size() + " images for folder id: " + folderId); - return images; - } catch (Exception e) { - workspaceLogger.error("Error in server get images by folder id: " + folderId, e); - throw new Exception(e.getMessage()); - } - } - - /* - * (non-Javadoc) - * - * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# - * getListOfVREsForLoggedUser() - */ - /** - * Gets the list of vr es for logged user. - * - * @return the list of vr es for logged user - * @throws Exception - * the exception - */ - @Override - public List getListOfVREsForLoggedUser() throws Exception { - workspaceLogger.debug("getListOfVREsForLoggedUser...: "); - // PortalContextInfo context = - // WsUtil.getPortalContext(this.getThreadLocalRequest()); - GCubeUser user = PortalContext.getConfiguration().getCurrentUser(this.getThreadLocalRequest()); - long userId = user.getUserId(); - - // Instanciate the manager - GroupManager groupManager = new LiferayGroupManager(); - List listOfVres = new ArrayList(); - - if (isTestMode()) { - listOfVres.add(new GcubeVRE("devVRE", "/gcube/devsec/devVRE")); - listOfVres.add(new GcubeVRE("NextNext", "/gcube/devNext/NextNext")); - return listOfVres; - } - - try { - - List listOfGroups = groupManager.listGroupsByUser(userId); - for (GCubeGroup gCubeGroup : listOfGroups) { - if (groupManager.isVRE(gCubeGroup.getGroupId())) { - GcubeVRE gcubeVRE = new GcubeVRE(gCubeGroup.getGroupName(), - groupManager.getInfrastructureScope(gCubeGroup.getGroupId())); - listOfVres.add(gcubeVRE); - } - } - - } catch (UserRetrievalFault | UserManagementSystemException | GroupRetrievalFault e) { - workspaceLogger.error("Error occurred server-side getting VRE folders: ", e); - throw new Exception("Sorry, an error occurred server-side getting VRE folders, try again later"); - } - - workspaceLogger.info("Returning list of VREs: " + listOfVres); - return listOfVres; - } - + /** * Checks if is item under sync. * @@ -2143,6 +250,52 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT throw new Exception("Error on checking item " + itemId + " is under sync"); } } + + /* + * (non-Javadoc) + * + * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# + * getMyLogin() + */ + /** + * Gets the my login. + * + * @param currentPortletUrl + * the current portlet url + * @return the my login + */ + @Override + public UserBean getMyLogin(String currentPortletUrl) { + + PortalContextInfo info = WsUtil.getPortalContext(this.getThreadLocalRequest()); + String username = info.getUsername(); + String email = info.getUserEmail(); + String firstName = "Testing"; + String lastName = "User"; + + if (isWithinPortal() && username != null) { + try { + LiferayUserManager l = new LiferayUserManager(); + GCubeUser user = l.getUserByUsername(username); + firstName = user.getFirstName(); + lastName = user.getLastName(); + email = user.getEmail(); + } catch (UserManagementSystemException e) { + workspaceLogger.error("UserManagementSystemException for username: " + username); + } catch (UserRetrievalFault e) { + workspaceLogger.error("UserRetrievalFault for username: " + username); + + } catch (Exception e) { + workspaceLogger.error("Error during getMyLogin for username: " + username, e); + } + + } + + UserBean us = new UserBean(username, firstName, lastName, email); + workspaceLogger.info("Returning myLogin: " + us); + return us; + } + /** * Gets the CLARIN switch board endpoint. @@ -2171,6 +324,76 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT ScopeProvider.instance.set(currContext); return res.profile().runtime().hostedOn(); } + + /* + * (non-Javadoc) + * + * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# + * getMyLogin() + */ + /** + * Gets the my first name. + * + * @return the my first name + */ + @Override + public String getMyFirstName() { + if (!isWithinPortal()) + return ""; + + PortalContextInfo info = WsUtil.getPortalContext(this.getThreadLocalRequest()); + String username = info.getUsername(); + String firstName = ""; + if (isWithinPortal() && username != null) { + try { + LiferayUserManager l = new LiferayUserManager(); + GCubeUser user = l.getUserByUsername(username); + workspaceLogger.info("My login first name is: " + user.getFirstName()); + firstName = user.getFirstName(); + } catch (UserManagementSystemException e) { + workspaceLogger.error("UserManagementSystemException for username: " + username); + } catch (UserRetrievalFault e) { + workspaceLogger.error("UserRetrievalFault for username: " + username); + } + + } + return firstName; + } + + + /* + * (non-Javadoc) + * + * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# + * isSessionExpired() + */ + /** + * Checks if is session expired. + * + * @return true, if is session expired + * @throws Exception + * the exception + */ + @Override + public boolean isSessionExpired() throws Exception { + return WsUtil.isSessionExpired(this.getThreadLocalRequest()); + } + + /** + * Checks if is within portal. + * + * @return true if you're running into the portal, false if in development + */ + private boolean isWithinPortal() { + try { + UserLocalServiceUtil.getService(); + return true; + } catch (Exception ex) { + workspaceLogger.trace("Development Mode ON"); + return false; + } + } + /** * Gets the workspace from storage hub. @@ -2270,7 +493,8 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem theItem = null; try { - + + workspaceLogger.error("called deleteItem: "+itemId); if (itemId == null) throw new Exception(IDENTIFIER_IS_NULL); @@ -2290,33 +514,34 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT // HERE REMOVING THE ITEM workspaceLogger.info("Calling storageHub to delete item with id: " + itemId); workspaceSH.deleteItem(itemId); - + + NotificationsProducerToStorageHub np = getNotificationProducerToStorageHub(); if (sourceFolderSharedId != null) - NotificationsUtil.checkSendNotifyRemoveItemToShare(this.getThreadLocalRequest(), theItem.isShared(), - itemName, itemId, sourceFolderSharedId); + NotificationStorageHubUtil.checkSendNotifyRemovedItemFromShare(this.getThreadLocalRequest(), theItem.isShared(), + itemName, itemId, sourceFolderSharedId, workspaceSH, np); return Boolean.TRUE; } catch (WorkspaceFolderLocked e1) { throw new Exception(e1.getMessage()); - } catch (InsufficientPrivilegesException e) { - workspaceLogger.error("Error in server Item remove", e); - String error = "Insufficient Privileges to remove the item"; - throw new Exception(error); - - } catch (ItemNotFoundException e) { - String error = "An error occurred on deleting item. " + ConstantsExplorer.ERROR_ITEM_DOES_NOT_EXIST; - workspaceLogger.error(error, e); - throw new Exception(error); - - //TO STORAGEHUB EXCEPTION - } catch (UserNotAuthorizedException e) { - String error = "Insufficient Privileges to delete the item"; - workspaceLogger.error(error, e); - throw new Exception(error); +// } catch (InsufficientPrivilegesException e) { +// workspaceLogger.error("Error in server Item remove", e); +// String error = "Insufficient Privileges to remove the item"; +// throw new Exception(error); +// +// } catch (ItemNotFoundException e) { +// String error = "An error occurred on deleting item. " + ConstantsExplorer.ERROR_ITEM_DOES_NOT_EXIST; +// workspaceLogger.error(error, e); +// throw new Exception(error); +// +// //TO STORAGEHUB EXCEPTION +// } catch (UserNotAuthorizedException e) { +// String error = "Insufficient Privileges to delete the item"; +// workspaceLogger.error(error, e); +// throw new Exception(error); } catch (Exception e) { - workspaceLogger.error("Remoing item error:", e); + workspaceLogger.error("Removing item error:", e); StringBuilder error = new StringBuilder(); if(theItem!=null && theItem.isShared()) { if(theItem.isFolder()) { @@ -2613,6 +838,7 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT .debug("Converting grid item: " + workspaceItem.getId() + " name " + workspaceItem.getName()); listFileGridModels.add(converter.toGridFileModel(workspaceItem, wsParent)); } + workspaceLogger.info("All converted grid item/s is/are: " + listFileGridModels.size()); return listFileGridModels; } catch (Exception e) { @@ -2836,11 +1062,10 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT if (ids == null) throw new Exception("List identifiers is null"); + workspaceLogger.debug("called deleteListItemsForIds with: " + ids.size() +" id/s"); + // Workspace workspace = getWorkspace(); org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace = getWorkspaceFromStorageHub(); - - workspaceLogger.trace("removeItem item for list size: " + ids.size()); - String[] items = new String[ids.size()]; items = ids.toArray(items); @@ -2862,23 +1087,15 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT sourceFolderSharedId = rootSharedFolder.getId(); } // REMOVE ITEM - garbage.put(itemId, new GarbageItem(sourceItemIsShared, itemName, itemId, sourceFolderSharedId)); } catch (Exception e) { workspaceLogger.warn("Impossible to send notifiaction for item with id: " + itemId); } - - // workspace.removeItem(itemId); - //// IF SOURCE SHARED FOLDER IS NOT NULL - // if(sourceFolderSharedId!=null) - // NotificationsUtil.checkSendNotifyRemoveItemToShare(this.getThreadLocalRequest().getSession(), - // sourceItemIsShared, itemName, itemId, sourceFolderSharedId); } // ITEM ID - ERROR Map backendError = workspace.removeItems(items); - // GARBAGE ITEM ERROR List frontEndError = new ArrayList(backendError.size()); @@ -2891,14 +1108,15 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT } } + NotificationsProducerToStorageHub np = getNotificationProducerToStorageHub(); for (String idItem : garbage.keySet()) { GarbageItem item = garbage.get(idItem); workspaceLogger.trace("Check notification for " + item); // IF SOURCE SHARED FOLDER IS NOT NULL if (item.getSourceFolderSharedId() != null) - NotificationsUtil.checkSendNotifyRemoveItemToShare(this.getThreadLocalRequest(), + NotificationStorageHubUtil.checkSendNotifyRemovedItemFromShare(this.getThreadLocalRequest(), item.isSourceItemIsShared(), item.getOldItemName(), item.getOldItemName(), - item.getSourceFolderSharedId()); + item.getSourceFolderSharedId(), workspace, np); } return frontEndError; @@ -2906,15 +1124,15 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT } catch (WorkspaceFolderLocked e1) { throw new Exception(e1.getMessage()); - } catch (InsufficientPrivilegesException e) { - workspaceLogger.error("Error in server Item remove", e); - String error = "An error occurred on deleting item. " + e.getMessage(); - throw new Exception(error); - - } catch (ItemNotFoundException e) { - String error = "An error occurred on deleting item. " + ConstantsExplorer.ERROR_ITEM_DOES_NOT_EXIST; - workspaceLogger.error(error, e); - throw new Exception(error); +// } catch (InsufficientPrivilegesException e) { +// workspaceLogger.error("Error in server Item remove", e); +// String error = "An error occurred on deleting item. " + e.getMessage(); +// throw new Exception(error); +// +// } catch (ItemNotFoundException e) { +// String error = "An error occurred on deleting item. " + ConstantsExplorer.ERROR_ITEM_DOES_NOT_EXIST; +// workspaceLogger.error(error, e); +// throw new Exception(error); } catch (Exception e) { workspaceLogger.error("Error in server Item remove", e); String error = ConstantsExplorer.SERVER_ERROR + " deleting item. " + e.getMessage(); @@ -2946,13 +1164,14 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT @Override public FolderModel createFolder(String nameFolder, String description, FileModel parent) throws Exception { - workspaceLogger.debug("Create folder: " + nameFolder + " parent is null? " + parent == null); - if (isSessionExpired()) throw new SessionExpiredException(); try { + boolean isParentNull = parent == null; + workspaceLogger.debug("Create folder: " + nameFolder + " parent is null? "+isParentNull); + if (nameFolder == null) throw new Exception("Folder name is null"); @@ -2974,14 +1193,14 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT } catch (WorkspaceFolderLocked e1) { throw new Exception(e1.getMessage()); - } catch (InsufficientPrivilegesException e) { - String error = "Insufficient Privileges to create the folder"; - workspaceLogger.error(error, e); - throw new Exception(error); - } catch (ItemAlreadyExistException e) { - String error = "An error occurred on creating folder, " + e.getMessage(); - workspaceLogger.error(error, e); - throw new Exception(error); +// } catch (InsufficientPrivilegesException e) { +// String error = "Insufficient Privileges to create the folder"; +// workspaceLogger.error(error, e); +// throw new Exception(error); +// } catch (ItemAlreadyExistException e) { +// String error = "An error occurred on creating folder, " + e.getMessage(); +// workspaceLogger.error(error, e); +// throw new Exception(error); } catch (Exception e) { String error = "Error on creating folder. Either the folder already exist or you do not have the permission to create it"; workspaceLogger.error(error, e); @@ -3107,10 +1326,10 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT } catch (WorkspaceFolderLocked e1) { throw new Exception(e1.getMessage()); - } catch (InsufficientPrivilegesException e) { - workspaceLogger.error("Error in server Item move", e); - String error1 = "An error occurred on moving item. " + e.getMessage(); - throw new Exception(error1); +// } catch (InsufficientPrivilegesException e) { +// workspaceLogger.error("Error in server Item move", e); +// String error1 = "An error occurred on moving item. " + e.getMessage(); +// throw new Exception(error1); } catch (Exception e) { workspaceLogger.error("Item move error.", e); @@ -3216,14 +1435,14 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT } catch (WorkspaceFolderLocked e1) { throw new Exception(e1.getMessage()); - } catch (ItemAlreadyExistException e) { - String error = "An error occurred on renaming item, " + e.getMessage(); - workspaceLogger.error(error, e); - throw new Exception(error); - } catch (ItemNotFoundException e2) { - String error = "An error occurred on renaming item. " + ConstantsExplorer.ERROR_ITEM_DOES_NOT_EXIST; - workspaceLogger.error(error, e2); - throw new Exception(error); +// } catch (ItemAlreadyExistException e) { +// String error = "An error occurred on renaming item, " + e.getMessage(); +// workspaceLogger.error(error, e); +// throw new Exception(error); +// } catch (ItemNotFoundException e2) { +// String error = "An error occurred on renaming item. " + ConstantsExplorer.ERROR_ITEM_DOES_NOT_EXIST; +// workspaceLogger.error(error, e2); +// throw new Exception(error); //TO STORAGEHUB EXCEPTION } catch (UserNotAuthorizedException e) { String error = "Insufficient Privileges to rename the item"; @@ -3335,13 +1554,13 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT } catch (WorkspaceFolderLocked e1) { throw new Exception(e1.getMessage()); - } catch (InsufficientPrivilegesException e) { - String error = "An error occurred on copying item, " + e.getMessage() + ". " + ConstantsExplorer.TRY_AGAIN; - throw new Exception(error); - - } catch (ItemAlreadyExistException e) { - String error = "An error occurred on copying item, " + e.getMessage(); - throw new Exception(error); +// } catch (InsufficientPrivilegesException e) { +// String error = "An error occurred on copying item, " + e.getMessage() + ". " + ConstantsExplorer.TRY_AGAIN; +// throw new Exception(error); +// +// } catch (ItemAlreadyExistException e) { +// String error = "An error occurred on copying item, " + e.getMessage(); +// throw new Exception(error); } catch (Exception e) { workspaceLogger.error("Error in server copyItem by id", e); String error = ConstantsExplorer.SERVER_ERROR + " copying item " + ConstantsExplorer.TRY_AGAIN; @@ -3520,7 +1739,7 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT public List getListParentsByItemIdentifier(String itemIdentifier, boolean includeItemAsParent) throws Exception { - workspaceLogger.debug("get List Parents by SHUB for id " + itemIdentifier + workspaceLogger.debug("called get List Parents by SHUB for id " + itemIdentifier + ", include Item As (Last) Parent: " + includeItemAsParent); if (isSessionExpired()) @@ -3650,10 +1869,10 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT workspaceLogger.warn(msg, e2); throw new WorkspaceFolderLocked(itemId, msg); - } catch (InternalErrorException | ItemNotFoundException | HomeNotFoundException - | WorkspaceFolderNotFoundException e) { - workspaceLogger.warn(e); - throw new Exception("Sorry an error occurred during checking is folder locked, Refresh and try again"); +// } catch (InternalErrorException | ItemNotFoundException | HomeNotFoundException +// | WorkspaceFolderNotFoundException e) { +// workspaceLogger.warn(e); +// throw new Exception("Sorry an error occurred during checking is folder locked, Refresh and try again"); } catch (Exception e) { workspaceLogger @@ -3723,7 +1942,1071 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT throw new Exception(error); } } + + + /* (non-Javadoc) + * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService#getImageById(java.lang.String, boolean, boolean) + */ + @Override + public GWTWorkspaceItem getImageById(String identifier, boolean isInteralImage, boolean fullDetails) + throws Exception { + + if (identifier == null) + throw new Exception(IDENTIFIER_IS_NULL); + try { + + workspaceLogger.debug("get image by id: " + identifier); + org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace = getWorkspaceFromStorageHub(); + org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem wsItem = workspace.getItem(identifier); + + if(wsItem instanceof ImageFileItem) { + ImageFileItem imageFile = (ImageFileItem) wsItem; + PortalContextInfo context = WsUtil.getPortalContext(this.getThreadLocalRequest()); + GCubeUser user = PortalContext.getConfiguration().getCurrentUser(this.getThreadLocalRequest()); + return ObjectStorageHubToWorkpaceMapper.buildGWTWorkspaceImage(imageFile, isInteralImage, fullDetails, context.getCurrGroupId() + "", + user.getUserId() + ""); + }else { + throw new Exception("The input id is not an image"); + } + } catch (Exception e) { + workspaceLogger.error("Error in server get image by id", e); + throw new Exception(e.getMessage()); + } + } + + /* + * (non-Javadoc) + * + * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# + * getUrlById(java.lang.String, boolean, boolean) + */ + /** + * Gets the url by id. + * + * @param identifier + * the identifier + * @param isInternalUrl + * the is internal url + * @param fullDetails + * the full details + * @return the url by id + * @throws Exception + * the exception + */ + @Override + public GWTWorkspaceItem getUrlById(String identifier, boolean isInternalUrl, boolean fullDetails) throws Exception { + + try { + + if (identifier == null) + throw new Exception(IDENTIFIER_IS_NULL); + + workspaceLogger.debug("get URL by id: " + identifier); + org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace = getWorkspaceFromStorageHub(); + org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem wsItem = workspace.getItem(identifier); + // workspace + + if(wsItem instanceof org.gcube.common.storagehubwrapper.shared.tohl.impl.URLFileItem) { + URLFileItem fileItem = (URLFileItem) wsItem; + return ObjectStorageHubToWorkpaceMapper.buildGWTWorspaceUrl(workspace, fileItem, isInternalUrl, fullDetails); + }else if (wsItem instanceof URLItem){ + URLItem urlFile = (URLItem) wsItem; + return new GWTExternalUrl(urlFile.getValue().toString()); + }else { + throw new Exception("The input id is not a FILE or a URL"); + } + + } catch (Exception e) { + workspaceLogger.error("Error in server get image by id ", e); + // workspaceLogger.trace("Error in server get image by id " + e); + // GWT can't serialize all exceptions + throw new Exception(e.getMessage()); + } + } + + + /** + * Sets the value in session. + * + * @param name + * the name + * @param value + * the value + * @throws Exception + * the exception + */ + @Override + public void setValueInSession(String name, String value) throws Exception { + + try { + this.getThreadLocalRequest().getSession().setAttribute(name, value); + workspaceLogger.trace("set value in session with name: " + name + ", value: " + value); + } catch (Exception e) { + workspaceLogger.error("setValueInSession", e); + throw new Exception(e.getMessage()); + } + } + + + /* (non-Javadoc) + * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService#getItemCreationDateById(java.lang.String) + */ + @Override + public Date getItemCreationDateById(String itemId) throws Exception { + workspaceLogger.trace("get Item Creation Date By ItemId " + itemId); + try { + + if (itemId == null) + throw new Exception(IDENTIFIER_IS_NULL); + + workspaceLogger.debug("getItemCreationDateById by id: " + itemId); + org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace = getWorkspaceFromStorageHub(); + org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem wsItem = workspace.getItem(itemId); + + Calendar cl = wsItem.getCreationTime(); + + if (cl != null) + return cl.getTime(); + + return null; + + } catch (Exception e) { + workspaceLogger.error("get Item Creation Date By ItemId ", e); + throw new Exception(e.getMessage()); + } + } + + /* + * (non-Javadoc) + * + * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# + * loadSizeByItemId(java.lang.String) + */ + /** + * Load size by item id. + * + * @param itemId + * the item id + * @return the long + * @throws Exception + * the exception + */ + @Override + public Long loadSizeByItemId(String itemId) throws Exception { + + if (itemId == null) + throw new Exception(IDENTIFIER_IS_NULL); + + workspaceLogger.info("get Size By ItemId " + itemId); + try { + + org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace = getWorkspaceFromStorageHub(); + org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem wsItem = workspace.getItem(itemId); + Long size = new Long(-1); + + if (wsItem instanceof org.gcube.common.storagehubwrapper.shared.tohl.impl.FileItem) { // ITEM + org.gcube.common.storagehubwrapper.shared.tohl.impl.FileItem fileItem = (org.gcube.common.storagehubwrapper.shared.tohl.impl.FileItem) wsItem; + size = new Long(fileItem.getSize()); + } else if (wsItem instanceof org.gcube.common.storagehubwrapper.shared.tohl.impl.WorkspaceFolder) { // FOLDER + org.gcube.common.storagehubwrapper.shared.tohl.impl.WorkspaceFolder theFolder = (org.gcube.common.storagehubwrapper.shared.tohl.impl.WorkspaceFolder) wsItem; + //TODO ASK TO LUCIO; + //size = theFolder.getSize(); + } else if (wsItem instanceof org.gcube.common.storagehubwrapper.shared.tohl.impl.WorkspaceSharedFolder) { // SHARED FOLDER + org.gcube.common.storagehubwrapper.shared.tohl.impl.WorkspaceSharedFolder theFolder = (org.gcube.common.storagehubwrapper.shared.tohl.impl.WorkspaceSharedFolder) wsItem; + //TODO ASK TO LUCIO; + //size = theFolder.getSize(); + } + workspaceLogger.info("returning size: " + size); + return size; + + } catch (Exception e) { + workspaceLogger.error("get Size By ItemId ", e); + throw new Exception(e.getMessage()); + } + } + + + /* (non-Javadoc) + * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService#loadLastModificationDateById(java.lang.String) + */ + @Override + public Date loadLastModificationDateById(String itemId) throws Exception { + + if (itemId == null) + throw new Exception(IDENTIFIER_IS_NULL); + + workspaceLogger.trace("get last modification date ItemId " + itemId); + try { + + org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace = getWorkspaceFromStorageHub(); + org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem wsItem = workspace.getItem(itemId); + Date lastModification = null; + + if (wsItem.getLastModificationTime() != null) { + lastModification = wsItem.getLastModificationTime().getTime(); + } + + return lastModification; + + } catch (Exception e) { + workspaceLogger.error("get last modification date ItemId ", e); + throw new Exception(e.getMessage()); + } + } + + + /* (non-Javadoc) + * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService#getParentByItemId(java.lang.String) + */ + //TODO NEED TO TEST IT + @Override + public FileModel getParentByItemId(String identifier) throws Exception { + + if (identifier == null) + throw new Exception(IDENTIFIER_IS_NULL); + + workspaceLogger.trace("get Parent By Item Identifier " + identifier); + try { + + org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace = getWorkspaceFromStorageHub(); + org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem wsItem = workspace.getItem(identifier); + workspaceLogger.trace("workspace has returned item name: " + wsItem.getName()); + + FileModel parentModel = null; + if(wsItem!=null && wsItem.getParentId()!=null) { + org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem parent = workspace.getItem(wsItem.getParentId()); + StorageHubToWorkpaceConverter converter = getStorageHubToWorkpaceConverter(); + parentModel = converter.toTreeFileModel(parent, null, parent.isShared()); + + } + + workspaceLogger.trace("parent not found - retuning"); + return parentModel; + + } catch (Exception e) { + workspaceLogger.error("Error in get Parent By Item Identifier", e); + e.printStackTrace(); + throw new Exception(e.getMessage()); + } + } + + /* + * (non-Javadoc) + * + * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# + * getShortUrl(java.lang.String) + */ + /** + * Gets the short url. + * + * @param longUrl + * the long url + * @return the short url + * @throws Exception + * the exception + */ + @Override + public String getShortUrl(String longUrl) throws Exception { + + workspaceLogger.trace("get short url for " + longUrl); + UrlShortener shortener = getUrlShortener(); + try { + + if (shortener != null && shortener.isAvailable()) + return shortener.shorten(longUrl); + + return longUrl; + + } catch (Exception e) { + workspaceLogger.error("Error get short url for ", e); + return null; + } + } + + /* + * (non-Javadoc) + * + * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# + * getLinkForSendToSwitchBoard(java.lang.String) + */ + /** + * Gets the link for send to switch board. + * + * @param itemId + * the item id + * @return the link for send to switch board + * @throws Exception + * the exception + */ + @Override + public String getLinkForSendToSwitchBoard(String itemId) throws Exception { + String fallbackValue = ConstantsExplorer.CLARIN_SWITCHBOARD_ENDPOINT_FALLBACK; + String sbEndpoint = ""; + try { + sbEndpoint = getCLARINSwitchBoardEndpoint(); + } catch (Exception e) { + workspaceLogger.error( + "Could not find CLARINSwitchBoardEndpoint on IS, returning fallback value: " + fallbackValue); + sbEndpoint = fallbackValue; + } + String URI = getPublicLinkForFileItemId(itemId, false).getCompleteURL(); + workspaceLogger.debug("Got LinkForSendToSwitchBoard: " + URI + " encoding ..."); + String encodedURI = URLEncoder.encode(getPublicLinkForFileItemId(itemId, false).getCompleteURL(), "UTF-8"); + workspaceLogger.debug("LinkForSendToSwitchBoard: " + encodedURI + " encoded ..."); + return new StringBuilder(sbEndpoint).append(encodedURI).toString(); + } + + + + /* (non-Javadoc) + * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService#getItemDescriptionById(java.lang.String) + */ + @Override + public String getItemDescriptionById(String identifier) throws Exception { + + workspaceLogger.info("Getting ItemDescriptionById: " + identifier); + if (identifier == null || identifier.isEmpty()) { + workspaceLogger.warn("Getting ItemDescriptionById identifier is null or empty, returning null"); + return null; + } + + try { + + org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace = getWorkspaceFromStorageHub(); + org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem wsItem = workspace.getItem(identifier); + workspaceLogger.trace("workspace has returned item name: " + wsItem.getName()); + return wsItem.getDescription(); + + } catch (Exception e) { + workspaceLogger.error("Error in server ItemDescriptionById: ", e); + String error = ConstantsExplorer.SERVER_ERROR + " getting description for item id: " + identifier; + throw new Exception(error); + } + } + + + /* (non-Javadoc) + * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService#getUserWorkspaceSize() + */ + @Override + public String getUserWorkspaceSize() throws Exception { + try { + workspaceLogger.info("Getting workspace size.."); + org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace = getWorkspaceFromStorageHub(); + long size = workspace.getDiskUsage(); + // workspaceLogger.info("Root size is: "+size +" formatting.."); + String formatSize = FormatterUtil.formatFileSize(size); + workspaceLogger.info("returning workspace size: " + formatSize); + return formatSize; + } catch (Exception e) { + workspaceLogger.error("Error on UserWorkspaceSize", e); + String error = ConstantsExplorer.SERVER_ERROR + " getting disk usage"; + throw new Exception(error); + } + + } + + /* + * (non-Javadoc) + * + * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# + * getUserWorkspaceTotalItems() + */ + /** + * Gets the user workspace total items. + * + * @return the user workspace total items + * @throws Exception + * the exception + */ + @Override + public long getUserWorkspaceTotalItems() throws Exception { + try { + workspaceLogger.info("Getting total items.."); + org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace = getWorkspaceFromStorageHub(); + long size = workspace.getTotalItems(); + workspaceLogger.info("returning total items value: " + size); + return size; + } catch (Exception e) { + workspaceLogger.error("Error on UserWorkspaceSize", e); + String error = ConstantsExplorer.SERVER_ERROR + " getting total items"; + throw new Exception(error); + } + } + + /* + * (non-Javadoc) + * + * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# + * getUserWorkspaceQuote() + */ + /** + * Gets the user workspace quote. + * + * @return the user workspace quote + * @throws Exception + * the exception + */ + @Override + public WorkspaceUserQuote getUserWorkspaceQuote() throws Exception { + try { + workspaceLogger.info("Getting UserWorkspaceQuote.."); + org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace = getWorkspaceFromStorageHub(); + long size = workspace.getDiskUsage(); + workspaceLogger.info("Root size is: " + size + " formatting.."); + String formatSize = FormatterUtil.formatFileSize(size); + long total = getUserWorkspaceTotalItems(); + + WorkspaceUserQuote quote = new WorkspaceUserQuote(); + quote.setDiskSpace(size); + quote.setDiskSpaceFormatted(formatSize); + quote.setTotalItems(total); + workspaceLogger.info("returning user quote: " + quote); + return quote; + } catch (Exception e) { + workspaceLogger.error("Error on UserWorkspaceQuote", e); + return null; + } + } + + + /* + * (non-Javadoc) + * + * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# + * loadGcubeItemProperties(java.lang.String) + */ + /** + * Load gcube item properties. + * + * @param itemId + * the item id + * @return the map + * @throws Exception + * the exception + */ + @Override + public Map loadGcubeItemProperties(String itemId) throws Exception { + + workspaceLogger.info("Getting GcubeItemProperties for itemId: " + itemId); + if (itemId == null || itemId.isEmpty()) { + workspaceLogger.warn("Getting GcubeItemProperties identifier is null or empty, returning null"); + return null; + } + + try { + org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace = getWorkspaceFromStorageHub(); + PropertyMap properties = workspace.getGcubeItemProperties(itemId); + StorageHubToWorkpaceConverter converter = getStorageHubToWorkpaceConverter(); + Map mapProperties = converter.toSimpleMap(properties); + if (mapProperties != null) + workspaceLogger.info("Returning " + mapProperties.size() + " properties"); + else + workspaceLogger.info("Returning null properties"); + + return mapProperties; + } catch (Exception e) { + workspaceLogger.error("Error in server GcubeItemProperties: ", e); + String error = ConstantsExplorer.SERVER_ERROR + " getting gcube item properties for item id: " + itemId; + throw new Exception(error); + } + } + + /* + * (non-Javadoc) + * + * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# + * getItemsBySearchName(java.lang.String) + */ + /** + * Gets the items by search name. + * + * @param text + * the text + * @param folderId + * the folder id + * @return the items by search name + * @throws Exception + * the exception + */ + @Override + public List getItemsBySearchName(String text, String folderId) throws Exception { + + + try { + org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace = getWorkspaceFromStorageHub(); + if (folderId == null || folderId.isEmpty()) { + workspaceLogger.debug("searching folderId is null, searching from the root folder"); + folderId = workspace.getRoot().getId(); + } + + workspaceLogger.info("searching by name: " + text + " in the folder id: " + folderId); + List foundItems = workspace.find(text, folderId); + + if(foundItems==null) { + workspaceLogger.info("Searching by SHUB returned null, instancing empty list"); + foundItems = new ArrayList(); + } + + workspaceLogger.info("Searching by SHUB returned" + foundItems.size() + " item/s, converting it/them"); + + StorageHubToWorkpaceConverter converter = getStorageHubToWorkpaceConverter(); + List listFileGridModels = new ArrayList(); + + for (org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem workspaceItem : foundItems) { + workspaceLogger.debug("Converting grid item: " + workspaceItem.getId() + " name " + workspaceItem.getName()); + listFileGridModels.add(converter.toGridFileModel(workspaceItem, null)); + } + + workspaceLogger.info("Search objects converted is/are, "+listFileGridModels.size()+"returning"); + + return listFileGridModels; + } catch (Exception e) { + workspaceLogger.error("Error occured on searching: ", e); + throw new Exception("Error occured on searching, please retry or contact the support"); + } + } + + /** + * Gets the children sub tree to root by identifier. + * + * @param itemIdentifier + * the item identifier + * @return the children sub tree to root by identifier + * @throws Exception + * the exception + */ + @Override + public ArrayList getChildrenSubTreeToRootByIdentifier(String itemIdentifier) throws Exception { + + throw new Exception("The method getChildrenSubTreeToRootByIdentifier is not implement to interact with SHUB"); + } + + /* + * (non-Javadoc) + * + * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# + * itemExistsInWorkpaceFolder(java.lang.String, java.lang.String) + */ + /** + * Item exists in workpace folder. + * + * @param parentId + * the parent id + * @param itemName + * the item name + * @return the string + * @throws Exception + * the exception + */ + @Override + public String itemExistsInWorkpaceFolder(String parentId, String itemName) throws Exception { + + workspaceLogger.debug("called itemExistsInWorkpace for name "+itemName+" in the parent Id: " + parentId); + + if (parentId == null) + throw new Exception("I'm not able to perform searching.. the folder id is null"); + + + try { + + org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace = getWorkspaceFromStorageHub(); + workspaceLogger.info("searching by name: " + itemName + " in the folder id: " + parentId); + List foundItems = workspace.find(itemName, parentId); + + if (foundItems == null || foundItems.isEmpty()) + return null; + + return foundItems.get(0).getId(); + +// } catch (InternalErrorException e) { +// return null; +// } catch (ItemNotFoundException e) { +// return null; + } catch (Exception e) { + String error = "Error on searching the item "+itemName+" in the passed folder id"; + workspaceLogger.error(error, e); + throw new Exception(e.getMessage()); + } + } + + + /* + * (non-Javadoc) + * + * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# + * getAccountingHistory(java.lang.String) + */ + /** + * Gets the accounting history. + * + * @param identifier + * the identifier + * @return the accounting history + * @throws Exception + * the exception + */ + @Override + public List getAccountingHistory(String identifier) throws Exception { + + if (identifier == null) + throw new Exception("I'm not able to get accounting history... the folder id is null"); + + try { + + org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace = getWorkspaceFromStorageHub(); + org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem wsItem = workspace.getItem(identifier,true,false,false); + List accoutings = wsItem.getAccounting(); + StorageHubToWorkpaceConverter converter = getStorageHubToWorkpaceConverter(); + List listAccounting = converter.buildGXTAccountingItem(accoutings, GxtAccountingEntryType.ALL); + workspaceLogger.debug("get accouting returning size " + listAccounting.size()); + return listAccounting; + + } catch (Exception e) { + workspaceLogger.error("Error reading the accounting history for item id: "+identifier, e); + String error = ConstantsExplorer.SERVER_ERROR + " getting accounting History. " + ConstantsExplorer.TRY_AGAIN; + throw new Exception(error); + } + } + + /* + * (non-Javadoc) + * + * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# + * getListOfVREsForLoggedUser() + */ + /** + * Gets the list of vr es for logged user. + * + * @return the list of vr es for logged user + * @throws Exception + * the exception + */ + @Override + public List getListOfVREsForLoggedUser() throws Exception { + workspaceLogger.debug("getListOfVREsForLoggedUser...: "); + // PortalContextInfo context = + // WsUtil.getPortalContext(this.getThreadLocalRequest()); + GCubeUser user = PortalContext.getConfiguration().getCurrentUser(this.getThreadLocalRequest()); + long userId = user.getUserId(); + + // Instanciate the manager + GroupManager groupManager = new LiferayGroupManager(); + List listOfVres = new ArrayList(); + + if (isTestMode()) { + listOfVres.add(new GcubeVRE("devVRE", "/gcube/devsec/devVRE")); + listOfVres.add(new GcubeVRE("NextNext", "/gcube/devNext/NextNext")); + return listOfVres; + } + + try { + + List listOfGroups = groupManager.listGroupsByUser(userId); + for (GCubeGroup gCubeGroup : listOfGroups) { + if (groupManager.isVRE(gCubeGroup.getGroupId())) { + GcubeVRE gcubeVRE = new GcubeVRE(gCubeGroup.getGroupName(), + groupManager.getInfrastructureScope(gCubeGroup.getGroupId())); + listOfVres.add(gcubeVRE); + } + } + + } catch (UserRetrievalFault | UserManagementSystemException | GroupRetrievalFault e) { + workspaceLogger.error("Error occurred server-side getting VRE folders: ", e); + throw new Exception("Sorry, an error occurred server-side getting VRE folders, try again later"); + } + + workspaceLogger.info("Returning list of VREs: " + listOfVres); + return listOfVres; + } + + /** + * Gets the HTML gcube item properties. + * + * @param itemId + * the item id + * @return The Gcube Item Properties in HTML format if itemId is a GcubeItem + * and contains properties, null otherwise + * @throws Exception + * the exception + */ + @Override + public String getHTMLGcubeItemProperties(String itemId) throws Exception { + workspaceLogger.info("getting HTMLGcubeItemProperties for itemId: " + itemId); + if (itemId == null || itemId.isEmpty()) { + workspaceLogger.warn("Error on getting GcubeItemProperties the identifier is null or empty, returning null"); + return null; + } + + try { + + org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace = getWorkspaceFromStorageHub(); + org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem wsItem = workspace.getItem(itemId); + StorageHubToWorkpaceConverter converter = getStorageHubToWorkpaceConverter(); + return converter.getGcubeItemPropertiesForGcubeItemAsHTML(wsItem); + + } catch (Exception e) { + workspaceLogger.error("Error in server FormattedGcubeItemProperties: ", e); + String error = ConstantsExplorer.SERVER_ERROR + " getting gcube item properties for item id: " + itemId; + throw new Exception(error); + } + } + + /** + * Gets the accounting readers. + * + * @param identifier + * the identifier + * @return the accounting readers + * @throws Exception + * the exception + */ + @Override + public List getAccountingReaders(String identifier) throws Exception { + + if (identifier == null || identifier.isEmpty()) { + workspaceLogger.warn("Error on getting accounting history to readers, identifier is null, returning null"); + return null; + } + + workspaceLogger.debug("reading accounting history only to "+ GxtAccountingEntryType.READ+" for id: " + identifier); + try { + + org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace = getWorkspaceFromStorageHub(); + org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem wsItem = workspace.getItem(identifier,true,false,false); + List accoutings = wsItem.getAccounting(); + StorageHubToWorkpaceConverter converter = getStorageHubToWorkpaceConverter(); + List listOfReadFromAccounting = converter.buildGXTAccountingItem(accoutings, GxtAccountingEntryType.READ); + workspaceLogger.info("list of "+GxtAccountingEntryType.READ+" into accounting are:" + listOfReadFromAccounting.size()); + return listOfReadFromAccounting; + + } catch (Exception e) { + workspaceLogger.error("Error get accounting readers ", e); + String error = ConstantsExplorer.SERVER_ERROR + " getting account. " + ConstantsExplorer.TRY_AGAIN; + throw new Exception(error); + } + } + + /** + * Sets the gcube item properties. + * + * @param itemId + * the item id + * @param properties + * the properties + * @throws Exception + * the exception + */ + @Override + public void setGcubeItemProperties(String itemId, Map properties) throws Exception { + workspaceLogger.info("Set GcubeItemProperties for itemId: " + itemId); + if (itemId == null || itemId.isEmpty()) { + workspaceLogger.warn("Set GcubeItemProperties, identifier is null or empty, returning"); + throw new Exception("The item id is null or empty"); + } + + try { + + org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace = getWorkspaceFromStorageHub(); + org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem wsItem = workspace.getItem(itemId); + + if (wsItem instanceof org.gcube.common.storagehubwrapper.shared.tohl.impl.GcubeItem) { + workspaceLogger.info("Adding " + properties.size() + " properties to GCubeItem: " + itemId); + Map mapObjs = properties==null?null:new HashMap(properties.size()); + mapObjs.putAll(properties); + workspace.updateMetadata(itemId, mapObjs); + } else + throw new NoGcubeItemTypeException("The item is not a Gcube Item"); + + } catch (NoGcubeItemTypeException e) { + workspaceLogger.error("Error on settingss properties to GcubeItem: ", e); + throw new Exception(e.getMessage()); + } catch (Exception e) { + workspaceLogger.error("Error on settings properties to GcubeItem: ", e); + String error = ConstantsExplorer.SERVER_ERROR + " setting gcube item properties for item id: " + itemId; + throw new Exception(error); + } + } + + /** + * Creates the external url. + * + * @param parentId + * the parent id + * @param name + * the name + * @param description + * the description + * @param url + * the url + * @return the file model + * @throws Exception + * the exception + */ + @Override + public FileModel createExternalUrl(String parentId, String name, String description, String url) throws Exception { + workspaceLogger.info("Called createExternalUrl [parent: "+parentId+", url: "+url+"]"); + try { + + if (parentId == null) { + workspaceLogger.error("Error on creating url. Parent ID is null"); + throw new Exception("Parent ID is null"); + } + + checkItemLocked(parentId); + + org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace = getWorkspaceFromStorageHub(); + org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem wsFolderParent = workspace.getItem(parentId); + + StorageHubToWorkpaceConverter converter = getStorageHubToWorkpaceConverter(); + FileModel parentModel = converter.toTreeFileModel(wsFolderParent, null, wsFolderParent.isShared()); + + workspaceLogger.debug("creating the URL..."); + URLItem ext = workspace.createURL(name, description, url, parentId); + workspaceLogger.info("created URL file: " + ext.getName()); + FileModel urlFile = converter.toTreeFileModel(ext, parentModel, wsFolderParent.isShared()); + return urlFile; + + } catch (WorkspaceFolderLocked e1) { + throw new Exception(e1.getMessage()); + + } catch (Exception e) { + workspaceLogger.error("Error on creating the URL in the folder id: "+parentId, e); + throw new Exception(e.getMessage()); + } + } + + /* + * (non-Javadoc) + * + * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# + * markFolderAsPublicForFolderItemId(java.lang.String, boolean) + */ + /** + * Mark folder as public for folder item id. + * + * @param folderId + * the item id + * @param setPublic + * the set public + * @return the public link + * @throws SessionExpiredException + * the session expired exception + * @throws Exception + * the exception + */ + @Override + public PublicLink markFolderAsPublicForFolderItemId(String folderId, boolean setPublic) + throws SessionExpiredException, Exception { + workspaceLogger.info("called markFolderAsPublicForFolderItemId on folder id: " + folderId +" setPublic: "+setPublic); + + if (isSessionExpired()) + throw new SessionExpiredException(); + + try { + org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace = getWorkspaceFromStorageHub(); + String folderLink = null; + try { + + //Changing access to.. if needed + boolean newStatus = workspace.setFolderAsPublic(folderId, setPublic); + workspaceLogger.info("The folder "+folderId+" has the public status at " +newStatus+ " on SHUB"); + //If the folder was published + if (newStatus) { + + workspaceLogger.info("SHUB returned the folder link id: " + folderId); + ApplicationProfileReader apReader = new ApplicationProfileReader("Workspace-Explorer-App", "org.gcube.portlets.user.workspaceexplorerapp.server.WorkspaceExplorerAppServiceImpl"); + ApplicationProfile ap = apReader.readProfileFromInfrastrucure(); + + String encriptedFId = StringEncrypter.getEncrypter().encrypt(folderId); + workspaceLogger.info("Encrypted folder Id: " + encriptedFId); + String encodedFId = StringUtil.base64EncodeStringURLSafe(encriptedFId); + workspaceLogger.info("Encoded in Base 64: " + encodedFId); + workspaceLogger.info("Application profile returning url: " + ap.getUrl()); + folderLink = ap.getUrl() + "?folderId=" + encodedFId; + String shortURL = null; + try { + shortURL = getShortUrl(folderLink); + shortURL = shortURL != null ? shortURL : "not available"; + } catch (Exception e) { + workspaceLogger.warn("Short url error, skipping"); + shortURL = "not available"; + } + PublicLink pubL = new PublicLink(folderLink, shortURL); + workspaceLogger.info("Returning the: "+pubL); + return pubL; + } + workspaceLogger.info("The folder has the public status at "+setPublic+" so returning Public Link as null"); + return null; + + }catch (Exception e) { + workspaceLogger.error("Error on changing access to folder as public: "+setPublic, e); + String error = ConstantsExplorer.SERVER_ERROR + " changing access to folder id: " + folderId; + throw new Exception(error); + } + } catch (Exception e) { + workspaceLogger.error("Error on getting the folder id: "+folderId, e); + throw new Exception(e.getMessage()); + } + + } + + /* + * (non-Javadoc) + * + * @see org.gcube.portlets.user.workspace.client.rpc.GWTWorkspaceService# + * getImagesForFolder(java.lang.String, java.lang.String) + */ + /** + * Gets the images for folder. + * + * @param folderId + * the folder id + * @param currentImageId + * the current image id + * @return the images for folder + * @throws Exception + * the exception + */ + @Override + public List getImagesForFolder(String folderId, String currentImageId) throws Exception { + + if (folderId == null) + return null; + + try { + workspaceLogger.debug("get images for folder id: " + folderId); + org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace = getWorkspaceFromStorageHub(); + org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem wsItem = workspace.getItem(folderId); + + List images = new ArrayList(); + + if (wsItem.isFolder()) { + org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceFolder folder = (org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceFolder) wsItem; + List children = workspace.getChildren(folder.getId()); + +// GWTWorkspaceBuilder builder = getGWTWorkspaceBuilder(); + PortalContextInfo context = WsUtil.getPortalContext(this.getThreadLocalRequest()); + GCubeUser user = PortalContext.getConfiguration().getCurrentUser(this.getThreadLocalRequest()); + + for (org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem workspaceItem : children) { + boolean foundCurrentImage = false; + //IS AN IMAGE? + if (workspaceItem instanceof ImageFileItem) { + try { + ImageFileItem imageFileItem = (ImageFileItem) workspaceItem; + GWTWorkspaceItem image = null; + + image = ObjectStorageHubToWorkpaceMapper.buildGWTWorkspaceImage(imageFileItem, true, false, + context.getCurrGroupId() + "", user.getUserId() + ""); + image.setId(workspaceItem.getId()); + + + if (image != null) { + if (!foundCurrentImage && image.getId().compareTo(currentImageId) == 0) { + workspaceLogger.debug(image.getName() + " is the current displaying image so adding to list as first element"); + images.add(0, image); + foundCurrentImage = true; + } else { + workspaceLogger.debug("Adding thumbnail name to list: " + image.getName()); + images.add(image); + } + } + }catch (Exception e) { + workspaceLogger.warn("Error on managing the file item: "+workspaceItem.getId() +" as an "+ImageFileItem.class.getName()); + } + } + } + } + + if(workspaceLogger.isTraceEnabled()) { + workspaceLogger.trace("Returning list of images for folder: "+folderId); + for (GWTWorkspaceItem gwtWorkspaceItem : images) { + workspaceLogger.trace(gwtWorkspaceItem.toString()); + } + } + + workspaceLogger.info("Returning " + images.size() + " images for folder id: " + folderId); + return images; + } catch (Exception e) { + workspaceLogger.error("Error in server get images by folder id: " + folderId, e); + throw new Exception(e.getMessage()); + } + } + + + /** + * Perform operation on versioned file. + * + * @param fileId + * the file id + * @param olderVersionIDs + * the older version i ds + * @param operation + * the operation + * @return the list + * @throws Exception + * the exception + */ + @Override + public List performOperationOnVersionedFile(String fileId, List olderVersionIDs, + WorkspaceVersioningOperation operation) throws Exception { + + workspaceLogger.info("Called perform operation on Versioned File Id: " + fileId + ", Ids Version: " + olderVersionIDs + " perform operation: " + operation); + if (fileId == null || olderVersionIDs == null || olderVersionIDs.size() == 0) + throw new Exception("Versioned File id or List of versioned file is null"); + + try { + + org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace = getWorkspaceFromStorageHub(); + org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem wsItem = workspace.getItem(fileId); + if (wsItem instanceof org.gcube.common.storagehubwrapper.shared.tohl.items.FileItem) { + //org.gcube.common.storagehubwrapper.shared.tohl.items.FileItem fileItem = (org.gcube.common.storagehubwrapper.shared.tohl.items.FileItem) wsItem; + switch (operation) { + + case DOWNLOAD: { + // IMPLEMENTED CLIENT-SIDE + break; + } + case DELETE_ALL_OLDER_VERSIONS: { + throw new Exception(operation+" must be implemented on SHUB-side"); + // MUST BE OPTIMIZED HL-SIDE + // for (String olderVersionId : olderVersionIDs) { + //// fileItem.removeVersion(olderVersionId); + // throw new Exception(operation+" must be implemented on SHUB-side"); + // workspaceLogger.info("Version " + olderVersionId + " of file id: " + fileId + " removed"); + // } + // return getVersionHistory(fileId); + } + case REFRESH: { + return getVersionHistory(fileId); + } + case DELETE_PERMANENTLY: { + throw new Exception(operation+" must be implemented on SHUB-side"); + // for (String olderVersionId : olderVersionIDs) { + // fileItem.removeVersion(olderVersionId); + // workspaceLogger.info("Version " + olderVersionId + " of file id: " + fileId + " removed"); + // } + // return getVersionHistory(fileId); + } + default: { + break; + } + } + + return getVersionHistory(fileId); + + } else + throw new FileNotVersionedException("Selected file is not versioned"); + + } catch (Exception e) { + + workspaceLogger.error("Error during performing operation on versioned file with id: " + fileId, e); + String error = ConstantsExplorer.SERVER_ERROR + " updating versioning of file id: " + fileId; + throw new Exception(error); + } + } } diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/ImageServlet.java b/src/main/java/org/gcube/portlets/user/workspace/server/ImageServlet.java index cf266d7..fe33f8a 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/ImageServlet.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/ImageServlet.java @@ -3,23 +3,26 @@ */ package org.gcube.portlets.user.workspace.server; +import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import javax.activation.MimetypesFileTypeMap; +import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; -import org.apache.log4j.Logger; import org.gcube.common.portal.PortalContext; import org.gcube.common.storagehubwrapper.server.StorageHubWrapper; import org.gcube.common.storagehubwrapper.server.tohl.Workspace; import org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem; import org.gcube.common.storagehubwrapper.shared.tohl.exceptions.InternalErrorException; import org.gcube.common.storagehubwrapper.shared.tohl.exceptions.ItemNotFoundException; +import org.gcube.common.storagehubwrapper.shared.tohl.impl.StreamDescriptor; import org.gcube.common.storagehubwrapper.shared.tohl.items.FileItem; import org.gcube.common.storagehubwrapper.shared.tohl.items.FileItemType; import org.gcube.common.storagehubwrapper.shared.tohl.items.ImageFileItem; @@ -30,6 +33,8 @@ import org.gcube.portlets.user.workspace.server.util.ThumbnailGenerator; import org.gcube.portlets.user.workspace.server.util.WsUtil; import org.gcube.portlets.user.workspace.shared.SessionExpiredException; import org.gcube.vomanagement.usermanagement.model.GCubeUser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** @@ -44,10 +49,9 @@ public class ImageServlet extends HttpServlet{ * */ private static final int THUMB_MAX_SIZE = 300; - private static final long serialVersionUID = -8423345575690165644L; - protected static Logger logger = Logger.getLogger(ImageServlet.class); + protected static Logger logger = LoggerFactory.getLogger(ImageServlet.class); /** @@ -141,11 +145,23 @@ public class ImageServlet extends HttpServlet{ try{ streamDescr = wa.getThumbnailData(image.getId()); + + /*TODO + * UNCOMMENT THIS IF YOU WANT TO ADD MORE CONTROLS + ReusableInputStream ris = new ReusableInputStream(streamDescr.getStream()); + boolean isAvalidImage = isAnImage(ris, image.getName()); + if(!isAvalidImage) + //CREATING THE THUMBNAIL + streamDescr = createThumbnailForImage(wa, image); + else { + //ASSIGNING THE REUSABLE STREAM + streamDescr = new org.gcube.common.storagehubwrapper.shared.tohl.impl.StreamDescriptor(ris, image.getName(), null, image.getMimeType()); + }*/ + + }catch (Exception e) { - logger.warn("Thumbnail data not available from StorageHub, creating it by the "+ThumbnailGenerator.class.getSimpleName() +" provided by the "+ImageServlet.class.getSimpleName()); - streamDescr = wa.downloadFile(image.getId(), image.getName(), null, null); - InputStream thumbIs = ThumbnailGenerator.generateThumbnail(streamDescr.getStream(), image.getName(), THUMB_MAX_SIZE, THUMB_MAX_SIZE); - streamDescr = new org.gcube.common.storagehubwrapper.shared.tohl.impl.StreamDescriptor(thumbIs, image.getName(), null, image.getMimeType()); + //silent + streamDescr = createThumbnailForImage(wa, image); } mimeType = streamDescr.getMimeType()!=null?streamDescr.getMimeType():image.getMimeType(); size = streamDescr.getSize()==null?0:streamDescr.getSize(); //reading size from byte.lenght @@ -190,8 +206,62 @@ public class ImageServlet extends HttpServlet{ return; } } + + + /** + * Creates the thumbnail for image. + * + * @param wa the wa + * @param image the image + * @return the stream descriptor + * @throws Exception the exception + */ + public static StreamDescriptor createThumbnailForImage(Workspace wa, ImageFileItem image) throws Exception { + logger.warn("Thumbnail data not available from StorageHub, creating it by the "+ThumbnailGenerator.class.getSimpleName() +" provided by the "+ImageServlet.class.getSimpleName()); + ItemStreamDescriptor streamDescr = wa.downloadFile(image.getId(), image.getName(), null, null); + InputStream thumbIs = ThumbnailGenerator.generateThumbnail(streamDescr.getStream(), image.getName(), THUMB_MAX_SIZE, THUMB_MAX_SIZE); + return new org.gcube.common.storagehubwrapper.shared.tohl.impl.StreamDescriptor(thumbIs, image.getName(), null, image.getMimeType()); + } + + + /** + * Checks if is an image. + * + * @param image the image + * @param fileName the file name + * @return true, if is an image + */ + private boolean isAnImage(InputStream image, String fileName) { + + try { + logger.debug("Recognizing image type by "+ImageIO.class.getName()); + // It's an image + //Only BMP, GIF, JPG and PNG are recognized). + ImageIO.read(image); + logger.debug(ImageIO.class.getName()+ " recognized the image: "+fileName+" as an Image"); + return true; + } catch (Exception e) { + //Silent. It's not an image. + } + + try { + logger.debug("Recognizing image type by "+MimetypesFileTypeMap.class.getName()); + File f = ThumbnailGenerator.stream2file(image, fileName, ".tmp"); + String mimetype = new MimetypesFileTypeMap().getContentType(f); + String type = mimetype.split("/")[0]; + boolean isAnImage = type.equals("image")?true:false; + logger.debug(MimetypesFileTypeMap.class.getName()+ " is recognized the filename: "+fileName+" as an Image? "+isAnImage); + return isAnImage; + + }catch (Exception e) { + //Silent. It's not an image. + } + logger.debug("The filename "+fileName+" seems not to be an Image"); + return false; + } + /** * Gets the request type. diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/NoGcubeItemTypeException.java b/src/main/java/org/gcube/portlets/user/workspace/server/NoGcubeItemTypeException.java index cbbf380..143fb21 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/NoGcubeItemTypeException.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/NoGcubeItemTypeException.java @@ -21,6 +21,4 @@ public class NoGcubeItemTypeException extends Exception{ super(message); } - - } diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/ReusableInputStream.java b/src/main/java/org/gcube/portlets/user/workspace/server/ReusableInputStream.java new file mode 100644 index 0000000..b29b281 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/workspace/server/ReusableInputStream.java @@ -0,0 +1,94 @@ +/** + * + */ + +package org.gcube.portlets.user.workspace.server; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; + +/** + * The Class ReusableInputStream. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * + * Jul 30, 2019 + */ +public class ReusableInputStream extends InputStream { + + private InputStream input; + private ByteArrayOutputStream output; + private ByteBuffer buffer; + + /** + * Instantiates a new reusable input stream. + * + * @param input the input + * @throws IOException Signals that an I/O exception has occurred. + */ + public ReusableInputStream(InputStream input) throws IOException { + + this.input = input; + // Note: it's resizable anyway. + this.output = new ByteArrayOutputStream(input.available()); + } + + /* + * (non-Javadoc) + * + * @see java.io.InputStream#read() + */ + @Override + public int read() throws IOException { + + byte[] b = new byte[1]; + read(b, 0, 1); + return b[0]; + } + + /* + * (non-Javadoc) + * + * @see java.io.InputStream#read(byte[]) + */ + @Override + public int read(byte[] bytes) throws IOException { + + return read(bytes, 0, bytes.length); + } + + /* + * (non-Javadoc) + * + * @see java.io.InputStream#read(byte[], int, int) + */ + @Override + public int read(byte[] bytes, int offset, int length) throws IOException { + + if (buffer == null) { + int read = input.read(bytes, offset, length); + if (read <= 0) { + input.close(); + input = null; + buffer = ByteBuffer.wrap(output.toByteArray()); + output = null; + return -1; + } else { + output.write(bytes, offset, read); + return read; + } + } else { + int read = Math.min(length, buffer.remaining()); + if (read <= 0) { + buffer.flip(); + return -1; + } else { + buffer.get(bytes, offset, read); + return read; + } + } + } + // You might want to @Override flush(), close(), etc to delegate to input. +} diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/notifications/NotificationsProducer.java b/src/main/java/org/gcube/portlets/user/workspace/server/notifications/NotificationsProducer.java deleted file mode 100644 index f0753a2..0000000 --- a/src/main/java/org/gcube/portlets/user/workspace/server/notifications/NotificationsProducer.java +++ /dev/null @@ -1,695 +0,0 @@ -/** - * - */ -package org.gcube.portlets.user.workspace.server.notifications; - -import java.util.ArrayList; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -import org.apache.log4j.Logger; -import org.gcube.applicationsupportlayer.social.NotificationsManager; -import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; -import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; -import org.gcube.common.homelibrary.home.workspace.WorkspaceSharedFolder; -import org.gcube.common.scope.impl.ScopeBean; -import org.gcube.portlets.user.workspace.server.util.DifferenceBetweenInfoContactModel; -import org.gcube.portlets.user.workspace.server.util.PortalContextInfo; -import org.gcube.portlets.user.workspace.server.util.UserUtil; -import org.gcube.portlets.user.workspace.server.util.WsUtil; -import org.gcube.portlets.widgets.workspacesharingwidget.shared.InfoContactModel; - -/** - * The Class NotificationsProducer. - * - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - */ -public class NotificationsProducer { - - protected ScopeBean scope; - - protected static Logger logger = Logger.getLogger(NotificationsProducer.class); - - protected NotificationsManager notificationsMng; - protected HttpSession httpSession; - protected String userId; - - - /** - * Instantiates a new notifications producer. - * - * @param httpServletRequest the http servlet request - */ - public NotificationsProducer(HttpServletRequest httpServletRequest) { - PortalContextInfo info = WsUtil.getPortalContext(httpServletRequest); - this.notificationsMng = WsUtil.getNotificationManager(httpServletRequest); - this.userId = info.getUsername(); - } - - /** - * Gets the notifications mng. - * - * @return the notifications mng - */ - public NotificationsManager getNotificationsMng() { - return notificationsMng; - } - - /** - * Sets the notification mng. - * - * @param notificationMng the new notification mng - */ - public void setNotificationMng(NotificationsManager notificationMng) { - this.notificationsMng = notificationMng; - } - - /** - * Runs a new thread to notify the contacts passed in input. - * - * @param listContacts the list contacts - * @param sharedFolder the shared folder - */ - public void notifyFolderSharing(final List listContacts, final WorkspaceSharedFolder sharedFolder) { - - new Thread(){ - @Override - public void run() { - - logger.trace("Send notifies folder sharing is running..."); - - for (InfoContactModel infoContactModel : listContacts) { - try{ - //NOTIFIES ONLY THE USERS THAT ARE DIFFERENT FROM CURRENT USER - if(infoContactModel.getLogin().compareTo(userId)!=0){ - - logger.debug("Sending notification new share folder "+sharedFolder.getName()+" for user "+infoContactModel.getLogin()); - - //DEBUG -// System.out.println("Sending notification new share folder "+sharedFolder.getName()+" for user "+infoContactModel.getLogin()); - - boolean notify = notificationsMng.notifyFolderSharing(infoContactModel.getLogin(), sharedFolder); - - - if(!notify) - logger.error("An error occured when notify user: "+infoContactModel.getLogin()); - } - }catch (Exception e) { - logger.error("An error occured in notifyFolderSharing ", e); -// e.printStackTrace(); - } - } - - logger.trace("notifies share folder is completed"); - } - }.start(); - - - } - - - - /** - * Runs a new thread to notify the updated (add/remove) contacts to sharing. - * - * @param listSharedContact - list of contacts already shared - * @param listSharingContact - list of "new" contacts to share - * @param sharedFolder - the shared folder - */ - public void notifyUpdatedUsersToSharing(final List listSharedContact, final List listSharingContact, final WorkspaceSharedFolder sharedFolder) { - - new Thread() { - @Override - public void run() { - - try{ - - //NEW USER SHARED - DifferenceBetweenInfoContactModel diff = new DifferenceBetweenInfoContactModel(listSharingContact, listSharedContact); - - List listNewContactsShared = diff.getDifferentsContacts(); - - logger.info("list new contacts shared: "+listNewContactsShared.size()); - - if(listNewContactsShared.size()>0){ - - if(listNewContactsShared.size()==1){ //CASE ONLY ONE CONTACS WAS ADDED - - InfoContactModel infoContactModel = listNewContactsShared.get(0); - - for (InfoContactModel contact : listSharedContact) { //NOTIFIES ALREADY SHARED CONTACTS THAT A NEW USER WAS ADDED - - try{ - - logger.trace("Sending notification to user "+contact.getLogin()+", added user "+ infoContactModel.getLogin() +" to share folder "+sharedFolder.getName()); - - //DEBUG - // System.out.println("Sending notification added user "+ infoContactModel.getLogin() +" to share folder "+sharedFolder.getName() + " for user "+contact.getLogin()); - - boolean notify = notificationsMng.notifyFolderAddedUser(contact.getLogin(), sharedFolder, infoContactModel.getLogin()); - - if(!notify) - logger.error("An error occured when notifies user: "+contact.getLogin()); - - }catch (Exception e) { - logger.error("An error occured in notifyFolderAddedUser ", e); -// e.printStackTrace(); - } - } - - List listCts = new ArrayList(); - listCts.add(infoContactModel); - notifyFolderSharing(listCts, sharedFolder); //NOTIFIER NEW USER OF SHARING FOLDER - - }else{ //CASE MORE THEN ONE CONTACT WAS ADDED - - List listLogins = UserUtil.getListLoginByInfoContactModel(listNewContactsShared); - - for (InfoContactModel contact : listSharedContact) { //NOTIFIES ALREADY SHARED CONTACTS THATH A NEW USER WAS ADDED - - try{ - - logger.trace("Sending notification to user "+contact.getLogin()+", added "+listLogins.size()+" users to share folder "+sharedFolder.getName()); - - //DEBUG - // System.out.println("Sending notification added user "+ infoContactModel.getLogin() +" to share folder "+sharedFolder.getName() + " for user "+contact.getLogin()); - - boolean notify = notificationsMng.notifyFolderAddedUsers(contact.getLogin(), sharedFolder, listLogins); - - if(!notify) - logger.error("An error occured when notifies user: "+contact.getLogin()); - - }catch (Exception e) { - logger.error("An error occured in notifyFolderAddedUser ", e); -// e.printStackTrace(); - } - } - - notifyFolderSharing(listNewContactsShared, sharedFolder); //NOTIFIER NEW USER OF SHARING FOLDER - - } - } - - //USER REMOVED FROM SHARE - DifferenceBetweenInfoContactModel diff2 = new DifferenceBetweenInfoContactModel(listSharedContact, listSharingContact); - - List listRemovedUsersFromShare = diff2.getDifferentsContacts(); - - logger.info("list removed contacts from share: "+listRemovedUsersFromShare.size()); - - if(listRemovedUsersFromShare.size()>0){ - - for (InfoContactModel contact : listRemovedUsersFromShare) - notifyFolderRemovedUser(contact, sharedFolder); - } - - }catch (Exception e) { - logger.error("An error occured in notifyAddedUserToSharing ", e); -// e.printStackTrace(); - } - } - - }.start(); - - } - - - /** - * Runs a new thread to notify the contacts passed in input. - * - * @param listContacts the list contacts - * @param unShareFolderId the un share folder id - * @param unSharedFolderName the un shared folder name - */ - public void notifyFolderUnSharing(final List listContacts, final String unShareFolderId, final String unSharedFolderName) { - - - new Thread() { - @Override - public void run() { - -// printContacts(listContacts); - logger.trace("Send notifies folder un share is running..."); - - for (InfoContactModel infoContactModel : listContacts) { - try{ - - //NOTIFIES ONLY THE USERS THAT ARE DIFFERENT FROM CURRENT USER - if(infoContactModel.getLogin().compareTo(userId)!=0){ - - logger.trace("Sending notification to user "+infoContactModel.getLogin() +" unshare folder "+unSharedFolderName); - - //DEBUG -// System.out.println("Sending notification to user "+infoContactModel.getLogin() +" un shared folder "+unSharedFolder.getName()); -// boolean notify = notificationsMng.notifyFolderRemovedUser(infoContactModel.getLogin(), (WorkspaceSharedFolder) unSharedFolder); - - boolean notify = notificationsMng.notifyFolderUnsharing(infoContactModel.getLogin(), unShareFolderId, unSharedFolderName); - if(!notify) - logger.error("An error occured when notifies user: "+infoContactModel.getLogin()); - } - }catch (Exception e) { - logger.error("An error occured in notifyFolderUnSharing ", e); -// e.printStackTrace(); - } - } - - logger.trace("notifies of un share notifications is completed"); - } - - }.start(); - - } - - /** - * Notify folder removed user. - * - * @param userUnShared the user un shared - * @param shareFolder the share folder - */ - public void notifyFolderRemovedUser(final InfoContactModel userUnShared, final WorkspaceSharedFolder shareFolder) { - - new Thread() { - @Override - public void run() { - - logger.trace("Send notifies removed user from shared folder is running..."); - try{ - //NOTIFIES ONLY THE USERS THAT ARE DIFFERENT FROM CURRENT USER - if(userUnShared.getLogin().compareTo(userId)!=0){ - - logger.debug("Sending notification to user "+userUnShared.getLogin() +" unshared from folder "+shareFolder.getName()); - boolean notify = notificationsMng.notifyFolderRemovedUser(userUnShared.getLogin(), shareFolder); - - if(!notify) - logger.error("An error occured when notifies user: "+userUnShared.getLogin()); - } - - }catch (Exception e) { - logger.error("An error occured in notifyFolderRemovedUser ", e); - } - - logger.trace("notifies of un unshare user is completed"); - } - - }.start(); - - } - - - /** - * Runs a new thread to notify the contacts passed in input. - * - * @param listContacts the list contacts - * @param workspaceItem the workspace item - * @param sharedFolder the shared folder - */ - public void notifyAddedItemToSharing(final List listContacts, final WorkspaceItem workspaceItem, final WorkspaceSharedFolder sharedFolder) { - - new Thread() { - @Override - public void run() { - -// printContacts(listContacts); - logger.trace("Send notifies added item in sharedfolder is running..."); - - //DEBUG - System.out.println("Send notifies added item in sharedfolder is running..."); - - for (InfoContactModel infoContactModel : listContacts) { - try{ - - //NOTIFIES ONLY THE USERS THAT ARE DIFFERENT FROM CURRENT USER - if(infoContactModel.getLogin().compareTo(userId)!=0){ - - logger.info("Sending notification to user "+infoContactModel.getLogin() +" added item [id: "+workspaceItem.getId() +"] name: "+workspaceItem.getName()+" in shared folder "+sharedFolder.getName()); - - //DEBUG -// System.out.println("Send notify folder un share user "+infoContactModel.getLogin()); - - boolean notify = notificationsMng.notifyAddedItem(infoContactModel.getLogin(), workspaceItem, sharedFolder); - - if(!notify){ - logger.error("An error occured when notify user: "+infoContactModel.getLogin()); - //DEBUG -// System.out.println("An error occured when notify user: "+infoContactModel.getLogin()); - } - } - }catch (Exception e) { - logger.error("An error occured in notifyAddedItemToSharing ", e); -// e.printStackTrace(); - } - } - - logger.trace("notifies of added item in shared folder is completed"); - - //DEBUG -// System.out.println("notifies of added item in shared folder is completed"); - } - - }.start(); - } - - - /** - * Runs a new thread to notify the contacts passed in input. - * - * @param listContacts the list contacts - * @param workspaceItem the workspace item - * @param sharedFolder the shared folder - */ - public void notifyUpdatedItemToSharing(final List listContacts, final WorkspaceItem workspaceItem, final WorkspaceSharedFolder sharedFolder) { - - new Thread() { - @Override - public void run() { - -// printContacts(listContacts); - logger.trace("Send notifies updated item in shared folder is running..."); - - //DEBUG -// System.out.println("Send notifies updated item in shared folder is running..."); - - for (InfoContactModel infoContactModel : listContacts) { - try{ - - //NOTIFIES ONLY THE USERS THAT ARE DIFFERENT FROM CURRENT USER - if(infoContactModel.getLogin().compareTo(userId)!=0){ - - logger.trace("Sending notification to user "+infoContactModel.getLogin() +" updated item "+workspaceItem.getName()+" in shared folder "+sharedFolder.getName()); - - //DEBUG -// System.out.println("Sending notification to user "+infoContactModel.getLogin() +" updated item "+workspaceItem.getName()+" in shared folder "+sharedFolder.getName()); - - //DEBUG -// System.out.println("Send notify folder un share user "+infoContactModel.getLogin()); - - boolean notify = notificationsMng.notifyUpdatedItem(infoContactModel.getLogin(), workspaceItem, sharedFolder); - - if(!notify){ - logger.error("An error updated when notify user: "+infoContactModel.getLogin()); - //DEBUG -// System.out.println("An error updated when notify user: "+infoContactModel.getLogin()); - } - } - }catch (Exception e) { - logger.error("An error updated in notifyAddedItemToSharing ", e); - e.printStackTrace(); - } - } - - logger.trace("notifies of updated item in shared folder is completed"); - - //DEBUG -// System.out.println("notifies of updated item in shared folder is completed"); - } - - }.start(); - } - - - - - - /** - * Runs a new thread to notify the contacts passed in input. - * - * @param listContacts the list contacts - * @param workspaceItem the workspace item - * @param sharedFolder the shared folder - */ - public void notifyMovedItemToSharing(final List listContacts, final WorkspaceItem workspaceItem, final WorkspaceSharedFolder sharedFolder) { - - - new Thread() { - @Override - public void run() { - - logger.trace("Sending notification remove item in shared folder is running..."); -// printContacts(listContacts); - - try { - - if(NotificationsUtil.checkIsRootFolderShared(workspaceItem.getId(), sharedFolder.getId())){ - logger.trace("Notification isn't sent because the event is on root shared folder"); - return; - } - - } catch (InternalErrorException e1) { - logger.error("An error occurred in checkIsRootFolderShared ", e1); - return; - } - - logger.trace("Sending notification moved item in shared folder is running..."); - -// System.out.println("Sending notification moved item in shared folder is running..."); - - for (InfoContactModel infoContactModel : listContacts) { - try{ - - //NOTIFIES ONLY THE USERS THAT ARE DIFFERENT FROM CURRENT USER - if(infoContactModel.getLogin().compareTo(userId)!=0){ - - logger.trace("Sending notification to user "+infoContactModel.getLogin() +" moved item "+workspaceItem.getName()+" in shared folder "+sharedFolder.getName()); - - //DEBUG -// System.out.println("Sending notification to user "+infoContactModel.getLogin() +" moved item "+workspaceItem.getName()+" in shared folder "+sharedFolder.getName()); - - boolean notify = notificationsMng.notifyMovedItem(infoContactModel.getLogin(), workspaceItem, sharedFolder); - - if(!notify){ - logger.error("An error occured when notify user: "+infoContactModel.getLogin()); - - //DEBUG -// System.out.println("An error occured when notify user: "+infoContactModel.getLogin()); - } - } - }catch (Exception e) { - logger.error("An error occurred in notifyMovedItemToSharing ", e); - e.printStackTrace(); - } - } - - logger.trace("notifies of moved item in shared folder is completed"); - - //DEBUG -// System.out.println("notifies of moved item in shared folder is completed"); - } - - - - }.start(); - - } - - - /** - * Runs a new thread to notify the contacts passed in input. - * - * @param listContacts the list contacts - * @param itemName the item name - * @param sharedFolder the shared folder - */ - public void notifyRemovedItemToSharing(final List listContacts, final String itemName, final WorkspaceSharedFolder sharedFolder) { - - - new Thread() { - @Override - public void run() { - - logger.trace("Sending notification remove item in shared folder is running..."); -// printContacts(listContacts); - - if(itemName==null || itemName.isEmpty()){ - logger.trace("Notification isn't sent - itemName is null or empty"); - return; - } - - if(sharedFolder==null){ - logger.trace("Notification isn't sent - sharedFolder is null"); - } - - logger.trace("Sending notification removed item in shared folder is running..."); - -// System.out.println("Sending notification removed item in shared folder is running..."); - - for (InfoContactModel infoContactModel : listContacts) { - try{ - - //NOTIFIES ONLY THE USERS THAT ARE DIFFERENT FROM CURRENT USER - if(infoContactModel.getLogin().compareTo(userId)!=0){ - - logger.trace("Sending notification to user "+infoContactModel.getLogin() +" removed item "+itemName+" in shared folder "+sharedFolder.getName()); - - //DEBUG -// System.out.println("Sending notification to user "+infoContactModel.getLogin() +" removed item "+itemName+" in shared folder "+sharedFolder.getName()); - - boolean notify = notificationsMng.notifyRemovedItem(infoContactModel.getLogin(), itemName, sharedFolder); - - if(!notify){ - logger.error("An error occured when notify user: "+infoContactModel.getLogin()); - - //DEBUG -// System.out.println("An error occured when notify user: "+infoContactModel.getLogin()); - } - } - }catch (Exception e) { - logger.error("An error occurred in notifyRemovedItemToSharing ", e); -// e.printStackTrace(); - } - } - - logger.trace("notifies of moved item in shared folder is completed"); - - //DEBUG -// System.out.println("notifies of moved item in shared folder is completed"); - } - }.start(); - - } - - /** - * Runs a new thread to notify the contacts passed in input. - * - * @param listContacts the list contacts - * @param folderNameDeleted the folder name deleted - */ - public void notifySharedFolderDeleted(final List listContacts, final String folderNameDeleted) { - - - new Thread() { - @Override - public void run() { - -// printContacts(listContacts); - logger.trace("Send notifies shared folder deleted is running..."); - - for (InfoContactModel infoContactModel : listContacts) { - try{ - - //NOTIFIES ONLY THE USERS THAT ARE DIFFERENT FROM CURRENT USER - if(infoContactModel.getLogin().compareTo(userId)!=0){ - - logger.trace("Sending notification to user "+infoContactModel.getLogin() +" deleted shared folder "+folderNameDeleted); - - //DEBUG - System.out.println("Sending notification to user "+infoContactModel.getLogin() +" deleted shared folder "+folderNameDeleted); - - //TODO -// boolean notify = notificationsMng. - -// if(!notify) -// logger.error("An error occured when notifies user: "+infoContactModel.getLogin()); - } - }catch (Exception e) { - logger.error("An error occured in notifySharedFolderDeleted ", e); -// e.printStackTrace(); - } - } - - logger.trace("notifies of deleted shared foder is completed"); - } - - }.start(); - - } - - - /** - * Runs a new thread to notify the contacts passed in input. - * - * @param userToNotify the user to notify - * @param sharedFolder the shared folder - */ - public void notifyAdministratorUpgrade(final InfoContactModel userToNotify, final WorkspaceSharedFolder sharedFolder){ - - new Thread() { - @Override - public void run() { - -// printContacts(listContacts); - logger.trace("Send notifies administrator upgrade is running..."); - if(userToNotify==null || userToNotify.getLogin()==null){ - logger.warn("Notification abort user to notify is null..."); - return; - } - - if(sharedFolder==null){ - logger.warn("Notification abort sharedFolder to notify is null..."); - return; - } - try{ - String login = userToNotify.getLogin(); - logger.trace("Send notifies administrator upgrade for login: "+login); - - boolean notify = notificationsMng.notifyAdministratorUpgrade(login, sharedFolder); - logger.trace("Notification sent correctly? "+notify); - }catch (Exception e) { - logger.error("An error occured in notifyAdministratorUpgrade ", e); - } - - - logger.trace("notifies of administrator upgrade completed"); - } - - }.start(); - - } - - /** - * Runs a new thread to notify the contacts passed in input. - * - * @param userToNotify the user to notify - * @param sharedFolder the shared folder - */ - public void notifyAdministratorDowngrade(final InfoContactModel userToNotify, final WorkspaceSharedFolder sharedFolder){ - - new Thread() { - @Override - public void run() { - -// printContacts(listContacts); - logger.trace("Send notifies administrator Downgrade is running..."); - if(userToNotify==null || userToNotify.getLogin()==null){ - logger.warn("Notification abort user to notify is null..."); - return; - } - - if(sharedFolder==null){ - logger.warn("Notification abort sharedFolder to notify is null..."); - return; - } - try{ - String login = userToNotify.getLogin(); - logger.trace("Send notifies administrator Downgrade for login: "+login); - - boolean notify = notificationsMng.notifyAdministratorDowngrade(login, sharedFolder); - logger.trace("Notification sent correctly? "+notify); - }catch (Exception e) { - logger.error("An error occured in notifyAdministratorDowngrade ", e); - } - - - logger.trace("notifies of administrator Downgrade completed"); - } - - }.start(); - - } - - //DEBUG - /** - * Prints the contacts. - * - * @param listContacts the list contacts - */ - private void printContacts(List listContacts){ - - System.out.println("Print contacts"); - for (InfoContactModel infoContactModel : listContacts) { - System.out.println(infoContactModel); - } - System.out.println("End print contacts"); - } -} diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/notifications/NotificationsUtil.java b/src/main/java/org/gcube/portlets/user/workspace/server/notifications/NotificationsUtil.java deleted file mode 100644 index 64355b1..0000000 --- a/src/main/java/org/gcube/portlets/user/workspace/server/notifications/NotificationsUtil.java +++ /dev/null @@ -1,252 +0,0 @@ -/** - * - */ -package org.gcube.portlets.user.workspace.server.notifications; - -import java.util.ArrayList; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -import org.apache.log4j.Logger; -import org.gcube.common.homelibary.model.items.type.WorkspaceItemType; -import org.gcube.common.homelibrary.home.workspace.Workspace; -import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; -import org.gcube.common.homelibrary.home.workspace.WorkspaceSharedFolder; -import org.gcube.portlets.user.workspace.server.GWTWorkspaceBuilder; -import org.gcube.portlets.user.workspace.server.util.WsUtil; -import org.gcube.portlets.widgets.workspacesharingwidget.shared.InfoContactModel; - -/** - * The Class NotificationsUtil. - * - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * May 27, 2013 - */ -public class NotificationsUtil { - - - protected static Logger logger = Logger.getLogger(NotificationsUtil.class); - - /** - * Send a notification if an item is added or updated to sharing folder. - * - * @param request the request - * @param httpSession the http session - * @param sourceItem the source item - * @param sourceSharedId the source shared id - * @param folderDestinationItem the folder destination item - * @param isOverwrite the is overwrite - */ - public static void checkSendNotifyChangedItemToShare(HttpServletRequest request, HttpSession httpSession, final WorkspaceItem sourceItem, final String sourceSharedId, final WorkspaceItem folderDestinationItem, boolean isOverwrite) { - - logger.trace("checkSendNotifyAddItemToShare"); - - if(folderDestinationItem!=null){ - - try{ - if(folderDestinationItem.isShared()){ //Notify Added Item To Sharing? - - logger.trace("checkNotifyAddItemToShare source item: "+sourceItem.getName()+" sourceSharedId: "+sourceSharedId + " folder destination: "+folderDestinationItem.getName() + " folder destination shared folder id: "+folderDestinationItem.getIdSharedFolder()); - //share condition is true if source shared folder is not null - boolean shareChangeCondition = sourceSharedId==null?false:true; - //System.out.println("shareChangeCondition add item: "+ shareChangeCondition); - logger.trace("shareChangeCondition add item: "+shareChangeCondition); - - //if shareChangeCondition is true.. notifies added item to sharing - if(shareChangeCondition){ - - Workspace workspace = WsUtil.getWorkspace(request); - List listContacts = getListUsersSharedByFolderSharedId(workspace, folderDestinationItem.getIdSharedFolder()); - WorkspaceItem destinationSharedFolder = workspace.getItem(folderDestinationItem.getIdSharedFolder()); - NotificationsProducer np = new NotificationsProducer(request); - - if(destinationSharedFolder instanceof WorkspaceSharedFolder){ - - //SWITCH BEETWEEN ADDED OR UPDATED - if(!isOverwrite) - np.notifyAddedItemToSharing(listContacts, sourceItem, (WorkspaceSharedFolder) destinationSharedFolder); - else - np.notifyUpdatedItemToSharing(listContacts, sourceItem, (WorkspaceSharedFolder) destinationSharedFolder); - - logger.trace("The notifies was sent correctly"); - }else - logger.trace("The notifies doesn't sent because "+destinationSharedFolder+ " is not instance of WorkspaceSharedFolder"); -// np.notifyAddedItemToSharing(listContacts, (WorkspaceFolder) folderDestinationItem); - } - } - else - logger.trace("folder destination is not shared"); - - }catch (Exception e) { - logger.error("An error occurred in checkSendNotifyAddItemToShare ",e); - } - }else - logger.warn("The notifies is failure in checkSendNotifyAddItemToShare because folder destination item is null"); - } - - - /** - * Gets the list users shared by folder shared id. - * - * @param workspace the workspace - * @param idSharedFolder the id shared folder - * @return the list users shared by folder shared id - * @throws Exception the exception - */ - public static List getListUsersSharedByFolderSharedId(Workspace workspace, String idSharedFolder) throws Exception { - - logger.trace("getListUsersSharedByFolderSharedId "+ idSharedFolder); - - try { - - WorkspaceItem wsItem = workspace.getItem(idSharedFolder); - - if(isASharedFolder(wsItem)){ - - WorkspaceSharedFolder wsFolder = (WorkspaceSharedFolder) wsItem; - GWTWorkspaceBuilder builder = new GWTWorkspaceBuilder(); - List listPortalLogin = wsFolder.getUsers(); - logger.trace("getListUserSharedByFolderSharedId return "+ listPortalLogin.size() + " user"); - return builder.buildGxtInfoContactsFromPortalLogins(listPortalLogin); - } - else{ - logger.trace("the item with id: "+idSharedFolder+ " is not "+WorkspaceItemType.SHARED_FOLDER); - - //DEBUG - //System.out.println("the item with id: "+folderSharedId+ " is not "+WorkspaceItemType.SHARED_FOLDER); - } - return new ArrayList(); - - } catch (Exception e) { - logger.error("Error in getListUserSharedByItemId ", e); - throw new Exception(e.getMessage()); - } - } - - - /** - * Check send notify remove item to share. - * - * @param request the request - * @param sourceItemIsShared the source item is shared - * @param oldItemName the old item name - * @param oldItemId the old item id - * @param sourceFolderSharedId the source folder shared id - */ - public static void checkSendNotifyRemoveItemToShare(HttpServletRequest request, final boolean sourceItemIsShared, final String oldItemName, String oldItemId, final String sourceFolderSharedId) { - - logger.trace("checkNotifyRemoveItemToShare:"); - - try{ - - if(!sourceItemIsShared){ - logger.trace("checkSendNotifyRemoveItemToShare returned, source item is not shared"); - return; - } - - String idSharedFolder = sourceFolderSharedId!=null?sourceFolderSharedId:""; - boolean isRootFolderShared = checkIsRootFolderShared(oldItemId, idSharedFolder); - logger.trace("isRootFolderShared is: "+ isRootFolderShared); - /* - if(isRootFolderShared){ - logger.trace("Notification doesn't sent because the event is on root shared folder"); - return; - }*/ - boolean isSharedFolder = isASharedFolderForId(request,idSharedFolder); - if(isSharedFolder){ - - logger.trace("idSharedFolder is: "+ idSharedFolder +" is shared folder: "+isSharedFolder); - Workspace workspace = WsUtil.getWorkspace(request); - //get contacts - List listContacts = getListUsersSharedByFolderSharedId(workspace, idSharedFolder); - WorkspaceItem sourceSharedFolder = workspace.getItem(idSharedFolder); - //System.out.println(" name sourceSharedFolder: "+ sourceSharedFolder.getName()); - NotificationsProducer np = new NotificationsProducer(request); - - //Notify Removed Item To Sharing? - if(!isRootFolderShared){ - if(sourceSharedFolder instanceof WorkspaceSharedFolder){ - np.notifyRemovedItemToSharing(listContacts, oldItemName, (WorkspaceSharedFolder) sourceSharedFolder); - logger.trace("The notifies was sent correctly"); - } - else - logger.trace("The notifies doesn't sent because "+sourceSharedFolder+ " is not instance of WorkspaceSharedFolder"); - - }else{ - //Case removed shared folder - np.notifySharedFolderDeleted(listContacts, oldItemName); - } - } - - }catch (Exception e) { - logger.error("An error occurred in checkSendNotifyRemoveItemToShare ",e); - } - - } - - /** - * Checks if is a shared folder. - * - * @param wsItem the ws item - * @return true, if is a shared folder - */ - public static boolean isASharedFolder(WorkspaceItem wsItem){ - if(wsItem!=null) - return wsItem.getType().equals(WorkspaceItemType.SHARED_FOLDER); - return false; - } - - - /** - * Checks if is a shared folder for id. - * - * @param request the request - * @param itemId the item id - * @return true, if is a shared folder for id - */ - public static boolean isASharedFolderForId(HttpServletRequest request, String itemId){ - - if(itemId==null || itemId.isEmpty()) - return false; - - try { - - Workspace workspace = WsUtil.getWorkspace(request); - - WorkspaceItem wsItem = workspace.getItem(itemId); - - if(wsItem!=null) - return wsItem.getType().equals(WorkspaceItemType.SHARED_FOLDER); - return false; - - } catch (Exception e) { - logger.error("An errror occurred in isASharedFolderForId", e); - return false; - } - } - - - /** - * Check is root folder shared. - * - * @param itemId the item id - * @param rootFolderSharedId the root folder shared id - * @return true, if successful - */ - public static boolean checkIsRootFolderShared(String itemId, String rootFolderSharedId) { - - logger.trace("checkIsRootFolderShared between [itemid: "+itemId +", rootFolderSharedId: "+rootFolderSharedId+"]"); - if(itemId==null) - return false; - - if(rootFolderSharedId==null) - return false; - - if(itemId.compareTo(rootFolderSharedId)==0) - return true; - - return false; - } -} diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/notifications/tostoragehub/NotificationMapperToStorageHub.java b/src/main/java/org/gcube/portlets/user/workspace/server/notifications/tostoragehub/NotificationMapperToStorageHub.java index b9379b4..f11efbe 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/notifications/tostoragehub/NotificationMapperToStorageHub.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/notifications/tostoragehub/NotificationMapperToStorageHub.java @@ -3,25 +3,22 @@ */ package org.gcube.portlets.user.workspace.server.notifications.tostoragehub; - -import org.apache.log4j.Logger; import org.gcube.applicationsupportlayer.social.shared.SocialFileItem; import org.gcube.applicationsupportlayer.social.shared.SocialSharedFolder; import org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem; import org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceSharedFolder; - - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * The Class NotificationMapper. * * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * Oct 2, 2018 + * Oct 2, 2018 */ public class NotificationMapperToStorageHub { - protected static Logger logger = Logger.getLogger(NotificationMapperToStorageHub.class); - + protected static Logger logger = LoggerFactory.getLogger(NotificationMapperToStorageHub.class); /** * To social shared folder. @@ -29,39 +26,33 @@ public class NotificationMapperToStorageHub { * @param sharedFolder the shared folder * @return the social shared folder */ - public static SocialSharedFolder toSocialSharedFolder(WorkspaceSharedFolder sharedFolder){ + public static SocialSharedFolder toSocialSharedFolder(WorkspaceSharedFolder sharedFolder) { - return new SocialSharedFolder(sharedFolder.getId(), - sharedFolder.getName(), - sharedFolder.getTitle(), - sharedFolder.getName(), - sharedFolder.getPath(), - sharedFolder.getParentId(), - sharedFolder.isVreFolder()); + return new SocialSharedFolder(sharedFolder.getId(), sharedFolder.getName(), sharedFolder.getTitle(), + sharedFolder.getName(), sharedFolder.getPath(), sharedFolder.getParentId(), sharedFolder.isVreFolder()); } - /** * To social item. * * @param workspace the workspace - * @param item the item + * @param item the item * @return the social file item */ - public static SocialFileItem toSocialItem(org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace, WorkspaceItem item){ + public static SocialFileItem toSocialItem(org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace, + WorkspaceItem item) { WorkspaceItem theParentFolder = null; try { theParentFolder = workspace.getItem(item.getParentId()); - } - catch (Exception e) { - logger.warn("Impossible the item using the parent id: "+item.getParentId()); + } catch (Exception e) { + logger.warn("Impossible the item using the parent id: " + item.getParentId()); } // SocialSharedFolder parent = null; - if(theParentFolder!=null && theParentFolder instanceof WorkspaceSharedFolder) + if (theParentFolder != null && theParentFolder instanceof WorkspaceSharedFolder) parent = toSocialSharedFolder((WorkspaceSharedFolder) theParentFolder); // - return new SocialFileItem(item.getId(), item.getName(), item.getTitle(), item.getPath(), parent); + return new SocialFileItem(item.getId(), item.getName(), item.getTitle(), item.getPath(), parent); } } diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/notifications/tostoragehub/NotificationStorageHubUtil.java b/src/main/java/org/gcube/portlets/user/workspace/server/notifications/tostoragehub/NotificationStorageHubUtil.java index 0b8545f..d2f6883 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/notifications/tostoragehub/NotificationStorageHubUtil.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/notifications/tostoragehub/NotificationStorageHubUtil.java @@ -6,42 +6,46 @@ package org.gcube.portlets.user.workspace.server.notifications.tostoragehub; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; +import javax.servlet.http.HttpServletRequest; + import org.gcube.common.storagehub.model.types.WorkspaceItemType; import org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceFolder; import org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem; import org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceSharedFolder; -import org.gcube.portlets.user.workspace.server.GWTWorkspaceBuilder; +import org.gcube.portlets.user.workspace.server.tostoragehub.StorageHubToWorkpaceConverter; import org.gcube.portlets.user.workspace.server.util.WsUtil; import org.gcube.portlets.widgets.workspacesharingwidget.shared.InfoContactModel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** - * The Class NotificationFromStorageHub. + * The Class NotificationStorageHubUtil. * - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * Oct 2, 2018 + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * + * Jul 31, 2019 */ public class NotificationStorageHubUtil { - private static Logger logger = Logger.getLogger(NotificationStorageHubUtil.class); - + private static Logger logger = LoggerFactory.getLogger(NotificationStorageHubUtil.class); + /** * Check notify add item to share. * * @param workspaceItem the workspace item - * @param sourceRootSharedFolderId the source shared id + * @param sourceRootSharedFolderId the source root shared folder id * @param parentFolderItem the parent folder item * @param workspace the workspace - * @param np the NotificationsProducerToStorageHub + * @param np the np */ public static void checkNotifyAddItemToShare(final WorkspaceItem workspaceItem, final String sourceRootSharedFolderId, final WorkspaceFolder parentFolderItem, org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace, NotificationsProducerToStorageHub np) { - logger.trace("checkNotifyAddItemToShare"); - if(parentFolderItem!=null){ - + + logger.debug("Sending notification added item to share is running..."); try{ //if folder destination is shared folder if(parentFolderItem.isShared()){ //Notify Added Item To Sharing? @@ -97,7 +101,8 @@ public class NotificationStorageHubUtil { org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceFolder folderDestination, org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace, NotificationsProducerToStorageHub np) { try{ - + logger.debug("Sending notification moved item from share is running..."); + String rootDestSharedFolderId = null; WorkspaceItem rootDestSharedFolder = null; @@ -148,7 +153,7 @@ public class NotificationStorageHubUtil { */ public static List getListUserSharedByFolderSharedId(WorkspaceItem rootSharedFolder, org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace) throws Exception{ - logger.debug("getListUserSharedByFolderSharedId "+ rootSharedFolder); + logger.debug("called getListUserSharedByFolderSharedId on: "+ rootSharedFolder); try { @@ -158,9 +163,14 @@ public class NotificationStorageHubUtil { logger.debug("StorageHub returned "+ listPortalLogin.size() + " user/s"); if(!WsUtil.isWithinPortal()) - return GWTWorkspaceBuilder.buildGxtInfoContactFromPortalLoginTestMode(listPortalLogin); + return StorageHubToWorkpaceConverter.buildGxtInfoContactFromPortalLoginTestMode(listPortalLogin); - return GWTWorkspaceBuilder.buildGxtInfoContactsFromPortalLogins(listPortalLogin); + List listContacts = new ArrayList(listPortalLogin.size()); + for (String login : listPortalLogin) { + listContacts.add(StorageHubToWorkpaceConverter.buildGxtInfoContactFromPortalLogin(login)); + } + + return listContacts; } else logger.debug("the item with id: "+rootSharedFolder.getId()+ " is not "+WorkspaceItemType.SHARED_FOLDER); @@ -172,6 +182,94 @@ public class NotificationStorageHubUtil { throw new Exception(e.getMessage()); } } + + + + /** + * Check send notify removed item from share. + * + * @param request the request + * @param sourceItemIsShared the source item is shared + * @param oldItemName the old item name + * @param oldItemId the old item id + * @param sourceFolderSharedId the source folder shared id + * @param workspace the workspace + * @param np the np + */ + public static void checkSendNotifyRemovedItemFromShare(HttpServletRequest request, final boolean sourceItemIsShared, final String oldItemName, String oldItemId, final String sourceFolderSharedId, org.gcube.common.storagehubwrapper.server.tohl.Workspace workspace, NotificationsProducerToStorageHub np) { + + try{ + logger.debug("Sending notification removed item from share is running..."); + if(!sourceItemIsShared){ + logger.trace("checkSendNotifyRemoveItemToShare returned, source item is not shared"); + return; + } + + String idSharedFolder = sourceFolderSharedId!=null?sourceFolderSharedId:""; + boolean isRootFolderShared = checkIsRootFolderShared(oldItemId, idSharedFolder); + logger.trace("isRootFolderShared is: "+ isRootFolderShared); + + WorkspaceItem sourceSharedFolder = workspace.getItem(idSharedFolder); + boolean isSharedFolder = isASharedFolder(sourceSharedFolder); + if(isSharedFolder){ + + logger.trace("idSharedFolder is: "+ idSharedFolder +" is shared folder: "+isSharedFolder); + //get contacts + List listContacts = getListUserSharedByFolderSharedId(sourceSharedFolder, workspace); + + //Notify Removed Item To Sharing? + if(!isRootFolderShared){ + if(sourceSharedFolder instanceof org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceSharedFolder){ + np.notifyRemovedItemToSharing(listContacts, oldItemName, (org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceSharedFolder) sourceSharedFolder); + logger.debug("Notification was sent correctly"); + } + else + logger.debug("The notifies doesn't sent because "+sourceSharedFolder+ " is not instance of WorkspaceSharedFolder"); + + }else{ + //Case removed shared folder + np.notifySharedFolderDeleted(listContacts, oldItemName); + } + } + + }catch (Exception e) { + logger.error("An error occurred in checkSendNotifyRemoveItemToShare ",e); + } + + } + + + /** + * Notify shared folder deleted. + * + * @param listContacts the list contacts + * @param folderNameDeleted the folder name deleted + * @param userId the user id + */ + public void notifySharedFolderDeleted(final List listContacts, final String folderNameDeleted, final String userId) { + + + new Thread() { + @Override + public void run() { + logger.trace("Send notification shared folder deleted is running..."); + for (InfoContactModel infoContactModel : listContacts) { + try{ + //NOTIFIES ONLY THE USERS THAT ARE DIFFERENT FROM CURRENT USER + if(infoContactModel.getLogin().compareTo(userId)!=0){ + logger.debug("Notification to user "+infoContactModel.getLogin() +" deleted shared folder "+folderNameDeleted +" HAS BEEN REMOVED!"); + } + }catch (Exception e) { + logger.error("An error occured in notifySharedFolderDeleted ", e); + } + } + logger.trace("notifies of deleted shared foder is completed"); + } + + }.start(); + + } + /** * Checks if is a shared folder. diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/notifications/tostoragehub/NotificationsProducerToStorageHub.java b/src/main/java/org/gcube/portlets/user/workspace/server/notifications/tostoragehub/NotificationsProducerToStorageHub.java index a78b2c5..288ba67 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/notifications/tostoragehub/NotificationsProducerToStorageHub.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/notifications/tostoragehub/NotificationsProducerToStorageHub.java @@ -8,14 +8,17 @@ import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; -import org.apache.log4j.Logger; import org.gcube.applicationsupportlayer.social.NotificationsManager; +import org.gcube.applicationsupportlayer.social.shared.SocialFileItem; +import org.gcube.applicationsupportlayer.social.shared.SocialSharedFolder; import org.gcube.common.scope.impl.ScopeBean; import org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem; import org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceSharedFolder; import org.gcube.portlets.user.workspace.server.util.PortalContextInfo; import org.gcube.portlets.user.workspace.server.util.WsUtil; import org.gcube.portlets.widgets.workspacesharingwidget.shared.InfoContactModel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** @@ -28,7 +31,7 @@ public class NotificationsProducerToStorageHub { protected ScopeBean scope; - protected static Logger logger = Logger.getLogger(NotificationsProducerToStorageHub.class); + protected static Logger logger = LoggerFactory.getLogger(NotificationsProducerToStorageHub.class); protected NotificationsManager notificationsMng; protected HttpSession httpSession; @@ -71,7 +74,10 @@ public class NotificationsProducerToStorageHub { if(infoContactModel.getLogin().compareTo(userId)!=0){ logger.debug("Sending notification to user "+infoContactModel.getLogin() +" added item [id: "+workspaceItem.getId() +"] name: "+workspaceItem.getName()+" in shared folder "+sharedFolder.getName()); - boolean notify = notificationsMng.notifyAddedItem(infoContactModel.getLogin(), NotificationMapperToStorageHub.toSocialItem(workspace, workspaceItem), NotificationMapperToStorageHub.toSocialSharedFolder(sharedFolder)); + //boolean notify = notificationsMng.notifyAddedItem(infoContactModel.getLogin(), NotificationMapperToStorageHub.toSocialItem(workspace, workspaceItem), NotificationMapperToStorageHub.toSocialSharedFolder(sharedFolder)); + SocialFileItem toSocialItem = NotificationMapperToStorageHub.toSocialItem(workspace, workspaceItem); + SocialSharedFolder toSocialFolder = NotificationMapperToStorageHub.toSocialSharedFolder(sharedFolder); + boolean notify = notificationsMng.notifyAddedItem(infoContactModel.getLogin(), toSocialItem, toSocialFolder); if(!notify){ logger.error("An error occured when notify user: "+infoContactModel.getLogin()); @@ -224,5 +230,88 @@ public class NotificationsProducerToStorageHub { } + + /** + * Notify removed item to sharing. + * + * @param listContacts the list contacts + * @param itemName the item name + * @param sharedFolder the shared folder + */ + public void notifyRemovedItemToSharing(final List listContacts, final String itemName, final WorkspaceSharedFolder sharedFolder) { + + + new Thread() { + @Override + public void run() { + + logger.trace("Sending notification removed item in shared folder is running..."); + if(itemName==null || itemName.isEmpty()){ + logger.trace("Notification isn't sent - itemName is null or empty"); + return; + } + + if(sharedFolder==null){ + logger.debug("Impossible to send notification - sharedFolder is null"); + } + + for (InfoContactModel infoContactModel : listContacts) { + try{ + + //NOTIFIES ONLY THE USERS THAT ARE DIFFERENT FROM CURRENT USER + if(infoContactModel.getLogin().compareTo(userId)!=0){ + + logger.debug("Sending notification to user "+infoContactModel.getLogin() +" removed item "+itemName+" in the shared folder "+sharedFolder.getName()); + //DEBUG +// System.out.println("Sending notification to user "+infoContactModel.getLogin() +" removed item "+itemName+" in shared folder "+sharedFolder.getName()); + boolean notify = notificationsMng.notifyRemovedItem(infoContactModel.getLogin(), itemName, NotificationMapperToStorageHub.toSocialSharedFolder(sharedFolder)); + if(!notify){ + logger.error("An error occured when notify user: "+infoContactModel.getLogin()); + } + } + }catch (Exception e) { + logger.error("An error occurred in notifyRemovedItemToSharing ", e); + } + } + + logger.debug("notifies of moved item in shared folder is completed"); + } + }.start(); + + } + + /** + * Runs a new thread to notify the contacts passed in input. + * + * @param listContacts the list contacts + * @param folderNameDeleted the folder name deleted + */ + public void notifySharedFolderDeleted(final List listContacts, final String folderNameDeleted) { + + + new Thread() { + @Override + public void run() { +// printContacts(listContacts); + logger.trace("Sending notification shared folder deleted is running..."); + for (InfoContactModel infoContactModel : listContacts) { + try{ + + //NOTIFIES ONLY THE USERS THAT ARE DIFFERENT FROM CURRENT USER + if(infoContactModel.getLogin().compareTo(userId)!=0){ + logger.trace("Sending notification to user "+infoContactModel.getLogin() +" deleted shared folder "+folderNameDeleted); + //THIS NOTIFCATION HAS BEEN REMOVED + } + }catch (Exception e) { + logger.error("An error occured in notifySharedFolderDeleted ", e); + } + } + + logger.debug("notifies of deleted shared foder is completed"); + } + + }.start(); + + } } diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/property/PortalUrlGroupGatewayProperty.java b/src/main/java/org/gcube/portlets/user/workspace/server/property/PortalUrlGroupGatewayProperty.java index 40eefab..2098a59 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/property/PortalUrlGroupGatewayProperty.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/property/PortalUrlGroupGatewayProperty.java @@ -3,7 +3,8 @@ package org.gcube.portlets.user.workspace.server.property; import java.io.InputStream; import java.util.Properties; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it @@ -18,7 +19,7 @@ public class PortalUrlGroupGatewayProperty { */ protected static final String PORTALURL_PROPERTIES = "portalurl.properties"; - protected static Logger log = Logger.getLogger(PortalUrlGroupGatewayProperty.class); + protected static Logger log = LoggerFactory.getLogger(PortalUrlGroupGatewayProperty.class); private String server = ""; private String path = ""; diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/property/PropertyFileNotFoundException.java b/src/main/java/org/gcube/portlets/user/workspace/server/property/PropertyFileNotFoundException.java index 67736c1..92ba23c 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/property/PropertyFileNotFoundException.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/property/PropertyFileNotFoundException.java @@ -10,4 +10,13 @@ package org.gcube.portlets.user.workspace.server.property; */ public class PropertyFileNotFoundException extends Exception { + /** + * + */ + private static final long serialVersionUID = -3220297615560720000L; + + public PropertyFileNotFoundException() { + super(); + } + } diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/reader/ApplicationProfileReader.java b/src/main/java/org/gcube/portlets/user/workspace/server/reader/ApplicationProfileReader.java index f3b5e3d..bc839f2 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/reader/ApplicationProfileReader.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/reader/ApplicationProfileReader.java @@ -8,13 +8,14 @@ import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import org.apache.commons.lang.StringUtils; -import org.apache.log4j.Logger; import org.gcube.common.resources.gcore.utils.XPathHelper; import org.gcube.common.scope.api.ScopeProvider; +import org.gcube.portlets.user.workspace.server.util.WsUtil; import org.gcube.resources.discovery.client.api.DiscoveryClient; import org.gcube.resources.discovery.client.queries.api.Query; import org.gcube.resources.discovery.client.queries.impl.QueryBox; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.w3c.dom.Node; import org.xml.sax.InputSource; @@ -41,7 +42,7 @@ public class ApplicationProfileReader { protected static final String RESOURCE_PROFILE_DESCRIPTION_TEXT = "/Resource/Profile/Description/text()"; protected static final String RESOURCE_PROFILE_NAME_TEXT = "/Resource/Profile/Name/text()"; - private Logger logger = Logger.getLogger(ApplicationProfileReader.class); + private Logger logger = LoggerFactory.getLogger(ApplicationProfileReader.class); private String secondaryType; private String scope; private String resourceName; @@ -131,9 +132,12 @@ public class ApplicationProfileReader { List scopes = currValue; String currentScope = scopes.get(0); - int slashCount = StringUtils.countMatches(currentScope, "/"); + //int slashCount = StringUtils.countMatches(currentScope, "/"); + + boolean isVRE = WsUtil.isVRE(currentScope); - if(slashCount < 3){//CASE not VRE - set session scope + //if(slashCount < 3){//CASE not VRE - set session scope + if(!isVRE){//CASE not VRE - set session scope logger.info("Scope "+ scope.toString() + " is not a VRE"); List listSessionScope = helper.evaluate("/Resource/Profile/Body/EndPoint[Scope='"+scope.toString()+"']/Sessionscope/text()"); //get session scope of i+1-mo scope diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/resolver/UriResolverReaderParameterForResolverIndex.java b/src/main/java/org/gcube/portlets/user/workspace/server/resolver/UriResolverReaderParameterForResolverIndex.java index c4988ae..32c1d65 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/resolver/UriResolverReaderParameterForResolverIndex.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/resolver/UriResolverReaderParameterForResolverIndex.java @@ -13,7 +13,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.apache.log4j.Logger; import org.gcube.common.resources.gcore.ServiceEndpoint; import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint; import org.gcube.common.scope.api.ScopeProvider; @@ -21,6 +20,8 @@ import org.gcube.portlets.user.workspace.server.util.UrlEncoderUtil; import org.gcube.portlets.user.workspace.server.util.scope.ScopeUtilFilter; import org.gcube.resources.discovery.client.api.DiscoveryClient; import org.gcube.resources.discovery.client.queries.impl.XQuery; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** @@ -43,7 +44,7 @@ public class UriResolverReaderParameterForResolverIndex { private String contentTypeParameter = ""; private String query = ""; private boolean isAvailable = false; - public static Logger logger = Logger.getLogger(UriResolverReaderParameterForResolverIndex.class); + public static Logger logger = LoggerFactory.getLogger(UriResolverReaderParameterForResolverIndex.class); /** * The Enum RESOLVER_TYPE. diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/tostoragehub/BuildServiceURLUtil.java b/src/main/java/org/gcube/portlets/user/workspace/server/tostoragehub/BuildServiceURLUtil.java new file mode 100644 index 0000000..fd584d2 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/workspace/server/tostoragehub/BuildServiceURLUtil.java @@ -0,0 +1,74 @@ +package org.gcube.portlets.user.workspace.server.tostoragehub; + +import java.util.UUID; + +import org.gcube.portlets.user.workspace.client.ConstantsExplorer; +import org.gcube.portlets.user.workspace.client.util.ImageRequestType; + +/** + * The Class BuildServiceURLUtil. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * + * Jul 17, 2019 + */ +public class BuildServiceURLUtil { + + + protected static final String IMAGE_SERVICE_URL = "ImageService"; + + /** + * Builds the image url. + * + * @param id the id + * @param currentGroupId the current group id + * @param currUserId the curr user id + * @return the string + */ + protected static String buildImageUrl(String id, String currentGroupId, String currUserId) + { + return buildImageServiceUrl(id, ImageRequestType.IMAGE, currentGroupId, currUserId); + } + + + + /** + * Builds the thumbnail url. + * + * @param id the id + * @param currentGroupId the current group id + * @param currUserId the curr user id + * @return the string + */ + protected static String buildThumbnailUrl(String id, String currentGroupId, String currUserId) + { + return buildImageServiceUrl(id, ImageRequestType.THUMBNAIL, currentGroupId, currUserId); + } + + + /** + * Builds the image service url. + * + * @param id the id + * @param requestType the request type + * @param currentGroupId the current group id read from PortalContext + * @param currUserId the curr user id + * @return the string + */ + protected static String buildImageServiceUrl(String id, ImageRequestType requestType, String currentGroupId, String currUserId){ + StringBuilder sb = new StringBuilder(); + sb.append(IMAGE_SERVICE_URL); + sb.append("?id="); + sb.append(id); + sb.append("&type="); + sb.append(requestType.toString()); + sb.append("&"+ConstantsExplorer.CURRENT_CONTEXT_ID+"="); + sb.append(currentGroupId); + // sb.append("&"+ConstantsExplorer.CURRENT_USER_ID+"="); + // sb.append(currUserId); + sb.append("&random="); + sb.append(UUID.randomUUID().toString()); + return sb.toString(); + } + +} diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/tostoragehub/FormatterUtil.java b/src/main/java/org/gcube/portlets/user/workspace/server/tostoragehub/FormatterUtil.java new file mode 100644 index 0000000..d681b25 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/workspace/server/tostoragehub/FormatterUtil.java @@ -0,0 +1,118 @@ +package org.gcube.portlets.user.workspace.server.tostoragehub; + +import java.text.DecimalFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + + +/** + * The Class FormatterUtil. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * + * Jul 17, 2019 + */ +public class FormatterUtil { + + /** + * To date. + * + * @param calendar the calendar + * @return the date + */ + public static Date toDate(Calendar calendar){ + if (calendar == null) return new Date(0); + return calendar.getTime(); + + } + + /** + * To date format to string. + * + * @param calendar the calendar + * @return the string + */ + protected String toDateFormatToString(Calendar calendar){ + + SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM, yyyy HH:mm:ss z"); + Date resultdate = getDate(calendar); + return dateFormat.format(resultdate); + } + + /** + * To date format. + * + * @param calendar + * the calendar + * @return the date + */ + protected Date toDateFormat(Calendar calendar) { + + SimpleDateFormat dateFormat = + new SimpleDateFormat("dd-MM, yyyy HH:mm:ss z"); + Date resultdate = getDate(calendar); + try { + resultdate = dateFormat.parse(dateFormat.format(resultdate)); + } + catch (ParseException e) { + e.printStackTrace(); + resultdate = new Date(0); + } + return resultdate; + } + + /** + * Gets the date. + * + * @param calendar the calendar + * @return the date + */ + private Date getDate(Calendar calendar) { + + Date resultdate = null; + + if (calendar == null) + resultdate = new Date(0); + else + resultdate = new Date(calendar.getTimeInMillis()); + + return resultdate; + + } + + + /** + * Format file size. + * + * @param size the size + * @return the string + */ + public static String formatFileSize(long size) { + String formattedSize = null; + + double b = size; + double k = size/1024.0; + double m = size/1024.0/1024.0; + double g = size/1024.0/1024.0/1024.0; + double t = size/1024.0/1024.0/1024.0/1024.0; + + DecimalFormat dec = new DecimalFormat("0.00"); + + if ( t>1 ) { + formattedSize = dec.format(t).concat(" TB"); + } else if ( g>1 ) { + formattedSize = dec.format(g).concat(" GB"); + } else if ( m>1 ) { + formattedSize = dec.format(m).concat(" MB"); + } else if ( k>1 ) { + formattedSize = dec.format(k).concat(" KB"); + } else { + formattedSize = dec.format(b).concat(" Bytes"); + } + + return formattedSize; + } + +} diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/tostoragehub/ObjectStorageHubToWorkpaceMapper.java b/src/main/java/org/gcube/portlets/user/workspace/server/tostoragehub/ObjectStorageHubToWorkpaceMapper.java index d3b8473..9e01357 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/tostoragehub/ObjectStorageHubToWorkpaceMapper.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/tostoragehub/ObjectStorageHubToWorkpaceMapper.java @@ -4,8 +4,14 @@ package org.gcube.portlets.user.workspace.server.tostoragehub; -import org.apache.log4j.Logger; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +import org.gcube.common.storagehubwrapper.server.tohl.Workspace; import org.gcube.common.storagehubwrapper.shared.tohl.exceptions.InternalErrorException; +import org.gcube.common.storagehubwrapper.shared.tohl.impl.URLFile; import org.gcube.common.storagehubwrapper.shared.tohl.impl.WorkspaceSharedFolder; import org.gcube.common.storagehubwrapper.shared.tohl.items.FileItem; import org.gcube.portlets.user.workspace.client.interfaces.GXTCategorySmartFolder; @@ -14,22 +20,29 @@ import org.gcube.portlets.user.workspace.client.model.FileGridModel; import org.gcube.portlets.user.workspace.client.model.FileModel; import org.gcube.portlets.user.workspace.client.model.FolderGridModel; import org.gcube.portlets.user.workspace.client.model.FolderModel; -import org.gcube.portlets.user.workspace.server.GWTWorkspaceBuilder; +import org.gcube.portlets.user.workspace.client.workspace.GWTProperties; +import org.gcube.portlets.user.workspace.client.workspace.GWTWorkspaceFolder; +import org.gcube.portlets.user.workspace.client.workspace.GWTWorkspaceItem; +import org.gcube.portlets.user.workspace.client.workspace.GWTWorkspaceItemAction; +import org.gcube.portlets.user.workspace.client.workspace.folder.item.GWTExternalImage; +import org.gcube.portlets.user.workspace.client.workspace.folder.item.GWTExternalUrl; import org.gcube.portlets.user.workspace.server.util.UserUtil; import org.gcube.vomanagement.usermanagement.model.GCubeUser; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * The Class StorageHubToWorkpaceConveter. + * The Class ObjectStorageHubToWorkpaceMapper. * - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * Sep 20, 2018 + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * + * Jul 17, 2019 */ public class ObjectStorageHubToWorkpaceMapper { - protected static Logger logger = Logger.getLogger(ObjectStorageHubToWorkpaceMapper.class); + protected static Logger logger = LoggerFactory.getLogger(ObjectStorageHubToWorkpaceMapper.class); /** * To root folder. @@ -162,7 +175,7 @@ public class ObjectStorageHubToWorkpaceMapper { case FOLDER: boolean isPublicFolder = ((org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceFolder) wrappedItem).isPublicFolder(); //TODO - fileGridModel = new FolderGridModel(wrappedItem.getId(), wrappedItem.getName(), GWTWorkspaceBuilder.toDate(wrappedItem.getLastModificationTime()), parentFolderModel, -1, true, false,false, isPublicFolder); + fileGridModel = new FolderGridModel(wrappedItem.getId(), wrappedItem.getName(), FormatterUtil.toDate(wrappedItem.getLastModificationTime()), parentFolderModel, -1, true, false,false, isPublicFolder); if(isPublicFolder) fileGridModel.setType(GXTFolderItemTypeEnum.FOLDER_PUBLIC.getLabel().toString()); else @@ -177,7 +190,7 @@ public class ObjectStorageHubToWorkpaceMapper { FileItem fileItem = (FileItem) wrappedItem; fileGridModel = new FileGridModel(fileItem.getId(), fileItem.getName(), - GWTWorkspaceBuilder. + FormatterUtil. toDate(fileItem.getLastModificationTime()), parentFolderModel, fileItem.getSize()==null?0:fileItem.getSize(), @@ -187,7 +200,7 @@ public class ObjectStorageHubToWorkpaceMapper { break; case VRE_FOLDER: - fileGridModel = new FolderGridModel(wrappedItem.getId(), wrappedItem.getName(), GWTWorkspaceBuilder.toDate(wrappedItem.getLastModificationTime()), parentFolderModel, -1, true, false,true, false); + fileGridModel = new FolderGridModel(wrappedItem.getId(), wrappedItem.getName(), FormatterUtil.toDate(wrappedItem.getLastModificationTime()), parentFolderModel, -1, true, false,true, false); fileGridModel.setType(GXTFolderItemTypeEnum.FOLDER_SHARED.toString()); fileGridModel.setShareable(true); fileGridModel.setDescription(wrappedItem.getDescription()); @@ -197,7 +210,7 @@ public class ObjectStorageHubToWorkpaceMapper { WorkspaceSharedFolder shared = (WorkspaceSharedFolder) wrappedItem; boolean isPublicDir = ((org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceFolder) wrappedItem).isPublicFolder(); //TODO //String name = shared.isVreFolder()?shared.getTitle():shared.getName(); - fileGridModel = new FolderGridModel(wrappedItem.getId(), wrappedItem.getName(), GWTWorkspaceBuilder.toDate(wrappedItem.getLastModificationTime()), parentFolderModel, -1, true, true, shared.isVreFolder(), isPublicDir); + fileGridModel = new FolderGridModel(wrappedItem.getId(), wrappedItem.getName(), FormatterUtil.toDate(wrappedItem.getLastModificationTime()), parentFolderModel, -1, true, true, shared.isVreFolder(), isPublicDir); if(isPublicDir) fileGridModel.setType(GXTFolderItemTypeEnum.FOLDER_SHARED_PUBLIC.getLabel().toString()); @@ -208,6 +221,21 @@ public class ObjectStorageHubToWorkpaceMapper { fileGridModel.setShareable(true); fileGridModel.setDescription(wrappedItem.getDescription()); break; + + case URL_ITEM: + URLFile urlItem = (URLFile) wrappedItem; + fileGridModel = new FileGridModel(urlItem.getId(), + urlItem.getName(), + FormatterUtil. + toDate(urlItem.getLastModificationTime()), + parentFolderModel, + -1, + false, + false); + //fileGridModel.setType("URL"); + fileGridModel.setFolderItemType(GXTFolderItemTypeEnum.EXTERNAL_URL); + fileGridModel.setShortcutCategory(GXTCategorySmartFolder.SMF_DOCUMENTS); + break; default: logger.error("gxt conversion return null for item "+wrappedItem.getName()); @@ -296,5 +324,160 @@ public class ObjectStorageHubToWorkpaceMapper { return fileModel; } + + + /** + * Builds the GWT workspace image. + * + * @param wrappedImage the wrapped image + * @param isInteralImage the is interal image + * @param fullDetails the full details + * @param currentGroupId the current group id + * @param currentUserId the current user id + * @return the GWT workspace item + */ + @SuppressWarnings("unchecked") + public static GWTWorkspaceItem buildGWTWorkspaceImage(org.gcube.common.storagehubwrapper.shared.tohl.items.ImageFileItem wrappedImage, boolean isInteralImage, boolean fullDetails, String currentGroupId, String currentUserId) + { + + GWTWorkspaceItem gwtImage; + GWTProperties gwtProperties = null; + GWTWorkspaceItemAction lastAction = null; + GWTWorkspaceFolder parent = null; + + if(fullDetails){ + + gwtImage = new GWTExternalImage( + FormatterUtil.toDate(wrappedImage.getCreationTime()), + wrappedImage.getId(), + gwtProperties, + wrappedImage.getName(), + wrappedImage.getOwner(), + wrappedImage.getDescription(), + FormatterUtil.toDate(wrappedImage.getLastModificationTime()), + lastAction, + parent, //parent + BuildServiceURLUtil.buildImageUrl(wrappedImage.getId(), currentGroupId, currentUserId), + BuildServiceURLUtil.buildThumbnailUrl(wrappedImage.getId(), currentGroupId, currentUserId), + toValidInt(wrappedImage.getWidth()), + toValidInt(wrappedImage.getHeight()), + wrappedImage.getSize(), + toValidInt(wrappedImage.getThumbnailWidth()), + toValidInt(wrappedImage.getThumbnailHeight()), + -1, + wrappedImage.getMimeType()); + }else{ + gwtImage = new GWTExternalImage(wrappedImage.getId(), wrappedImage.getName(), + BuildServiceURLUtil.buildImageUrl(wrappedImage.getId(), currentGroupId, currentUserId), + BuildServiceURLUtil.buildThumbnailUrl(wrappedImage.getId(), currentGroupId, currentUserId), + toValidInt(wrappedImage.getWidth()), + toValidInt(wrappedImage.getHeight()), + toValidInt(wrappedImage.getSize()), + toValidInt(wrappedImage.getThumbnailWidth()), + toValidInt(wrappedImage.getThumbnailHeight()), + -1, + wrappedImage.getMimeType()); + } + return gwtImage; + } + + + /** + * To valid int. + * + * @param aLong the a long + * @return the int + */ + public static int toValidInt(Long aLong){ + + if(aLong==null) + return -1; + + try { + return Integer.parseInt(aLong.toString()); + }catch (Exception e) { + logger.warn("Exception on parsing the value "+aLong+" as long"); + return -1; + } + + } + + + /** + * Builds the GWT worspace url. + * + * @param workspace the workspace + * @param fileItem the file item + * @param isInternalUrl the is internal url + * @param fullDetails the full details + * @return the GWT workspace item + * @throws Exception the exception + */ + @SuppressWarnings("unchecked") + public static GWTWorkspaceItem buildGWTWorspaceUrl(Workspace workspace, FileItem fileItem, boolean isInternalUrl, boolean fullDetails) throws Exception + { + + + //TODO EXTRACT THE URL FROM THE FILE + GWTWorkspaceItem gwtUrl = null; + GWTProperties gwtProperties = null; + GWTWorkspaceItemAction lastAction = null; + + if(fullDetails){ + gwtUrl = new GWTExternalUrl( + FormatterUtil.toDate(fileItem.getCreationTime()), + fileItem.getId(), + gwtProperties, + fileItem.getName(), + fileItem.getOwner(), + fileItem.getDescription(), + FormatterUtil.toDate(fileItem.getLastModificationTime()), + lastAction, + null, + fileItem.getSize(), + getUrl(workspace, fileItem)); + } + else + gwtUrl = new GWTExternalUrl(getUrl(workspace, fileItem)); + + return gwtUrl; + } + + /** + * Gets the url. + * + * @param workspace the workspace + * @param fileItem the file item + * @return the url + * @throws Exception the exception + */ + public static String getUrl(Workspace workspace, org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem fileItem) throws Exception { + try { + return readStreamAsString(workspace.downloadFile(fileItem.getId(), fileItem.getName(), null, null).getStream()); + } catch (IOException e) { + logger.error("GET URL error for file: " +fileItem, e); + throw new InternalErrorException(e.getMessage()); + } + } + + /** + * Read the entire input stream as string. The system encoding is used. + * + * @param is the input stream. + * @return the read string. + * @throws IOException Signals that an I/O exception has occurred. + */ + public static String readStreamAsString(InputStream is) throws java.io.IOException{ + StringBuilder sb = new StringBuilder(1000); + BufferedReader reader = new BufferedReader(new InputStreamReader(is)); + char[] buf = new char[1024]; + int numRead=0; + while((numRead=reader.read(buf)) != -1){ + sb.append(buf, 0, numRead); + } + reader.close(); + return sb.toString(); + } + } diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/tostoragehub/StorageHubToWorkpaceConverter.java b/src/main/java/org/gcube/portlets/user/workspace/server/tostoragehub/StorageHubToWorkpaceConverter.java index 13d4121..0ff12a5 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/tostoragehub/StorageHubToWorkpaceConverter.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/tostoragehub/StorageHubToWorkpaceConverter.java @@ -6,14 +6,32 @@ package org.gcube.portlets.user.workspace.server.tostoragehub; import java.io.Serializable; import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; import java.util.List; +import java.util.Map; -import org.apache.log4j.Logger; +import org.gcube.common.storagehub.model.items.nodes.accounting.AccountEntry; +import org.gcube.common.storagehub.model.items.nodes.accounting.AccountEntryCreate; +import org.gcube.common.storagehub.model.items.nodes.accounting.AccountEntryDisabledPublicAccess; +import org.gcube.common.storagehub.model.items.nodes.accounting.AccountEntryEnabledPublicAccess; +import org.gcube.common.storagehub.model.items.nodes.accounting.AccountEntryPaste; +import org.gcube.common.storagehub.model.items.nodes.accounting.AccountEntryRead; +import org.gcube.common.storagehub.model.items.nodes.accounting.AccountEntryRestore; +import org.gcube.common.storagehub.model.items.nodes.accounting.AccountEntryShare; +import org.gcube.common.storagehub.model.items.nodes.accounting.AccountEntryUnshare; +import org.gcube.common.storagehub.model.items.nodes.accounting.AccountEntryUpdate; +import org.gcube.common.storagehub.model.items.nodes.accounting.AccountFolderEntryAdd; +import org.gcube.common.storagehub.model.items.nodes.accounting.AccountFolderEntryCut; +import org.gcube.common.storagehub.model.items.nodes.accounting.AccountFolderEntryRemoval; +import org.gcube.common.storagehub.model.items.nodes.accounting.AccountFolderEntryRenaming; +import org.gcube.common.storagehub.model.items.nodes.accounting.AccountingEntryType; import org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItem; import org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceItemType; import org.gcube.common.storagehubwrapper.shared.tohl.WorkspaceSharedFolder; import org.gcube.common.storagehubwrapper.shared.tohl.exceptions.InternalErrorException; import org.gcube.common.storagehubwrapper.shared.tohl.impl.WorkspaceFileVersion; +import org.gcube.common.storagehubwrapper.shared.tohl.items.GCubeItem; import org.gcube.common.storagehubwrapper.shared.tohl.items.PropertyMap; import org.gcube.portal.wssynclibrary.shared.thredds.Sync_Status; import org.gcube.portal.wssynclibrary.thredds.WorkspaceThreddsSynchronize; @@ -23,10 +41,13 @@ import org.gcube.portlets.user.workspace.client.model.FileModel; import org.gcube.portlets.user.workspace.client.model.FileTrashedModel; import org.gcube.portlets.user.workspace.client.model.FileVersionModel; import org.gcube.portlets.user.workspace.client.model.FolderModel; -import org.gcube.portlets.user.workspace.server.GWTWorkspaceBuilder; import org.gcube.portlets.user.workspace.server.util.UserUtil; +import org.gcube.portlets.user.workspace.shared.accounting.GxtAccountingEntryType; +import org.gcube.portlets.user.workspace.shared.accounting.GxtAccountingField; import org.gcube.portlets.widgets.workspacesharingwidget.shared.InfoContactModel; import org.gcube.vomanagement.usermanagement.model.GCubeUser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @@ -45,7 +66,7 @@ public class StorageHubToWorkpaceConverter implements Serializable{ */ private static final long serialVersionUID = 6935303928299846569L; - protected static Logger logger = Logger.getLogger(StorageHubToWorkpaceConverter.class); + protected static Logger logger = LoggerFactory.getLogger(StorageHubToWorkpaceConverter.class); private String scope; private GCubeUser loggedUser; private String workspaceRootId; @@ -58,6 +79,67 @@ public class StorageHubToWorkpaceConverter implements Serializable{ public StorageHubToWorkpaceConverter() { } + + /********************************************************************************************************************************************** + * + * + * + * + * TESTING MODE METHODS + * + * + * + * + ***********************************************************************************************************************************************/ + protected static HashMap hashTestUser = null; + /** + * Used in test mode. + * + * @return the hash test users + */ + public static HashMap getHashTestUsers(){ + + if(hashTestUser==null){ + hashTestUser = new HashMap(); + + //USERS + hashTestUser.put("federico.defaveri", new InfoContactModel("federico.defaveri", "federico.defaveri", "Federico de Faveri",null, false)); + hashTestUser.put("antonio.gioia", new InfoContactModel("antonio.gioia", "antonio.gioia", "Antonio Gioia",null, false)); + hashTestUser.put("fabio.sinibaldi", new InfoContactModel("fabio.sinibaldi", "fabio.sinibaldi", "Fabio Sinibaldi",null, false)); + hashTestUser.put("pasquale.pagano", new InfoContactModel("pasquale.pagano", "pasquale.pagano", "Pasquale Pagano",null, false)); + hashTestUser.put("valentina.marioli", new InfoContactModel("valentina.marioli", "valentina.marioli", "Valentina Marioli",null, false)); + hashTestUser.put("roberto.cirillo", new InfoContactModel("roberto.cirillo", "roberto.cirillo", "Roberto Cirillo",null, false)); + hashTestUser.put("francesco.mangiacrapa", new InfoContactModel("francesco.mangiacrapa", "francesco.mangiacrapa", "Francesco Mangiacrapa",null, false)); + hashTestUser.put("massimiliano.assante", new InfoContactModel("massimiliano.assante", "massimiliano.assante", "Massimiliano Assante",null, false)); + + } + + return hashTestUser; + } + + + public static List buildGxtInfoContactFromPortalLoginTestMode(List listPortalLogin){ + + List listContact = new ArrayList(); + + for (String portalLogin : listPortalLogin) + listContact.add(getHashTestUsers().get(portalLogin)); + + return listContact; + } + + /********************************************************************************************************************************************** + * + * + * + * + * END TESTING MODE + * + * + * + * + ***********************************************************************************************************************************************/ + /** @@ -76,7 +158,7 @@ public class StorageHubToWorkpaceConverter implements Serializable{ List listVersions = new ArrayList(versions.size()); for (WorkspaceFileVersion wsVersion : versions) { String user = UserUtil.getUserFullName(wsVersion.getOwner()); - FileVersionModel file = new FileVersionModel(wsVersion.getId(), wsVersion.getName(), wsVersion.getRemotePath(), user, GWTWorkspaceBuilder.toDate(wsVersion.getCreated()), wsVersion.isCurrentVersion()); + FileVersionModel file = new FileVersionModel(wsVersion.getId(), wsVersion.getName(), wsVersion.getRemotePath(), user, FormatterUtil.toDate(wsVersion.getCreated()), wsVersion.isCurrentVersion()); listVersions.add(file); } return listVersions; @@ -215,7 +297,7 @@ public class StorageHubToWorkpaceConverter implements Serializable{ fileTrashModel.setIsDirectory(trashItem.isFolder()); //SETTING DELETE DATE - fileTrashModel.setDeleteDate(GWTWorkspaceBuilder.toDate(trashItem.getDeletedTime())); + fileTrashModel.setDeleteDate(FormatterUtil.toDate(trashItem.getDeletedTime())); fileTrashModel.setShared(trashItem.isShared()); @@ -233,21 +315,33 @@ public class StorageHubToWorkpaceConverter implements Serializable{ return fileTrashModel; } - + + /** * Builds the gxt info contact from portal login. * * @param portalLogin the portal login * @return the info contact model */ - protected InfoContactModel buildGxtInfoContactFromPortalLogin(String portalLogin){ + public static InfoContactModel buildGxtInfoContactFromPortalLogin(String portalLogin){ if(portalLogin==null){ logger.warn("portal login is null, return empty"); portalLogin = ""; } - - return new InfoContactModel(portalLogin, portalLogin, UserUtil.getUserFullName(portalLogin), "",false); + GCubeUser theUser = null; + try { + theUser = UserUtil.getUserByUsername(portalLogin); + }catch (Exception e) { + logger.warn("Error on retrieving user information, so using the portal login"); + } + String fullName = null; + String emailDomain = null; + if(theUser!=null) { + fullName = theUser.getFullname(); + emailDomain = theUser.getEmail(); + } + return new InfoContactModel(portalLogin, portalLogin, fullName, emailDomain,false); } /** @@ -309,7 +403,6 @@ public class StorageHubToWorkpaceConverter implements Serializable{ } - /** * Gets the workspace root id. * @@ -321,7 +414,6 @@ public class StorageHubToWorkpaceConverter implements Serializable{ } - /** * Sets the workspace root id. * @@ -331,5 +423,386 @@ public class StorageHubToWorkpaceConverter implements Serializable{ this.workspaceRootId = workspaceRootId; } + + + /** + * To simple map. + * + * @param propertyMap the property map + * @return the map + */ + public Map toSimpleMap(PropertyMap propertyMap) { + + if (propertyMap == null) + return null; + + try { + Map properties = null; + Map map = propertyMap.getValues(); + + if (map != null) { + properties = new HashMap(map.size()); + for (String key : map.keySet()) { + Object theValue = map.get(key); + properties.put(key, (String) theValue); + } + } + + if(properties!=null) + logger.error("Converted: "+properties.size()+" property/properties"); + + return properties; + } catch (Exception e) { + logger.error("Error on converting a PropertyMap to simple Map: ", e); + return null; + } + } + + + /** + * Builds the GXT accounting item. + * + * @param accoutings the accoutings + * @param gxtEntryType the gxt entry type + * @return the list + */ + public List buildGXTAccountingItem(List accoutings, GxtAccountingEntryType gxtEntryType) { + + List listAccFields = new ArrayList(); + + if(accoutings!=null){ + logger.trace("accouting entry/entrie is/are "+accoutings.size()+ ", converting it/them..."); + + for (AccountEntry shubAccEntry : accoutings) { + + GxtAccountingField af = new GxtAccountingField(); + InfoContactModel user = buildGxtInfoContactFromPortalLogin(shubAccEntry.getUser()); + af.setUser(user); + af.setDate(FormatterUtil.toDate(shubAccEntry.getDate())); + + switch (shubAccEntry.getType()) { + + case CREATE: + + if(gxtEntryType==null || gxtEntryType.equals(GxtAccountingEntryType.ALL) || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) || gxtEntryType.equals(GxtAccountingEntryType.CREATE)){ + AccountEntryCreate create = (AccountEntryCreate) shubAccEntry; + af.setOperation(GxtAccountingEntryType.CREATE); + + // af.setDescription(GxtAccountingEntryType.CREATE.getName() + " by "+user.getName()); + String msg = ""; + if(create.getItemName()==null || create.getItemName().isEmpty()) + msg = GxtAccountingEntryType.CREATE.getId() + " by "+user.getName(); + else{ + + if(create.getVersion()==null) + msg = create.getItemName() + " " + GxtAccountingEntryType.CREATE.getName() + " by "+user.getName(); + else + msg = create.getItemName() + " v. "+create.getVersion()+" "+ GxtAccountingEntryType.CREATE.getName() + " by "+user.getName(); + } + + af.setDescription(msg); + } + + break; + + case READ: + + if(gxtEntryType==null || gxtEntryType.equals(GxtAccountingEntryType.ALL) || gxtEntryType.equals(GxtAccountingEntryType.READ)){ + + AccountEntryRead read = (AccountEntryRead) shubAccEntry; + af.setOperation(GxtAccountingEntryType.READ); + af.setDescription(read.getItemName() + " " + GxtAccountingEntryType.READ.getName() + " by "+user.getName()); + + String msg = ""; + if(read.getItemName()==null || read.getItemName().isEmpty()) + msg = GxtAccountingEntryType.READ.getId() + " by "+user.getName(); + else{ + + if(read.getVersion()==null) + msg = read.getItemName() + " " + GxtAccountingEntryType.READ.getName() + " by "+user.getName(); + else + msg = read.getItemName() + " v."+read.getVersion() +" "+ GxtAccountingEntryType.READ.getName() + " by "+user.getName(); + } + + af.setDescription(msg); + } + + break; + + case CUT: + + if(gxtEntryType==null || gxtEntryType.equals(GxtAccountingEntryType.ALL) || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) || gxtEntryType.equals(GxtAccountingEntryType.CUT)){ + + af.setOperation(GxtAccountingEntryType.CUT); + + if(shubAccEntry instanceof AccountFolderEntryCut) { + + AccountFolderEntryCut cut = (AccountFolderEntryCut) shubAccEntry; + + String msg = ""; + if(cut.getItemName()==null || cut.getItemName().isEmpty()) + msg = GxtAccountingEntryType.CUT.getName() +" by "+user.getName(); + else{ + if(cut.getVersion()==null) + msg = cut.getItemName()+" "+GxtAccountingEntryType.CUT.getName() +" by "+user.getName(); + else + msg = cut.getItemName()+" v."+cut.getVersion()+" "+GxtAccountingEntryType.CUT.getName() +" by "+user.getName(); + } + + af.setDescription(msg); + }else { + logger.warn("Found an "+AccountingEntryType.class.getSimpleName()+" of kind "+shubAccEntry.getType()+ " not castable to (instance of) "+AccountFolderEntryCut.class.getSimpleName()); + } + } + + break; + + case PASTE: + + if(gxtEntryType==null || gxtEntryType.equals(GxtAccountingEntryType.ALL) || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) || gxtEntryType.equals(GxtAccountingEntryType.PASTE)){ + + af.setOperation(GxtAccountingEntryType.PASTE); + AccountEntryPaste paste = (AccountEntryPaste) shubAccEntry; + + if(paste.getVersion()==null) + af.setDescription(GxtAccountingEntryType.PASTE.getName() + " from "+paste.getFromPath()+" by "+user.getName()); + else + af.setDescription(GxtAccountingEntryType.PASTE.getName() + " v. "+paste.getVersion()+" from "+paste.getFromPath()+" by "+user.getName()); + } + + break; + + case REMOVAL: + + if(gxtEntryType==null || gxtEntryType.equals(GxtAccountingEntryType.ALL) || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) || gxtEntryType.equals(GxtAccountingEntryType.REMOVE)){ + + if(shubAccEntry instanceof AccountFolderEntryRemoval) { + af.setOperation(GxtAccountingEntryType.REMOVE); + AccountFolderEntryRemoval rem = (AccountFolderEntryRemoval) shubAccEntry; + String msg = rem.getItemName()==null || rem.getItemName().isEmpty()?"":rem.getItemName()+" "; + + if(rem.getVersion()==null) + msg+= GxtAccountingEntryType.REMOVE.getName() +" by "+user.getName(); + else + msg+= GxtAccountingEntryType.REMOVE.getName() +" v."+rem.getVersion()+" by "+user.getName(); + + af.setDescription(msg); + }else { + logger.warn("Found an "+AccountingEntryType.class.getSimpleName()+" of kind "+shubAccEntry.getType()+ " not castable to (instance of) "+AccountFolderEntryRemoval.class.getSimpleName()); + } + } + break; + + case RENAMING: + + if(gxtEntryType==null || gxtEntryType.equals(GxtAccountingEntryType.ALL) || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) || gxtEntryType.equals(GxtAccountingEntryType.RENAME)){ + + if(shubAccEntry instanceof AccountFolderEntryRenaming) { + af.setOperation(GxtAccountingEntryType.RENAME); + AccountFolderEntryRenaming ren = (AccountFolderEntryRenaming) shubAccEntry; + String msg = ren.getOldItemName()==null || ren.getOldItemName().isEmpty()?"":ren.getOldItemName()+" "; + if(ren.getVersion()==null) + msg+= GxtAccountingEntryType.RENAME.getName() +" to "+ ren.getNewItemName()+ " by "+user.getName(); + else + msg+= " v."+ren.getVersion() +" "+GxtAccountingEntryType.RENAME.getName() +" to "+ ren.getNewItemName()+ " by "+user.getName(); + + af.setDescription(msg); + }else { + logger.warn("Found an "+AccountingEntryType.class.getSimpleName()+" of kind "+shubAccEntry.getType()+ " not castable to (instance of) "+AccountFolderEntryRenaming.class.getSimpleName()); + } + } + break; + + case ADD: + + if(gxtEntryType==null || gxtEntryType.equals(GxtAccountingEntryType.ALL) || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) || gxtEntryType.equals(GxtAccountingEntryType.ADD)){ + + if(shubAccEntry instanceof AccountFolderEntryAdd) { + af.setOperation(GxtAccountingEntryType.ADD); + AccountFolderEntryAdd acc = (AccountFolderEntryAdd) shubAccEntry; + String msg = acc.getItemName()==null || acc.getItemName().isEmpty()?"":acc.getItemName()+" "; + if(acc.getVersion()==null) + msg+=GxtAccountingEntryType.ADD.getName()+ " by "+user.getName(); + else + msg+=" v."+acc.getVersion()+ " "+GxtAccountingEntryType.ADD.getName()+ " by "+user.getName(); + + af.setDescription(msg); + }else { + logger.warn("Found an "+AccountingEntryType.class.getSimpleName()+" of kind "+shubAccEntry.getType()+ " not castable to (instance of) "+AccountFolderEntryAdd.class.getSimpleName()); + } + } + break; + + case UPDATE: + + if(gxtEntryType==null || gxtEntryType.equals(GxtAccountingEntryType.ALL) || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) || gxtEntryType.equals(GxtAccountingEntryType.UPDATE)){ + + af.setOperation(GxtAccountingEntryType.UPDATE); + AccountEntryUpdate upd = (AccountEntryUpdate) shubAccEntry; + String msg = upd.getItemName()==null || upd.getItemName().isEmpty()?"":upd.getItemName()+" "; + if(upd.getVersion()==null) + msg+=GxtAccountingEntryType.UPDATE.getName()+" by "+user.getName(); + else + msg+=" v."+upd.getVersion()+" "+GxtAccountingEntryType.UPDATE.getName()+" by "+user.getName(); + + af.setDescription(msg); + } + break; + + case SHARE: + + if(gxtEntryType==null || gxtEntryType.equals(GxtAccountingEntryType.ALL) || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) || gxtEntryType.equals(GxtAccountingEntryType.SHARE)){ + + af.setOperation(GxtAccountingEntryType.SHARE); + + AccountEntryShare acc = (AccountEntryShare) shubAccEntry; + + String msg = ""; + if(acc.getItemName()==null || acc.getItemName().isEmpty()) + msg = user.getName() + " "+GxtAccountingEntryType.SHARE.getName()+ " workspace folder"; + else + msg = user.getName() + " "+GxtAccountingEntryType.SHARE.getName()+ " workspace folder "+acc.getItemName(); + + if(acc.getMembers()!=null && acc.getMembers().length>0) + msg+=" with "+UserUtil.separateFullNameToCommaForPortalLogin(Arrays.asList(acc.getMembers())); + + af.setDescription(msg); + } + break; + + case UNSHARE: + + if(gxtEntryType==null || gxtEntryType.equals(GxtAccountingEntryType.ALL) || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) || gxtEntryType.equals(GxtAccountingEntryType.UNSHARE)){ + + af.setOperation(GxtAccountingEntryType.UNSHARE); + AccountEntryUnshare uns = (AccountEntryUnshare) shubAccEntry; + String msg = uns.getItemName()==null || uns.getItemName().isEmpty()?"":uns.getItemName()+" "; + msg+=GxtAccountingEntryType.UNSHARE.getName()+" by "+user.getName(); + af.setDescription(msg); + } + break; + + case RESTORE: + + if(gxtEntryType==null || gxtEntryType.equals(GxtAccountingEntryType.ALL) || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) || gxtEntryType.equals(GxtAccountingEntryType.RESTORE)){ + + af.setOperation(GxtAccountingEntryType.RESTORE); + AccountEntryRestore acc = (AccountEntryRestore) shubAccEntry; + String msg = acc.getItemName()==null || acc.getItemName().isEmpty()?"":acc.getItemName()+" "; + + if(acc.getVersion()==null) + msg+=GxtAccountingEntryType.RESTORE.getName()+" by "+user.getName(); + else + msg+=" v."+acc.getVersion()+" "+GxtAccountingEntryType.RESTORE.getName() +" by "+user.getName(); + + af.setDescription(msg); + } + break; + + case DISABLED_PUBLIC_ACCESS: + + if(gxtEntryType==null || gxtEntryType.equals(GxtAccountingEntryType.ALL) || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) || gxtEntryType.equals(GxtAccountingEntryType.DISABLED_PUBLIC_ACCESS)){ + + af.setOperation(GxtAccountingEntryType.DISABLED_PUBLIC_ACCESS); + AccountEntryDisabledPublicAccess acc = (AccountEntryDisabledPublicAccess) shubAccEntry; + //TODO acc.getItemName() is missing in SHUB + //String msg = acc.getItemName()==null || acc.getItemName().isEmpty()?"":acc.getItemName()+" "; + String msg=GxtAccountingEntryType.DISABLED_PUBLIC_ACCESS.getName()+" by "+user.getName(); + af.setDescription(msg); + } + + break; + + case ENABLED_PUBLIC_ACCESS: + + if(gxtEntryType==null || gxtEntryType.equals(GxtAccountingEntryType.ALL) || gxtEntryType.equals(GxtAccountingEntryType.ALLWITHOUTREAD) || gxtEntryType.equals(GxtAccountingEntryType.ENABLED_PUBLIC_ACCESS)){ + + af.setOperation(GxtAccountingEntryType.ENABLED_PUBLIC_ACCESS); + AccountEntryEnabledPublicAccess acc = (AccountEntryEnabledPublicAccess) shubAccEntry; + //TODO acc.getItemName() is missing in SHUB + //String msg = acc.getItemName()==null || acc.getItemName().isEmpty()?"":acc.getItemName()+" "; + String msg=GxtAccountingEntryType.ENABLED_PUBLIC_ACCESS.getName()+" by "+user.getName(); + af.setDescription(msg); + } + + break; + + default: + + break; + + } + listAccFields.add(af); + } + } + logger.debug("get accounting readers converting completed - returning size "+listAccFields.size()); + + return listAccFields; + + } + + + /** + * Gets the gcube item properties for gcube item as HTML. + * + * @param wsItem the ws item + * @return the gcube item properties for gcube item as HTML + */ + public String getGcubeItemPropertiesForGcubeItemAsHTML(WorkspaceItem wsItem) { + + + Map properties = getGcubeItemProperties(wsItem); + + if(properties!=null){ + + if(properties.size()==0){ + logger.warn("Map of Gcube Item Properties is empty for item: "+wsItem.getId()); + return null; + } + + String html = "
"; + + for (String key : properties.keySet()) { + String value = properties.get(key); + logger.trace("Getting property: ["+key+","+properties.get(key)+"]"); + html+=""+key+": "; + html+=""; + html+=value; + html+="
"; + } + + html+="
"; + + return html; + }else { + logger.warn("Gcube Item Properties not found for item: "+wsItem.getId()); + return null; + } + } + + + /** + * Gets the gcube item properties. + * + * @param wsItem the ws item + * @return the gcube item properties + */ + public Map getGcubeItemProperties(WorkspaceItem wsItem) { + + if(wsItem instanceof org.gcube.common.storagehubwrapper.shared.tohl.items.GCubeItem){ + GCubeItem gItem = (GCubeItem) wsItem; + try { + if(gItem.getProperties()!=null){ + PropertyMap map = gItem.getProperty(); + return toSimpleMap(map); + } + } catch (Exception e) { + logger.error("Error on reading getProperty: ", e); + return null; + } + } + return null; + + } } diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/util/AclTypeComparator.java b/src/main/java/org/gcube/portlets/user/workspace/server/util/AclTypeComparator.java deleted file mode 100644 index 6042fdb..0000000 --- a/src/main/java/org/gcube/portlets/user/workspace/server/util/AclTypeComparator.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * - */ -package org.gcube.portlets.user.workspace.server.util; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.gcube.common.homelibrary.home.workspace.accessmanager.ACLType; - -/** - * The Class AclTypeComparator. - * - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * Mar 5, 2015 - */ -public class AclTypeComparator implements Comparator{ - - - public static final Map aclTypeOrder; - static - { - aclTypeOrder = new LinkedHashMap(); - aclTypeOrder.put(ACLType.READ_ONLY, 0); - aclTypeOrder.put(ACLType.WRITE_OWNER, 1); - aclTypeOrder.put(ACLType.WRITE_ALL, 2); -// aclTypeOrder.put(ACLType.ADMINISTRATOR, 3); - } - - - /* (non-Javadoc) - * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) - */ - @Override - public int compare(ACLType o1, ACLType o2) { - if(o1==null) - return -1; - if(o2==null) - return 1; - - Integer order1 = aclTypeOrder.get(o1); - Integer order2 = aclTypeOrder.get(o2); - - if(order1==null) - return -1; - - if(order2==null) - return 1; - - if(order1==order2) - return 0; - - return order1 getAllowed(ACLType aclType, boolean includeEqual) { - - List allowed = new ArrayList(); - - if(aclType==null) - return allowed; - - //IF MAP DOES NOT CONTAINS ACT TYPE IT IS NOT COMPARABLE - if(aclTypeOrder.get(aclType)==null) - return allowed; - - for (ACLType aMap : aclTypeOrder.keySet()) { - int comparator = compare(aMap, aclType); - if(comparator==1) - allowed.add(aMap); - else if(includeEqual && comparator==0) - allowed.add(aMap); - } - - return allowed; - } - - - /** - * The main method. - * - * @param args the arguments - */ - public static void main(String[] args) { - - AclTypeComparator comparator = new AclTypeComparator(); - - List allowed = comparator.getAllowed(ACLType.WRITE_ALL, false); - - System.out.println(allowed); - - } - - -} diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/util/AllowedMimeTypeToInline.java b/src/main/java/org/gcube/portlets/user/workspace/server/util/AllowedMimeTypeToInline.java index 5d4fd0c..6fd0c2e 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/util/AllowedMimeTypeToInline.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/util/AllowedMimeTypeToInline.java @@ -6,7 +6,8 @@ import java.util.ArrayList; import java.util.List; import java.util.Properties; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** @@ -20,7 +21,7 @@ public class AllowedMimeTypeToInline { public static final String filename = "MimeTypePrefixToInline.properties"; - protected static Logger logger = Logger.getLogger(WsUtil.class); + protected static Logger logger = LoggerFactory.getLogger(WsUtil.class); /** * Load mime type prefix. diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/util/DifferenceBetweenInfoContactModel.java b/src/main/java/org/gcube/portlets/user/workspace/server/util/DifferenceBetweenInfoContactModel.java index 132fd13..a308572 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/util/DifferenceBetweenInfoContactModel.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/util/DifferenceBetweenInfoContactModel.java @@ -6,10 +6,6 @@ import java.util.List; import org.gcube.portlets.widgets.workspacesharingwidget.shared.InfoContactModel; - - - - /** * The Class DifferenceBetweenInfoContactModel. * diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/util/HttpRequestUtil.java b/src/main/java/org/gcube/portlets/user/workspace/server/util/HttpRequestUtil.java index 215a9ad..8e0ca8c 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/util/HttpRequestUtil.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/util/HttpRequestUtil.java @@ -7,7 +7,8 @@ import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLConnection; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** @@ -18,7 +19,7 @@ import org.apache.log4j.Logger; public class HttpRequestUtil { private static final int CONNECTION_TIMEOUT = 1000; - public static Logger logger = Logger.getLogger(HttpRequestUtil.class); + public static Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class); public static boolean urlExists(String urlConn) throws Exception { diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/util/MimeTypeUtility.java b/src/main/java/org/gcube/portlets/user/workspace/server/util/MimeTypeUtility.java index ae295d4..454d9f7 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/util/MimeTypeUtility.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/util/MimeTypeUtility.java @@ -14,12 +14,13 @@ import java.util.List; import java.util.Map; import org.apache.commons.io.FilenameUtils; -import org.apache.log4j.Logger; import org.apache.tika.config.TikaConfig; import org.apache.tika.detect.Detector; import org.apache.tika.io.TikaInputStream; import org.apache.tika.metadata.Metadata; import org.apache.tika.mime.MediaType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * The Class MimeTypeUtil. @@ -35,7 +36,7 @@ public class MimeTypeUtility { private static final String DOT_STRING = "."; - protected static Logger logger = Logger.getLogger(MimeTypeUtility.class); + protected static Logger logger = LoggerFactory.getLogger(MimeTypeUtility.class); /** * diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/util/StringUtil.java b/src/main/java/org/gcube/portlets/user/workspace/server/util/StringUtil.java index 0a43795..f31a2d9 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/util/StringUtil.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/util/StringUtil.java @@ -7,7 +7,8 @@ package org.gcube.portlets.user.workspace.server.util; import java.io.UnsupportedEncodingException; import org.apache.commons.codec.binary.Base64; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * The Class StringUtil. @@ -20,7 +21,7 @@ public class StringUtil { /** The Constant UTF_8. */ public static final String UTF_8 = "UTF-8"; public static String regx = ",@+^'?!\"%&$£/#()"; - protected static Logger logger = Logger.getLogger(StringUtil.class); + protected static Logger logger = LoggerFactory.getLogger(StringUtil.class); /** * Removes the special characters. diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/util/ThumbnailGenerator.java b/src/main/java/org/gcube/portlets/user/workspace/server/util/ThumbnailGenerator.java index 20ba23c..af11c18 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/util/ThumbnailGenerator.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/util/ThumbnailGenerator.java @@ -1,7 +1,3 @@ -/** - * - */ - package org.gcube.portlets.user.workspace.server.util; import java.awt.Color; @@ -21,11 +17,13 @@ import javax.imageio.ImageIO; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; + /** * The Class ThumbnailGenerator. * - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * Oct 18, 2018 + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * + * Aug 1, 2019 */ public class ThumbnailGenerator { @@ -138,7 +136,7 @@ public class ThumbnailGenerator { extension = extension.startsWith(".") ? extension : "." + extension; final File tempFile = File.createTempFile(filename, extension); - // tempFile.deleteOnExit(); + //tempFile.deleteOnExit(); try (FileOutputStream out = new FileOutputStream(tempFile)) { IOUtils.copy(in, out); } diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/util/UrlEncoderUtil.java b/src/main/java/org/gcube/portlets/user/workspace/server/util/UrlEncoderUtil.java index a23c688..294e2bd 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/util/UrlEncoderUtil.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/util/UrlEncoderUtil.java @@ -7,7 +7,8 @@ import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Map; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * The Class UrlEncoderUtil. @@ -18,7 +19,7 @@ import org.apache.log4j.Logger; public class UrlEncoderUtil { public static String charset = "UTF-8"; - public static Logger logger = Logger.getLogger(UrlEncoderUtil.class); + public static Logger logger = LoggerFactory.getLogger(UrlEncoderUtil.class); /** * Encode query. @@ -33,7 +34,7 @@ public class UrlEncoderUtil { try { query+=URLEncoder.encode(string, charset)+"&"; } catch (UnsupportedEncodingException e) { - logger.error(e); + logger.error("Error: ",e); return query; } } @@ -56,7 +57,7 @@ public class UrlEncoderUtil { return URLEncoder.encode(value, charset); } catch (UnsupportedEncodingException e) { - logger.error(e); + logger.error("Error: ",e); return null; } } @@ -79,7 +80,7 @@ public class UrlEncoderUtil { try { query+=String.format(key+"=%s", URLEncoder.encode(parameters.get(key), charset))+"&"; } catch (UnsupportedEncodingException e) { - logger.error(e); + logger.error("Error: ",e); return query; } } diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/util/UserUtil.java b/src/main/java/org/gcube/portlets/user/workspace/server/util/UserUtil.java index 39868a7..876687a 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/util/UserUtil.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/util/UserUtil.java @@ -3,13 +3,14 @@ package org.gcube.portlets.user.workspace.server.util; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.gcube.portlets.widgets.workspacesharingwidget.shared.InfoContactModel; import org.gcube.vomanagement.usermanagement.UserManager; import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException; import org.gcube.vomanagement.usermanagement.exception.UserRetrievalFault; import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager; import org.gcube.vomanagement.usermanagement.model.GCubeUser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @@ -22,7 +23,47 @@ import org.gcube.vomanagement.usermanagement.model.GCubeUser; public class UserUtil { static UserManager um = new LiferayUserManager(); - protected static Logger logger = Logger.getLogger(UserUtil.class); + protected static Logger logger = LoggerFactory.getLogger(UserUtil.class); + + + /** + * Gets the user by username. + * + * @param portalLogin the portal login + * @return the user by username + * @throws Exception + */ + public static GCubeUser getUserByUsername(String portalLogin) throws Exception{ + + if(portalLogin==null) + return null; + + if (WsUtil.isWithinPortal()) { //INTO PORTAL + + try { + + return um.getUserByUsername(portalLogin); + + } catch (UserManagementSystemException e) { + logger.error("Error on getting user for: "+portalLogin, e); + throw new Exception("Error on reading the user info for login: "+portalLogin); + } catch (UserRetrievalFault e) { + logger.error("Error on getting user for: "+portalLogin, e); + throw new Exception("Error on reading the user info for login: "+portalLogin); + }catch (Exception e) { + logger.error("Error on getting user for: "+portalLogin, e); + //logger.warn("Return portal login "+portalLogin); + throw new Exception("Error on reading the user info for login: "+portalLogin); + } + + }else{ + logger.trace("DEVELOPEMENT MODE ON"); + GCubeUser fakeUser = new GCubeUser(1, portalLogin, "mail","","","", portalLogin, 0, null, true, "", "", null); + logger.trace("Returning fake USER: "+fakeUser); + return fakeUser; + + } + } /** @@ -42,7 +83,7 @@ public class UserUtil { try { - curr = um.getUserByScreenName(portalLogin); + curr = um.getUserByUsername(portalLogin); } catch (UserManagementSystemException e) { logger.error("UserManagementSystemException, during getting fullname for: "+portalLogin); diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/util/WorkspaceEventCollector.java b/src/main/java/org/gcube/portlets/user/workspace/server/util/WorkspaceEventCollector.java deleted file mode 100644 index 4e03a3f..0000000 --- a/src/main/java/org/gcube/portlets/user/workspace/server/util/WorkspaceEventCollector.java +++ /dev/null @@ -1,47 +0,0 @@ -///** -// * -// */ -//package org.gcube.portlets.user.workspace.server.util; -// -//import java.util.concurrent.BlockingQueue; -//import java.util.concurrent.LinkedBlockingQueue; -// -//import org.apache.log4j.Logger; -//import org.gcube.common.homelibrary.home.workspace.events.WorkspaceEvent; -//import org.gcube.common.homelibrary.home.workspace.events.WorkspaceListener; -// -///** -// * @author Federico De Faveri defaveriAtisti.cnr.it -// * -// */ -//public class WorkspaceEventCollector implements WorkspaceListener { -// -// protected static Logger logger = Logger.getLogger(WorkspaceEventCollector.class); -// -// protected BlockingQueue eventsQueue = new LinkedBlockingQueue(); -// -// /** -// * @param logger -// */ -// public WorkspaceEventCollector() { -// } -// -// /** -// * {@inheritDoc} -// */ -// public void workspaceEvent(WorkspaceEvent event) { -// try { -// logger.trace("EventCollector workspaceEvent"+event); -// eventsQueue.put(event); -// } catch (InterruptedException e) { -// logger.warn("Error adding a new event", e); -// } -// } -// -// public WorkspaceEvent getEvent() throws InterruptedException -// { -// logger.trace("getEvent"); -// return eventsQueue.take(); -// } -// -//} diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/util/WsUtil.java b/src/main/java/org/gcube/portlets/user/workspace/server/util/WsUtil.java index fcd3a5d..4611e31 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/util/WsUtil.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/util/WsUtil.java @@ -6,46 +6,40 @@ package org.gcube.portlets.user.workspace.server.util; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; -import org.apache.commons.lang.StringUtils; -import org.apache.log4j.Logger; import org.gcube.applicationsupportlayer.social.ApplicationNotificationsManager; import org.gcube.applicationsupportlayer.social.NotificationsManager; import org.gcube.applicationsupportlayer.social.shared.SocialNetworkingSite; import org.gcube.applicationsupportlayer.social.shared.SocialNetworkingUser; -import org.gcube.common.homelibrary.home.HomeLibrary; -import org.gcube.common.homelibrary.home.exceptions.HomeNotFoundException; -import org.gcube.common.homelibrary.home.workspace.Workspace; import org.gcube.common.portal.PortalContext; -import org.gcube.common.scope.api.ScopeProvider; import org.gcube.common.storagehubwrapper.server.StorageHubWrapper; -import org.gcube.common.storagehubwrapper.shared.tohl.exceptions.InternalErrorException; -import org.gcube.common.storagehubwrapper.shared.tohl.exceptions.WorkspaceFolderNotFoundException; import org.gcube.portlets.user.urlshortener.UrlShortener; import org.gcube.portlets.user.workspace.client.model.FileModel; -import org.gcube.portlets.user.workspace.server.GWTWorkspaceBuilder; -import org.gcube.portlets.user.workspace.server.notifications.NotificationsProducer; import org.gcube.portlets.user.workspace.server.notifications.tostoragehub.NotificationsProducerToStorageHub; import org.gcube.portlets.user.workspace.server.resolver.UriResolverReaderParameterForResolverIndex; import org.gcube.portlets.user.workspace.server.resolver.UriResolverReaderParameterForResolverIndex.RESOLVER_TYPE; import org.gcube.portlets.user.workspace.server.tostoragehub.StorageHubToWorkpaceConverter; import org.gcube.portlets.user.workspace.server.util.resource.PropertySpecialFolderReader; import org.gcube.portlets.user.workspace.server.util.scope.ScopeUtilFilter; -import org.gcube.portlets.widgets.workspacesharingwidget.shared.InfoContactModel; +import org.gcube.portlets.widgets.workspacesharingwidget.server.notifications.NotificationsProducer; import org.gcube.vomanagement.usermanagement.model.GCubeUser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import com.liferay.portal.service.UserLocalServiceUtil; + /** * The Class WsUtil. * - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * Nov 25, 2016 + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * + * Aug 1, 2019 */ public class WsUtil { public static final String FOLDER_PUBLISHING_ON_THREDDS = "FolderPublishingOnThredds"; - protected static Logger logger = Logger.getLogger(WsUtil.class); + protected static Logger logger = LoggerFactory.getLogger(WsUtil.class); public static final String FOLDERIMPORTER_ATTRIBUTE = "FOLDER_IMPORTER"; public static final String METADATACONVERTER_ATTRIBUTE = "METADATA_CONVERTER"; @@ -134,136 +128,6 @@ public class WsUtil { return PortalContext.getConfiguration().getCurrentUser(httpServletRequest) == null; } - /** - * Gets the workspace. - * - * @param httpServletRequest - * Servlet request - * @return Workspace - * @throws org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException - * Folder not found error - * @throws org.gcube.common.homelibrary.home.exceptions.InternalErrorException - * Internal error - * @throws HomeNotFoundException - * Home not found error - */ - public static Workspace getWorkspace(HttpServletRequest httpServletRequest) - throws org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException, - org.gcube.common.homelibrary.home.exceptions.InternalErrorException, HomeNotFoundException { - - logger.trace("Get Workspace"); - PortalContextInfo info = getPortalContext(httpServletRequest); - logger.trace("PortalContextInfo: " + info); - - ScopeProvider.instance.set(info.getCurrentScope()); - logger.trace("Scope provider instancied"); - - Workspace workspace = HomeLibrary.getUserWorkspace(info.getUsername()); - return workspace; - } - - /** - * Gets the workspace. - * - * - * @param httpServletRequest - * Workspace - * @param contextID - * contexId - * @param user - * user - * @return Workspace - * @throws InternalErrorException - * Internal error - * @throws HomeNotFoundException - * Home not found error - * @throws WorkspaceFolderNotFoundException - * Folder not found error - * @throws org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException - * folder not found error - * @throws org.gcube.common.homelibrary.home.exceptions.InternalErrorException - * internal error - */ - public static Workspace getWorkspace(HttpServletRequest httpServletRequest, String contextID, GCubeUser user) - throws InternalErrorException, HomeNotFoundException, WorkspaceFolderNotFoundException, - org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException, - org.gcube.common.homelibrary.home.exceptions.InternalErrorException { - logger.info("Get workspace using contextID: " + contextID + ", current user: " + user.getUsername()); - String currentScope; - - if (isWithinPortal()) - currentScope = PortalContext.getConfiguration().getCurrentScope(contextID); - else { - currentScope = PortalContext.getConfiguration().getCurrentScope(httpServletRequest); - logger.warn("STARTING IN TEST MODE!!!! USING SCOPE: " + currentScope); - } - - logger.info("For ContextID: " + contextID + ", read scope from Portal Context: " + currentScope); - PortalContextInfo info = getPortalContext(httpServletRequest, currentScope); - logger.trace("PortalContextInfo: " + info); - - ScopeProvider.instance.set(info.getCurrentScope()); - logger.trace("Scope provider instancied"); - - String username = null; - try { - if (user.getUsername().compareTo(info.getUsername()) != 0) { - logger.debug("Gcube user read from Portal Context " + user.getUsername() - + " is different by GCubeUser passed, using the second one: " + info.getUsername()); - username = user.getUsername(); - } - - } catch (Exception e) { - logger.error("Error comparing username read from input parameter and Portal context"); - } - - if (username != null) - info.setUsername(username); - - Workspace workspace = HomeLibrary.getUserWorkspace(info.getUsername()); - return workspace; - - } - - /** - * utility method extract the @domain.com from an email address - * return @unknown-domain in case of no emails - */ - private String extractDomainFromEmail(String email) { - int index = email.indexOf('@'); - if (index > 0) - return email.substring(index); - else - return "@unknown-domain"; - } - - /** - * Gets the GWT workspace builder. - * - * @param httpServletRequest - * the http servlet request - * @return the GWT workspace builder - */ - public static GWTWorkspaceBuilder getGWTWorkspaceBuilder(HttpServletRequest httpServletRequest) { - PortalContextInfo info = getPortalContext(httpServletRequest); - logger.trace("PortalContextInfo: " + info); - - HttpSession session = httpServletRequest.getSession(); - - GWTWorkspaceBuilder builder = (GWTWorkspaceBuilder) session.getAttribute(WORKSPACEBUILDER_ATTRIBUTE); - if (builder == null) { - logger.info("Initializing the workspace area builder"); - builder = new GWTWorkspaceBuilder(); - // ADDED 03/09/2013 - builder.setContexInfo( - new InfoContactModel(info.getUsername(), info.getUsername(), info.getUserFullName(), "", false), - info.getCurrentScope()); - session.setAttribute(WORKSPACEBUILDER_ATTRIBUTE, builder); - } - - return builder; - } - /** * Gets the notification manager. * @@ -338,19 +202,24 @@ public class WsUtil { * @return true, if is vre */ public static boolean isVRE(String scope) { - - int slashCount = StringUtils.countMatches(scope, "/"); - - if (slashCount < 3) { - logger.trace("currentScope is not VRE"); + + if(scope==null || scope.isEmpty()) return false; + + String[] splitted = scope.split("/"); + logger.trace("scope splitted: "+splitted.length); + + if(splitted.length==4) { + logger.trace("currentScope is VRE"); + return true; } - - logger.trace("currentScope is VRE"); - return true; + + logger.trace("currentScope is not VRE"); + return false; } - + + /** * Gets the scope util filter. * @@ -566,42 +435,6 @@ public class WsUtil { } - // /** - // * Gets the notification manager to storage hub. - // * - // * @param httpServletRequest the http servlet request - // * @return the notification manager to storage hub - // */ - // public static NotificationsManager - // getNotificationManagerToStorageHub(HttpServletRequest httpServletRequest) - // { - // PortalContextInfo info = getPortalContext(httpServletRequest); - // HttpSession session = httpServletRequest.getSession(); - // NotificationsManager notifMng = (NotificationsManager) - // session.getAttribute(NOTIFICATION_MANAGER_TO_STORAGEHUB); - // - // if (notifMng == null) { - // try{ - // logger.trace("Create new NotificationsManager for user: - // "+info.getUsername()); - // logger.trace("New ApplicationNotificationsManager with portlet class - // name: "+NOTIFICATION_PORTLET_CLASS_ID); - // SocialNetworkingSite site = new SocialNetworkingSite(httpServletRequest); - // SocialNetworkingUser curser = new - // SocialNetworkingUser(info.getUsername(), info.getUserEmail(), - // info.getUserFullName(), info.getUserAvatarID()); - // notifMng = new ApplicationNotificationsManager(site, - // info.getCurrentScope(), curser, NOTIFICATION_PORTLET_CLASS_ID); - // session.setAttribute(NOTIFICATION_MANAGER_TO_STORAGEHUB, notifMng); - // }catch (Exception e) { - // logger.error("An error occurred instancing - // ApplicationNotificationsManager for user: "+info.getUsername(),e); - // } - // } - // - // return notifMng; - // } - /** * Gets the notification producer to storage hub. * diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/util/resource/PropertySpecialFolderReader.java b/src/main/java/org/gcube/portlets/user/workspace/server/util/resource/PropertySpecialFolderReader.java index e0f81f7..56c8624 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/util/resource/PropertySpecialFolderReader.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/util/resource/PropertySpecialFolderReader.java @@ -7,8 +7,9 @@ import java.io.File; import java.io.FileInputStream; import java.util.Properties; -import org.apache.log4j.Logger; import org.gcube.portlets.user.workspace.client.ConstantsExplorer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it @@ -18,7 +19,7 @@ import org.gcube.portlets.user.workspace.client.ConstantsExplorer; public class PropertySpecialFolderReader { - protected static Logger logger = Logger.getLogger(PropertySpecialFolderReader.class); + protected static Logger logger = LoggerFactory.getLogger(PropertySpecialFolderReader.class); protected String specialFolderName = ""; public PropertySpecialFolderReader(String absolutePath) throws PropertyFileReadingErrorException { diff --git a/src/main/java/org/gcube/portlets/user/workspace/server/util/scope/ScopeUtilFilter.java b/src/main/java/org/gcube/portlets/user/workspace/server/util/scope/ScopeUtilFilter.java index 820523a..d4709dd 100644 --- a/src/main/java/org/gcube/portlets/user/workspace/server/util/scope/ScopeUtilFilter.java +++ b/src/main/java/org/gcube/portlets/user/workspace/server/util/scope/ScopeUtilFilter.java @@ -1,18 +1,18 @@ package org.gcube.portlets.user.workspace.server.util.scope; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class ScopeUtilFilter { private static final String SCOPE_SEPARATOR = "/"; private String scopeRoot = null; - public static Logger logger = Logger.getLogger(ScopeUtilFilter.class); + public static Logger logger = LoggerFactory.getLogger(ScopeUtilFilter.class); public Map hashScopesFiltered = new HashMap(); public static final String ALLSCOPE = "All spaces"; @@ -20,10 +20,9 @@ public class ScopeUtilFilter { /** * - * @param scopeName - * scope name - * @param addIdAllSpaces - * if true add "ID All spaces" - "All spaces" pair into map + * @param scopeName scope name + * @param addIdAllSpaces if true add "ID All spaces" - "All spaces" pair into + * map */ public ScopeUtilFilter(String scopeName, boolean addIdAllSpaces) { @@ -48,7 +47,6 @@ public class ScopeUtilFilter { public List convertListScopeToPortlet(List listScopes) { logger.trace("List Scope converting..." + listScopes); - List scopesConverted = new ArrayList(); scopesConverted.add(ALLSCOPE); @@ -128,23 +126,15 @@ public class ScopeUtilFilter { public String getScopeRoot() { return scopeRoot; } - - public static void main(String[] args) { - String scope = "/gcube"; - - List listTest = Arrays.asList(new String[] { "/gcube/devsec/devre", "/gcube/devsec", - "/gcube/devsec/devNEXT", "/", "/gcub", "/gcube" }); - - ScopeUtilFilter filter = new ScopeUtilFilter(scope, false); - - System.out.println("scope root is: " + filter.getScopeRoot()); - - filter.convertListScopeToPortlet(listTest); - - System.out.println("get portal scope for /devsec: " + filter.getPortalScopeFromFilteredScope("/devsec")); - - filter.printScopes(); - - } + /* + * public static void main(String[] args) { String scope = "/gcube"; + * List listTest = Arrays.asList(new String[] { "/gcube/devsec/devre", + * "/gcube/devsec", "/gcube/devsec/devNEXT", "/", "/gcub", "/gcube" }); + * ScopeUtilFilter filter = new ScopeUtilFilter(scope, false); + * System.out.println("scope root is: " + filter.getScopeRoot()); + * filter.convertListScopeToPortlet(listTest); + * System.out.println("get portal scope for /devsec: " + + * filter.getPortalScopeFromFilteredScope("/devsec")); filter.printScopes(); } + */ } diff --git a/src/main/java/org/gcube/portlets/user/workspace/shared/ListContact.java b/src/main/java/org/gcube/portlets/user/workspace/shared/ListContact.java new file mode 100644 index 0000000..e9ae794 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/workspace/shared/ListContact.java @@ -0,0 +1,43 @@ +/** + * + */ +package org.gcube.portlets.user.workspace.shared; + +import java.io.Serializable; +import java.util.ArrayList; + +import org.gcube.portlets.widgets.workspacesharingwidget.shared.InfoContactModel; + +/** + * + * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it + * Nov 4, 2015 + */ +public class ListContact extends ArrayList implements Serializable{ + + + private static final long serialVersionUID = 544202687567940083L; + + public ListContact() { + } + + public boolean contains(InfoContactModel infoContactModel) { + + if(infoContactModel==null) + return false; + + + if(infoContactModel.getLogin()==null) + return false; + + + for (int i = 0; i < this.size(); i++){ + + InfoContactModel log = get(i); + if (log.getLogin()!=null && log.getLogin().compareTo(infoContactModel.getLogin())==0) + return true; + } + + return false; + } +} diff --git a/src/main/resources/WsExtensionToMimeTypeMap.properties b/src/main/resources/WsExtensionToMimeTypeMap.properties index f122032..f70f355 100644 --- a/src/main/resources/WsExtensionToMimeTypeMap.properties +++ b/src/main/resources/WsExtensionToMimeTypeMap.properties @@ -185,6 +185,7 @@ text/plain=txt text/richtext=rtx text/scriptlet=sct text/tab-separated-values=tsv +text/uri-list=txt text/webviewhtml=htt text/x-component=htc text/x-setext=etx diff --git a/src/main/resources/WsMimeTypeToExtensionMap.properties b/src/main/resources/WsMimeTypeToExtensionMap.properties index a8b324b..f0ee081 100644 --- a/src/main/resources/WsMimeTypeToExtensionMap.properties +++ b/src/main/resources/WsMimeTypeToExtensionMap.properties @@ -153,6 +153,7 @@ text/plain=txt text/richtext=rtx text/scriptlet=sct text/tab-separated-values=tsv +text/uri-list=txt text/webviewhtml=htt text/x-component=htc text/x-setext=etx diff --git a/src/test/java/org/gcube/portlets/user/workspace/CreateSharedFolder.java b/src/test/java/org/gcube/portlets/user/workspace/CreateSharedFolder.java index 9ac196d..2fd85ff 100644 --- a/src/test/java/org/gcube/portlets/user/workspace/CreateSharedFolder.java +++ b/src/test/java/org/gcube/portlets/user/workspace/CreateSharedFolder.java @@ -1,86 +1,88 @@ -/** - * - */ -package org.gcube.portlets.user.workspace; +//TODO IT MUST BE MOVED TO SHUB -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Logger; -import org.gcube.common.homelibrary.home.HomeLibrary; -import org.gcube.common.homelibrary.home.exceptions.HomeNotFoundException; -import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; -import org.gcube.common.homelibrary.home.exceptions.UserNotFoundException; -import org.gcube.common.homelibrary.home.workspace.Workspace; -import org.gcube.common.homelibrary.home.workspace.WorkspaceSharedFolder; -import org.gcube.common.homelibrary.home.workspace.exceptions.InsufficientPrivilegesException; -import org.gcube.common.homelibrary.home.workspace.exceptions.ItemAlreadyExistException; -import org.gcube.common.homelibrary.home.workspace.exceptions.ItemNotFoundException; -import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException; -import org.gcube.common.homelibrary.home.workspace.exceptions.WrongDestinationException; -import org.gcube.common.scope.api.ScopeProvider; -import org.gcube.common.scope.impl.ScopeBean; - -/** - * - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it Jul 14, 2015 - */ -public class CreateSharedFolder { - - protected static Logger logger = Logger.getLogger(CreateSharedFolder.class); -// public static String DEFAULT_SCOPE = "/d4science.research-infrastructures.eu/gCubeApps/EcologicalModelling"; //PRODUCTION - public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV - - public static String USER = "francesco.mangiacrapa"; //PRODUCTION - - public static void main(String[] args) { - - try { - ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); - ScopeProvider.instance.set(scope.toString()); - Workspace workspace = HomeLibrary.getHomeManagerFactory() - .getHomeManager().getHome(USER) - .getWorkspace(); - - String folderName = "Test Folder"; - String desc = "descr"; - List listLogin = new ArrayList(); - - listLogin.add("valentina.marioli"); - listLogin.add("massimiliano.assante"); - - WorkspaceSharedFolder sharedFolder = workspace.createSharedFolder( - folderName, desc, listLogin, workspace.getRoot().getId()); - - if (sharedFolder == null) - System.out.println("shared folder is null"); - - System.out - .println("Shared folder created: " + sharedFolder.getId()); - } catch (InsufficientPrivilegesException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (ItemAlreadyExistException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (WrongDestinationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (ItemNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (WorkspaceFolderNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InternalErrorException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (HomeNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (UserNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } -} +///** +// * +// */ +//package org.gcube.portlets.user.workspace; +// +//import java.util.ArrayList; +//import java.util.List; +// +//import org.apache.log4j.Logger; +//import org.gcube.common.homelibrary.home.HomeLibrary; +//import org.gcube.common.homelibrary.home.exceptions.HomeNotFoundException; +//import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; +//import org.gcube.common.homelibrary.home.exceptions.UserNotFoundException; +//import org.gcube.common.homelibrary.home.workspace.Workspace; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceSharedFolder; +//import org.gcube.common.homelibrary.home.workspace.exceptions.InsufficientPrivilegesException; +//import org.gcube.common.homelibrary.home.workspace.exceptions.ItemAlreadyExistException; +//import org.gcube.common.homelibrary.home.workspace.exceptions.ItemNotFoundException; +//import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException; +//import org.gcube.common.homelibrary.home.workspace.exceptions.WrongDestinationException; +//import org.gcube.common.scope.api.ScopeProvider; +//import org.gcube.common.scope.impl.ScopeBean; +// +///** +// * +// * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it Jul 14, 2015 +// */ +//public class CreateSharedFolder { +// +// protected static Logger logger = Logger.getLogger(CreateSharedFolder.class); +//// public static String DEFAULT_SCOPE = "/d4science.research-infrastructures.eu/gCubeApps/EcologicalModelling"; //PRODUCTION +// public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV +// +// public static String USER = "francesco.mangiacrapa"; //PRODUCTION +// +// public static void main(String[] args) { +// +// try { +// ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); +// ScopeProvider.instance.set(scope.toString()); +// Workspace workspace = HomeLibrary.getHomeManagerFactory() +// .getHomeManager().getHome(USER) +// .getWorkspace(); +// +// String folderName = "Test Folder"; +// String desc = "descr"; +// List listLogin = new ArrayList(); +// +// listLogin.add("valentina.marioli"); +// listLogin.add("massimiliano.assante"); +// +// WorkspaceSharedFolder sharedFolder = workspace.createSharedFolder( +// folderName, desc, listLogin, workspace.getRoot().getId()); +// +// if (sharedFolder == null) +// System.out.println("shared folder is null"); +// +// System.out +// .println("Shared folder created: " + sharedFolder.getId()); +// } catch (InsufficientPrivilegesException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (ItemAlreadyExistException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (WrongDestinationException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (ItemNotFoundException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (WorkspaceFolderNotFoundException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (InternalErrorException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (HomeNotFoundException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (UserNotFoundException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } +// } +//} diff --git a/src/test/java/org/gcube/portlets/user/workspace/DeleteTest.java b/src/test/java/org/gcube/portlets/user/workspace/DeleteTest.java index b052877..5e85747 100644 --- a/src/test/java/org/gcube/portlets/user/workspace/DeleteTest.java +++ b/src/test/java/org/gcube/portlets/user/workspace/DeleteTest.java @@ -1,229 +1,238 @@ -/** - * - */ -package org.gcube.portlets.user.workspace; - -import java.util.ArrayList; -import java.util.List; - -import org.gcube.common.homelibary.model.items.type.WorkspaceItemType; -import org.gcube.common.homelibrary.home.HomeLibrary; -import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; -import org.gcube.common.homelibrary.home.workspace.Workspace; -import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; -import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; -import org.gcube.common.homelibrary.home.workspace.exceptions.InsufficientPrivilegesException; -import org.gcube.common.homelibrary.home.workspace.exceptions.ItemNotFoundException; -import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; -import org.gcube.common.scope.api.ScopeProvider; -import org.gcube.common.scope.impl.ScopeBean; -import org.gcube.portlets.user.workspace.client.model.FileGridModel; -import org.gcube.portlets.user.workspace.server.GWTWorkspaceBuilder; - -/** - * - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * Oct 28, 2015 - */ -public class DeleteTest { - - - public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV -// public static String DEFAULT_SCOPE = "/d4science.research-infrastructures.eu/gCubeApps/DESCRAMBLE"; - public static String TEST_USER = "francesco.mangiacrapa"; - - public static String PARENT_ID = "a9ead58c-d645-4699-addd-5c6e5f1aff06"; - private static Workspace ws; - - private static GWTWorkspaceBuilder builder = new GWTWorkspaceBuilder(); - - public static void main(String[] args) { - - try { - - ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); - ScopeProvider.instance.set(scope.toString()); - - ws = HomeLibrary - .getHomeManagerFactory() - .getHomeManager() - .getHome(TEST_USER) - .getWorkspace(); - // - - final List children = getIdsOnlyFolderForID(PARENT_ID); - - - if(children.size()<2){ - System.err.println("children size < 2, add others children"); - return; - } - - final int medium = children.size()/2; - - Thread t1 = new Thread("T1"){ - public void run() { - System.out.println("T1 start..."); - removeRange(children, 0, medium); - System.out.println("T1 end"); - - }; - }; - - t1.start(); - t1.join(); - - List childrenNEW = getChildrenForID(PARENT_ID); - - print(childrenNEW); - - - Thread t2 = new Thread("T2"){ - public void run() { - System.out.println("T2 start..."); - removeRange(children, medium, children.size()); - System.out.println("T2 end"); - }; - }; - - t2.start(); - t2.join(); - - childrenNEW = getChildrenForID(PARENT_ID); - print(childrenNEW); - - - System.out.println("\n\nDONE!"); - } catch (Exception e) { - e.printStackTrace(); - } - } - - - private static void print(final List children){ - int i=0; - System.out.println("\n\n"); - for (WorkspaceItem workspaceItem : children) { - - if(workspaceItem.getType().equals(WorkspaceItemType.FOLDER) || workspaceItem.getType().equals(WorkspaceItemType.SHARED_FOLDER)){ - - WorkspaceFolder folder = (WorkspaceFolder) workspaceItem; - - try { - System.err.println(++i+") folder id: "+folder.getId() +", folder name: "+folder.getName()); - } catch (InternalErrorException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else{ - - - if(workspaceItem.getType().equals(WorkspaceItemType.FOLDER_ITEM)){ - - FolderItem folderItem = (FolderItem) workspaceItem; - - try { - System.err.println(++i+") folderItem id: "+folderItem.getId() +", name: "+folderItem.getName() + ", size: "+folderItem.getLength()); - } catch (InternalErrorException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - } - } - - System.out.println("\n\n"); - } - - private static List getChildrenForID(String id){ - - WorkspaceFolder folder; - try { - System.out.println("start getItem on id "+id); - folder = (WorkspaceFolder) ws.getItem(id); - System.out.println("start get children on folder "+folder.getName()); - final List children = folder.getChildren(); - - builder.buildGXTListFileGridModelItem(folder.getChildren(), null); - -// builder.buildGXTFileGridModelItem(folder, null); - - System.out.println("children size: "+children.size()); - return children; - } catch (ItemNotFoundException | InternalErrorException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return null; - } - } - - private static List getIdsForID(String id){ - - - try { - List children = getChildrenForID(id); - List ids = new ArrayList(children.size()); - for (WorkspaceItem workspaceItem : children) { - ids.add(workspaceItem.getId()); - } - return ids; - } catch (InternalErrorException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return null; - } - } - - private static List getIdsOnlyFolderForID(String id){ - - - try { - List children = getChildrenForID(id); - List ids = new ArrayList(children.size()); - for (WorkspaceItem workspaceItem : children) { - if(workspaceItem.isFolder()) - ids.add(workspaceItem.getId()); - } - return ids; - } catch (InternalErrorException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return null; - } - } - - - - private static void removeRange(List children, int start, int end) { - - System.out.println("start "+start); - System.out.println("end "+end); -// System.out.println("(end - start)"+(end - start)); - - List sub = children.subList(start, end); - String[] array = new String[sub.size()]; - array = sub.toArray(array); - - System.out.println("array lenght: "+array.length); - - for (String id : array) - System.out.println("Removing "+id); - - try { - ws.removeItems(array); - - System.out.println("Remove OK "); - } catch (ItemNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InsufficientPrivilegesException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InternalErrorException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - -} +//TODO IT MUST BE MOVED TO SHUB +///** +// * +// */ +//package org.gcube.portlets.user.workspace; +// +//import java.util.ArrayList; +//import java.util.List; +// +//import org.gcube.common.homelibary.model.items.type.WorkspaceItemType; +//import org.gcube.common.homelibrary.home.HomeLibrary; +//import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; +//import org.gcube.common.homelibrary.home.workspace.Workspace; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; +//import org.gcube.common.homelibrary.home.workspace.exceptions.InsufficientPrivilegesException; +//import org.gcube.common.homelibrary.home.workspace.exceptions.ItemNotFoundException; +//import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; +//import org.gcube.common.scope.api.ScopeProvider; +//import org.gcube.common.scope.impl.ScopeBean; +//import org.gcube.portlets.user.workspace.client.model.FileGridModel; +// +///** +// * +// * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it +// * Oct 28, 2015 +// */ +///* +// * +// * +// * IT MUST BE MOVED TO SHUB +// * +// * +// * +//public class DeleteTest { +// +// +// public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV +//// public static String DEFAULT_SCOPE = "/d4science.research-infrastructures.eu/gCubeApps/DESCRAMBLE"; +// public static String TEST_USER = "francesco.mangiacrapa"; +// +// public static String PARENT_ID = "a9ead58c-d645-4699-addd-5c6e5f1aff06"; +// private static Workspace ws; +// +// private static GWTWorkspaceBuilder builder = new GWTWorkspaceBuilder(); +// +// public static void main(String[] args) { +// +// try { +// +// ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); +// ScopeProvider.instance.set(scope.toString()); +// +// ws = HomeLibrary +// .getHomeManagerFactory() +// .getHomeManager() +// .getHome(TEST_USER) +// .getWorkspace(); +// // +// +// final List children = getIdsOnlyFolderForID(PARENT_ID); +// +// +// if(children.size()<2){ +// System.err.println("children size < 2, add others children"); +// return; +// } +// +// final int medium = children.size()/2; +// +// Thread t1 = new Thread("T1"){ +// public void run() { +// System.out.println("T1 start..."); +// removeRange(children, 0, medium); +// System.out.println("T1 end"); +// +// }; +// }; +// +// t1.start(); +// t1.join(); +// +// List childrenNEW = getChildrenForID(PARENT_ID); +// +// print(childrenNEW); +// +// +// Thread t2 = new Thread("T2"){ +// public void run() { +// System.out.println("T2 start..."); +// removeRange(children, medium, children.size()); +// System.out.println("T2 end"); +// }; +// }; +// +// t2.start(); +// t2.join(); +// +// childrenNEW = getChildrenForID(PARENT_ID); +// print(childrenNEW); +// +// +// System.out.println("\n\nDONE!"); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +// +// +// private static void print(final List children){ +// int i=0; +// System.out.println("\n\n"); +// for (WorkspaceItem workspaceItem : children) { +// +// if(workspaceItem.getType().equals(WorkspaceItemType.FOLDER) || workspaceItem.getType().equals(WorkspaceItemType.SHARED_FOLDER)){ +// +// WorkspaceFolder folder = (WorkspaceFolder) workspaceItem; +// +// try { +// System.err.println(++i+") folder id: "+folder.getId() +", folder name: "+folder.getName()); +// } catch (InternalErrorException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } +// }else{ +// +// +// if(workspaceItem.getType().equals(WorkspaceItemType.FOLDER_ITEM)){ +// +// FolderItem folderItem = (FolderItem) workspaceItem; +// +// try { +// System.err.println(++i+") folderItem id: "+folderItem.getId() +", name: "+folderItem.getName() + ", size: "+folderItem.getLength()); +// } catch (InternalErrorException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } +// } +// +// } +// } +// +// System.out.println("\n\n"); +// } +// +// private static List getChildrenForID(String id){ +// +// WorkspaceFolder folder; +// try { +// System.out.println("start getItem on id "+id); +// folder = (WorkspaceFolder) ws.getItem(id); +// System.out.println("start get children on folder "+folder.getName()); +// final List children = folder.getChildren(); +// +// builder.buildGXTListFileGridModelItem(folder.getChildren(), null); +// +//// builder.buildGXTFileGridModelItem(folder, null); +// +// System.out.println("children size: "+children.size()); +// return children; +// } catch (ItemNotFoundException | InternalErrorException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// return null; +// } +// } +// +// private static List getIdsForID(String id){ +// +// +// try { +// List children = getChildrenForID(id); +// List ids = new ArrayList(children.size()); +// for (WorkspaceItem workspaceItem : children) { +// ids.add(workspaceItem.getId()); +// } +// return ids; +// } catch (InternalErrorException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// return null; +// } +// } +// +// private static List getIdsOnlyFolderForID(String id){ +// +// +// try { +// List children = getChildrenForID(id); +// List ids = new ArrayList(children.size()); +// for (WorkspaceItem workspaceItem : children) { +// if(workspaceItem.isFolder()) +// ids.add(workspaceItem.getId()); +// } +// return ids; +// } catch (InternalErrorException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// return null; +// } +// } +// +// +// +// private static void removeRange(List children, int start, int end) { +// +// System.out.println("start "+start); +// System.out.println("end "+end); +//// System.out.println("(end - start)"+(end - start)); +// +// List sub = children.subList(start, end); +// String[] array = new String[sub.size()]; +// array = sub.toArray(array); +// +// System.out.println("array lenght: "+array.length); +// +// for (String id : array) +// System.out.println("Removing "+id); +// +// try { +// ws.removeItems(array); +// +// System.out.println("Remove OK "); +// } catch (ItemNotFoundException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (InsufficientPrivilegesException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (InternalErrorException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } +// } +// +//} +// +//*/ diff --git a/src/test/java/org/gcube/portlets/user/workspace/DephtVisitDonwloadFilesTester.java b/src/test/java/org/gcube/portlets/user/workspace/DephtVisitDonwloadFilesTester.java index 82d7496..9ba0e1e 100644 --- a/src/test/java/org/gcube/portlets/user/workspace/DephtVisitDonwloadFilesTester.java +++ b/src/test/java/org/gcube/portlets/user/workspace/DephtVisitDonwloadFilesTester.java @@ -1,199 +1,209 @@ -/** - * - */ -package org.gcube.portlets.user.workspace; - -import java.io.BufferedWriter; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStreamWriter; -import java.util.List; - -import org.apache.log4j.Logger; -import org.gcube.common.homelibary.model.items.type.FolderItemType; -import org.gcube.common.homelibary.model.items.type.WorkspaceItemType; -import org.gcube.common.homelibrary.home.HomeLibrary; -import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; -import org.gcube.common.homelibrary.home.workspace.Workspace; -import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; -import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; -import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; -import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalFile; -import org.gcube.common.scope.api.ScopeProvider; -import org.gcube.common.scope.impl.ScopeBean; - -/** - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * @Dec 17, 2013 - * - */ -public class DephtVisitDonwloadFilesTester { - - - protected static Logger logger = Logger.getLogger(SearchTextTest.class); -// public static String DEFAULT_SCOPE = "/d4science.research-infrastructures.eu/gCubeApps/EcologicalModelling"; //PRODUCTION - public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV - - public static String USER = "francesco.mangiacrapa"; //PRODUCTION - - private static BufferedWriter writer; - private static OutputStreamWriter out; - - static final String itemID = "165ba18a-a08a-42c6-ade5-9b93d1f844ac"; - static WorkspaceItem root; - - public static void main(String[] args) { - - try { - - ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); - ScopeProvider.instance.set(scope.toString()); - - Workspace ws = HomeLibrary.getHomeManagerFactory().getHomeManager().getHome(USER).getWorkspace(); - out = new OutputStreamWriter(new FileOutputStream("Csv-error-file.csv"), "UTF-8"); - writer = new BufferedWriter(out); - - writer.write("Id;Name;Path;Parent"); - - - System.out.println("Start"); -// WorkspaceItem root = ws.getRoot(); - - root = ws.getItem(itemID); - - depthVisit(root); - -// new Thread(){ -// public void run() { -// try { -// -// depthVisit(root); -// -// } catch (InternalErrorException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } -// }; -// -// }.start(); - - System.out.println("waiting 10 sec.."); - Thread.sleep(10000); - - - System.out.println("End"); - } catch (Exception e) { - e.printStackTrace(); - }finally{ - System.out.println("writer close"); - try {writer.close();} catch (Exception ex) {} - } - } - - public static void depthVisit(WorkspaceItem item) throws InternalErrorException { - - if (item.getType().equals(WorkspaceItemType.FOLDER) || item.getType().equals(WorkspaceItemType.SHARED_FOLDER)) { - - WorkspaceFolder folder = (WorkspaceFolder) item; - System.out.println("\nVisit Folder: " + folder.getName() +"; Folder is shared: "+folder.isShared()); - List children = folder.getChildren(); - - for (WorkspaceItem workspaceItem : children) { - depthVisit(workspaceItem); - } - } else { - - System.out.println("Item name: " + item.getName() +"; Parent Folder: "+item.getParent().getName()); - - if(item.getType().equals(WorkspaceItemType.FOLDER_ITEM)){ - - FolderItem folderItem = (FolderItem) item; - - if(folderItem.getFolderItemType().equals(FolderItemType.EXTERNAL_FILE)){ - - System.out.println("Item is external file: " + item.getName()); - - final ExternalFile f = (ExternalFile) folderItem; - - try{ - - Thread t = new Thread(){ - - public void run() { - - try { - tryGetPayload(f); - - } catch (Exception e) { - try { - System.out.println("Item name: "+f.getName() + "not exists into storage"); - erroFile(f); - } catch (InternalErrorException e1) { - } - - } - } - }; - - t.start(); - -// System.out.println("join 3 sec"); -// t.join(1000); +////TODO IT MUST BE MOVED TO SHUB +///** +// * +// */ +//package org.gcube.portlets.user.workspace; // -// System.out.println("join 1 sec terminated"); -// if(is==null) -// throw new Exception("is is null"); - - }catch (Exception e) { - System.out.println("Item name: "+f.getName() + "not exists into storage"); - erroFile(f); - } - - } - } - - } - } - - public static void tryGetPayload(ExternalFile f) throws Exception{ - - try { - - InputStream is = f.getData(); - System.out.println("Get payload for file : "+f.getName() +" terminated"); - - if(is==null) - throw new Exception("is is null"); - - } catch (InternalErrorException e1) { - System.out.println("Error on :"+f.getName()); - throw new Exception("is is null"); - } - - } - - public synchronized static void erroFile(WorkspaceItem item) throws InternalErrorException{ - - try{ - - try { - - String parentName=""; - - if(item.getParent()!=null) - parentName = item.getParent().getName(); - - writer.write("\n "+item.getId()+";"+item.getName()+";"+item.getPath()+";"+parentName); - - } catch (IOException ex) { - ex.printStackTrace(); - } - - - } catch (Exception e) { - e.printStackTrace(); - } - } - -} +//import java.io.BufferedWriter; +//import java.io.FileOutputStream; +//import java.io.IOException; +//import java.io.InputStream; +//import java.io.OutputStreamWriter; +//import java.util.List; +// +//import org.apache.log4j.Logger; +//import org.gcube.common.homelibary.model.items.type.FolderItemType; +//import org.gcube.common.homelibary.model.items.type.WorkspaceItemType; +//import org.gcube.common.homelibrary.home.HomeLibrary; +//import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; +//import org.gcube.common.homelibrary.home.workspace.Workspace; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; +//import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; +//import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalFile; +//import org.gcube.common.scope.api.ScopeProvider; +//import org.gcube.common.scope.impl.ScopeBean; +// +///** +// * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it +// * @Dec 17, 2013 +// * +// */ +///* +// * +// * +// * IT MUST BE MOVED TO SHUB +// * +// * +// * +//public class DephtVisitDonwloadFilesTester { +// +// +// protected static Logger logger = Logger.getLogger(SearchTextTest.class); +//// public static String DEFAULT_SCOPE = "/d4science.research-infrastructures.eu/gCubeApps/EcologicalModelling"; //PRODUCTION +// public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV +// +// public static String USER = "francesco.mangiacrapa"; //PRODUCTION +// +// private static BufferedWriter writer; +// private static OutputStreamWriter out; +// +// static final String itemID = "165ba18a-a08a-42c6-ade5-9b93d1f844ac"; +// static WorkspaceItem root; +// +// public static void main(String[] args) { +// +// try { +// +// ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); +// ScopeProvider.instance.set(scope.toString()); +// +// Workspace ws = HomeLibrary.getHomeManagerFactory().getHomeManager().getHome(USER).getWorkspace(); +// out = new OutputStreamWriter(new FileOutputStream("Csv-error-file.csv"), "UTF-8"); +// writer = new BufferedWriter(out); +// +// writer.write("Id;Name;Path;Parent"); +// +// +// System.out.println("Start"); +//// WorkspaceItem root = ws.getRoot(); +// +// root = ws.getItem(itemID); +// +// depthVisit(root); +// +//// new Thread(){ +//// public void run() { +//// try { +//// +//// depthVisit(root); +//// +//// } catch (InternalErrorException e) { +//// // TODO Auto-generated catch block +//// e.printStackTrace(); +//// } +//// }; +//// +//// }.start(); +// +// System.out.println("waiting 10 sec.."); +// Thread.sleep(10000); +// +// +// System.out.println("End"); +// } catch (Exception e) { +// e.printStackTrace(); +// }finally{ +// System.out.println("writer close"); +// try {writer.close();} catch (Exception ex) {} +// } +// } +// +// public static void depthVisit(WorkspaceItem item) throws InternalErrorException { +// +// if (item.getType().equals(WorkspaceItemType.FOLDER) || item.getType().equals(WorkspaceItemType.SHARED_FOLDER)) { +// +// WorkspaceFolder folder = (WorkspaceFolder) item; +// System.out.println("\nVisit Folder: " + folder.getName() +"; Folder is shared: "+folder.isShared()); +// List children = folder.getChildren(); +// +// for (WorkspaceItem workspaceItem : children) { +// depthVisit(workspaceItem); +// } +// } else { +// +// System.out.println("Item name: " + item.getName() +"; Parent Folder: "+item.getParent().getName()); +// +// if(item.getType().equals(WorkspaceItemType.FOLDER_ITEM)){ +// +// FolderItem folderItem = (FolderItem) item; +// +// if(folderItem.getFolderItemType().equals(FolderItemType.EXTERNAL_FILE)){ +// +// System.out.println("Item is external file: " + item.getName()); +// +// final ExternalFile f = (ExternalFile) folderItem; +// +// try{ +// +// Thread t = new Thread(){ +// +// public void run() { +// +// try { +// tryGetPayload(f); +// +// } catch (Exception e) { +// try { +// System.out.println("Item name: "+f.getName() + "not exists into storage"); +// erroFile(f); +// } catch (InternalErrorException e1) { +// } +// +// } +// } +// }; +// +// t.start(); +// +//// System.out.println("join 3 sec"); +//// t.join(1000); +//// +//// System.out.println("join 1 sec terminated"); +//// if(is==null) +//// throw new Exception("is is null"); +// +// }catch (Exception e) { +// System.out.println("Item name: "+f.getName() + "not exists into storage"); +// erroFile(f); +// } +// +// } +// } +// +// } +// } +// +// public static void tryGetPayload(ExternalFile f) throws Exception{ +// +// try { +// +// InputStream is = f.getData(); +// System.out.println("Get payload for file : "+f.getName() +" terminated"); +// +// if(is==null) +// throw new Exception("is is null"); +// +// } catch (InternalErrorException e1) { +// System.out.println("Error on :"+f.getName()); +// throw new Exception("is is null"); +// } +// +// } +// +// public synchronized static void erroFile(WorkspaceItem item) throws InternalErrorException{ +// +// try{ +// +// try { +// +// String parentName=""; +// +// if(item.getParent()!=null) +// parentName = item.getParent().getName(); +// +// writer.write("\n "+item.getId()+";"+item.getName()+";"+item.getPath()+";"+parentName); +// +// } catch (IOException ex) { +// ex.printStackTrace(); +// } +// +// +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +// +//} +// +//*/ diff --git a/src/test/java/org/gcube/portlets/user/workspace/DonwloadServletTest.java b/src/test/java/org/gcube/portlets/user/workspace/DonwloadServletTest.java index e1d86dd..d041ad7 100644 --- a/src/test/java/org/gcube/portlets/user/workspace/DonwloadServletTest.java +++ b/src/test/java/org/gcube/portlets/user/workspace/DonwloadServletTest.java @@ -1,119 +1,121 @@ -/** - * - */ -package org.gcube.portlets.user.workspace; +//TODO IT MUST BE MOVED TO SHUB +///** -import java.util.List; - -import org.gcube.common.homelibary.model.items.type.FolderItemType; -import org.gcube.common.homelibary.model.items.type.WorkspaceItemType; -import org.gcube.common.homelibrary.home.HomeLibrary; -import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; -import org.gcube.common.homelibrary.home.workspace.Workspace; -import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; -import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; -import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; -import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalFile; - -/** - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * Jun 18, 2013 - * - */ -public class DonwloadServletTest { - - public static void main(String[] args) { - -// InputStream is = null; +// * +// */ +//package org.gcube.portlets.user.workspace; // -// System.out.println("start"); +//import java.util.List; // -// is = GCUBEStorage.getRemoteFile("/Home/francesco.mangiacrapa/Workspace284ee688-e6fb-4080-bbcb-cc7c8cc5c381"); - - try { - - Workspace ws = HomeLibrary - .getHomeManagerFactory() - .getHomeManager() - .getHome("francesco.mangiacrapa") - .getWorkspace(); - // - - WorkspaceItem root = ws.getRoot(); - - List children = root.getChildren(); - - - for (WorkspaceItem workspaceItem : children) { - - if(workspaceItem.getType().equals(WorkspaceItemType.FOLDER_ITEM)){ - - FolderItem folderItem = (FolderItem) workspaceItem; - - if(folderItem.getFolderItemType().equals(FolderItemType.EXTERNAL_FILE)){ - - ExternalFile f = (ExternalFile) folderItem; - - System.out.println("folderItem name: "+f.getName() + ", public link: "+f.getPublicLink()); - } - - } - - - } - - -// WorkspaceItem item = ws.getItem("8ad4e104-0f34-413e-a88c-e754a81104e7"); +//import org.gcube.common.homelibary.model.items.type.FolderItemType; +//import org.gcube.common.homelibary.model.items.type.WorkspaceItemType; +//import org.gcube.common.homelibrary.home.HomeLibrary; +//import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; +//import org.gcube.common.homelibrary.home.workspace.Workspace; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; +//import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; +//import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalFile; +// +///** +// * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it +// * Jun 18, 2013 +// * +// */ +//public class DonwloadServletTest { +// +// public static void main(String[] args) { +// +//// InputStream is = null; +//// +//// System.out.println("start"); +//// +//// is = GCUBEStorage.getRemoteFile("/Home/francesco.mangiacrapa/Workspace284ee688-e6fb-4080-bbcb-cc7c8cc5c381"); +// +// try { +// +// Workspace ws = HomeLibrary +// .getHomeManagerFactory() +// .getHomeManager() +// .getHome("francesco.mangiacrapa") +// .getWorkspace(); +// // +// +// WorkspaceItem root = ws.getRoot(); +// +// List children = root.getChildren(); // // -// ExternalFile f = (ExternalFile) item; +// for (WorkspaceItem workspaceItem : children) { +// +// if(workspaceItem.getType().equals(WorkspaceItemType.FOLDER_ITEM)){ +// +// FolderItem folderItem = (FolderItem) workspaceItem; +// +// if(folderItem.getFolderItemType().equals(FolderItemType.EXTERNAL_FILE)){ +// +// ExternalFile f = (ExternalFile) folderItem; +// +// System.out.println("folderItem name: "+f.getName() + ", public link: "+f.getPublicLink()); +// } +// +// } // // -// System.out.println("Public link: "+f.getPublicLink()); -// FileOutputStream out = new FileOutputStream(new File("/tmp/bla")); -// // byte[] buffer = new byte[1024]; -// // int len; -// // while ((len = is.read(buffer)) != -1) { -// // out.write(buffer, 0, len); -// // } +// } // - - -// is = f.getData(); - - -// IOUtils.copy(is, out); -// is.close(); // -// out.close(); - - // System.out.println("Sleeping"); - // Thread.sleep(20000); - // System.out.println("Alive"); - - System.out.println("end"); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public void depthVisit(WorkspaceItem item) throws InternalErrorException{ - - - if(item.getType().equals(WorkspaceItemType.FOLDER_ITEM)){ - - WorkspaceFolder folder = (WorkspaceFolder) item; - System.out.println("Visit Folder: "+folder.getName()); - List children = folder.getChildren(); - - for (WorkspaceItem workspaceItem : children) { - depthVisit(workspaceItem); - } - }else{ - - System.out.println("Item name: "+item.getName()); - - } - } - -} +//// WorkspaceItem item = ws.getItem("8ad4e104-0f34-413e-a88c-e754a81104e7"); +//// +//// +//// ExternalFile f = (ExternalFile) item; +//// +//// +//// System.out.println("Public link: "+f.getPublicLink()); +//// FileOutputStream out = new FileOutputStream(new File("/tmp/bla")); +//// // byte[] buffer = new byte[1024]; +//// // int len; +//// // while ((len = is.read(buffer)) != -1) { +//// // out.write(buffer, 0, len); +//// // } +//// +// +// +//// is = f.getData(); +// +// +//// IOUtils.copy(is, out); +//// is.close(); +//// +//// out.close(); +// +// // System.out.println("Sleeping"); +// // Thread.sleep(20000); +// // System.out.println("Alive"); +// +// System.out.println("end"); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +// +// public void depthVisit(WorkspaceItem item) throws InternalErrorException{ +// +// +// if(item.getType().equals(WorkspaceItemType.FOLDER_ITEM)){ +// +// WorkspaceFolder folder = (WorkspaceFolder) item; +// System.out.println("Visit Folder: "+folder.getName()); +// List children = folder.getChildren(); +// +// for (WorkspaceItem workspaceItem : children) { +// depthVisit(workspaceItem); +// } +// }else{ +// +// System.out.println("Item name: "+item.getName()); +// +// } +// } +// +//} diff --git a/src/test/java/org/gcube/portlets/user/workspace/GcubeProperties.java b/src/test/java/org/gcube/portlets/user/workspace/GcubeProperties.java index 8d1f7db..2549d36 100644 --- a/src/test/java/org/gcube/portlets/user/workspace/GcubeProperties.java +++ b/src/test/java/org/gcube/portlets/user/workspace/GcubeProperties.java @@ -1,53 +1,54 @@ -/** - * - */ -package org.gcube.portlets.user.workspace; - -import org.apache.log4j.Logger; -import org.gcube.common.homelibrary.home.HomeLibrary; -import org.gcube.common.homelibrary.home.exceptions.HomeNotFoundException; -import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; -import org.gcube.common.homelibrary.home.workspace.Workspace; -import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException; -import org.gcube.common.homelibrary.home.workspace.folder.items.GCubeItem; -import org.gcube.common.scope.api.ScopeProvider; -import org.gcube.common.scope.impl.ScopeBean; - -/** - * - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * Jun 12, 2015 - */ -public class GcubeProperties { - public static Logger logger = Logger.getLogger(GcubeProperties.class); - public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV - public static String TEST_USER = "francesco.mangiacrapa"; - - public static void main(String[] args) { - - try{ - ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); - ScopeProvider.instance.set(scope.toString()); - Workspace ws = getWorkspace(); - GCubeItem item = (GCubeItem) ws.getItem("7d5fd78a-6543-4d20-b6e7-9ae490fa1ad8"); - // Properties props = item.getProperties(); -// item.getProperties().addProperty("key06", "value0006"); -// item.getProperties().addProperty("key05", "value0005"); -// item.getProperties().update(); +////TODO IT MUST BE MOVED TO SHUB +///** +// * +// */ +//package org.gcube.portlets.user.workspace; +// +//import org.apache.log4j.Logger; +//import org.gcube.common.homelibrary.home.HomeLibrary; +//import org.gcube.common.homelibrary.home.exceptions.HomeNotFoundException; +//import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; +//import org.gcube.common.homelibrary.home.workspace.Workspace; +//import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException; +//import org.gcube.common.homelibrary.home.workspace.folder.items.GCubeItem; +//import org.gcube.common.scope.api.ScopeProvider; +//import org.gcube.common.scope.impl.ScopeBean; +// +///** +// * +// * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it +// * Jun 12, 2015 +// */ +//public class GcubeProperties { +// public static Logger logger = Logger.getLogger(GcubeProperties.class); +// public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV +// public static String TEST_USER = "francesco.mangiacrapa"; +// +// public static void main(String[] args) { +// +// try{ +// ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); +// ScopeProvider.instance.set(scope.toString()); +// Workspace ws = getWorkspace(); +// GCubeItem item = (GCubeItem) ws.getItem("7d5fd78a-6543-4d20-b6e7-9ae490fa1ad8"); +// // Properties props = item.getProperties(); +//// item.getProperties().addProperty("key06", "value0006"); +//// item.getProperties().addProperty("key05", "value0005"); +//// item.getProperties().update(); +//// +// +// System.out.println(item.getProperties().getProperties()); // - - System.out.println(item.getProperties().getProperties()); - - }catch (Exception e) { - e.printStackTrace(); - } - } - - public static Workspace getWorkspace() throws InternalErrorException, HomeNotFoundException, WorkspaceFolderNotFoundException{ - logger.trace("Get Workspace scope: "+DEFAULT_SCOPE + " username: "+TEST_USER); - ScopeProvider.instance.set(DEFAULT_SCOPE); - logger.trace("Scope provider instancied"); - Workspace workspace = HomeLibrary.getUserWorkspace(TEST_USER); - return workspace; - } -} +// }catch (Exception e) { +// e.printStackTrace(); +// } +// } +// +// public static Workspace getWorkspace() throws InternalErrorException, HomeNotFoundException, WorkspaceFolderNotFoundException{ +// logger.trace("Get Workspace scope: "+DEFAULT_SCOPE + " username: "+TEST_USER); +// ScopeProvider.instance.set(DEFAULT_SCOPE); +// logger.trace("Scope provider instancied"); +// Workspace workspace = HomeLibrary.getUserWorkspace(TEST_USER); +// return workspace; +// } +//} diff --git a/src/test/java/org/gcube/portlets/user/workspace/ItemCreate.java b/src/test/java/org/gcube/portlets/user/workspace/ItemCreate.java index ca9609c..8ea9f48 100644 --- a/src/test/java/org/gcube/portlets/user/workspace/ItemCreate.java +++ b/src/test/java/org/gcube/portlets/user/workspace/ItemCreate.java @@ -1,242 +1,243 @@ -/** - * - */ -package org.gcube.portlets.user.workspace; - -import java.util.List; -import java.util.concurrent.TimeUnit; - -import org.apache.log4j.Logger; -import org.gcube.common.homelibrary.home.HomeLibrary; -import org.gcube.common.homelibrary.home.exceptions.HomeNotFoundException; -import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; -import org.gcube.common.homelibrary.home.exceptions.UserNotFoundException; -import org.gcube.common.homelibrary.home.workspace.Workspace; -import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; -import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; -import org.gcube.common.homelibrary.home.workspace.WorkspaceSharedFolder; -import org.gcube.common.homelibrary.home.workspace.exceptions.ItemNotFoundException; -import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException; -import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; -import org.gcube.common.scope.api.ScopeProvider; -import org.gcube.common.scope.impl.ScopeBean; - -/** - * - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * Jan 29, 2014 - * - */ -public class ItemCreate { - - -// public static String DEFAULT_SCOPE = "/d4science.research-infrastructures.eu/gCubeApps"; //PRODUCTION - public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV - public static String TEST_USER = "costantino.perciante"; -// public static String ITEMID = "63832213-098d-42d1-8774-89b6349764c0"; //Activity T3.4 working drafts/T2-EC-IMAR-HO-14-015 iMarine Sustainability WP - Business Model tools.pdf - public static String ITEMID = "ce4866ee-8079-4acf-bcd6-1c9dd786eb73"; -// d81d3a64-603f-4907-ae74-be8353211807 - protected static Logger logger = Logger.getLogger(ItemCreate.class); - - - - - public static void main(String[] args) { - - ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); - ScopeProvider.instance.set(scope.toString()); - - System.out.println("init HL"); - try { - Workspace ws = getWorkspace(); - - String rootId = ws.getRoot().getId(); - System.out.println("Root ID: "+rootId); - - //[]/\ - - //CREATO ^<>?*%$:*$ -// //String folderNameSpecialChars = "[^.]<>|?*%$:*$\\/"; - String folderNameSpecialChars = "‘"; - - - WorkspaceFolder folder = null; - String folderName = null; - for (int i = 1; i < folderNameSpecialChars.length(); i++) { - folderName = folderNameSpecialChars.substring(0,i); - try{ - folder = ws.createFolder(folderName, "", rootId); - System.out.println("Created folder: "+folder.getName() +" with id: "+folder.getId()); - }catch(Exception e){ - System.err.println("Folder with name: "+folderName +" not created"); - e.printStackTrace(); - return; - } - - try{ - if (folder!=null){ - ws.renameItem(folder.getId(), folder.getName()+"_renamed"); - System.out.println("Renamed folder: "+folder.getName() +" with id: "+folder.getId()); - } - }catch (Exception e) { - System.err.println("Folder with name: "+folderName +" not renamed"); - e.printStackTrace(); - } - - try{ - if (folder!=null){ - ws.removeItem(folder.getId()); - System.out.println("Removed folder: "+folder.getName() +" with id: "+folder.getId()); - try{ - ws.getItem(folder.getId()); - }catch(ItemNotFoundException e){ - System.out.println("Folder Id folder: "+folder.getId() +" removed correctly"); - } - - } - }catch (Exception e) { - System.err.println("Folder with name: "+folderName +" not removed"); - e.printStackTrace(); - return; - } - - } - - retrieveFirstLevel(ws, null); +//TODO IT MUST BE MOVED TO SHUB +///** +// * +// */ +//package org.gcube.portlets.user.workspace; // -// retrieveFirstLevel(ws, ITEMID); +//import java.util.List; +//import java.util.concurrent.TimeUnit; // -// System.out.println("get workspace -> OK"); - //WorkspaceItem item = ws.getItem(ITEMID); - //System.out.println("get item id: "+item.getId()+", name: "+item.getName() +", parent: "+item.getParent().getId() +", parent name: "+item.getParent().getName()+", path :"+item.getPath()); - //System.out.println(item); - }catch(Exception e){ - e.printStackTrace(); - } - -// } catch (WorkspaceFolderNotFoundException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } catch (InternalErrorException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } catch (HomeNotFoundException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } catch (UserNotFoundException e) { -// // TODO Auto-generated catch block +//import org.apache.log4j.Logger; +//import org.gcube.common.homelibrary.home.HomeLibrary; +//import org.gcube.common.homelibrary.home.exceptions.HomeNotFoundException; +//import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; +//import org.gcube.common.homelibrary.home.exceptions.UserNotFoundException; +//import org.gcube.common.homelibrary.home.workspace.Workspace; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceSharedFolder; +//import org.gcube.common.homelibrary.home.workspace.exceptions.ItemNotFoundException; +//import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException; +//import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; +//import org.gcube.common.scope.api.ScopeProvider; +//import org.gcube.common.scope.impl.ScopeBean; +// +///** +// * +// * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it +// * Jan 29, 2014 +// * +// */ +//public class ItemCreate { +// +// +//// public static String DEFAULT_SCOPE = "/d4science.research-infrastructures.eu/gCubeApps"; //PRODUCTION +// public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV +// public static String TEST_USER = "costantino.perciante"; +//// public static String ITEMID = "63832213-098d-42d1-8774-89b6349764c0"; //Activity T3.4 working drafts/T2-EC-IMAR-HO-14-015 iMarine Sustainability WP - Business Model tools.pdf +// public static String ITEMID = "ce4866ee-8079-4acf-bcd6-1c9dd786eb73"; +//// d81d3a64-603f-4907-ae74-be8353211807 +// protected static Logger logger = Logger.getLogger(ItemCreate.class); +// +// +// +// +// public static void main(String[] args) { +// +// ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); +// ScopeProvider.instance.set(scope.toString()); +// +// System.out.println("init HL"); +// try { +// Workspace ws = getWorkspace(); +// +// String rootId = ws.getRoot().getId(); +// System.out.println("Root ID: "+rootId); +// +// //[]/\ +// +// //CREATO ^<>?*%$:*$ +//// //String folderNameSpecialChars = "[^.]<>|?*%$:*$\\/"; +// String folderNameSpecialChars = "‘"; +// +// +// WorkspaceFolder folder = null; +// String folderName = null; +// for (int i = 1; i < folderNameSpecialChars.length(); i++) { +// folderName = folderNameSpecialChars.substring(0,i); +// try{ +// folder = ws.createFolder(folderName, "", rootId); +// System.out.println("Created folder: "+folder.getName() +" with id: "+folder.getId()); +// }catch(Exception e){ +// System.err.println("Folder with name: "+folderName +" not created"); +// e.printStackTrace(); +// return; +// } +// +// try{ +// if (folder!=null){ +// ws.renameItem(folder.getId(), folder.getName()+"_renamed"); +// System.out.println("Renamed folder: "+folder.getName() +" with id: "+folder.getId()); +// } +// }catch (Exception e) { +// System.err.println("Folder with name: "+folderName +" not renamed"); +// e.printStackTrace(); +// } +// +// try{ +// if (folder!=null){ +// ws.removeItem(folder.getId()); +// System.out.println("Removed folder: "+folder.getName() +" with id: "+folder.getId()); +// try{ +// ws.getItem(folder.getId()); +// }catch(ItemNotFoundException e){ +// System.out.println("Folder Id folder: "+folder.getId() +" removed correctly"); +// } +// +// } +// }catch (Exception e) { +// System.err.println("Folder with name: "+folderName +" not removed"); +// e.printStackTrace(); +// return; +// } +// +// } +// +// retrieveFirstLevel(ws, null); +//// +//// retrieveFirstLevel(ws, ITEMID); +//// +//// System.out.println("get workspace -> OK"); +// //WorkspaceItem item = ws.getItem(ITEMID); +// //System.out.println("get item id: "+item.getId()+", name: "+item.getName() +", parent: "+item.getParent().getId() +", parent name: "+item.getParent().getName()+", path :"+item.getPath()); +// //System.out.println(item); +// }catch(Exception e){ // e.printStackTrace(); // } // - } - - public static Workspace getWorkspace() throws InternalErrorException, HomeNotFoundException, WorkspaceFolderNotFoundException, UserNotFoundException - { - - logger.trace("Get Workspace scope: "+DEFAULT_SCOPE + " username: "+TEST_USER); - ScopeProvider.instance.set(DEFAULT_SCOPE); - logger.trace("Scope provider instancied"); - -// return HomeLibrary.getUserWorkspace(TEST_USER); - return HomeLibrary.getHomeManagerFactory().getHomeManager().getHome(TEST_USER).getWorkspace(); - } - - - private static void retrieveFirstLevel(Workspace ws, String foundFolder){ - - try { - - //TEST TIME - Long startTime = System.currentTimeMillis(); - Long endTime = System.currentTimeMillis() - startTime; - String time = String.format("%d msc %d sec", endTime, TimeUnit.MILLISECONDS.toSeconds(endTime)); - - startTime = System.currentTimeMillis(); - System.out.println("Start foundFolder at time: "+startTime); -// WorkspaceItem root = ws.getItem(ITEMID); - WorkspaceItem fd; - if(foundFolder!=null){ - fd = ws.getItem(foundFolder); - System.out.println("foundFolder id: "+foundFolder); - System.out.println("start get children"); - }else - fd = ws.getRoot(); - - List children = fd.getChildren(); - System.out.println("tree getChildren() returning "+children.size()+" elements in " + time); - - System.out.println("children size: "+children.size()); - - int i=0; - int foldersCounter = 0; - int sharedFoldersCounter = 0; - int folderItemCounter = 0; - int othersCounter = 0; - for (WorkspaceItem workspaceItem : children) { - try{ - - /*if(foundFolder!=null && !foundFolder.isEmpty()){ - if(workspaceItem.getId().compareTo(foundFolder)==0){ - System.out.println("ITEM FOUND id: "+workspaceItem.getId()+", name: "+workspaceItem.getName()); - return; - } - }*/ - - switch (workspaceItem.getType()) { - - case FOLDER: - - WorkspaceFolder folder = (WorkspaceFolder) workspaceItem; - -// System.out.println(++i+") "+folder.getId() +" folder name: "+folder.getName() + " owner "+folder.getOwner() +" path: "+folder.getPath()); - System.out.println(++i+") "+folder.getId() +" folder name: "+folder.getName() + " owner "+folder.getOwner()); - foldersCounter++; - - break; - - case SHARED_FOLDER: - - WorkspaceSharedFolder shared = (WorkspaceSharedFolder) workspaceItem; - -// System.out.println(++i+") "+shared.getId() +" shared folder name: "+shared.getName() + " owner "+shared.getOwner()+" isVRE "+shared.isVreFolder() +" ACLOwner: "+shared.getACLOwner()+" AclUser: "+shared.getACLUser() +" path: "+shared.getPath()); - System.out.println(++i+") "+shared.getId() +" shared folder name: "+shared.getName()); - - // System.out.println(++i+") shared folder name: "+shared.getName() + " owner "+shared.getOwner().getPortalLogin()); - sharedFoldersCounter++; - - break; - - case FOLDER_ITEM: - - FolderItem folderItem = (FolderItem) workspaceItem; - -// System.out.println(++i+") folderItem id: "+folderItem.getId() +", name: "+folderItem.getName() + ", own: "+folderItem.getOwner() +" path: "+folderItem.getPath()); - System.out.println(++i+") folderItem id: "+folderItem.getId() +", name: "+folderItem.getName() + ", own: "+folderItem.getOwner()); - folderItemCounter++; - - break; - default: - // System.out.println(++i+") DEFAULT - item id: "+workspaceItem.getId() +", name: "+workspaceItem.getName() + ", own: "+workspaceItem.getOwner()); - // othersCounter++; - break; - } - }catch (Exception e) { - // TODO: handle exception - } - - } - - //TEST TIME - endTime = System.currentTimeMillis(); - long difference = endTime - startTime; - time = String.format("%d msc %d sec", difference, TimeUnit.MILLISECONDS.toSeconds(difference)); - System.out.println("End time is "+endTime+ " difference is "+time); - System.out.println("Folders are: "+foldersCounter); - System.out.println("Shared Folders are: "+sharedFoldersCounter); - System.out.println("Folder Item are: "+folderItemCounter); - System.out.println("Others are: "+othersCounter); - } catch (Exception e) { - e.printStackTrace(); - } - } -} +//// } catch (WorkspaceFolderNotFoundException e) { +//// // TODO Auto-generated catch block +//// e.printStackTrace(); +//// } catch (InternalErrorException e) { +//// // TODO Auto-generated catch block +//// e.printStackTrace(); +//// } catch (HomeNotFoundException e) { +//// // TODO Auto-generated catch block +//// e.printStackTrace(); +//// } catch (UserNotFoundException e) { +//// // TODO Auto-generated catch block +//// e.printStackTrace(); +//// } +//// +// } +// +// public static Workspace getWorkspace() throws InternalErrorException, HomeNotFoundException, WorkspaceFolderNotFoundException, UserNotFoundException +// { +// +// logger.trace("Get Workspace scope: "+DEFAULT_SCOPE + " username: "+TEST_USER); +// ScopeProvider.instance.set(DEFAULT_SCOPE); +// logger.trace("Scope provider instancied"); +// +//// return HomeLibrary.getUserWorkspace(TEST_USER); +// return HomeLibrary.getHomeManagerFactory().getHomeManager().getHome(TEST_USER).getWorkspace(); +// } +// +// +// private static void retrieveFirstLevel(Workspace ws, String foundFolder){ +// +// try { +// +// //TEST TIME +// Long startTime = System.currentTimeMillis(); +// Long endTime = System.currentTimeMillis() - startTime; +// String time = String.format("%d msc %d sec", endTime, TimeUnit.MILLISECONDS.toSeconds(endTime)); +// +// startTime = System.currentTimeMillis(); +// System.out.println("Start foundFolder at time: "+startTime); +//// WorkspaceItem root = ws.getItem(ITEMID); +// WorkspaceItem fd; +// if(foundFolder!=null){ +// fd = ws.getItem(foundFolder); +// System.out.println("foundFolder id: "+foundFolder); +// System.out.println("start get children"); +// }else +// fd = ws.getRoot(); +// +// List children = fd.getChildren(); +// System.out.println("tree getChildren() returning "+children.size()+" elements in " + time); +// +// System.out.println("children size: "+children.size()); +// +// int i=0; +// int foldersCounter = 0; +// int sharedFoldersCounter = 0; +// int folderItemCounter = 0; +// int othersCounter = 0; +// for (WorkspaceItem workspaceItem : children) { +// try{ +// +// /*if(foundFolder!=null && !foundFolder.isEmpty()){ +// if(workspaceItem.getId().compareTo(foundFolder)==0){ +// System.out.println("ITEM FOUND id: "+workspaceItem.getId()+", name: "+workspaceItem.getName()); +// return; +// } +// }*/ +// +// switch (workspaceItem.getType()) { +// +// case FOLDER: +// +// WorkspaceFolder folder = (WorkspaceFolder) workspaceItem; +// +//// System.out.println(++i+") "+folder.getId() +" folder name: "+folder.getName() + " owner "+folder.getOwner() +" path: "+folder.getPath()); +// System.out.println(++i+") "+folder.getId() +" folder name: "+folder.getName() + " owner "+folder.getOwner()); +// foldersCounter++; +// +// break; +// +// case SHARED_FOLDER: +// +// WorkspaceSharedFolder shared = (WorkspaceSharedFolder) workspaceItem; +// +//// System.out.println(++i+") "+shared.getId() +" shared folder name: "+shared.getName() + " owner "+shared.getOwner()+" isVRE "+shared.isVreFolder() +" ACLOwner: "+shared.getACLOwner()+" AclUser: "+shared.getACLUser() +" path: "+shared.getPath()); +// System.out.println(++i+") "+shared.getId() +" shared folder name: "+shared.getName()); +// +// // System.out.println(++i+") shared folder name: "+shared.getName() + " owner "+shared.getOwner().getPortalLogin()); +// sharedFoldersCounter++; +// +// break; +// +// case FOLDER_ITEM: +// +// FolderItem folderItem = (FolderItem) workspaceItem; +// +//// System.out.println(++i+") folderItem id: "+folderItem.getId() +", name: "+folderItem.getName() + ", own: "+folderItem.getOwner() +" path: "+folderItem.getPath()); +// System.out.println(++i+") folderItem id: "+folderItem.getId() +", name: "+folderItem.getName() + ", own: "+folderItem.getOwner()); +// folderItemCounter++; +// +// break; +// default: +// // System.out.println(++i+") DEFAULT - item id: "+workspaceItem.getId() +", name: "+workspaceItem.getName() + ", own: "+workspaceItem.getOwner()); +// // othersCounter++; +// break; +// } +// }catch (Exception e) { +// // TODO: handle exception +// } +// +// } +// +// //TEST TIME +// endTime = System.currentTimeMillis(); +// long difference = endTime - startTime; +// time = String.format("%d msc %d sec", difference, TimeUnit.MILLISECONDS.toSeconds(difference)); +// System.out.println("End time is "+endTime+ " difference is "+time); +// System.out.println("Folders are: "+foldersCounter); +// System.out.println("Shared Folders are: "+sharedFoldersCounter); +// System.out.println("Folder Item are: "+folderItemCounter); +// System.out.println("Others are: "+othersCounter); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +//} diff --git a/src/test/java/org/gcube/portlets/user/workspace/ItemRetrieve.java b/src/test/java/org/gcube/portlets/user/workspace/ItemRetrieve.java index 030b9c8..5417721 100644 --- a/src/test/java/org/gcube/portlets/user/workspace/ItemRetrieve.java +++ b/src/test/java/org/gcube/portlets/user/workspace/ItemRetrieve.java @@ -1,188 +1,189 @@ -/** - * - */ -package org.gcube.portlets.user.workspace; - -import java.util.List; -import java.util.concurrent.TimeUnit; - -import org.apache.log4j.Logger; -import org.gcube.common.homelibrary.home.HomeLibrary; -import org.gcube.common.homelibrary.home.exceptions.HomeNotFoundException; -import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; -import org.gcube.common.homelibrary.home.exceptions.UserNotFoundException; -import org.gcube.common.homelibrary.home.workspace.Workspace; -import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; -import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; -import org.gcube.common.homelibrary.home.workspace.WorkspaceSharedFolder; -import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException; -import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; -import org.gcube.common.scope.api.ScopeProvider; -import org.gcube.common.scope.impl.ScopeBean; - -/** - * - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * Jan 29, 2014 - * - */ -public class ItemRetrieve { - - -// public static String DEFAULT_SCOPE = "/d4science.research-infrastructures.eu/gCubeApps"; //PRODUCTION - public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV - public static String TEST_USER = "francesco.mangiacrapa"; -// public static String ITEMID = "63832213-098d-42d1-8774-89b6349764c0"; //Activity T3.4 working drafts/T2-EC-IMAR-HO-14-015 iMarine Sustainability WP - Business Model tools.pdf - public static String ITEMID = "ce4866ee-8079-4acf-bcd6-1c9dd786eb73"; -// d81d3a64-603f-4907-ae74-be8353211807 - protected static Logger logger = Logger.getLogger(ItemRetrieve.class); - - - public static void main(String[] args) { - - ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); - ScopeProvider.instance.set(scope.toString()); - - System.out.println("init HL"); - try { - Workspace ws = getWorkspace(); - - System.out.println(ws.getRoot().getId()); - retrieveFirstLevel(ws, null); +////TODO IT MUST BE MOVED TO SHUB +///** +// * +// */ +//package org.gcube.portlets.user.workspace; // -// retrieveFirstLevel(ws, ITEMID); +//import java.util.List; +//import java.util.concurrent.TimeUnit; // -// System.out.println("get workspace -> OK"); - WorkspaceItem item = ws.getItem(ITEMID); - System.out.println("get item id: "+item.getId()+", name: "+item.getName() +", parent: "+item.getParent().getId() +", parent name: "+item.getParent().getName()+", path :"+item.getPath()); - System.out.println(item); - }catch(Exception e){ - e.printStackTrace(); - } - -// } catch (WorkspaceFolderNotFoundException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } catch (InternalErrorException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } catch (HomeNotFoundException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } catch (UserNotFoundException e) { -// // TODO Auto-generated catch block +//import org.apache.log4j.Logger; +//import org.gcube.common.homelibrary.home.HomeLibrary; +//import org.gcube.common.homelibrary.home.exceptions.HomeNotFoundException; +//import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; +//import org.gcube.common.homelibrary.home.exceptions.UserNotFoundException; +//import org.gcube.common.homelibrary.home.workspace.Workspace; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceSharedFolder; +//import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException; +//import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; +//import org.gcube.common.scope.api.ScopeProvider; +//import org.gcube.common.scope.impl.ScopeBean; +// +///** +// * +// * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it +// * Jan 29, 2014 +// * +// */ +//public class ItemRetrieve { +// +// +//// public static String DEFAULT_SCOPE = "/d4science.research-infrastructures.eu/gCubeApps"; //PRODUCTION +// public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV +// public static String TEST_USER = "francesco.mangiacrapa"; +//// public static String ITEMID = "63832213-098d-42d1-8774-89b6349764c0"; //Activity T3.4 working drafts/T2-EC-IMAR-HO-14-015 iMarine Sustainability WP - Business Model tools.pdf +// public static String ITEMID = "ce4866ee-8079-4acf-bcd6-1c9dd786eb73"; +//// d81d3a64-603f-4907-ae74-be8353211807 +// protected static Logger logger = Logger.getLogger(ItemRetrieve.class); +// +// +// public static void main(String[] args) { +// +// ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); +// ScopeProvider.instance.set(scope.toString()); +// +// System.out.println("init HL"); +// try { +// Workspace ws = getWorkspace(); +// +// System.out.println(ws.getRoot().getId()); +// retrieveFirstLevel(ws, null); +//// +//// retrieveFirstLevel(ws, ITEMID); +//// +//// System.out.println("get workspace -> OK"); +// WorkspaceItem item = ws.getItem(ITEMID); +// System.out.println("get item id: "+item.getId()+", name: "+item.getName() +", parent: "+item.getParent().getId() +", parent name: "+item.getParent().getName()+", path :"+item.getPath()); +// System.out.println(item); +// }catch(Exception e){ // e.printStackTrace(); // } // - } - - public static Workspace getWorkspace() throws InternalErrorException, HomeNotFoundException, WorkspaceFolderNotFoundException, UserNotFoundException - { - - logger.trace("Get Workspace scope: "+DEFAULT_SCOPE + " username: "+TEST_USER); - ScopeProvider.instance.set(DEFAULT_SCOPE); - logger.trace("Scope provider instancied"); - -// return HomeLibrary.getUserWorkspace(TEST_USER); - return HomeLibrary.getHomeManagerFactory().getHomeManager().getHome(TEST_USER).getWorkspace(); - } - - - private static void retrieveFirstLevel(Workspace ws, String foundFolder){ - - try { - - //TEST TIME - Long startTime = System.currentTimeMillis(); - Long endTime = System.currentTimeMillis() - startTime; - String time = String.format("%d msc %d sec", endTime, TimeUnit.MILLISECONDS.toSeconds(endTime)); - - startTime = System.currentTimeMillis(); - System.out.println("Start foundFolder at time: "+startTime); -// WorkspaceItem root = ws.getItem(ITEMID); - WorkspaceItem fd; - if(foundFolder!=null){ - fd = ws.getItem(foundFolder); - System.out.println("foundFolder id: "+foundFolder); - System.out.println("start get children"); - }else - fd = ws.getRoot(); - - List children = fd.getChildren(); - System.out.println("tree getChildren() returning "+children.size()+" elements in " + time); - - System.out.println("children size: "+children.size()); - - int i=0; - int foldersCounter = 0; - int sharedFoldersCounter = 0; - int folderItemCounter = 0; - int othersCounter = 0; - for (WorkspaceItem workspaceItem : children) { - try{ - - /*if(foundFolder!=null && !foundFolder.isEmpty()){ - if(workspaceItem.getId().compareTo(foundFolder)==0){ - System.out.println("ITEM FOUND id: "+workspaceItem.getId()+", name: "+workspaceItem.getName()); - return; - } - }*/ - - switch (workspaceItem.getType()) { - - case FOLDER: - - WorkspaceFolder folder = (WorkspaceFolder) workspaceItem; - -// System.out.println(++i+") "+folder.getId() +" folder name: "+folder.getName() + " owner "+folder.getOwner() +" path: "+folder.getPath()); - System.out.println(++i+") "+folder.getId() +" folder name: "+folder.getName() + " owner "+folder.getOwner()); - foldersCounter++; - - break; - - case SHARED_FOLDER: - - WorkspaceSharedFolder shared = (WorkspaceSharedFolder) workspaceItem; - -// System.out.println(++i+") "+shared.getId() +" shared folder name: "+shared.getName() + " owner "+shared.getOwner()+" isVRE "+shared.isVreFolder() +" ACLOwner: "+shared.getACLOwner()+" AclUser: "+shared.getACLUser() +" path: "+shared.getPath()); - System.out.println(++i+") "+shared.getId() +" shared folder name: "+shared.getName()); - - // System.out.println(++i+") shared folder name: "+shared.getName() + " owner "+shared.getOwner().getPortalLogin()); - sharedFoldersCounter++; - - break; - - case FOLDER_ITEM: - - FolderItem folderItem = (FolderItem) workspaceItem; - -// System.out.println(++i+") folderItem id: "+folderItem.getId() +", name: "+folderItem.getName() + ", own: "+folderItem.getOwner() +" path: "+folderItem.getPath()); - System.out.println(++i+") folderItem id: "+folderItem.getId() +", name: "+folderItem.getName() + ", own: "+folderItem.getOwner()); - folderItemCounter++; - - break; - default: - // System.out.println(++i+") DEFAULT - item id: "+workspaceItem.getId() +", name: "+workspaceItem.getName() + ", own: "+workspaceItem.getOwner()); - // othersCounter++; - break; - } - }catch (Exception e) { - // TODO: handle exception - } - - } - - //TEST TIME - endTime = System.currentTimeMillis(); - long difference = endTime - startTime; - time = String.format("%d msc %d sec", difference, TimeUnit.MILLISECONDS.toSeconds(difference)); - System.out.println("End time is "+endTime+ " difference is "+time); - System.out.println("Folders are: "+foldersCounter); - System.out.println("Shared Folders are: "+sharedFoldersCounter); - System.out.println("Folder Item are: "+folderItemCounter); - System.out.println("Others are: "+othersCounter); - } catch (Exception e) { - e.printStackTrace(); - } - } -} +//// } catch (WorkspaceFolderNotFoundException e) { +//// // TODO Auto-generated catch block +//// e.printStackTrace(); +//// } catch (InternalErrorException e) { +//// // TODO Auto-generated catch block +//// e.printStackTrace(); +//// } catch (HomeNotFoundException e) { +//// // TODO Auto-generated catch block +//// e.printStackTrace(); +//// } catch (UserNotFoundException e) { +//// // TODO Auto-generated catch block +//// e.printStackTrace(); +//// } +//// +// } +// +// public static Workspace getWorkspace() throws InternalErrorException, HomeNotFoundException, WorkspaceFolderNotFoundException, UserNotFoundException +// { +// +// logger.trace("Get Workspace scope: "+DEFAULT_SCOPE + " username: "+TEST_USER); +// ScopeProvider.instance.set(DEFAULT_SCOPE); +// logger.trace("Scope provider instancied"); +// +//// return HomeLibrary.getUserWorkspace(TEST_USER); +// return HomeLibrary.getHomeManagerFactory().getHomeManager().getHome(TEST_USER).getWorkspace(); +// } +// +// +// private static void retrieveFirstLevel(Workspace ws, String foundFolder){ +// +// try { +// +// //TEST TIME +// Long startTime = System.currentTimeMillis(); +// Long endTime = System.currentTimeMillis() - startTime; +// String time = String.format("%d msc %d sec", endTime, TimeUnit.MILLISECONDS.toSeconds(endTime)); +// +// startTime = System.currentTimeMillis(); +// System.out.println("Start foundFolder at time: "+startTime); +//// WorkspaceItem root = ws.getItem(ITEMID); +// WorkspaceItem fd; +// if(foundFolder!=null){ +// fd = ws.getItem(foundFolder); +// System.out.println("foundFolder id: "+foundFolder); +// System.out.println("start get children"); +// }else +// fd = ws.getRoot(); +// +// List children = fd.getChildren(); +// System.out.println("tree getChildren() returning "+children.size()+" elements in " + time); +// +// System.out.println("children size: "+children.size()); +// +// int i=0; +// int foldersCounter = 0; +// int sharedFoldersCounter = 0; +// int folderItemCounter = 0; +// int othersCounter = 0; +// for (WorkspaceItem workspaceItem : children) { +// try{ +// +// /*if(foundFolder!=null && !foundFolder.isEmpty()){ +// if(workspaceItem.getId().compareTo(foundFolder)==0){ +// System.out.println("ITEM FOUND id: "+workspaceItem.getId()+", name: "+workspaceItem.getName()); +// return; +// } +// }*/ +// +// switch (workspaceItem.getType()) { +// +// case FOLDER: +// +// WorkspaceFolder folder = (WorkspaceFolder) workspaceItem; +// +//// System.out.println(++i+") "+folder.getId() +" folder name: "+folder.getName() + " owner "+folder.getOwner() +" path: "+folder.getPath()); +// System.out.println(++i+") "+folder.getId() +" folder name: "+folder.getName() + " owner "+folder.getOwner()); +// foldersCounter++; +// +// break; +// +// case SHARED_FOLDER: +// +// WorkspaceSharedFolder shared = (WorkspaceSharedFolder) workspaceItem; +// +//// System.out.println(++i+") "+shared.getId() +" shared folder name: "+shared.getName() + " owner "+shared.getOwner()+" isVRE "+shared.isVreFolder() +" ACLOwner: "+shared.getACLOwner()+" AclUser: "+shared.getACLUser() +" path: "+shared.getPath()); +// System.out.println(++i+") "+shared.getId() +" shared folder name: "+shared.getName()); +// +// // System.out.println(++i+") shared folder name: "+shared.getName() + " owner "+shared.getOwner().getPortalLogin()); +// sharedFoldersCounter++; +// +// break; +// +// case FOLDER_ITEM: +// +// FolderItem folderItem = (FolderItem) workspaceItem; +// +//// System.out.println(++i+") folderItem id: "+folderItem.getId() +", name: "+folderItem.getName() + ", own: "+folderItem.getOwner() +" path: "+folderItem.getPath()); +// System.out.println(++i+") folderItem id: "+folderItem.getId() +", name: "+folderItem.getName() + ", own: "+folderItem.getOwner()); +// folderItemCounter++; +// +// break; +// default: +// // System.out.println(++i+") DEFAULT - item id: "+workspaceItem.getId() +", name: "+workspaceItem.getName() + ", own: "+workspaceItem.getOwner()); +// // othersCounter++; +// break; +// } +// }catch (Exception e) { +// // TODO: handle exception +// } +// +// } +// +// //TEST TIME +// endTime = System.currentTimeMillis(); +// long difference = endTime - startTime; +// time = String.format("%d msc %d sec", difference, TimeUnit.MILLISECONDS.toSeconds(difference)); +// System.out.println("End time is "+endTime+ " difference is "+time); +// System.out.println("Folders are: "+foldersCounter); +// System.out.println("Shared Folders are: "+sharedFoldersCounter); +// System.out.println("Folder Item are: "+folderItemCounter); +// System.out.println("Others are: "+othersCounter); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +//} diff --git a/src/test/java/org/gcube/portlets/user/workspace/PublicLinkTest.java b/src/test/java/org/gcube/portlets/user/workspace/PublicLinkTest.java index a182d48..5eed930 100644 --- a/src/test/java/org/gcube/portlets/user/workspace/PublicLinkTest.java +++ b/src/test/java/org/gcube/portlets/user/workspace/PublicLinkTest.java @@ -1,138 +1,139 @@ -/** - * - */ -package org.gcube.portlets.user.workspace; - -import java.util.List; - -import org.apache.log4j.Logger; -import org.gcube.common.homelibary.model.items.type.WorkspaceItemType; -import org.gcube.common.homelibrary.home.HomeLibrary; -import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; -import org.gcube.common.homelibrary.home.workspace.Workspace; -import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; -import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; -import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; -import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalFile; -import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalImage; -import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalPDFFile; -import org.gcube.common.homelibrary.home.workspace.folder.items.GCubeItem; -import org.gcube.common.scope.api.ScopeProvider; -import org.gcube.common.scope.impl.ScopeBean; - -/** - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * Jul 3, 2013 - * - */ -public class PublicLinkTest { - - - protected static Logger logger = Logger.getLogger(PublicLinkTest.class); - - public static String DEFAULT_SCOPE = "/d4science.research-infrastructures.eu/gCubeApps/EcologicalModelling"; //PRODUCTION -// public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV - - public static void main(String[] args) { - - try { - - ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); - ScopeProvider.instance.set(scope.toString()); - - Workspace ws = HomeLibrary - .getHomeManagerFactory() - .getHomeManager() - .getHome("leonardo.candela") - .getWorkspace(); - // - - System.out.println("start get root"); - WorkspaceItem root = ws.getRoot(); - - System.out.println("start get children"); - List children = root.getChildren(); - - - System.out.println("children size: "+children.size()); - - int i=0; - for (WorkspaceItem workspaceItem : children) { - - - if(workspaceItem.getType().equals(WorkspaceItemType.FOLDER) || workspaceItem.getType().equals(WorkspaceItemType.SHARED_FOLDER)){ - - WorkspaceFolder folder = (WorkspaceFolder) workspaceItem; - - System.out.println(++i+") folder name: "+folder.getName() + " is shared: "+folder.isShared()); - }else{ - - - if(workspaceItem.getType().equals(WorkspaceItemType.FOLDER_ITEM)){ - - FolderItem folderItem = (FolderItem) workspaceItem; - - String publicLink = getPubliLinkForFolderItem(folderItem); - - System.out.println(++i+") folderItem id: "+folderItem.getId() +", name: "+folderItem.getName() + ", ### Public link: "+publicLink); - } - - } - } - System.out.println("end"); - } catch (Exception e) { - e.printStackTrace(); - } - } - - protected static String getPubliLinkForFolderItem(FolderItem worspaceFolderItem) throws InternalErrorException{ - - if(worspaceFolderItem==null) - return ""; - - try{ - - switch(worspaceFolderItem.getFolderItemType()) - { - case EXTERNAL_IMAGE: - return ((ExternalImage) worspaceFolderItem).getPublicLink(); - case EXTERNAL_FILE: - return ((ExternalFile) worspaceFolderItem).getPublicLink(); - case EXTERNAL_PDF_FILE: - return ((ExternalPDFFile) worspaceFolderItem).getPublicLink(); - case EXTERNAL_URL: - break; - case REPORT_TEMPLATE: - break; - case REPORT: - break; - case QUERY: - break; - case TIME_SERIES: - break; - // case AQUAMAPS_ITEM: - // break; - case PDF_DOCUMENT: - break; - case IMAGE_DOCUMENT: - GCubeItem imgDoc = (GCubeItem) worspaceFolderItem; //Cast GCubeItem - return imgDoc.getPublicLink(false); - case DOCUMENT: - break; - case URL_DOCUMENT: - break; - case METADATA: - break; - default: - return ""; - } - - }catch (Exception e) { - logger.error("an error occurred when get public link for item: "+worspaceFolderItem.getName()); - return ""; - } - - return ""; - } - -} +////TODO IT MUST BE MOVED TO SHUB +///** +// * +// */ +//package org.gcube.portlets.user.workspace; +// +//import java.util.List; +// +//import org.apache.log4j.Logger; +//import org.gcube.common.homelibary.model.items.type.WorkspaceItemType; +//import org.gcube.common.homelibrary.home.HomeLibrary; +//import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; +//import org.gcube.common.homelibrary.home.workspace.Workspace; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; +//import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; +//import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalFile; +//import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalImage; +//import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalPDFFile; +//import org.gcube.common.homelibrary.home.workspace.folder.items.GCubeItem; +//import org.gcube.common.scope.api.ScopeProvider; +//import org.gcube.common.scope.impl.ScopeBean; +// +///** +// * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it +// * Jul 3, 2013 +// * +// */ +//public class PublicLinkTest { +// +// +// protected static Logger logger = Logger.getLogger(PublicLinkTest.class); +// +// public static String DEFAULT_SCOPE = "/d4science.research-infrastructures.eu/gCubeApps/EcologicalModelling"; //PRODUCTION +//// public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV +// +// public static void main(String[] args) { +// +// try { +// +// ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); +// ScopeProvider.instance.set(scope.toString()); +// +// Workspace ws = HomeLibrary +// .getHomeManagerFactory() +// .getHomeManager() +// .getHome("leonardo.candela") +// .getWorkspace(); +// // +// +// System.out.println("start get root"); +// WorkspaceItem root = ws.getRoot(); +// +// System.out.println("start get children"); +// List children = root.getChildren(); +// +// +// System.out.println("children size: "+children.size()); +// +// int i=0; +// for (WorkspaceItem workspaceItem : children) { +// +// +// if(workspaceItem.getType().equals(WorkspaceItemType.FOLDER) || workspaceItem.getType().equals(WorkspaceItemType.SHARED_FOLDER)){ +// +// WorkspaceFolder folder = (WorkspaceFolder) workspaceItem; +// +// System.out.println(++i+") folder name: "+folder.getName() + " is shared: "+folder.isShared()); +// }else{ +// +// +// if(workspaceItem.getType().equals(WorkspaceItemType.FOLDER_ITEM)){ +// +// FolderItem folderItem = (FolderItem) workspaceItem; +// +// String publicLink = getPubliLinkForFolderItem(folderItem); +// +// System.out.println(++i+") folderItem id: "+folderItem.getId() +", name: "+folderItem.getName() + ", ### Public link: "+publicLink); +// } +// +// } +// } +// System.out.println("end"); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +// +// protected static String getPubliLinkForFolderItem(FolderItem worspaceFolderItem) throws InternalErrorException{ +// +// if(worspaceFolderItem==null) +// return ""; +// +// try{ +// +// switch(worspaceFolderItem.getFolderItemType()) +// { +// case EXTERNAL_IMAGE: +// return ((ExternalImage) worspaceFolderItem).getPublicLink(); +// case EXTERNAL_FILE: +// return ((ExternalFile) worspaceFolderItem).getPublicLink(); +// case EXTERNAL_PDF_FILE: +// return ((ExternalPDFFile) worspaceFolderItem).getPublicLink(); +// case EXTERNAL_URL: +// break; +// case REPORT_TEMPLATE: +// break; +// case REPORT: +// break; +// case QUERY: +// break; +// case TIME_SERIES: +// break; +// // case AQUAMAPS_ITEM: +// // break; +// case PDF_DOCUMENT: +// break; +// case IMAGE_DOCUMENT: +// GCubeItem imgDoc = (GCubeItem) worspaceFolderItem; //Cast GCubeItem +// return imgDoc.getPublicLink(false); +// case DOCUMENT: +// break; +// case URL_DOCUMENT: +// break; +// case METADATA: +// break; +// default: +// return ""; +// } +// +// }catch (Exception e) { +// logger.error("an error occurred when get public link for item: "+worspaceFolderItem.getName()); +// return ""; +// } +// +// return ""; +// } +// +//} diff --git a/src/test/java/org/gcube/portlets/user/workspace/SearchTextTest.java b/src/test/java/org/gcube/portlets/user/workspace/SearchTextTest.java index ac92cf7..383f78b 100644 --- a/src/test/java/org/gcube/portlets/user/workspace/SearchTextTest.java +++ b/src/test/java/org/gcube/portlets/user/workspace/SearchTextTest.java @@ -1,72 +1,83 @@ -/** - * - */ -package org.gcube.portlets.user.workspace; - -import java.util.List; - -import org.apache.log4j.Logger; -import org.gcube.common.homelibrary.home.HomeLibrary; -import org.gcube.common.homelibrary.home.workspace.Workspace; -import org.gcube.common.homelibrary.home.workspace.search.SearchItem; -import org.gcube.common.scope.api.ScopeProvider; -import org.gcube.common.scope.impl.ScopeBean; -import org.gcube.portlets.user.workspace.client.model.FileGridModel; -import org.gcube.portlets.user.workspace.server.GWTWorkspaceBuilder; - -/** - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * Jul 3, 2013 - * - */ -public class SearchTextTest { - - - protected static Logger logger = Logger.getLogger(SearchTextTest.class); - private static String text = "1_Networking Activities"; - public static String DEFAULT_SCOPE = "/gcube/devsec/devVRE"; //PRODUCTION - - public static String USER = "francesco.mangiacrapa"; //PRODUCTION - - static GWTWorkspaceBuilder builder = new GWTWorkspaceBuilder(); - static Workspace workspace; - - public static void main(String[] args) { - - try { -// DEFAULT_SCOPE = "/gcube/devsec"; - - - ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); - ScopeProvider.instance.set(scope.toString()); - - System.out.println("start get workspace\n"); - - workspace = HomeLibrary - .getHomeManagerFactory() - .getHomeManager() - .getHome(USER) - .getWorkspace(); - // - -// List listSearchItems = ws.searchByName(text); - - logger.info("Calling search HL.."); - List listSearchItems = workspace.searchByName(text, workspace.getRoot().getId()); - logger.info("HL search returning "+listSearchItems.size()+" items"); - - logger.info("Converting "+listSearchItems.size()+" items"); - - List listFileGridModels = builder.buildGXTListFileGridModelItemForSearch(listSearchItems); - logger.info("Search objects converted, returning"); - - for (FileGridModel fileGridModel : listFileGridModels) { - logger.info(fileGridModel); - } - - }catch(Exception e){ - e.printStackTrace(); - } - } - -} +//TODO IT MUST BE MOVED TO SHUB +///** +// * +// */ +//package org.gcube.portlets.user.workspace; +// +//import java.util.List; +// +//import org.apache.log4j.Logger; +//import org.gcube.common.homelibrary.home.HomeLibrary; +//import org.gcube.common.homelibrary.home.workspace.Workspace; +//import org.gcube.common.homelibrary.home.workspace.search.SearchItem; +//import org.gcube.common.scope.api.ScopeProvider; +//import org.gcube.common.scope.impl.ScopeBean; +//import org.gcube.portlets.user.workspace.client.model.FileGridModel; +// +///** +// * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it +// * Jul 3, 2013 +// * +// */ +// +// +///* +// * +// * +// * IT MUST BE MOVED TO SHUB +// * +// * +// * +//public class SearchTextTest { +// +// +// protected static Logger logger = Logger.getLogger(SearchTextTest.class); +// private static String text = "1_Networking Activities"; +// public static String DEFAULT_SCOPE = "/gcube/devsec/devVRE"; //PRODUCTION +// +// public static String USER = "francesco.mangiacrapa"; //PRODUCTION +// +// static GWTWorkspaceBuilder builder = new GWTWorkspaceBuilder(); +// static Workspace workspace; +// +// public static void main(String[] args) { +// +// try { +//// DEFAULT_SCOPE = "/gcube/devsec"; +// +// +// ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); +// ScopeProvider.instance.set(scope.toString()); +// +// System.out.println("start get workspace\n"); +// +// workspace = HomeLibrary +// .getHomeManagerFactory() +// .getHomeManager() +// .getHome(USER) +// .getWorkspace(); +// // +// +//// List listSearchItems = ws.searchByName(text); +// +// logger.info("Calling search HL.."); +// List listSearchItems = workspace.searchByName(text, workspace.getRoot().getId()); +// logger.info("HL search returning "+listSearchItems.size()+" items"); +// +// logger.info("Converting "+listSearchItems.size()+" items"); +// +// List listFileGridModels = builder.buildGXTListFileGridModelItemForSearch(listSearchItems); +// logger.info("Search objects converted, returning"); +// +// for (FileGridModel fileGridModel : listFileGridModels) { +// logger.info(fileGridModel); +// } +// +// }catch(Exception e){ +// e.printStackTrace(); +// } +// } +// +//} +// +//*/ diff --git a/src/test/java/org/gcube/portlets/user/workspace/ShareFolder.java b/src/test/java/org/gcube/portlets/user/workspace/ShareFolder.java index 0372f92..5a62cdd 100644 --- a/src/test/java/org/gcube/portlets/user/workspace/ShareFolder.java +++ b/src/test/java/org/gcube/portlets/user/workspace/ShareFolder.java @@ -1,78 +1,79 @@ -package org.gcube.portlets.user.workspace; - -import java.util.ArrayList; -import java.util.List; - -import org.gcube.common.homelibary.model.items.type.WorkspaceItemType; -import org.gcube.common.homelibrary.home.HomeLibrary; -import org.gcube.common.homelibrary.home.workspace.Workspace; -import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; -import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; -import org.gcube.common.homelibrary.home.workspace.WorkspaceSharedFolder; -import org.gcube.common.homelibrary.home.workspace.accessmanager.ACLType; -import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; -import org.gcube.common.scope.api.ScopeProvider; -import org.gcube.common.scope.impl.ScopeBean; - -public class ShareFolder { - - private static final String SUB_FOLDER_NAME = "subfoldermycourse"; - private static final String FOLDER_NAME = "_mycourse"; - public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV -// public static String DEFAULT_SCOPE = "/d4science.research-infrastructures.eu/gCubeApps"; - public static String TEST_USER = "francesco.mangiacrapa"; -// public static String FOLDER_ID = "4f0ff79d-3c1e-4d2a-bc74-6f731edcac98"; - - public static void main(String[] args) { - - try { - -// System.out.println("start"); -// ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); - ScopeProvider.instance.set(DEFAULT_SCOPE); - - Workspace workspace = HomeLibrary - .getHomeManagerFactory() - .getHomeManager() - .getHome(TEST_USER) - .getWorkspace(); - // - - System.out.println("start get root"); - WorkspaceItem theRoot = workspace.getRoot(); - - System.out.println("\n\n CREATING folder: "+FOLDER_NAME + "\n\n"); - - WorkspaceFolder myCourseFolder = workspace.createFolder(FOLDER_NAME, "", theRoot.getId()); - - System.out.println("\n\n FOLDER id: "+myCourseFolder.getId() +"\n\n"); - - System.out.println("\n\n CREATING sub folder: "+SUB_FOLDER_NAME+"\n\n"); - - WorkspaceFolder subFolderMyCourse = workspace.createFolder(SUB_FOLDER_NAME, "", myCourseFolder.getId()); - - System.out.println("\n\n SUB_FOLDER id: "+subFolderMyCourse.getId() +"\n\n"); - - List users = new ArrayList(); - users.add("costantino.perciante"); - WorkspaceSharedFolder subShareFolder = workspace.shareFolder(users, subFolderMyCourse.getId()); - subShareFolder.setACL(users, ACLType.READ_ONLY); - System.out.println("\n\n SHARED SUB_FOLDER id: "+subShareFolder.getId() +"\n\n"); - -// WorkspaceSharedFolder sharedFolder = subFolderMyCourse.share(users); - - -// System.out.println("\n\n SHARED subFolderMyCourse id: "+sharedFolder.getId()); -// +////TODO IT MUST BE MOVED TO SHUB +//package org.gcube.portlets.user.workspace; // -// WorkspaceFolder folder = (WorkspaceFolder) workspace.getItem(sharedFolder.getId()); +//import java.util.ArrayList; +//import java.util.List; +// +//import org.gcube.common.homelibary.model.items.type.WorkspaceItemType; +//import org.gcube.common.homelibrary.home.HomeLibrary; +//import org.gcube.common.homelibrary.home.workspace.Workspace; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceSharedFolder; +//import org.gcube.common.homelibrary.home.workspace.accessmanager.ACLType; +//import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; +//import org.gcube.common.scope.api.ScopeProvider; +//import org.gcube.common.scope.impl.ScopeBean; +// +//public class ShareFolder { +// +// private static final String SUB_FOLDER_NAME = "subfoldermycourse"; +// private static final String FOLDER_NAME = "_mycourse"; +// public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV +//// public static String DEFAULT_SCOPE = "/d4science.research-infrastructures.eu/gCubeApps"; +// public static String TEST_USER = "francesco.mangiacrapa"; +//// public static String FOLDER_ID = "4f0ff79d-3c1e-4d2a-bc74-6f731edcac98"; +// +// public static void main(String[] args) { +// +// try { +// +//// System.out.println("start"); +//// ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); +// ScopeProvider.instance.set(DEFAULT_SCOPE); // -// System.out.println("\n\n FINAL id: "+folder.getId()); - - System.out.println("end"); - } catch (Exception e) { - e.printStackTrace(); - } - } - -} +// Workspace workspace = HomeLibrary +// .getHomeManagerFactory() +// .getHomeManager() +// .getHome(TEST_USER) +// .getWorkspace(); +// // +// +// System.out.println("start get root"); +// WorkspaceItem theRoot = workspace.getRoot(); +// +// System.out.println("\n\n CREATING folder: "+FOLDER_NAME + "\n\n"); +// +// WorkspaceFolder myCourseFolder = workspace.createFolder(FOLDER_NAME, "", theRoot.getId()); +// +// System.out.println("\n\n FOLDER id: "+myCourseFolder.getId() +"\n\n"); +// +// System.out.println("\n\n CREATING sub folder: "+SUB_FOLDER_NAME+"\n\n"); +// +// WorkspaceFolder subFolderMyCourse = workspace.createFolder(SUB_FOLDER_NAME, "", myCourseFolder.getId()); +// +// System.out.println("\n\n SUB_FOLDER id: "+subFolderMyCourse.getId() +"\n\n"); +// +// List users = new ArrayList(); +// users.add("costantino.perciante"); +// WorkspaceSharedFolder subShareFolder = workspace.shareFolder(users, subFolderMyCourse.getId()); +// subShareFolder.setACL(users, ACLType.READ_ONLY); +// System.out.println("\n\n SHARED SUB_FOLDER id: "+subShareFolder.getId() +"\n\n"); +// +//// WorkspaceSharedFolder sharedFolder = subFolderMyCourse.share(users); +// +// +//// System.out.println("\n\n SHARED subFolderMyCourse id: "+sharedFolder.getId()); +//// +//// +//// WorkspaceFolder folder = (WorkspaceFolder) workspace.getItem(sharedFolder.getId()); +//// +//// System.out.println("\n\n FINAL id: "+folder.getId()); +// +// System.out.println("end"); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +// +//} diff --git a/src/test/java/org/gcube/portlets/user/workspace/SinglePublicLinkTest.java b/src/test/java/org/gcube/portlets/user/workspace/SinglePublicLinkTest.java index 5b5d8b2..8ba1e96 100644 --- a/src/test/java/org/gcube/portlets/user/workspace/SinglePublicLinkTest.java +++ b/src/test/java/org/gcube/portlets/user/workspace/SinglePublicLinkTest.java @@ -1,208 +1,217 @@ -/** - * - */ -package org.gcube.portlets.user.workspace; - -import org.apache.log4j.Logger; -import org.gcube.common.homelibary.model.items.type.WorkspaceItemType; -import org.gcube.common.homelibrary.home.HomeLibrary; -import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; -import org.gcube.common.homelibrary.home.workspace.Workspace; -import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; -import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; -import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalFile; -import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalImage; -import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalPDFFile; -import org.gcube.common.homelibrary.home.workspace.folder.items.GCubeItem; -import org.gcube.common.scope.api.ScopeProvider; -import org.gcube.common.scope.impl.ScopeBean; -import org.gcube.portlets.user.workspace.server.GWTWorkspaceBuilder; -import org.gcube.portlets.user.workspace.server.resolver.UriResolverReaderParameterForResolverIndex; -import org.gcube.portlets.user.workspace.server.resolver.UriResolverReaderParameterForResolverIndex.RESOLVER_TYPE; -import org.gcube.portlets.user.workspace.server.util.HttpRequestUtil; -import org.gcube.portlets.user.workspace.server.util.StringUtil; - -/** - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * Jul 3, 2013 - * - */ -public class SinglePublicLinkTest { - - - protected static Logger logger = Logger.getLogger(SinglePublicLinkTest.class); - -// public static String DEFAULT_SCOPE = "/d4science.research-infrastructures.eu/gCubeApps"; //PRODUCTION - public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV - - public static void main(String[] args) { - - try { - - ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); - ScopeProvider.instance.set(scope.toString()); - - Workspace ws = HomeLibrary - .getHomeManagerFactory() - .getHomeManager() - .getHome("francesco.mangiacrapa") - .getWorkspace(); - // - - System.out.println("start get root"); - WorkspaceItem root = ws.getRoot(); - - - for (WorkspaceItem wsi : root.getChildren()) { - if(wsi.getType().equals(WorkspaceItemType.FOLDER_ITEM)){ - try{ - String publicLink = getPublicLinkForFolderItemId(wsi.getId(), true, ws); - System.out.println("\nITEM: "+wsi.getName()); - System.out.println(publicLink); -// break; - }catch(Exception e){ - e.printStackTrace(); - } - } - } - - -// System.out.println("start get children"); -// List children = root.getChildren(); +////TODO IT MUST BE MOVED TO SHUB +///** +// * +// */ +//package org.gcube.portlets.user.workspace; // +//import org.apache.log4j.Logger; +//import org.gcube.common.homelibary.model.items.type.WorkspaceItemType; +//import org.gcube.common.homelibrary.home.HomeLibrary; +//import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; +//import org.gcube.common.homelibrary.home.workspace.Workspace; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; +//import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; +//import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalFile; +//import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalImage; +//import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalPDFFile; +//import org.gcube.common.homelibrary.home.workspace.folder.items.GCubeItem; +//import org.gcube.common.scope.api.ScopeProvider; +//import org.gcube.common.scope.impl.ScopeBean; +//import org.gcube.portlets.user.workspace.server.resolver.UriResolverReaderParameterForResolverIndex; +//import org.gcube.portlets.user.workspace.server.resolver.UriResolverReaderParameterForResolverIndex.RESOLVER_TYPE; +//import org.gcube.portlets.user.workspace.server.util.HttpRequestUtil; +//import org.gcube.portlets.user.workspace.server.util.StringUtil; +// +///** +// * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it +// * Jul 3, 2013 +// * +// */ +///* +// * +// * +// * IT MUST BE MOVED TO SHUB +// * +// * +// * +//public class SinglePublicLinkTest { +// +// +// protected static Logger logger = Logger.getLogger(SinglePublicLinkTest.class); +// +//// public static String DEFAULT_SCOPE = "/d4science.research-infrastructures.eu/gCubeApps"; //PRODUCTION +// public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV +// +// public static void main(String[] args) { +// +// try { +// +// ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); +// ScopeProvider.instance.set(scope.toString()); // -// System.out.println("children size: "+children.size()); +// Workspace ws = HomeLibrary +// .getHomeManagerFactory() +// .getHomeManager() +// .getHome("francesco.mangiacrapa") +// .getWorkspace(); +// // // -// int i=0; -// for (WorkspaceItem workspaceItem : children) { -// -// -// if(workspaceItem.getType().equals(WorkspaceItemType.FOLDER) || workspaceItem.getType().equals(WorkspaceItemType.SHARED_FOLDER)){ -// -// WorkspaceFolder folder = (WorkspaceFolder) workspaceItem; -// -// System.out.println(++i+") folder name: "+folder.getName() + " is shared: "+folder.isShared()); -// }else{ -// -// -// if(workspaceItem.getType().equals(WorkspaceItemType.FOLDER_ITEM)){ -// -// FolderItem folderItem = (FolderItem) workspaceItem; -// -// String publicLink = getPubliLinkForFolderItem(folderItem); -// -// System.out.println(++i+") folderItem id: "+folderItem.getId() +", name: "+folderItem.getName() + ", ### Public link: "+publicLink); +// System.out.println("start get root"); +// WorkspaceItem root = ws.getRoot(); +// +// +// for (WorkspaceItem wsi : root.getChildren()) { +// if(wsi.getType().equals(WorkspaceItemType.FOLDER_ITEM)){ +// try{ +// String publicLink = getPublicLinkForFolderItemId(wsi.getId(), true, ws); +// System.out.println("\nITEM: "+wsi.getName()); +// System.out.println(publicLink); +//// break; +// }catch(Exception e){ +// e.printStackTrace(); // } -// // } // } - System.out.println("end"); - } catch (Exception e) { - e.printStackTrace(); - } - } - - - public static String getPublicLinkForFolderItemId(String itemId, boolean shortenUrl, Workspace workspace) throws Exception{ - - logger.trace("get Public Link For ItemId: "+ itemId); - - GWTWorkspaceBuilder builder = new GWTWorkspaceBuilder(); - - try{ - - WorkspaceItem wsItem = workspace.getItem(itemId); - - if(wsItem.getType().equals(WorkspaceItemType.FOLDER_ITEM)){ - - FolderItem folderItem = (FolderItem) wsItem; - String storageID = builder.getStorageIDForFolderItem(folderItem); - - if(storageID==null || storageID.isEmpty()) - throw new Exception("Sorry, public link on "+wsItem.getName() +" is not available"); - - UriResolverReaderParameterForResolverIndex uriResolver = new UriResolverReaderParameterForResolverIndex(DEFAULT_SCOPE, RESOLVER_TYPE.SMP_ID); - - String uriRequest = ""; - - if(uriResolver!=null && uriResolver.isAvailable()){ - - String itemName = StringUtil.removeSpecialCharacters(folderItem.getName()); - itemName = StringUtil.replaceAllWhiteSpace(itemName, "_"); - uriRequest = uriResolver.resolveAsUriRequest(storageID, itemName, folderItem.getMimeType(), true); - - //VALIDATE CONNECTION - if(!HttpRequestUtil.urlExists(uriRequest+"&validation=true")) - throw new Exception("Sorry, The Public Link for selected file is unavailable"); - -// if(shortenUrl) -// uriRequest = getShortUrl(uriRequest); - - return uriRequest; - } - else - throw new Exception("Sorry, The Uri resolver service is temporarily unavailable. Please try again later"); - - }else{ - logger.warn("ItemId: "+ itemId +" is not a folder item, sent exception Public Link unavailable"); - throw new Exception("Sorry, The Public Link for selected file is unavailable"); - } - - }catch (Exception e) { - logger.error("Error getPublicLinkForFolderItemId for item: "+itemId, e); - e.printStackTrace(); - throw new Exception(e.getMessage()); - } - - } - protected static String getPubliLinkForFolderItem(FolderItem worspaceFolderItem) throws InternalErrorException{ - - if(worspaceFolderItem==null) - return ""; - - try{ - - switch(worspaceFolderItem.getFolderItemType()) - { - case EXTERNAL_IMAGE: - return ((ExternalImage) worspaceFolderItem).getPublicLink(); - case EXTERNAL_FILE: - return ((ExternalFile) worspaceFolderItem).getPublicLink(); - case EXTERNAL_PDF_FILE: - return ((ExternalPDFFile) worspaceFolderItem).getPublicLink(); - case EXTERNAL_URL: - break; - case REPORT_TEMPLATE: - break; - case REPORT: - break; - case QUERY: - break; - case TIME_SERIES: - break; - // case AQUAMAPS_ITEM: - // break; - case PDF_DOCUMENT: - break; - case IMAGE_DOCUMENT: - GCubeItem imgDoc = (GCubeItem) worspaceFolderItem; //Cast GCubeItem - return imgDoc.getPublicLink(false); - case DOCUMENT: - break; - case URL_DOCUMENT: - break; - case METADATA: - break; - default: - return ""; - } - - }catch (Exception e) { - logger.error("an error occurred when get public link for item: "+worspaceFolderItem.getName()); - return ""; - } - - return ""; - } - -} +// +// +//// System.out.println("start get children"); +//// List children = root.getChildren(); +//// +//// +//// System.out.println("children size: "+children.size()); +//// +//// int i=0; +//// for (WorkspaceItem workspaceItem : children) { +//// +//// +//// if(workspaceItem.getType().equals(WorkspaceItemType.FOLDER) || workspaceItem.getType().equals(WorkspaceItemType.SHARED_FOLDER)){ +//// +//// WorkspaceFolder folder = (WorkspaceFolder) workspaceItem; +//// +//// System.out.println(++i+") folder name: "+folder.getName() + " is shared: "+folder.isShared()); +//// }else{ +//// +//// +//// if(workspaceItem.getType().equals(WorkspaceItemType.FOLDER_ITEM)){ +//// +//// FolderItem folderItem = (FolderItem) workspaceItem; +//// +//// String publicLink = getPubliLinkForFolderItem(folderItem); +//// +//// System.out.println(++i+") folderItem id: "+folderItem.getId() +", name: "+folderItem.getName() + ", ### Public link: "+publicLink); +//// } +//// +//// } +//// } +// System.out.println("end"); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +// +// +// public static String getPublicLinkForFolderItemId(String itemId, boolean shortenUrl, Workspace workspace) throws Exception{ +// +// logger.trace("get Public Link For ItemId: "+ itemId); +// +// GWTWorkspaceBuilder builder = new GWTWorkspaceBuilder(); +// +// try{ +// +// WorkspaceItem wsItem = workspace.getItem(itemId); +// +// if(wsItem.getType().equals(WorkspaceItemType.FOLDER_ITEM)){ +// +// FolderItem folderItem = (FolderItem) wsItem; +// String storageID = builder.getStorageIDForFolderItem(folderItem); +// +// if(storageID==null || storageID.isEmpty()) +// throw new Exception("Sorry, public link on "+wsItem.getName() +" is not available"); +// +// UriResolverReaderParameterForResolverIndex uriResolver = new UriResolverReaderParameterForResolverIndex(DEFAULT_SCOPE, RESOLVER_TYPE.SMP_ID); +// +// String uriRequest = ""; +// +// if(uriResolver!=null && uriResolver.isAvailable()){ +// +// String itemName = StringUtil.removeSpecialCharacters(folderItem.getName()); +// itemName = StringUtil.replaceAllWhiteSpace(itemName, "_"); +// uriRequest = uriResolver.resolveAsUriRequest(storageID, itemName, folderItem.getMimeType(), true); +// +// //VALIDATE CONNECTION +// if(!HttpRequestUtil.urlExists(uriRequest+"&validation=true")) +// throw new Exception("Sorry, The Public Link for selected file is unavailable"); +// +//// if(shortenUrl) +//// uriRequest = getShortUrl(uriRequest); +// +// return uriRequest; +// } +// else +// throw new Exception("Sorry, The Uri resolver service is temporarily unavailable. Please try again later"); +// +// }else{ +// logger.warn("ItemId: "+ itemId +" is not a folder item, sent exception Public Link unavailable"); +// throw new Exception("Sorry, The Public Link for selected file is unavailable"); +// } +// +// }catch (Exception e) { +// logger.error("Error getPublicLinkForFolderItemId for item: "+itemId, e); +// e.printStackTrace(); +// throw new Exception(e.getMessage()); +// } +// +// } +// protected static String getPubliLinkForFolderItem(FolderItem worspaceFolderItem) throws InternalErrorException{ +// +// if(worspaceFolderItem==null) +// return ""; +// +// try{ +// +// switch(worspaceFolderItem.getFolderItemType()) +// { +// case EXTERNAL_IMAGE: +// return ((ExternalImage) worspaceFolderItem).getPublicLink(); +// case EXTERNAL_FILE: +// return ((ExternalFile) worspaceFolderItem).getPublicLink(); +// case EXTERNAL_PDF_FILE: +// return ((ExternalPDFFile) worspaceFolderItem).getPublicLink(); +// case EXTERNAL_URL: +// break; +// case REPORT_TEMPLATE: +// break; +// case REPORT: +// break; +// case QUERY: +// break; +// case TIME_SERIES: +// break; +// // case AQUAMAPS_ITEM: +// // break; +// case PDF_DOCUMENT: +// break; +// case IMAGE_DOCUMENT: +// GCubeItem imgDoc = (GCubeItem) worspaceFolderItem; //Cast GCubeItem +// return imgDoc.getPublicLink(false); +// case DOCUMENT: +// break; +// case URL_DOCUMENT: +// break; +// case METADATA: +// break; +// default: +// return ""; +// } +// +// }catch (Exception e) { +// logger.error("an error occurred when get public link for item: "+worspaceFolderItem.getName()); +// return ""; +// } +// +// return ""; +// } +// +//} +// +//*/ \ No newline at end of file diff --git a/src/test/java/org/gcube/portlets/user/workspace/SizeRetrieving.java b/src/test/java/org/gcube/portlets/user/workspace/SizeRetrieving.java index 557a424..d9297f3 100644 --- a/src/test/java/org/gcube/portlets/user/workspace/SizeRetrieving.java +++ b/src/test/java/org/gcube/portlets/user/workspace/SizeRetrieving.java @@ -1,92 +1,101 @@ -/** - * - */ -package org.gcube.portlets.user.workspace; - -import java.util.List; - -import org.gcube.common.homelibary.model.items.type.WorkspaceItemType; -import org.gcube.common.homelibrary.home.HomeLibrary; -import org.gcube.common.homelibrary.home.workspace.Workspace; -import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; -import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; -import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; -import org.gcube.common.scope.api.ScopeProvider; -import org.gcube.common.scope.impl.ScopeBean; -import org.gcube.portlets.user.workspace.server.GWTWorkspaceBuilder; - -/** - * - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * Jan 29, 2014 - * - */ -public class SizeRetrieving { - - - public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV -// public static String DEFAULT_SCOPE = "/d4science.research-infrastructures.eu/gCubeApps"; - public static String TEST_USER = "francesco.mangiacrapa"; -// public static String FOLDER_ID = "4f0ff79d-3c1e-4d2a-bc74-6f731edcac98"; - - public static void main(String[] args) { - - try { - - ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); - ScopeProvider.instance.set(scope.toString()); - - Workspace ws = HomeLibrary - .getHomeManagerFactory() - .getHomeManager() - .getHome(TEST_USER) - .getWorkspace(); - // - -// System.out.println("start get root"); - WorkspaceItem folder = ws.getRoot(); -// List children = (List) root.getChildren(); - - System.out.println("start get children"); - -// WorkspaceFolder folder = (WorkspaceFolder) ws.getItem(FOLDER_ID); - List children = (List) folder.getChildren(); -// List children = root.getChildren(); - - System.out.println("children size: "+children.size()); - -// GWTWorkspaceBuilder builder = new GWTWorkspaceBuilder(); +////TODO IT MUST BE MOVED TO SHUB +///** +// * +// */ +//package org.gcube.portlets.user.workspace; +// +//import java.util.List; +// +//import org.gcube.common.homelibary.model.items.type.WorkspaceItemType; +//import org.gcube.common.homelibrary.home.HomeLibrary; +//import org.gcube.common.homelibrary.home.workspace.Workspace; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; +//import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; +//import org.gcube.common.scope.api.ScopeProvider; +//import org.gcube.common.scope.impl.ScopeBean; +// +///** +// * +// * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it +// * Jan 29, 2014 +// * +// */ +///* +// * +// * +// * IT MUST BE MOVED TO SHUB +// * +// * +// * +//public class SizeRetrieving { +// +// +// public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV +//// public static String DEFAULT_SCOPE = "/d4science.research-infrastructures.eu/gCubeApps"; +// public static String TEST_USER = "francesco.mangiacrapa"; +//// public static String FOLDER_ID = "4f0ff79d-3c1e-4d2a-bc74-6f731edcac98"; +// +// public static void main(String[] args) { +// +// try { +// +// ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); +// ScopeProvider.instance.set(scope.toString()); // -// builder.buildGXTListFileGridModelItem(children, null); - - - - int i=0; - for (WorkspaceItem workspaceItem : children) { - - - if(workspaceItem.getType().equals(WorkspaceItemType.FOLDER) || workspaceItem.getType().equals(WorkspaceItemType.SHARED_FOLDER)){ - - folder = (WorkspaceFolder) workspaceItem; - - - System.out.println(++i+") folder name: "+folder.getName() +", id: "+folder.getId()); - }else{ - - - if(workspaceItem.getType().equals(WorkspaceItemType.FOLDER_ITEM)){ - - FolderItem folderItem = (FolderItem) workspaceItem; - - System.out.println(++i+") folderItem id: "+folderItem.getId() +", name: "+folderItem.getName() + ", size: "+folderItem.getLength()); - } - - } - } - System.out.println("end"); - } catch (Exception e) { - e.printStackTrace(); - } - } - -} +// Workspace ws = HomeLibrary +// .getHomeManagerFactory() +// .getHomeManager() +// .getHome(TEST_USER) +// .getWorkspace(); +// // +// +//// System.out.println("start get root"); +// WorkspaceItem folder = ws.getRoot(); +//// List children = (List) root.getChildren(); +// +// System.out.println("start get children"); +// +//// WorkspaceFolder folder = (WorkspaceFolder) ws.getItem(FOLDER_ID); +// List children = (List) folder.getChildren(); +//// List children = root.getChildren(); +// +// System.out.println("children size: "+children.size()); +// +//// GWTWorkspaceBuilder builder = new GWTWorkspaceBuilder(); +//// +//// builder.buildGXTListFileGridModelItem(children, null); +// +// +// +// int i=0; +// for (WorkspaceItem workspaceItem : children) { +// +// +// if(workspaceItem.getType().equals(WorkspaceItemType.FOLDER) || workspaceItem.getType().equals(WorkspaceItemType.SHARED_FOLDER)){ +// +// folder = (WorkspaceFolder) workspaceItem; +// +// +// System.out.println(++i+") folder name: "+folder.getName() +", id: "+folder.getId()); +// }else{ +// +// +// if(workspaceItem.getType().equals(WorkspaceItemType.FOLDER_ITEM)){ +// +// FolderItem folderItem = (FolderItem) workspaceItem; +// +// System.out.println(++i+") folderItem id: "+folderItem.getId() +", name: "+folderItem.getName() + ", size: "+folderItem.getLength()); +// } +// +// } +// } +// System.out.println("end"); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +// +//} +// +//*/ \ No newline at end of file diff --git a/src/test/java/org/gcube/portlets/user/workspace/SmartFolderTest.java b/src/test/java/org/gcube/portlets/user/workspace/SmartFolderTest.java index 71e6279..1ee3a77 100644 --- a/src/test/java/org/gcube/portlets/user/workspace/SmartFolderTest.java +++ b/src/test/java/org/gcube/portlets/user/workspace/SmartFolderTest.java @@ -1,138 +1,137 @@ -/** - * - */ -package org.gcube.portlets.user.workspace; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Logger; -import org.gcube.common.homelibary.model.items.type.FolderItemType; -import org.gcube.common.homelibrary.home.HomeLibrary; -import org.gcube.common.homelibrary.home.workspace.Workspace; -import org.gcube.common.homelibrary.home.workspace.search.SearchItem; -import org.gcube.common.scope.api.ScopeProvider; -import org.gcube.common.scope.impl.ScopeBean; -import org.gcube.portlets.user.workspace.client.interfaces.GXTCategorySmartFolder; -import org.gcube.portlets.user.workspace.client.model.FileGridModel; -import org.gcube.portlets.user.workspace.server.GWTWorkspaceBuilder; - -/** - * The Class SmartFolderTest. - * - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * Sep 29, 2016 - */ -public class SmartFolderTest { - - - protected static Logger logger = Logger.getLogger(SmartFolderTest.class); - -// public static String DEFAULT_SCOPE = "/d4science.research-infrastructures.eu/gCubeApps/EcologicalModelling"; //PRODUCTION - public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV - - private static Workspace workspace; - - /** - * The main method. - * - * @param args the arguments - */ - public static void main(String[] args) { - - try { - - ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); - ScopeProvider.instance.set(scope.toString()); - - System.out.println("instancing workspace"); - workspace = HomeLibrary - .getHomeManagerFactory() - .getHomeManager() - .getHome("francesco.mangiacrapa") - .getWorkspace(); - // - System.out.println("start"); - List smarts = getSmartFolderResultsByCategory(GXTCategorySmartFolder.SMF_IMAGES); - - for (FileGridModel fileGridModel : smarts) { - System.out.println(fileGridModel.toString()); - } - System.out.println("end"); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Gets the smart folder results by category. - * - * @param category the category - * @return the smart folder results by category - * @throws Exception the exception - */ - public static List getSmartFolderResultsByCategory(GXTCategorySmartFolder category) throws Exception { - - try { - - - GWTWorkspaceBuilder builder = new GWTWorkspaceBuilder(); - - List listWorkspaceItems = new ArrayList(); - - //Category IMAGES - if(category.equals(GXTCategorySmartFolder.SMF_IMAGES.toString())){ - - listWorkspaceItems = workspace.getFolderItems(FolderItemType.IMAGE_DOCUMENT, FolderItemType.EXTERNAL_IMAGE); - - //Category BIODIVERSITY - }else if(category.equals(GXTCategorySmartFolder.SMF_BIODIVERSITY.toString())){ - -// listWorkspaceItems = workspace.getFolderItems(FolderItemType.AQUAMAPS_ITEM); - - //Category DOCUMENTS - }else if(category.equals(GXTCategorySmartFolder.SMF_DOCUMENTS.toString())){ - - listWorkspaceItems = workspace.getFolderItems( - FolderItemType.EXTERNAL_FILE, - FolderItemType.EXTERNAL_PDF_FILE, - FolderItemType.QUERY, - FolderItemType.PDF_DOCUMENT, - FolderItemType.METADATA, -// FolderItemType.WORKFLOW_REPORT, -// FolderItemType.WORKFLOW_TEMPLATE, -// FolderItemType.URL_DOCUMENT, - FolderItemType.DOCUMENT - ); - - //Category LINKS - }else if(category.equals(GXTCategorySmartFolder.SMF_LINKS.toString())){ - -// listWorkspaceItems = workspace.getFolderItems(FolderItemType.EXTERNAL_URL, FolderItemType.URL_DOCUMENT, FolderItemType.EXTERNAL_RESOURCE_LINK); - - //Category REPORTS - }else if(category.equals(GXTCategorySmartFolder.SMF_REPORTS.toString())){ - - listWorkspaceItems = workspace.getFolderItems(FolderItemType.REPORT_TEMPLATE, FolderItemType.REPORT); - - //Category TIME SERIES - }else if(category.equals(GXTCategorySmartFolder.SMF_TIMESERIES.toString())){ - - listWorkspaceItems = workspace.getFolderItems(FolderItemType.TIME_SERIES); - } - else - new Exception("Smart folder category unknown"); - - - return builder.filterListFileGridModelItemByCategory(listWorkspaceItems, category); - - - } catch (Exception e) { - System.out.println("Error in server get smart folder by category"); - e.printStackTrace(); - throw new Exception(e.getMessage()); - } - - } - -} +//TODO IT MUST BE MOVED TO SHUB +///** +// * +// */ +//package org.gcube.portlets.user.workspace; +// +//import java.util.ArrayList; +//import java.util.List; +// +//import org.apache.log4j.Logger; +//import org.gcube.common.homelibary.model.items.type.FolderItemType; +//import org.gcube.common.homelibrary.home.HomeLibrary; +//import org.gcube.common.homelibrary.home.workspace.Workspace; +//import org.gcube.common.homelibrary.home.workspace.search.SearchItem; +//import org.gcube.common.scope.api.ScopeProvider; +//import org.gcube.common.scope.impl.ScopeBean; +//import org.gcube.portlets.user.workspace.client.interfaces.GXTCategorySmartFolder; +//import org.gcube.portlets.user.workspace.client.model.FileGridModel; +// +// +///** +// * The Class SmartFolderTest. +// * +// * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it +// * Sep 29, 2016 +// */ +///* +// * +// * +// * IT MUST BE MOVED TO SHUB +// * +// * +// * +//public class SmartFolderTest { +// +// +// protected static Logger logger = Logger.getLogger(SmartFolderTest.class); +// +//// public static String DEFAULT_SCOPE = "/d4science.research-infrastructures.eu/gCubeApps/EcologicalModelling"; //PRODUCTION +// public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV +// +// private static Workspace workspace; +// +// public static void main(String[] args) { +// +// try { +// +// ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); +// ScopeProvider.instance.set(scope.toString()); +// +// System.out.println("instancing workspace"); +// workspace = HomeLibrary +// .getHomeManagerFactory() +// .getHomeManager() +// .getHome("francesco.mangiacrapa") +// .getWorkspace(); +// // +// System.out.println("start"); +// List smarts = getSmartFolderResultsByCategory(GXTCategorySmartFolder.SMF_IMAGES); +// +// for (FileGridModel fileGridModel : smarts) { +// System.out.println(fileGridModel.toString()); +// } +// System.out.println("end"); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +// +// +// public static List getSmartFolderResultsByCategory(GXTCategorySmartFolder category) throws Exception { +// +// try { +// +// +// GWTWorkspaceBuilder builder = new GWTWorkspaceBuilder(); +// +// List listWorkspaceItems = new ArrayList(); +// +// //Category IMAGES +// if(category.equals(GXTCategorySmartFolder.SMF_IMAGES.toString())){ +// +// listWorkspaceItems = workspace.getFolderItems(FolderItemType.IMAGE_DOCUMENT, FolderItemType.EXTERNAL_IMAGE); +// +// //Category BIODIVERSITY +// }else if(category.equals(GXTCategorySmartFolder.SMF_BIODIVERSITY.toString())){ +// +//// listWorkspaceItems = workspace.getFolderItems(FolderItemType.AQUAMAPS_ITEM); +// +// //Category DOCUMENTS +// }else if(category.equals(GXTCategorySmartFolder.SMF_DOCUMENTS.toString())){ +// +// listWorkspaceItems = workspace.getFolderItems( +// FolderItemType.EXTERNAL_FILE, +// FolderItemType.EXTERNAL_PDF_FILE, +// FolderItemType.QUERY, +// FolderItemType.PDF_DOCUMENT, +// FolderItemType.METADATA, +//// FolderItemType.WORKFLOW_REPORT, +//// FolderItemType.WORKFLOW_TEMPLATE, +//// FolderItemType.URL_DOCUMENT, +// FolderItemType.DOCUMENT +// ); +// +// //Category LINKS +// }else if(category.equals(GXTCategorySmartFolder.SMF_LINKS.toString())){ +// +//// listWorkspaceItems = workspace.getFolderItems(FolderItemType.EXTERNAL_URL, FolderItemType.URL_DOCUMENT, FolderItemType.EXTERNAL_RESOURCE_LINK); +// +// //Category REPORTS +// }else if(category.equals(GXTCategorySmartFolder.SMF_REPORTS.toString())){ +// +// listWorkspaceItems = workspace.getFolderItems(FolderItemType.REPORT_TEMPLATE, FolderItemType.REPORT); +// +// //Category TIME SERIES +// }else if(category.equals(GXTCategorySmartFolder.SMF_TIMESERIES.toString())){ +// +// listWorkspaceItems = workspace.getFolderItems(FolderItemType.TIME_SERIES); +// } +// else +// new Exception("Smart folder category unknown"); +// +// +// return builder.filterListFileGridModelItemByCategory(listWorkspaceItems, category); +// +// +// } catch (Exception e) { +// System.out.println("Error in server get smart folder by category"); +// e.printStackTrace(); +// throw new Exception(e.getMessage()); +// } +// +// } +// +//} +// +//*/ diff --git a/src/test/java/org/gcube/portlets/user/workspace/TestSync.java b/src/test/java/org/gcube/portlets/user/workspace/TestSync.java index 813df6d..0a15515 100644 --- a/src/test/java/org/gcube/portlets/user/workspace/TestSync.java +++ b/src/test/java/org/gcube/portlets/user/workspace/TestSync.java @@ -1,207 +1,208 @@ -/** - * - */ -package org.gcube.portlets.user.workspace; - -import java.util.List; -import java.util.concurrent.TimeUnit; - -import org.gcube.common.homelibrary.home.HomeLibrary; -import org.gcube.common.homelibrary.home.exceptions.HomeNotFoundException; -import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; -import org.gcube.common.homelibrary.home.workspace.Workspace; -import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; -import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; -import org.gcube.common.homelibrary.home.workspace.WorkspaceSharedFolder; -import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException; -import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; -import org.gcube.common.scope.api.ScopeProvider; -import org.gcube.common.scope.impl.ScopeBean; - -/** - * - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * Jan 29, 2014 - * - */ -public class TestSync { - - public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV - public static String TEST_USER = "francesco.mangiacrapa"; - public static String FOLDER_SYNC = "d6dae663-91d1-4da7-b13d-959de6fb2f86"; //TestSync is root Folder - - public static String FOLDER_A = "983d4ab9-e8fd-4c6d-869e-734a730e3e50"; - public static String FOLDER_B = "94995b10-6fcb-4ed8-a3ea-4a6dd7d33a7a"; - public static String FOLDER_C = "e945fcfd-9da9-45a0-98a9-d1940d1720bb"; - - protected static int i=0; - protected static int foldersCounter = 0; - protected static int sharedFoldersCounter = 0; - protected static int folderItemCounter = 0; - protected static int othersCounter = 0; - - public static void main(String[] args) { - - ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); - ScopeProvider.instance.set(scope.toString()); - - System.out.println("init HL"); - try { - - Workspace ws = getWorkspace(); -// List children = ws.getItem(FOLDER_A).getChildren(); +//TODO IT MUST BE MOVED TO SHUB +///** +// * +// */ +//package org.gcube.portlets.user.workspace; +// +//import java.util.List; +//import java.util.concurrent.TimeUnit; +// +//import org.gcube.common.homelibrary.home.HomeLibrary; +//import org.gcube.common.homelibrary.home.exceptions.HomeNotFoundException; +//import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; +//import org.gcube.common.homelibrary.home.workspace.Workspace; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceSharedFolder; +//import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException; +//import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; +//import org.gcube.common.scope.api.ScopeProvider; +//import org.gcube.common.scope.impl.ScopeBean; +// +///** +// * +// * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it +// * Jan 29, 2014 +// * +// */ +//public class TestSync { +// +// public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV +// public static String TEST_USER = "francesco.mangiacrapa"; +// public static String FOLDER_SYNC = "d6dae663-91d1-4da7-b13d-959de6fb2f86"; //TestSync is root Folder +// +// public static String FOLDER_A = "983d4ab9-e8fd-4c6d-869e-734a730e3e50"; +// public static String FOLDER_B = "94995b10-6fcb-4ed8-a3ea-4a6dd7d33a7a"; +// public static String FOLDER_C = "e945fcfd-9da9-45a0-98a9-d1940d1720bb"; +// +// protected static int i=0; +// protected static int foldersCounter = 0; +// protected static int sharedFoldersCounter = 0; +// protected static int folderItemCounter = 0; +// protected static int othersCounter = 0; +// +// public static void main(String[] args) { +// +// ScopeBean scope = new ScopeBean(DEFAULT_SCOPE); +// ScopeProvider.instance.set(scope.toString()); +// +// System.out.println("init HL"); +// try { +// +// Workspace ws = getWorkspace(); +//// List children = ws.getItem(FOLDER_A).getChildren(); +//// for (WorkspaceItem workspaceItem : children) { +//// printItem(workspaceItem); +//// } +// WorkspaceItem item_40MB = ws.getItem(FOLDER_A).getChildren().get(0); +// threadCopy(ws, item_40MB, FOLDER_B); +// +// System.out.println("THREAD MAIN SLEEPING 10 sec."); +// Thread.sleep(10000); +// System.out.println("THREAD MAIN ACTIVE.."); +//// WorkspaceItem cp_item_260MB = ws.getItem(FOLDER_B).getChildren().get(0); +// +// List children = ws.getItem(FOLDER_B).getChildren(); +// System.out.println("FOLDER_B children.."); // for (WorkspaceItem workspaceItem : children) { // printItem(workspaceItem); // } - WorkspaceItem item_40MB = ws.getItem(FOLDER_A).getChildren().get(0); - threadCopy(ws, item_40MB, FOLDER_B); - - System.out.println("THREAD MAIN SLEEPING 10 sec."); - Thread.sleep(10000); - System.out.println("THREAD MAIN ACTIVE.."); -// WorkspaceItem cp_item_260MB = ws.getItem(FOLDER_B).getChildren().get(0); - - List children = ws.getItem(FOLDER_B).getChildren(); - System.out.println("FOLDER_B children.."); - for (WorkspaceItem workspaceItem : children) { - printItem(workspaceItem); - } - - threadMove(ws, children.get(0), FOLDER_C); - - Thread.sleep(60000); - System.out.println("THREAD MAIN TERMINATED"); -// retrieveFirstLevel(ws); - }catch(Exception e){ - e.printStackTrace(); - } - } - - public static void threadCopy(final Workspace ws, final WorkspaceItem item, final String destinationFolderId){ - - new Thread(){ - @Override - public void run() { - try { - long time = System.currentTimeMillis(); - long diff; - System.out.println("Starting copy "+item.getName()+", time: "+time); - ws.copy(item.getId(), destinationFolderId); - diff = (System.currentTimeMillis()-time)/1000; - System.out.println("End copy! [time diff: "+diff+" sec.]"); - } catch (Exception e) { - System.out.println("Copy Exception: "+e.getMessage()); - } - } - }.start(); - } - - - public static void threadMove(final Workspace ws, final WorkspaceItem item, final String destinationFolderId){ - - new Thread(){ - @Override - public void run() { - try { - long time = System.currentTimeMillis(); - long diff; - System.out.println("Starting move "+item.getName()+", time: "+time); - ws.moveItem(item.getId(), destinationFolderId); - diff = (System.currentTimeMillis()-time)/1000; - System.out.println("End move! [time diff: "+diff+" sec.]"); - } catch (Exception e) { - System.out.println("Move Exception: "+e.getMessage()); - } - } - }.start(); - } - - public static Workspace getWorkspace() throws InternalErrorException, HomeNotFoundException, WorkspaceFolderNotFoundException - { - - System.out.println("Get Workspace scope: "+DEFAULT_SCOPE + " username: "+TEST_USER); - ScopeProvider.instance.set(DEFAULT_SCOPE); - Workspace workspace = HomeLibrary.getUserWorkspace(TEST_USER); - return workspace; - } - - - private static void retrieveFirstLevel(Workspace ws){ - - try { - - //TEST TIME - Long startTime = System.currentTimeMillis(); - Long endTime = System.currentTimeMillis() - startTime; - String time = String.format("%d msc %d sec", endTime, TimeUnit.MILLISECONDS.toSeconds(endTime)); - - startTime = System.currentTimeMillis(); - System.out.println("Start get root at time: "+startTime); -// WorkspaceItem root = ws.getItem(ITEMID); - WorkspaceItem root = ws.getRoot(); - - System.out.println("start get children"); - List children = root.getChildren(); - System.out.println("tree getChildren() returning "+children.size()+" elements in " + time); - - System.out.println("children size: "+children.size()); - - - for (WorkspaceItem workspaceItem : children) { - printItem(workspaceItem); - } - - //TEST TIME - endTime = System.currentTimeMillis(); - long difference = endTime - startTime; - time = String.format("%d msc %d sec", difference, TimeUnit.MILLISECONDS.toSeconds(difference)); - System.out.println("End time is "+endTime+ " difference is "+time); - System.out.println("Folders are: "+foldersCounter); - System.out.println("Shared Folders are: "+sharedFoldersCounter); - System.out.println("Folder Item are: "+folderItemCounter); - System.out.println("Others are: "+othersCounter); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static void printItem(WorkspaceItem workspaceItem) throws InternalErrorException{ - - switch (workspaceItem.getType()) { - - case FOLDER: - - WorkspaceFolder folder = (WorkspaceFolder) workspaceItem; - - System.out.println(++i+") "+folder.getId() +" folder name: "+folder.getName() + " owner "+folder.getOwner()); - foldersCounter++; - - break; - - case SHARED_FOLDER: - - WorkspaceSharedFolder shared = (WorkspaceSharedFolder) workspaceItem; - - System.out.println(++i+") "+shared.getId() +" shared folder name: "+shared.getName() + " owner "+shared.getOwner()+" isVRE "+shared.isVreFolder() +" ACLOwner: "+shared.getACLOwner()+" AclUser: "+shared.getACLUser()); - -// System.out.println(++i+") shared folder name: "+shared.getName() + " owner "+shared.getOwner().getPortalLogin()); - sharedFoldersCounter++; - - break; - - case FOLDER_ITEM: - - FolderItem folderItem = (FolderItem) workspaceItem; - - System.out.println(++i+") folderItem id: "+folderItem.getId() +", name: "+folderItem.getName() + ", own: "+folderItem.getOwner()); - folderItemCounter++; - - break; - default: - System.out.println(++i+") DEFAULT - item id: "+workspaceItem.getId() +", name: "+workspaceItem.getName() + ", own: "+workspaceItem.getOwner()); - othersCounter++; - break; - } - - } -} +// +// threadMove(ws, children.get(0), FOLDER_C); +// +// Thread.sleep(60000); +// System.out.println("THREAD MAIN TERMINATED"); +//// retrieveFirstLevel(ws); +// }catch(Exception e){ +// e.printStackTrace(); +// } +// } +// +// public static void threadCopy(final Workspace ws, final WorkspaceItem item, final String destinationFolderId){ +// +// new Thread(){ +// @Override +// public void run() { +// try { +// long time = System.currentTimeMillis(); +// long diff; +// System.out.println("Starting copy "+item.getName()+", time: "+time); +// ws.copy(item.getId(), destinationFolderId); +// diff = (System.currentTimeMillis()-time)/1000; +// System.out.println("End copy! [time diff: "+diff+" sec.]"); +// } catch (Exception e) { +// System.out.println("Copy Exception: "+e.getMessage()); +// } +// } +// }.start(); +// } +// +// +// public static void threadMove(final Workspace ws, final WorkspaceItem item, final String destinationFolderId){ +// +// new Thread(){ +// @Override +// public void run() { +// try { +// long time = System.currentTimeMillis(); +// long diff; +// System.out.println("Starting move "+item.getName()+", time: "+time); +// ws.moveItem(item.getId(), destinationFolderId); +// diff = (System.currentTimeMillis()-time)/1000; +// System.out.println("End move! [time diff: "+diff+" sec.]"); +// } catch (Exception e) { +// System.out.println("Move Exception: "+e.getMessage()); +// } +// } +// }.start(); +// } +// +// public static Workspace getWorkspace() throws InternalErrorException, HomeNotFoundException, WorkspaceFolderNotFoundException +// { +// +// System.out.println("Get Workspace scope: "+DEFAULT_SCOPE + " username: "+TEST_USER); +// ScopeProvider.instance.set(DEFAULT_SCOPE); +// Workspace workspace = HomeLibrary.getUserWorkspace(TEST_USER); +// return workspace; +// } +// +// +// private static void retrieveFirstLevel(Workspace ws){ +// +// try { +// +// //TEST TIME +// Long startTime = System.currentTimeMillis(); +// Long endTime = System.currentTimeMillis() - startTime; +// String time = String.format("%d msc %d sec", endTime, TimeUnit.MILLISECONDS.toSeconds(endTime)); +// +// startTime = System.currentTimeMillis(); +// System.out.println("Start get root at time: "+startTime); +//// WorkspaceItem root = ws.getItem(ITEMID); +// WorkspaceItem root = ws.getRoot(); +// +// System.out.println("start get children"); +// List children = root.getChildren(); +// System.out.println("tree getChildren() returning "+children.size()+" elements in " + time); +// +// System.out.println("children size: "+children.size()); +// +// +// for (WorkspaceItem workspaceItem : children) { +// printItem(workspaceItem); +// } +// +// //TEST TIME +// endTime = System.currentTimeMillis(); +// long difference = endTime - startTime; +// time = String.format("%d msc %d sec", difference, TimeUnit.MILLISECONDS.toSeconds(difference)); +// System.out.println("End time is "+endTime+ " difference is "+time); +// System.out.println("Folders are: "+foldersCounter); +// System.out.println("Shared Folders are: "+sharedFoldersCounter); +// System.out.println("Folder Item are: "+folderItemCounter); +// System.out.println("Others are: "+othersCounter); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +// +// public static void printItem(WorkspaceItem workspaceItem) throws InternalErrorException{ +// +// switch (workspaceItem.getType()) { +// +// case FOLDER: +// +// WorkspaceFolder folder = (WorkspaceFolder) workspaceItem; +// +// System.out.println(++i+") "+folder.getId() +" folder name: "+folder.getName() + " owner "+folder.getOwner()); +// foldersCounter++; +// +// break; +// +// case SHARED_FOLDER: +// +// WorkspaceSharedFolder shared = (WorkspaceSharedFolder) workspaceItem; +// +// System.out.println(++i+") "+shared.getId() +" shared folder name: "+shared.getName() + " owner "+shared.getOwner()+" isVRE "+shared.isVreFolder() +" ACLOwner: "+shared.getACLOwner()+" AclUser: "+shared.getACLUser()); +// +//// System.out.println(++i+") shared folder name: "+shared.getName() + " owner "+shared.getOwner().getPortalLogin()); +// sharedFoldersCounter++; +// +// break; +// +// case FOLDER_ITEM: +// +// FolderItem folderItem = (FolderItem) workspaceItem; +// +// System.out.println(++i+") folderItem id: "+folderItem.getId() +", name: "+folderItem.getName() + ", own: "+folderItem.getOwner()); +// folderItemCounter++; +// +// break; +// default: +// System.out.println(++i+") DEFAULT - item id: "+workspaceItem.getId() +", name: "+workspaceItem.getName() + ", own: "+workspaceItem.getOwner()); +// othersCounter++; +// break; +// } +// +// } +//} diff --git a/src/test/java/org/gcube/portlets/user/workspace/TestWithTime.java b/src/test/java/org/gcube/portlets/user/workspace/TestWithTime.java index 498362e..918da2f 100644 --- a/src/test/java/org/gcube/portlets/user/workspace/TestWithTime.java +++ b/src/test/java/org/gcube/portlets/user/workspace/TestWithTime.java @@ -1,76 +1,77 @@ -/** - * - */ -package org.gcube.portlets.user.workspace; - -import java.util.List; - -import org.gcube.common.homelibrary.home.HomeLibrary; -import org.gcube.common.homelibrary.home.workspace.Workspace; -import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; -import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; -import org.gcube.common.scope.api.ScopeProvider; -import org.junit.Test; - -/** - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * May 15, 2014 - * - */ -public class TestWithTime { - - public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV - public static String TEST_USER = "fabio.simeoni"; - - @Test - public void accessTest() throws Exception { - - ScopeProvider.instance.set(DEFAULT_SCOPE); - System.out.println("Start Test Simeoni"); - long time = System.currentTimeMillis(); - - Workspace ws = HomeLibrary.getUserWorkspace(TEST_USER); - - for (WorkspaceItem item : ws.getRoot().getChildren()) - item.getProperties().getProperties().keySet(); - - long diff = System.currentTimeMillis()-time; - System.out.println("End Test Simeoni: "+diff); - } - - @Test - public void accessTest1() throws Exception { - - ScopeProvider.instance.set(DEFAULT_SCOPE); - - System.out.println("Start Test"); - long time = System.currentTimeMillis(); - long diff; - - System.out.println("Get worskpace"); - Workspace ws = HomeLibrary.getUserWorkspace(TEST_USER); - diff = System.currentTimeMillis()-time; - System.out.println("Worskapce returned in: "+diff); - - System.out.println("Get Root"); - WorkspaceFolder root = ws.getRoot(); - diff = System.currentTimeMillis()-time; - System.out.println("Root returned in: "+diff); - - System.out.println("Get Children"); - List children = root.getChildren(); - diff = System.currentTimeMillis()-time; - System.out.println("Get Children returned in: "+diff); - - System.out.println("Children size is: "+children.size()); - for (WorkspaceItem item : children){ - diff = System.currentTimeMillis()-time; - System.out.println("Item: +"+item.getId()+", keyset: "+item.getProperties().getProperties().keySet() + ", Diff is: "+diff); - } - diff = System.currentTimeMillis()-time; - System.out.println("Children properties returned in: "+diff); - - diff = System.currentTimeMillis()-time; - System.out.println("End test: "+diff); - } -} +////TODO IT MUST BE MOVED TO SHUB +///** +// * +// */ +//package org.gcube.portlets.user.workspace; +// +//import java.util.List; +// +//import org.gcube.common.homelibrary.home.HomeLibrary; +//import org.gcube.common.homelibrary.home.workspace.Workspace; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; +//import org.gcube.common.scope.api.ScopeProvider; +//import org.junit.Test; +// +///** +// * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it +// * May 15, 2014 +// * +// */ +//public class TestWithTime { +// +// public static String DEFAULT_SCOPE = "/gcube/devsec"; //DEV +// public static String TEST_USER = "fabio.simeoni"; +// +// @Test +// public void accessTest() throws Exception { +// +// ScopeProvider.instance.set(DEFAULT_SCOPE); +// System.out.println("Start Test Simeoni"); +// long time = System.currentTimeMillis(); +// +// Workspace ws = HomeLibrary.getUserWorkspace(TEST_USER); +// +// for (WorkspaceItem item : ws.getRoot().getChildren()) +// item.getProperties().getProperties().keySet(); +// +// long diff = System.currentTimeMillis()-time; +// System.out.println("End Test Simeoni: "+diff); +// } +// +// @Test +// public void accessTest1() throws Exception { +// +// ScopeProvider.instance.set(DEFAULT_SCOPE); +// +// System.out.println("Start Test"); +// long time = System.currentTimeMillis(); +// long diff; +// +// System.out.println("Get worskpace"); +// Workspace ws = HomeLibrary.getUserWorkspace(TEST_USER); +// diff = System.currentTimeMillis()-time; +// System.out.println("Worskapce returned in: "+diff); +// +// System.out.println("Get Root"); +// WorkspaceFolder root = ws.getRoot(); +// diff = System.currentTimeMillis()-time; +// System.out.println("Root returned in: "+diff); +// +// System.out.println("Get Children"); +// List children = root.getChildren(); +// diff = System.currentTimeMillis()-time; +// System.out.println("Get Children returned in: "+diff); +// +// System.out.println("Children size is: "+children.size()); +// for (WorkspaceItem item : children){ +// diff = System.currentTimeMillis()-time; +// System.out.println("Item: +"+item.getId()+", keyset: "+item.getProperties().getProperties().keySet() + ", Diff is: "+diff); +// } +// diff = System.currentTimeMillis()-time; +// System.out.println("Children properties returned in: "+diff); +// +// diff = System.currentTimeMillis()-time; +// System.out.println("End test: "+diff); +// } +//} diff --git a/src/test/java/org/gcube/portlets/user/workspace/UploadServletTest.java b/src/test/java/org/gcube/portlets/user/workspace/UploadServletTest.java index 3abb673..4234aea 100644 --- a/src/test/java/org/gcube/portlets/user/workspace/UploadServletTest.java +++ b/src/test/java/org/gcube/portlets/user/workspace/UploadServletTest.java @@ -1,137 +1,138 @@ -/** - * - */ -package org.gcube.portlets.user.workspace; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.gcube.common.authorization.library.provider.SecurityTokenProvider; -import org.gcube.common.homelibrary.home.HomeLibrary; -import org.gcube.common.homelibrary.home.exceptions.HomeNotFoundException; -import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; -import org.gcube.common.homelibrary.home.exceptions.UserNotFoundException; -import org.gcube.common.homelibrary.home.workspace.Workspace; -import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; -import org.gcube.common.homelibrary.home.workspace.exceptions.InsufficientPrivilegesException; -import org.gcube.common.homelibrary.home.workspace.exceptions.ItemAlreadyExistException; -import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException; -import org.gcube.common.homelibrary.home.workspace.exceptions.WrongDestinationException; -import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalFile; -import org.gcube.common.homelibrary.util.WorkspaceUtil; -import org.gcube.common.scope.impl.ScopeBean; - - -/** - * The Class UploadServletTest. - * - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * Jul 23, 2018 - */ -public class UploadServletTest { - - - public static String YOUR_TOKEN = "YOUR TOKEN"; - public static String YOUR_USERNAME = "name.surname"; - - /** - * The main method. - * - * @param args the arguments - * @throws InternalErrorException the internal error exception - * @throws WorkspaceFolderNotFoundException the workspace folder not found exception - * @throws HomeNotFoundException the home not found exception - * @throws UserNotFoundException the user not found exception - * @throws InsufficientPrivilegesException the insufficient privileges exception - * @throws ItemAlreadyExistException the item already exist exception - * @throws WrongDestinationException the wrong destination exception - * @throws IOException Signals that an I/O exception has occurred. - */ - public static void main(String[] args) throws InternalErrorException, - WorkspaceFolderNotFoundException, HomeNotFoundException, - UserNotFoundException, InsufficientPrivilegesException, - ItemAlreadyExistException, WrongDestinationException, IOException { - - ScopeBean scope = new ScopeBean("/gcube/devsec"); - - - SecurityTokenProvider.instance.set("YOUR TOKEN"); - - Workspace workspace = HomeLibrary.getHomeManagerFactory() - .getHomeManager().getHome(YOUR_USERNAME) - .getWorkspace(); - - String filePath = "/home/francesco-mangiacrapa"; - - String fileName = "Geo Explorer 2016-01-15 18-51-51.png"; - - String fullPath = filePath + "/" + fileName; - - // String newFilePath = - // "/home/francesco-mangiacrapa/Desktop/icongeoexplorer/testupload.txt"; - - // String name = "TestReplaceContentImage"; - - // ExternalPDFFile file = workspace.createExternalPDFFile(name, "", - // null, new FileInputStream(new File(filePath)), - // workspace.getRoot().getId()); - - WorkspaceFolder root = workspace.getRoot(); - // ExternalImage file = (ExternalImage) root.find(name); - - // UPLOAD FILE -// String contentType = MimeTypeUtil.getMimeType(fileName, new BufferedInputStream( -// new FileInputStream(new File(fullPath)))); - - String itemName = WorkspaceUtil.getUniqueName(fileName, root); - System.out.println("Storing data...."); - System.out.println("content type " + null); - System.out.println("itemName " + itemName); - - ExternalFile file = (ExternalFile) WorkspaceUtil.createExternalFile( - root, itemName, "", null, new FileInputStream(new File( - fullPath))); - - System.out.println("Storing data - OK" + "File [id: " + file.getId() - + ", name: " + file.getName() + "]"); - // - // System.out.println("File mimeType" + file.getMimeType()); - // System.out.println("File size" + file.getLength()); - // - - // - // file.setData(new FileInputStream(new File(newFilePath))); - // System.out.println("New File mimeType" + file.getMimeType()); - // System.out.println("New File size" + file.getLength()); - - // - - System.out.println("Recovering data"); - InputStream inputStream = file.getData(); - // write the inputStream to a FileOutputStream - OutputStream out = new FileOutputStream(new File( - "/home/francesco-mangiacrapa/Desktop/download/"+fileName)); - - int read = 0; - byte[] bytes = new byte[1024]; - - while ((read = inputStream.read(bytes)) != -1) { - out.write(bytes, 0, read); - } - - inputStream.close(); - out.flush(); - out.close(); - - System.out.println("Recovering data - OK"); - - // File file = new File("/home/gioia/Desktop/test"); - // InputStream is = new FileInputStream(file); - - } - -} +//TODO IT MUST BE MOVED TO SHUB +///** +// * +// */ +//package org.gcube.portlets.user.workspace; +// +//import java.io.File; +//import java.io.FileInputStream; +//import java.io.FileOutputStream; +//import java.io.IOException; +//import java.io.InputStream; +//import java.io.OutputStream; +// +//import org.gcube.common.authorization.library.provider.SecurityTokenProvider; +//import org.gcube.common.homelibrary.home.HomeLibrary; +//import org.gcube.common.homelibrary.home.exceptions.HomeNotFoundException; +//import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; +//import org.gcube.common.homelibrary.home.exceptions.UserNotFoundException; +//import org.gcube.common.homelibrary.home.workspace.Workspace; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; +//import org.gcube.common.homelibrary.home.workspace.exceptions.InsufficientPrivilegesException; +//import org.gcube.common.homelibrary.home.workspace.exceptions.ItemAlreadyExistException; +//import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException; +//import org.gcube.common.homelibrary.home.workspace.exceptions.WrongDestinationException; +//import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalFile; +//import org.gcube.common.homelibrary.util.WorkspaceUtil; +//import org.gcube.common.scope.impl.ScopeBean; +// +// +///** +// * The Class UploadServletTest. +// * +// * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it +// * Jul 23, 2018 +// */ +//public class UploadServletTest { +// +// +// public static String YOUR_TOKEN = "YOUR TOKEN"; +// public static String YOUR_USERNAME = "name.surname"; +// +// /** +// * The main method. +// * +// * @param args the arguments +// * @throws InternalErrorException the internal error exception +// * @throws WorkspaceFolderNotFoundException the workspace folder not found exception +// * @throws HomeNotFoundException the home not found exception +// * @throws UserNotFoundException the user not found exception +// * @throws InsufficientPrivilegesException the insufficient privileges exception +// * @throws ItemAlreadyExistException the item already exist exception +// * @throws WrongDestinationException the wrong destination exception +// * @throws IOException Signals that an I/O exception has occurred. +// */ +// public static void main(String[] args) throws InternalErrorException, +// WorkspaceFolderNotFoundException, HomeNotFoundException, +// UserNotFoundException, InsufficientPrivilegesException, +// ItemAlreadyExistException, WrongDestinationException, IOException { +// +// ScopeBean scope = new ScopeBean("/gcube/devsec"); +// +// +// SecurityTokenProvider.instance.set("YOUR TOKEN"); +// +// Workspace workspace = HomeLibrary.getHomeManagerFactory() +// .getHomeManager().getHome(YOUR_USERNAME) +// .getWorkspace(); +// +// String filePath = "/home/francesco-mangiacrapa"; +// +// String fileName = "Geo Explorer 2016-01-15 18-51-51.png"; +// +// String fullPath = filePath + "/" + fileName; +// +// // String newFilePath = +// // "/home/francesco-mangiacrapa/Desktop/icongeoexplorer/testupload.txt"; +// +// // String name = "TestReplaceContentImage"; +// +// // ExternalPDFFile file = workspace.createExternalPDFFile(name, "", +// // null, new FileInputStream(new File(filePath)), +// // workspace.getRoot().getId()); +// +// WorkspaceFolder root = workspace.getRoot(); +// // ExternalImage file = (ExternalImage) root.find(name); +// +// // UPLOAD FILE +//// String contentType = MimeTypeUtil.getMimeType(fileName, new BufferedInputStream( +//// new FileInputStream(new File(fullPath)))); +// +// String itemName = WorkspaceUtil.getUniqueName(fileName, root); +// System.out.println("Storing data...."); +// System.out.println("content type " + null); +// System.out.println("itemName " + itemName); +// +// ExternalFile file = (ExternalFile) WorkspaceUtil.createExternalFile( +// root, itemName, "", null, new FileInputStream(new File( +// fullPath))); +// +// System.out.println("Storing data - OK" + "File [id: " + file.getId() +// + ", name: " + file.getName() + "]"); +// // +// // System.out.println("File mimeType" + file.getMimeType()); +// // System.out.println("File size" + file.getLength()); +// // +// +// // +// // file.setData(new FileInputStream(new File(newFilePath))); +// // System.out.println("New File mimeType" + file.getMimeType()); +// // System.out.println("New File size" + file.getLength()); +// +// // +// +// System.out.println("Recovering data"); +// InputStream inputStream = file.getData(); +// // write the inputStream to a FileOutputStream +// OutputStream out = new FileOutputStream(new File( +// "/home/francesco-mangiacrapa/Desktop/download/"+fileName)); +// +// int read = 0; +// byte[] bytes = new byte[1024]; +// +// while ((read = inputStream.read(bytes)) != -1) { +// out.write(bytes, 0, read); +// } +// +// inputStream.close(); +// out.flush(); +// out.close(); +// +// System.out.println("Recovering data - OK"); +// +// // File file = new File("/home/gioia/Desktop/test"); +// // InputStream is = new FileInputStream(file); +// +// } +// +//} diff --git a/src/test/java/org/gcube/portlets/user/workspace/UploadServletTestToken.java b/src/test/java/org/gcube/portlets/user/workspace/UploadServletTestToken.java index f7753e9..8ad5f89 100644 --- a/src/test/java/org/gcube/portlets/user/workspace/UploadServletTestToken.java +++ b/src/test/java/org/gcube/portlets/user/workspace/UploadServletTestToken.java @@ -1,116 +1,117 @@ -/** - * - */ -package org.gcube.portlets.user.workspace; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.gcube.common.homelibrary.home.HomeLibrary; -import org.gcube.common.homelibrary.home.exceptions.HomeNotFoundException; -import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; -import org.gcube.common.homelibrary.home.exceptions.UserNotFoundException; -import org.gcube.common.homelibrary.home.workspace.Workspace; -import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; -import org.gcube.common.homelibrary.home.workspace.exceptions.InsufficientPrivilegesException; -import org.gcube.common.homelibrary.home.workspace.exceptions.ItemAlreadyExistException; -import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException; -import org.gcube.common.homelibrary.home.workspace.exceptions.WrongDestinationException; -import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalFile; -import org.gcube.common.homelibrary.util.WorkspaceUtil; -import org.gcube.common.scope.api.ScopeProvider; -import org.gcube.common.scope.impl.ScopeBean; - -/** - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * Jun 20, 2013 - * - */ -public class UploadServletTestToken { - - public static void main(String[] args) throws InternalErrorException, - WorkspaceFolderNotFoundException, HomeNotFoundException, - UserNotFoundException, InsufficientPrivilegesException, - ItemAlreadyExistException, WrongDestinationException, IOException { - - ScopeBean scope = new ScopeBean("/gcube/devsec"); - ScopeProvider.instance.set(scope.toString()); - - Workspace workspace = HomeLibrary.getHomeManagerFactory() - .getHomeManager().getHome("francesco.mangiacrapa") - .getWorkspace(); - - String filePath = "/home/francesco-mangiacrapa"; - - String fileName = "Geo Explorer 2016-01-15 18-51-51.png"; - - String fullPath = filePath + "/" + fileName; - - // String newFilePath = - // "/home/francesco-mangiacrapa/Desktop/icongeoexplorer/testupload.txt"; - - // String name = "TestReplaceContentImage"; - - // ExternalPDFFile file = workspace.createExternalPDFFile(name, "", - // null, new FileInputStream(new File(filePath)), - // workspace.getRoot().getId()); - - WorkspaceFolder root = workspace.getRoot(); - // ExternalImage file = (ExternalImage) root.find(name); - - // UPLOAD FILE -// String contentType = MimeTypeUtil.getMimeType(fileName, new BufferedInputStream( -// new FileInputStream(new File(fullPath)))); - - String itemName = WorkspaceUtil.getUniqueName(fileName, root); - System.out.println("Storing data...."); - System.out.println("content type " + null); - System.out.println("itemName " + itemName); - - ExternalFile file = (ExternalFile) WorkspaceUtil.createExternalFile( - root, itemName, "", null, new FileInputStream(new File( - fullPath))); - - System.out.println("Storing data - OK" + "File [id: " + file.getId() - + ", name: " + file.getName() + "]"); - // - // System.out.println("File mimeType" + file.getMimeType()); - // System.out.println("File size" + file.getLength()); - // - - // - // file.setData(new FileInputStream(new File(newFilePath))); - // System.out.println("New File mimeType" + file.getMimeType()); - // System.out.println("New File size" + file.getLength()); - - // - - System.out.println("Recovering data"); - InputStream inputStream = file.getData(); - // write the inputStream to a FileOutputStream - OutputStream out = new FileOutputStream(new File( - "/home/francesco-mangiacrapa/Desktop/download/"+fileName)); - - int read = 0; - byte[] bytes = new byte[1024]; - - while ((read = inputStream.read(bytes)) != -1) { - out.write(bytes, 0, read); - } - - inputStream.close(); - out.flush(); - out.close(); - - System.out.println("Recovering data - OK"); - - // File file = new File("/home/gioia/Desktop/test"); - // InputStream is = new FileInputStream(file); - - } - -} +////TODO IT MUST BE MOVED TO SHUB +///** +// * +// */ +//package org.gcube.portlets.user.workspace; +// +//import java.io.File; +//import java.io.FileInputStream; +//import java.io.FileOutputStream; +//import java.io.IOException; +//import java.io.InputStream; +//import java.io.OutputStream; +// +//import org.gcube.common.homelibrary.home.HomeLibrary; +//import org.gcube.common.homelibrary.home.exceptions.HomeNotFoundException; +//import org.gcube.common.homelibrary.home.exceptions.InternalErrorException; +//import org.gcube.common.homelibrary.home.exceptions.UserNotFoundException; +//import org.gcube.common.homelibrary.home.workspace.Workspace; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder; +//import org.gcube.common.homelibrary.home.workspace.exceptions.InsufficientPrivilegesException; +//import org.gcube.common.homelibrary.home.workspace.exceptions.ItemAlreadyExistException; +//import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException; +//import org.gcube.common.homelibrary.home.workspace.exceptions.WrongDestinationException; +//import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalFile; +//import org.gcube.common.homelibrary.util.WorkspaceUtil; +//import org.gcube.common.scope.api.ScopeProvider; +//import org.gcube.common.scope.impl.ScopeBean; +// +///** +// * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it +// * Jun 20, 2013 +// * +// */ +//public class UploadServletTestToken { +// +// public static void main(String[] args) throws InternalErrorException, +// WorkspaceFolderNotFoundException, HomeNotFoundException, +// UserNotFoundException, InsufficientPrivilegesException, +// ItemAlreadyExistException, WrongDestinationException, IOException { +// +// ScopeBean scope = new ScopeBean("/gcube/devsec"); +// ScopeProvider.instance.set(scope.toString()); +// +// Workspace workspace = HomeLibrary.getHomeManagerFactory() +// .getHomeManager().getHome("francesco.mangiacrapa") +// .getWorkspace(); +// +// String filePath = "/home/francesco-mangiacrapa"; +// +// String fileName = "Geo Explorer 2016-01-15 18-51-51.png"; +// +// String fullPath = filePath + "/" + fileName; +// +// // String newFilePath = +// // "/home/francesco-mangiacrapa/Desktop/icongeoexplorer/testupload.txt"; +// +// // String name = "TestReplaceContentImage"; +// +// // ExternalPDFFile file = workspace.createExternalPDFFile(name, "", +// // null, new FileInputStream(new File(filePath)), +// // workspace.getRoot().getId()); +// +// WorkspaceFolder root = workspace.getRoot(); +// // ExternalImage file = (ExternalImage) root.find(name); +// +// // UPLOAD FILE +//// String contentType = MimeTypeUtil.getMimeType(fileName, new BufferedInputStream( +//// new FileInputStream(new File(fullPath)))); +// +// String itemName = WorkspaceUtil.getUniqueName(fileName, root); +// System.out.println("Storing data...."); +// System.out.println("content type " + null); +// System.out.println("itemName " + itemName); +// +// ExternalFile file = (ExternalFile) WorkspaceUtil.createExternalFile( +// root, itemName, "", null, new FileInputStream(new File( +// fullPath))); +// +// System.out.println("Storing data - OK" + "File [id: " + file.getId() +// + ", name: " + file.getName() + "]"); +// // +// // System.out.println("File mimeType" + file.getMimeType()); +// // System.out.println("File size" + file.getLength()); +// // +// +// // +// // file.setData(new FileInputStream(new File(newFilePath))); +// // System.out.println("New File mimeType" + file.getMimeType()); +// // System.out.println("New File size" + file.getLength()); +// +// // +// +// System.out.println("Recovering data"); +// InputStream inputStream = file.getData(); +// // write the inputStream to a FileOutputStream +// OutputStream out = new FileOutputStream(new File( +// "/home/francesco-mangiacrapa/Desktop/download/"+fileName)); +// +// int read = 0; +// byte[] bytes = new byte[1024]; +// +// while ((read = inputStream.read(bytes)) != -1) { +// out.write(bytes, 0, read); +// } +// +// inputStream.close(); +// out.flush(); +// out.close(); +// +// System.out.println("Recovering data - OK"); +// +// // File file = new File("/home/gioia/Desktop/test"); +// // InputStream is = new FileInputStream(file); +// +// } +// +//} diff --git a/src/test/java/org/gcube/portlets/user/workspace/UriResolverReaderRR.java b/src/test/java/org/gcube/portlets/user/workspace/UriResolverReaderRR.java index b7d3bcb..f84fa68 100644 --- a/src/test/java/org/gcube/portlets/user/workspace/UriResolverReaderRR.java +++ b/src/test/java/org/gcube/portlets/user/workspace/UriResolverReaderRR.java @@ -1,248 +1,242 @@ -/** - * - */ -package org.gcube.portlets.user.workspace; - -import static org.gcube.resources.discovery.icclient.ICFactory.clientFor; -import static org.gcube.resources.discovery.icclient.ICFactory.queryFor; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.List; - -import org.apache.commons.io.IOUtils; -import org.apache.log4j.Logger; -import org.gcube.common.homelibary.model.items.type.WorkspaceItemType; -import org.gcube.common.homelibrary.home.HomeLibrary; -import org.gcube.common.homelibrary.home.workspace.Workspace; -import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; -import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; -import org.gcube.common.resources.gcore.ServiceEndpoint; -import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint; -import org.gcube.common.scope.api.ScopeProvider; -import org.gcube.portlets.user.workspace.server.GWTWorkspaceBuilder; -import org.gcube.portlets.user.workspace.server.resolver.UriResolverReaderParameterForResolverIndex; -import org.gcube.portlets.user.workspace.server.resolver.UriResolverReaderParameterForResolverIndex.RESOLVER_TYPE; -import org.gcube.resources.discovery.client.api.DiscoveryClient; -import org.gcube.resources.discovery.client.queries.impl.XQuery; - -/** - * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it - * Jun 26, 2013 - * - */ -public class UriResolverReaderRR { - - //Base Address - String uri = ""; - //Query URL parameter - String parameter = ""; - private String uriRequest = ""; - public static String DEFAULT_SCOPE = "/d4science.research-infrastructures.eu/gCubeApps"; //PRODUCTION -// public static String DEFAULT_SCOPE = "/gcube/devsec"; //PRODUCTION - - public static Logger log = Logger.getLogger(UriResolverReaderRR.class); - - - /** - * @throws Exception - * - */ - public UriResolverReaderRR(String scope) throws Exception { - - ScopeProvider.instance.set(scope); - - XQuery query = queryFor(ServiceEndpoint.class); - - query.addCondition("$resource/Profile/Name/text() eq 'HTTP-URI-Resolver'").setResult("$resource/Profile/AccessPoint"); - - DiscoveryClient client = clientFor(AccessPoint.class); - - List endpoints = client.submit(query); - - if (endpoints.size() == 0) - throw new Exception("No Resolver available"); - - //Base Address -// System.out.println(endpoints.get(0).address()); - - uri = endpoints.get(0)!=null?endpoints.get(0).address():""; - - if(endpoints.get(0)!=null){ - - parameter = endpoints.get(0).propertyMap()!=null?endpoints.get(0).propertyMap().get("parameter").value():""; - } - - uriRequest = uri+"?"+parameter; - - - //Query URL parameter -// System.out.println(endpoints.get(0).propertyMap().get("parameter").value()); - - } - - public InputStream resolve(String smp) throws IOException{ - String query = uriRequest + "="+smp; - - URL url = new URL(query); - - return url.openStream(); - } - - - /** - * - * @return Base Address of Uri Resolver - */ - public String getUri() { - return uri; - } - - - /** - * - * @return Query URL parameter of Uri Resolver - */ - public String getParameter() { - return parameter; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("UriResolverReaderParameter [uri="); - builder.append(uri); - builder.append(", parameter="); - builder.append(parameter); - builder.append("]"); - return builder.toString(); - } - - - public static void main(String[] args) throws Exception { - - -// log.trace(new UriResolverReaderRR()); +//TODO IT MUST BE MOVED TO SHUB +///** +// * +// */ +//package org.gcube.portlets.user.workspace; // -// UriResolverReaderRR uriResolver = new UriResolverReaderRR(); -// InputStream is = uriResolver.resolve("smp://Wikipedia_logo_silver.png?5ezvFfBOLqaqBlwCEtAvz4ch5BUu1ag3yftpCvV+gayz9bAtSsnO1/sX6pemTKbDe0qbchLexXeWgGcJlskYE8td9QSDXSZj5VSl9kdN9SN0/LRYaWUZuP4Q1J7lEiwkU4GKPsiD6PDRVcT4QAqTEy5hSIbr6o4Y"); +//import static org.gcube.resources.discovery.icclient.ICFactory.clientFor; +//import static org.gcube.resources.discovery.icclient.ICFactory.queryFor; // -// File file = new File("test.png"); +//import java.io.File; +//import java.io.FileOutputStream; +//import java.io.IOException; +//import java.io.InputStream; +//import java.net.URL; +//import java.util.List; // -// FileOutputStream out = new FileOutputStream(file); +//import org.apache.commons.io.IOUtils; +//import org.apache.log4j.Logger; +//import org.gcube.common.homelibary.model.items.type.WorkspaceItemType; +//import org.gcube.common.homelibrary.home.HomeLibrary; +//import org.gcube.common.homelibrary.home.workspace.Workspace; +//import org.gcube.common.homelibrary.home.workspace.WorkspaceItem; +//import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; +//import org.gcube.common.resources.gcore.ServiceEndpoint; +//import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint; +//import org.gcube.common.scope.api.ScopeProvider; +//import org.gcube.portlets.user.workspace.server.resolver.UriResolverReaderParameterForResolverIndex; +//import org.gcube.portlets.user.workspace.server.resolver.UriResolverReaderParameterForResolverIndex.RESOLVER_TYPE; +//import org.gcube.resources.discovery.client.api.DiscoveryClient; +//import org.gcube.resources.discovery.client.queries.impl.XQuery; +// +///** +// * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it +// * Jun 26, 2013 +// * +// */ +///* +// * +// * +// * IT MUST BE MOVED TO SHUB +// * +// * +// * +//public class UriResolverReaderRR { +// +// //Base Address +// String uri = ""; +// //Query URL parameter +// String parameter = ""; +// private String uriRequest = ""; +// public static String DEFAULT_SCOPE = "/d4science.research-infrastructures.eu/gCubeApps"; //PRODUCTION +//// public static String DEFAULT_SCOPE = "/gcube/devsec"; //PRODUCTION +// +// public static Logger log = Logger.getLogger(UriResolverReaderRR.class); +// +// public UriResolverReaderRR(String scope) throws Exception { +// +// ScopeProvider.instance.set(scope); +// +// XQuery query = queryFor(ServiceEndpoint.class); +// +// query.addCondition("$resource/Profile/Name/text() eq 'HTTP-URI-Resolver'").setResult("$resource/Profile/AccessPoint"); +// +// DiscoveryClient client = clientFor(AccessPoint.class); +// +// List endpoints = client.submit(query); +// +// if (endpoints.size() == 0) +// throw new Exception("No Resolver available"); +// +// //Base Address +//// System.out.println(endpoints.get(0).address()); +// +// uri = endpoints.get(0)!=null?endpoints.get(0).address():""; +// +// if(endpoints.get(0)!=null){ +// +// parameter = endpoints.get(0).propertyMap()!=null?endpoints.get(0).propertyMap().get("parameter").value():""; +// } +// +// uriRequest = uri+"?"+parameter; // // -// IOUtils.copy(is, out); -// is.close(); +// //Query URL parameter +//// System.out.println(endpoints.get(0).propertyMap().get("parameter").value()); // -// out.close(); - -// 066086bc-5db1-48fc-b365-2ee821db2fb7 -// 370dc1cc-2e5e-4321-bc6f-ad860414db97 - -// id: f70f01f9-5a06-4123-b6ec-bd121c1af82f, name: testResponse.html, ### Public link: smp://Home/francesco.mangiacrapa/Workspace41e79e40-ec82-416b-ba83-29b54bb43426?5ezvFfBOLqb3YESyI/kesN4T+ZD0mtmc/4sZ0vGMrl0lgx7k85j8o2Q1vF0ezJi/xIGDhncO9jOkV1T8u6Db7GZ/4ePgMws8Jxu8ierJajHBd20bUotElPG3BVG0ODMHf1ztm6rKJIAeb9R/0FEIDQ== -// id: 35a0298e-da69-464f-9170-3dc764da564d, name: wiki ws backup, ### Public link: smp://Home/francesco.mangiacrapa/Workspaceb7c9bf85-b0e0-47ac-87e5-eba34048f7ab?5ezvFfBOLqb3YESyI/kesN4T+ZD0mtmc/4sZ0vGMrl0lgx7k85j8o2Q1vF0ezJi/xIGDhncO9jOkV1T8u6Db7GZ/4ePgMws8Jxu8ierJajHBd20bUotElPG3BVG0ODMHf1ztm6rKJIAeb9R/0FEIDQ== - - -// id: 370dc1cc-2e5e-4321-bc6f-ad860414db97, name: testupload.txt, ### Public link: smp://Home/francesco.mangiacrapa/Workspace284ee688-e6fb-4080-bbcb-cc7c8cc5c381?5ezvFfBOLqb3YESyI/kesN4T+ZD0mtmc/4sZ0vGMrl0lgx7k85j8o2Q1vF0ezJi/xIGDhncO9jOkV1T8u6Db7GZ/4ePgMws8Jxu8ierJajHBd20bUotElPG3BVG0ODMHf1ztm6rKJIAeb9R/0FEIDQ== - - String itemId = "0e875263-f6bc-4945-9435-bfb8774027ca"; -// itemId = "f70f01f9-5a06-4123-b6ec-bd121c1af82f"; - System.out.println("uri is: "+getPublicLinkForFolderItemId(itemId)); - - - +// } // - - - - } - - public static String getPublicLinkForFolderItemId(String itemId){ - - try{ - - ScopeProvider.instance.set(DEFAULT_SCOPE); - - Workspace workspace = HomeLibrary - .getHomeManagerFactory() - .getHomeManager() - .getHome("leonardo.candela") - .getWorkspace(); - - GWTWorkspaceBuilder builder = new GWTWorkspaceBuilder(); - - System.out.println("get item..."); - WorkspaceItem wsItem = workspace.getItem(itemId); - - if(wsItem.getType().equals(WorkspaceItemType.FOLDER_ITEM)){ - - FolderItem folderItem = (FolderItem) wsItem; - System.out.println("get public link..."); - String smpUri = builder.getPublicLinkForFolderItem(folderItem); - System.out.println("smpUri "+smpUri); - - System.out.println("get uriResolver..."); - UriResolverReaderParameterForResolverIndex uriResolver = new UriResolverReaderParameterForResolverIndex(DEFAULT_SCOPE, RESOLVER_TYPE.SMP_ID); - -// String url = uriResolver.resolveAsUriRequest(smpUri, "testResponse!@#$$%^^&&.html", folderItem.getMimeType(), true); - String url = uriResolver.resolveAsUriRequest(smpUri, folderItem.getName(), folderItem.getMimeType(), true); - System.out.println("url econded: "+url); +// public InputStream resolve(String smp) throws IOException{ +// String query = uriRequest + "="+smp; // -// url = uriResolver.resolveAsUriRequest(smpUri, folderItem.getName(), folderItem.getMimeType(), false); -// System.out.println("url doesn't econded: "+url); - - -// uriResolver.getHashParemeters(smpUri, folderItem.getName(), folderItem.getMimeType()); - - -// HttpCallerUtil callerUtil = new HttpCallerUtil(uriResolver.getBaseUri(), "", ""); -// String query = uriResolver.getQuery(); -// callerUtil.callPost("", query, "application/x-www-form-urlencoded"); - - -// String smpUri = "smp://Home/test.user/Workspace/bla8200ceb0-c525-40e6-bad1-a63f83811d3d?5ezvFfBOLqb3YESyI/kesN4T+ZD0mtmc/4sZ0vGMrl0lgx7k85j8o2Q1vF0ezJi/xIGDhncO9jOkV1T8u6Db7GZ/4ePgMws8Jxu8ierJajHBd20bUotElPG3BVG0ODMHf1ztm6rKJIAeb9R/0FEIDQ=="; - - - UrlShortener urlShortner = new UrlShortener(DEFAULT_SCOPE); - - String shortUrl = urlShortner.shorten(url); - System.out.println("url shortUrl: "+shortUrl); - - - - InputStream is = uriResolver.resolveAsInputStream(smpUri, folderItem.getName(), folderItem.getMimeType()); - - File file = new File(folderItem.getName()); - - FileOutputStream out = new FileOutputStream(file); - - - IOUtils.copy(is, out); - is.close(); - - out.close(); - - if(uriResolver!=null && uriResolver.isAvailable()){ - return uriResolver.resolveAsUriRequest(smpUri, folderItem.getName(), folderItem.getMimeType(), true); - } - - } - - - return ""; - - }catch (Exception e) { - System.out.println("Error getPublicLinkForFolderItemId url for"); - e.printStackTrace(); - return ""; - } - - } - - - -} +// URL url = new URL(query); +// +// return url.openStream(); +// } +// +// +// +// public String getUri() { +// return uri; +// } +// +// +// public String getParameter() { +// return parameter; +// } +// +// @Override +// public String toString() { +// StringBuilder builder = new StringBuilder(); +// builder.append("UriResolverReaderParameter [uri="); +// builder.append(uri); +// builder.append(", parameter="); +// builder.append(parameter); +// builder.append("]"); +// return builder.toString(); +// } +// +// +// public static void main(String[] args) throws Exception { +// +// +//// log.trace(new UriResolverReaderRR()); +//// +//// UriResolverReaderRR uriResolver = new UriResolverReaderRR(); +//// InputStream is = uriResolver.resolve("smp://Wikipedia_logo_silver.png?5ezvFfBOLqaqBlwCEtAvz4ch5BUu1ag3yftpCvV+gayz9bAtSsnO1/sX6pemTKbDe0qbchLexXeWgGcJlskYE8td9QSDXSZj5VSl9kdN9SN0/LRYaWUZuP4Q1J7lEiwkU4GKPsiD6PDRVcT4QAqTEy5hSIbr6o4Y"); +//// +//// File file = new File("test.png"); +//// +//// FileOutputStream out = new FileOutputStream(file); +//// +//// +//// IOUtils.copy(is, out); +//// is.close(); +//// +//// out.close(); +// +//// 066086bc-5db1-48fc-b365-2ee821db2fb7 +//// 370dc1cc-2e5e-4321-bc6f-ad860414db97 +// +//// id: f70f01f9-5a06-4123-b6ec-bd121c1af82f, name: testResponse.html, ### Public link: smp://Home/francesco.mangiacrapa/Workspace41e79e40-ec82-416b-ba83-29b54bb43426?5ezvFfBOLqb3YESyI/kesN4T+ZD0mtmc/4sZ0vGMrl0lgx7k85j8o2Q1vF0ezJi/xIGDhncO9jOkV1T8u6Db7GZ/4ePgMws8Jxu8ierJajHBd20bUotElPG3BVG0ODMHf1ztm6rKJIAeb9R/0FEIDQ== +//// id: 35a0298e-da69-464f-9170-3dc764da564d, name: wiki ws backup, ### Public link: smp://Home/francesco.mangiacrapa/Workspaceb7c9bf85-b0e0-47ac-87e5-eba34048f7ab?5ezvFfBOLqb3YESyI/kesN4T+ZD0mtmc/4sZ0vGMrl0lgx7k85j8o2Q1vF0ezJi/xIGDhncO9jOkV1T8u6Db7GZ/4ePgMws8Jxu8ierJajHBd20bUotElPG3BVG0ODMHf1ztm6rKJIAeb9R/0FEIDQ== +// +// +//// id: 370dc1cc-2e5e-4321-bc6f-ad860414db97, name: testupload.txt, ### Public link: smp://Home/francesco.mangiacrapa/Workspace284ee688-e6fb-4080-bbcb-cc7c8cc5c381?5ezvFfBOLqb3YESyI/kesN4T+ZD0mtmc/4sZ0vGMrl0lgx7k85j8o2Q1vF0ezJi/xIGDhncO9jOkV1T8u6Db7GZ/4ePgMws8Jxu8ierJajHBd20bUotElPG3BVG0ODMHf1ztm6rKJIAeb9R/0FEIDQ== +// +// String itemId = "0e875263-f6bc-4945-9435-bfb8774027ca"; +//// itemId = "f70f01f9-5a06-4123-b6ec-bd121c1af82f"; +// System.out.println("uri is: "+getPublicLinkForFolderItemId(itemId)); +// +// +// +//// +// +// +// +// } +// +// public static String getPublicLinkForFolderItemId(String itemId){ +// +// try{ +// +// ScopeProvider.instance.set(DEFAULT_SCOPE); +// +// Workspace workspace = HomeLibrary +// .getHomeManagerFactory() +// .getHomeManager() +// .getHome("leonardo.candela") +// .getWorkspace(); +// +// GWTWorkspaceBuilder builder = new GWTWorkspaceBuilder(); +// +// System.out.println("get item..."); +// WorkspaceItem wsItem = workspace.getItem(itemId); +// +// if(wsItem.getType().equals(WorkspaceItemType.FOLDER_ITEM)){ +// +// FolderItem folderItem = (FolderItem) wsItem; +// System.out.println("get public link..."); +// String smpUri = builder.getPublicLinkForFolderItem(folderItem); +// System.out.println("smpUri "+smpUri); +// +// System.out.println("get uriResolver..."); +// UriResolverReaderParameterForResolverIndex uriResolver = new UriResolverReaderParameterForResolverIndex(DEFAULT_SCOPE, RESOLVER_TYPE.SMP_ID); +// +//// String url = uriResolver.resolveAsUriRequest(smpUri, "testResponse!@#$$%^^&&.html", folderItem.getMimeType(), true); +// String url = uriResolver.resolveAsUriRequest(smpUri, folderItem.getName(), folderItem.getMimeType(), true); +// System.out.println("url econded: "+url); +//// +//// url = uriResolver.resolveAsUriRequest(smpUri, folderItem.getName(), folderItem.getMimeType(), false); +//// System.out.println("url doesn't econded: "+url); +// +// +//// uriResolver.getHashParemeters(smpUri, folderItem.getName(), folderItem.getMimeType()); +// +// +//// HttpCallerUtil callerUtil = new HttpCallerUtil(uriResolver.getBaseUri(), "", ""); +//// String query = uriResolver.getQuery(); +//// callerUtil.callPost("", query, "application/x-www-form-urlencoded"); +// +// +//// String smpUri = "smp://Home/test.user/Workspace/bla8200ceb0-c525-40e6-bad1-a63f83811d3d?5ezvFfBOLqb3YESyI/kesN4T+ZD0mtmc/4sZ0vGMrl0lgx7k85j8o2Q1vF0ezJi/xIGDhncO9jOkV1T8u6Db7GZ/4ePgMws8Jxu8ierJajHBd20bUotElPG3BVG0ODMHf1ztm6rKJIAeb9R/0FEIDQ=="; +// +// +// UrlShortener urlShortner = new UrlShortener(DEFAULT_SCOPE); +// +// String shortUrl = urlShortner.shorten(url); +// System.out.println("url shortUrl: "+shortUrl); +// +// +// +// InputStream is = uriResolver.resolveAsInputStream(smpUri, folderItem.getName(), folderItem.getMimeType()); +// +// File file = new File(folderItem.getName()); +// +// FileOutputStream out = new FileOutputStream(file); +// +// +// IOUtils.copy(is, out); +// is.close(); +// +// out.close(); +// +// if(uriResolver!=null && uriResolver.isAvailable()){ +// return uriResolver.resolveAsUriRequest(smpUri, folderItem.getName(), folderItem.getMimeType(), true); +// } +// +// } +// +// +// return ""; +// +// }catch (Exception e) { +// System.out.println("Error getPublicLinkForFolderItemId url for"); +// e.printStackTrace(); +// return ""; +// } +// +// } +//} +// +//*/