diff --git a/CHANGELOG.md b/CHANGELOG.md index c678c50..faf9dbc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm **Enhancements** [#19764] Porting ckan-metadata-publisher-widget to catalogue-util-library +[#20680] Ported to SHUB ## [v1.6.2] - 2021-02-08 diff --git a/pom.xml b/pom.xml index 92083ec..074fddc 100644 --- a/pom.xml +++ b/pom.xml @@ -121,24 +121,33 @@ [2.0.0, 3.0.0-SNAPSHOT) provided + org.gcube.common - home-library - [2.5.0,) - provided - - - asm-all - asm - - - - - org.gcube.common - home-library-jcr - [2.5.0,) - provided + storagehub-client-wrapper + [1.0.0, 2.0.0-SNAPSHOT) + compile + + + + + + + + + + + + + + + + + + + + org.gcube.dvos usermanagement-core @@ -146,20 +155,6 @@ provided - - - - - - - - - - - - - - org.gcube.datacatalogue catalogue-util-library diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/CKANPublisherServicesImpl.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/CKANPublisherServicesImpl.java index c607036..5b24a85 100644 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/CKANPublisherServicesImpl.java +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/CKANPublisherServicesImpl.java @@ -13,6 +13,9 @@ import java.util.concurrent.ConcurrentHashMap; import javax.servlet.http.HttpSession; +import org.gcube.common.portal.PortalContext; +import org.gcube.common.storagehubwrapper.server.StorageHubWrapper; +import org.gcube.common.storagehubwrapper.server.tohl.Workspace; import org.gcube.datacatalogue.utillibrary.server.DataCatalogue; import org.gcube.datacatalogue.utillibrary.server.DataCatalogueFactory; import org.gcube.datacatalogue.utillibrary.server.utils.CatalogueUtilMethods; @@ -68,10 +71,24 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C // map private ConcurrentHashMap mapOrganizationScope = new ConcurrentHashMap(); + /** - * Retrieve an instance of the library for the scope + * Dev mode set contexts. + */ + private void devModeSetContexts() { + if (!isWithinPortal()) { + logger.info("DETECTED DEV MODE"); + GenericUtils.getCurrentContext(getThreadLocalRequest(), true); + GenericUtils.getCurrentToken(getThreadLocalRequest(), true); + } + + } + + /** + * Retrieve an instance of the library for the scope. + * * @param scope if it is null it is evaluated from the session - * @return + * @return the catalogue */ public DataCatalogue getCatalogue(String scope){ @@ -88,11 +105,13 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C } /** - * Retrieve the list of organizations in which the user can publish (roles ADMIN/EDITOR) - * @param username + * Retrieve the list of organizations in which the user can publish (roles ADMIN/EDITOR). + * + * @param username the username + * @param scope the scope * @return the list of organizations - * @throws GroupRetrievalFault - * @throws UserManagementSystemException + * @throws UserManagementSystemException the user management system exception + * @throws GroupRetrievalFault the group retrieval fault */ private List getUserOrganizationsListAdmin(String username, String scope) throws UserManagementSystemException, GroupRetrievalFault { @@ -118,7 +137,8 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C } /** - * Online or in development mode? + * Online or in development mode?. + * * @return true if you're running into the portal, false if in development */ private boolean isWithinPortal() { @@ -131,11 +151,25 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C return false; } } + + /** + * Gets the workspace from storage hub. + * + * @return the workspace from storage hub + * @throws Exception + * the exception + */ + protected Workspace getWorkspaceFromStorageHub() throws Exception { + GCubeUser user = PortalContext.getConfiguration().getCurrentUser(this.getThreadLocalRequest()); + StorageHubWrapper storageHubWrapper = WorkspaceUtils.getStorageHubWrapper(this.getThreadLocalRequest(), null, user); + return storageHubWrapper.getWorkspace(); + } /** * Find a license id given the license text. - * @param chosenLicense - * @return + * + * @param chosenLicense the chosen license + * @return the string */ private String findLicenseIdByLicense(String chosenLicense) { @@ -145,6 +179,11 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C } + /** + * Gets the licenses. + * + * @return the licenses + */ @Override public List getLicenses() { @@ -178,7 +217,15 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C return licensesBean; } + + /** + * Gets the dataset bean. + * + * @param folderId the folder id + * @return the dataset bean + * @throws Exception the exception + */ @Override public DatasetBean getDatasetBean(String folderId) throws Exception{ @@ -193,7 +240,6 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C String scope = GenericUtils.getScopeFromClientUrl(getThreadLocalRequest()); logger.debug("Scope recovered from session is " + scope); - logger.debug("Request dataset metadata bean for folder with id " + folderId + " whose owner is " + userName); @@ -217,7 +263,8 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C // if the request comes from the workspace if(folderId != null && !folderId.isEmpty()){ - WorkspaceUtils.handleWorkspaceResources(folderId, userName, bean); + Workspace workspace = getWorkspaceFromStorageHub(); + WorkspaceUtils.handleWorkspaceResources(folderId, userName, bean, workspace); } }catch(Exception e){ @@ -251,7 +298,8 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C bean.setOwnerIdentifier(userName); if(folderId != null && !folderId.isEmpty()){ - WorkspaceUtils.handleWorkspaceResources(folderId, userName, bean); + Workspace workspace = getWorkspaceFromStorageHub(); + WorkspaceUtils.handleWorkspaceResources(folderId, userName, bean, workspace); } }catch(Exception e){ logger.error("Error while building bean into dev mode", e); @@ -264,9 +312,10 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C } /** - * Discover from the IS the vocabulary of tags for this scope, if present + * Discover from the IS the vocabulary of tags for this scope, if present. + * + * @param context the context * @return a list of tags vocabulary - * @throws Exception */ private List discoverTagsVocabulary(String context){ @@ -285,24 +334,30 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C return vocabulary; } + /** + * Gets the tags for organization. + * + * @param orgName the org name + * @return the tags for organization + * @throws Exception the exception + */ @Override public List getTagsForOrganization(String orgName) throws Exception{ return discoverTagsVocabulary(getScopeFromOrgName(orgName)); } + /** + * Creates the C kan dataset. + * + * @param toCreate the to create + * @return the dataset bean + * @throws Exception the exception + */ @Override public DatasetBean createCKanDataset(DatasetBean toCreate) throws Exception{ try{ - - - if (!isWithinPortal()) { - logger.info("DETECTED DEV MODE"); - GenericUtils.getCurrentContext(getThreadLocalRequest(), true); - GenericUtils.getCurrentToken(getThreadLocalRequest(), true); - } - - + devModeSetContexts(); logger.info("Request for creating a dataset with these information " + toCreate); String userName = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername(); String title = toCreate.getTitle(); @@ -329,8 +384,14 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C ResourceElementBean resourcesToAdd = toCreate.getResourceRoot(); // we need to copy such resource in the .catalogue area of the user's ws +// if(resourcesToAdd != null){ +// resources = WorkspaceUtils.copyResourcesToUserCatalogueArea(toCreate.getId(), userName, toCreate); +// } + + //converting to resources to be added if(resourcesToAdd != null){ - resources = WorkspaceUtils.copyResourcesToUserCatalogueArea(toCreate.getId(), userName, toCreate); + Workspace workspace = getWorkspaceFromStorageHub(); + resources = WorkspaceUtils.toResources(toCreate, workspace, userName); } logger.debug("The user wants to publish in organization with name " + organizationNameOrId); @@ -434,75 +495,84 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C return null; } - + + /** + * Adds the resource to dataset. + * + * @param resource the resource + * @param datasetId the dataset id + * @return the resource element bean + * @throws Exception the exception + */ @Override public ResourceElementBean addResourceToDataset(ResourceElementBean resource, String datasetId) throws Exception{ + logger.info("called addResourceToDataset"); + devModeSetContexts(); String username = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername(); - logger.debug("Incoming request for creating new resource for dataset with id " + datasetId + " and organization name of the dataset is " + resource.getOrganizationNameDatasetParent()); logger.debug("Owner is " + username + " and resource is " + resource); - if(!isWithinPortal()){ + ResourceBean resourceBean = new ResourceBean( + resource.getUrl(), + resource.getName(), + resource.getDescription(), + null, + username, + datasetId, + null); - logger.warn("Running outside the portal"); + // get the scope in which we should discover the ckan instance given the organization name in which the dataset was created + String scope = getScopeFromOrgName(resource.getOrganizationNameDatasetParent()); + DataCatalogue catalogue = getCatalogue(scope); + String resourceId = catalogue.addResourceToDataset(resourceBean); + + if(resourceId != null){ + logger.info("Resource " + resource.getName() + " is now available"); + // set its id and turn it to the client + resource.setOriginalIdInWorkspace(resourceId); return resource; + } - }else{ - - ResourceBean resourceBean = new ResourceBean( - resource.getUrl(), - resource.getName(), - resource.getDescription(), - null, - username, - datasetId, - null); + logger.debug("No resource created"); + return null; + } + /** + * Delete resource from dataset. + * + * @param resource the resource + * @return true, if successful + * @throws Exception the exception + */ + @Override + public boolean deleteResourceFromDataset(ResourceElementBean resource) throws Exception{ + logger.debug("Request for deleting resource " + resource); + boolean deleted = false; + devModeSetContexts(); + try{ // get the scope in which we should discover the ckan instance given the organization name in which the dataset was created String scope = getScopeFromOrgName(resource.getOrganizationNameDatasetParent()); DataCatalogue catalogue = getCatalogue(scope); - String resourceId = catalogue.addResourceToDataset(resourceBean); - - if(resourceId != null){ - logger.debug("Resource " + resource.getName() + " is now available"); - // set its id and turn it to the client - resource.setOriginalIdInWorkspace(resourceId); - return resource; - } - - logger.debug("No resource created"); - return null; - } - } - - @Override - public boolean deleteResourceFromDataset(ResourceElementBean resource) throws Exception{ - - logger.debug("Request for deleting resource " + resource); - boolean deleted = false; - - if(!isWithinPortal()){ - logger.warn("Running outside the portal"); - return deleted; - }else{ - - try{ - // get the scope in which we should discover the ckan instance given the organization name in which the dataset was created - String scope = getScopeFromOrgName(resource.getOrganizationNameDatasetParent()); - DataCatalogue catalogue = getCatalogue(scope); - deleted = catalogue.deleteResourceFromDataset(resource.getOriginalIdInWorkspace()); - if(deleted){ - logger.info("Resource described by " + resource + " deleted"); - }else - logger.error("Resource described by " + resource + " NOT deleted"); - }catch(Exception e){ - logger.error("Error while trying to delete resource described by " + resource, e); - throw new Exception("Error while trying to delete resource." + e.getMessage()); - } - return deleted; + deleted = catalogue.deleteResourceFromDataset(resource.getOriginalIdInWorkspace()); + if(deleted){ + logger.info("Resource described by " + resource + " deleted"); + }else + logger.error("Resource described by " + resource + " NOT deleted"); + }catch(Exception e){ + logger.error("Error while trying to delete resource described by " + resource, e); + throw new Exception("Error while trying to delete resource." + e.getMessage()); } + return deleted; + } + /** + * Gets the profiles. + * + * @param orgName the org name + * @return the profiles + * @throws Exception the exception + */ @Override public List getProfiles(String orgName) throws Exception{ @@ -520,6 +590,14 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C return toReturn; } + /** + * Dataset id already exists. + * + * @param title the title + * @param orgName the org name + * @return true, if successful + * @throws Exception the exception + */ @Override public boolean datasetIdAlreadyExists(String title, String orgName) throws Exception{ if(title == null || title.isEmpty()) @@ -537,7 +615,10 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C /** * The method tries to retrieve the scope related to the organization using the map first, - * if no match is found, it retrieves such information by using liferay + * if no match is found, it retrieves such information by using liferay. + * + * @param orgName the org name + * @return the scope from org name */ private String getScopeFromOrgName(String orgName){ @@ -568,6 +649,12 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C return toReturn; } + /** + * Gets the user groups. + * + * @param orgName the org name + * @return the user groups + */ @Override public List getUserGroups(String orgName) { @@ -621,6 +708,13 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C } + /** + * Checks if is publisher user. + * + * @param isWorkspaceRequest the is workspace request + * @return true, if is publisher user + * @throws Exception the exception + */ @Override public boolean isPublisherUser(boolean isWorkspaceRequest) throws Exception{ @@ -689,6 +783,13 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C } } + /** + * Checks if is geo JSON valid. + * + * @param geoJson the geo json + * @return true, if is geo JSON valid + * @throws Exception the exception + */ @Override public boolean isGeoJSONValid(String geoJson) throws Exception { try{ diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/WorkspaceUtils.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/WorkspaceUtils.java index c9c4760..84fec73 100644 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/WorkspaceUtils.java +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/WorkspaceUtils.java @@ -1,5 +1,6 @@ package org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils; +import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -8,24 +9,33 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; -import org.gcube.common.homelibary.model.items.type.FolderItemType; -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.catalogue.WorkspaceCatalogue; -import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; -import org.gcube.common.homelibrary.home.workspace.folder.items.ExternalUrl; -import org.gcube.common.homelibrary.home.workspace.folder.items.GCubeItem; -import org.gcube.datacatalogue.utillibrary.server.utils.CatalogueUtilMethods; +import javax.servlet.http.HttpServletRequest; + +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.impl.URLFile; +import org.gcube.common.storagehubwrapper.shared.tohl.items.FileItem; +import org.gcube.common.storagehubwrapper.shared.tohl.items.GCubeItem; +import org.gcube.common.storagehubwrapper.shared.tohl.items.PropertyMap; import org.gcube.datacatalogue.utillibrary.shared.ResourceBean; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetBean; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceElementBean; +import org.gcube.vomanagement.usermanagement.model.GCubeUser; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; +import com.liferay.portal.service.UserLocalServiceUtil; + +/** + * The Class WorkspaceUtils. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * + * Feb 18, 2021 + */ public class WorkspaceUtils { //private static final org.slf4j.Logger logger = LoggerFactory.getLogger(WorkspaceUtils.class); @@ -33,24 +43,75 @@ public class WorkspaceUtils { private static final String RESOURCES_NAME_SEPARATOR = "_"; private static final String STRIP_NOT_ALPHANUMERIC = "[^A-Za-z0-9.-_]"; + /** - * This method receives a folder id within the user's workspace and set the list of resources in the dataset bean to be returned - * @param folderId - * @param owner - * @param bean - * @param userName + * Checks if is within portal. + * + * @return true if you're running into the portal, false if in development + */ + public static boolean isWithinPortal() { + try { + UserLocalServiceUtil.getService(); + return true; + } catch (Exception ex) { + logger.trace("Development Mode ON"); + return false; + } + } + + /** + * Gets the storage hub wrapper. + * + * @param request + * the request + * @param scopeGroupId + * the scope group id. If scopeGroupId is null the scope is read + * by using the request else by using the scopeGroupId + * @param user + * the user + * @return the storage hub wrapper * @throws Exception + * the exception + */ + public static StorageHubWrapper getStorageHubWrapper(final HttpServletRequest request, String scopeGroupId, + GCubeUser user) throws Exception { + + if (user == null || user.getUsername().isEmpty()) + throw new Exception("Session expired"); + + try { + String scope; + PortalContext pContext = PortalContext.getConfiguration(); + if (isWithinPortal() && scopeGroupId != null) { + scope = pContext.getCurrentScope(scopeGroupId); + logger.debug(scope + " has retrieved by using the scopeGroupId=" + scopeGroupId); + } else + scope = pContext.getCurrentScope(request); + + logger.debug("Getting " + StorageHubWrapper.class.getSimpleName() + " for user: " + user.getUsername() + + " by using the scope: " + scope); + String token = pContext.getCurrentUserToken(scope, user.getUsername()); + return new StorageHubWrapper(scope, token, false, false, true); + } catch (Exception e) { + logger.error("Error during getting storageHub wrapper", e); + throw new Exception("Error on gettig the StorageHub wrapper for userId: " + user); + } + } + + /** + * This method receives a folder id within the user's workspace and set the list of resources in the dataset bean to be returned. + * + * @param folderId the folder id + * @param userName the user name + * @param bean the bean + * @param workspace the workspace + * @throws Exception the exception */ public static void handleWorkspaceResources(String folderId, String userName, - DatasetBean bean) throws Exception { + DatasetBean bean, Workspace workspace) throws Exception { - // get workspace - Workspace ws = HomeLibrary - .getHomeManagerFactory() - .getHomeManager() - .getHome().getWorkspace(); - WorkspaceItem originalFolderOrFile = ws.getItem(folderId); + WorkspaceItem originalFolderOrFile = workspace.getItem(folderId); logger.debug("Item retrieved is " + originalFolderOrFile); @@ -89,7 +150,7 @@ public class WorkspaceUtils { } // set them into the bean - bean.setResourceRoot(WorkspaceUtils.getTreeFromFolder(folderId, ws)); + bean.setResourceRoot(WorkspaceUtils.getTreeFromFolder(folderId, workspace)); } } @@ -104,35 +165,77 @@ public class WorkspaceUtils { 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)); + Map properties = null; + if(gItem.getPropertyMap()!=null){ + Map map = toSimpleMap(gItem.getPropertyMap()); + if(map!=null) { + 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) { + } catch (Exception e) { logger.error("Error in server getItemProperties: ", e); } } return null; } + + /** + * To simple map. + * + * @param propertyMap the property map + * @return the map + */ + public static 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; + } + } + /** - * Returns a tree object - * @param workspaceFolderId - * @param ws + * Returns a tree object. + * + * @param workspaceFolderId the workspace folder id + * @param workspace the workspace * @return ResourceElementBean a tree object - * @throws Exception + * @throws Exception the exception */ - public static ResourceElementBean getTreeFromFolder(String workspaceFolderId, Workspace ws) throws Exception{ + public static ResourceElementBean getTreeFromFolder(String workspaceFolderId, Workspace workspace) throws Exception{ ResourceElementBean rootElem = new ResourceElementBean(); - String pathSeparator = ws.getPathSeparator(); - WorkspaceItem initialItem = ws.getItem(workspaceFolderId); + String pathSeparator = "/"; + + //String pathSeparator = ws.getPathSeparator(); + + + WorkspaceItem initialItem = workspace.getItem(workspaceFolderId); String fullPathBase = initialItem.getPath(); - fullPathBase = fullPathBase.endsWith(ws.getPathSeparator()) ? fullPathBase : fullPathBase + ws.getPathSeparator(); + fullPathBase = fullPathBase.endsWith(pathSeparator) ? fullPathBase : fullPathBase + pathSeparator; rootElem.setFolder(initialItem.isFolder()); rootElem.setFullPath(initialItem.getPath().replace(fullPathBase, "")); rootElem.setName(initialItem.getName()); @@ -142,20 +245,27 @@ public class WorkspaceUtils { // recursive visiting if(initialItem.isFolder()) - visit(rootElem, initialItem, fullPathBase, pathSeparator); + visit(rootElem, initialItem, workspace, fullPathBase, pathSeparator); logger.debug("Tree that is going to be returned is " + rootElem); return rootElem; } /** - * Recursive visit of a workspace item - * @param rootElem - * @param initialItemWS - * @throws InternalErrorException + * Recursive visit of a workspace item. + * + * @param parent the parent + * @param initialItemWS the initial item WS + * @param workspace the ws + * @param fullPathBase the full path base + * @param pathSeparator the path separator + * @throws Exception the exception */ - private static void visit(ResourceElementBean parent, WorkspaceItem initialItemWS, String fullPathBase, String pathSeparator) throws InternalErrorException { - List children = initialItemWS.getChildren(); + private static void visit(ResourceElementBean parent, WorkspaceItem initialItemWS, Workspace workspace, String fullPathBase, String pathSeparator) throws Exception { + //List children = initialItemWS.getChildren(); + + List children = workspace.getChildren(initialItemWS.getId()); + ArrayList childrenInTree = new ArrayList(children.size()); for (WorkspaceItem item : children) { // logger.debug("Path BEFORE REPLACE is " + item.getPath()); @@ -173,16 +283,17 @@ public class WorkspaceUtils { childrenInTree.add(elem); logger.trace("Elem is " + elem); if(item.isFolder()) - visit(elem, item, fullPathBase, pathSeparator); + visit(elem, item, workspace, fullPathBase, pathSeparator); } // add these list as child of the rootElem parent.setChildren(childrenInTree); } /** - * Replaces the "/" char with a custom one and return an editable name for the user - * @param rootElem - * @param pathSeparatorInWs + * Replaces the "/" char with a custom one and return an editable name for the user. + * + * @param rootElem the root elem + * @param pathSeparatorInWs the path separator in ws */ private static void extractEditableNameFromPath(ResourceElementBean rootElem, String pathSeparatorInWs) { @@ -198,47 +309,24 @@ public class WorkspaceUtils { fullPath = fullPath.replaceAll(pathSeparatorInWs, RESOURCES_NAME_SEPARATOR) + elemName; rootElem.setEditableName(fullPath); } - + + /** * Copy into the .catalogue area folder the checked resources. * There is no difference among a single-file-publish and a folder-publish. - * @param folderId - * @param userName - * @param bean - * @return + * + * @param bean the bean + * @param workspace the workspace + * @param username the username + * @return the list + * @throws Exception the exception */ - public static List copyResourcesToUserCatalogueArea(String folderOrFileId, String userName, DatasetBean bean) throws Exception{ + public static List toResources(DatasetBean bean, Workspace workspace, String username) throws Exception{ logger.debug("Request to copy onto catalogue area...."); List resources = new ArrayList(); - WorkspaceItem copiedFolder = null; - WorkspaceCatalogue userCatalogue = null; ResourceElementBean rootResource = bean.getResourceRoot(); - // into the .catalogue area of the user's workspace - Workspace ws = HomeLibrary - .getHomeManagerFactory() - .getHomeManager() - .getHome() - .getWorkspace(); - - // Retrieve the catalogue of the user - userCatalogue = ws.getCatalogue(); - - // get workspace item (it could be a file or a folder) - WorkspaceItem originalItem = ws.getItem(folderOrFileId); - - // copy the folder in the catalogue if it is a folder, or create a new folder - long referenceTime = System.currentTimeMillis(); - if(originalItem.isFolder()){ - copiedFolder = userCatalogue.addWorkspaceItem(folderOrFileId, userCatalogue.getId()); // add to .catalogue root area - copiedFolder.setDescription(bean.getDescription()); - ((WorkspaceFolder)copiedFolder).rename(CatalogueUtilMethods.fromProductTitleToName(bean.getTitle()) + "_" + referenceTime); - } - else{ - copiedFolder = userCatalogue.createFolder(CatalogueUtilMethods.fromProductTitleToName(bean.getTitle()) + "_" + referenceTime, bean.getDescription()); - } - // retrieve the children List resourcesToAdd = rootResource.getChildren(); @@ -250,35 +338,130 @@ public class WorkspaceUtils { logger.debug("Resource to add is " + resource); // ok it is a file, so copy it into the copiedFolder - WorkspaceItem copiedFile = userCatalogue.addWorkspaceItem(resource.getOriginalIdInWorkspace(), copiedFolder.getId()); + WorkspaceItem wsItem = workspace.getItem(resource.getOriginalIdInWorkspace()); + + String mimeType = null; + if(wsItem instanceof FileItem) { + mimeType = ((FileItem)wsItem).getMimeType(); + } - // name and description could have been edited - copiedFile.setDescription(resource.getDescription()); - - // check if it is an external url + // check if it is an URLFile String externalUrl = null; try{ - boolean isExternalUrl = ((FolderItem)copiedFile).getFolderItemType().equals(FolderItemType.EXTERNAL_URL); - externalUrl = isExternalUrl ? ((ExternalUrl)copiedFile).getUrl() : null; + if(wsItem instanceof URLFile) { + URLFile urlFile = (URLFile) wsItem; + externalUrl = urlFile.getValue()!=null?urlFile.getValue().toString():null; + } + }catch(Exception e){ logger.warn("Unable to check if it is an external url file ", e); } + + String resourceURL = externalUrl; + + //it is not a URLFile + if(resourceURL==null) { + //getting public link of file + URL publicLink = workspace.getPublicLinkForFile(resource.getOriginalIdInWorkspace()); + if(publicLink!=null) + resourceURL = publicLink.toString(); + } - resources.add(new ResourceBean( - externalUrl != null ? externalUrl : copiedFile.getPublicLink(true), + resources.add(new ResourceBean(resourceURL, resource.getEditableName(), - copiedFile.getDescription(), - copiedFile.getId(), - userName, + resource.getDescription(), + wsItem.getId(), + username, null, // dataset id, to be set - ((FolderItem)copiedFile).getMimeType())); - - // postpone rename operation - copiedFile.rename(resource.getEditableName()); + mimeType)); } } return resources; } + +// //MOVED TO GCAT +// /** +// * Copy into the .catalogue area folder the checked resources. +// * There is no difference among a single-file-publish and a folder-publish. +// * @param folderId +// * @param userName +// * @param bean +// * @return +// */ +// public static List copyResourcesToUserCatalogueArea(String folderOrFileId, String userName, DatasetBean bean) throws Exception{ +// +// logger.debug("Request to copy onto catalogue area...."); +// List resources = new ArrayList(); +// WorkspaceItem copiedFolder = null; +// WorkspaceCatalogue userCatalogue = null; +// ResourceElementBean rootResource = bean.getResourceRoot(); +// +// // into the .catalogue area of the user's workspace +// Workspace ws = HomeLibrary +// .getHomeManagerFactory() +// .getHomeManager() +// .getHome() +// .getWorkspace(); +// +// // Retrieve the catalogue of the user +// userCatalogue = ws.getCatalogue(); +// +// // get workspace item (it could be a file or a folder) +// WorkspaceItem originalItem = ws.getItem(folderOrFileId); +// +// // copy the folder in the catalogue if it is a folder, or create a new folder +// long referenceTime = System.currentTimeMillis(); +// if(originalItem.isFolder()){ +// copiedFolder = userCatalogue.addWorkspaceItem(folderOrFileId, userCatalogue.getId()); // add to .catalogue root area +// copiedFolder.setDescription(bean.getDescription()); +// ((WorkspaceFolder)copiedFolder).rename(CatalogueUtilMethods.fromProductTitleToName(bean.getTitle()) + "_" + referenceTime); +// } +// else{ +// copiedFolder = userCatalogue.createFolder(CatalogueUtilMethods.fromProductTitleToName(bean.getTitle()) + "_" + referenceTime, bean.getDescription()); +// } +// +// // retrieve the children +// List resourcesToAdd = rootResource.getChildren(); +// +// // copy only the selected ones +// for(ResourceElementBean resource : resourcesToAdd){ +// +// if (resource.isToBeAdded()) { +// +// logger.debug("Resource to add is " + resource); +// +// // ok it is a file, so copy it into the copiedFolder +// WorkspaceItem copiedFile = userCatalogue.addWorkspaceItem(resource.getOriginalIdInWorkspace(), copiedFolder.getId()); +// +// // name and description could have been edited +// copiedFile.setDescription(resource.getDescription()); +// +// // check if it is an external url +// String externalUrl = null; +// try{ +// boolean isExternalUrl = ((FolderItem)copiedFile).getFolderItemType().equals(FolderItemType.EXTERNAL_URL); +// externalUrl = isExternalUrl ? ((ExternalUrl)copiedFile).getUrl() : null; +// }catch(Exception e){ +// logger.warn("Unable to check if it is an external url file ", e); +// } +// +// resources.add(new ResourceBean( +// externalUrl != null ? externalUrl : copiedFile.getPublicLink(true), +// resource.getEditableName(), +// copiedFile.getDescription(), +// copiedFile.getId(), +// userName, +// null, // dataset id, to be set +// ((FolderItem)copiedFile).getMimeType())); +// +// // postpone rename operation +// copiedFile.rename(resource.getEditableName()); +// } +// +// } +// return resources; +// } + } \ No newline at end of file