diff --git a/config/org/alfresco/repo/virtual/node/vanilla.js b/config/org/alfresco/repo/virtual/node/vanilla.js new file mode 100644 index 0000000000..ffb23ac60f --- /dev/null +++ b/config/org/alfresco/repo/virtual/node/vanilla.js @@ -0,0 +1,39 @@ +function applyTemplate(context, vanillaJSONx) +{ + var vanillaJSON=""+context.getParameter("vanillaJSON"); + + var ctxPlaceholders = context.placeholders; + var processedVanilla = vanillaJSON; + + for ( var ph in ctxPlaceholders) + { + processedVanilla = processedVanilla.replace(new RegExp("%" + ph + "%", "g"), ctxPlaceholders[ph]); + } + + var propertiesRegExp = new RegExp("<.+?>", "g"); + + if (context.actualNode!=null && context.actualNode.properties!=null) + { + var actualProperties = context.actualNode.properties; + + var propertiesPh = processedVanilla.match(propertiesRegExp); + + var processedPh = []; + + if (propertiesPh != null) + { + propertiesPh.forEach(function(ph) + { + if (processedPh.indexOf(ph) === -1) + { + var propertyValue = actualProperties[ph.substring(1, ph.length - 1)]; + processedVanilla = processedVanilla.replace(new RegExp(ph, "g"), propertyValue); + processedPh.push(ph); + } + }); + } + } + return JSON.parse(processedVanilla); +} + +applyTemplate(context, vanillaJSON); \ No newline at end of file diff --git a/source/java/org/alfresco/repo/rating/RatingServiceImpl.java b/source/java/org/alfresco/repo/rating/RatingServiceImpl.java index 80576f42ae..cba0f1ab3a 100644 --- a/source/java/org/alfresco/repo/rating/RatingServiceImpl.java +++ b/source/java/org/alfresco/repo/rating/RatingServiceImpl.java @@ -28,6 +28,8 @@ import java.util.Map; import org.alfresco.model.ContentModel; import org.alfresco.repo.policy.BehaviourFilter; +import org.alfresco.repo.rating.traitextender.RatingServiceExtension; +import org.alfresco.repo.rating.traitextender.RatingServiceTrait; import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.service.cmr.dictionary.AspectDefinition; import org.alfresco.service.cmr.dictionary.DictionaryService; @@ -40,6 +42,11 @@ import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.namespace.QName; import org.alfresco.service.namespace.QNamePattern; +import org.alfresco.traitextender.Extend; +import org.alfresco.traitextender.ExtendedTrait; +import org.alfresco.traitextender.Extensible; +import org.alfresco.traitextender.AJProxyTrait; +import org.alfresco.traitextender.Trait; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -47,7 +54,7 @@ import org.apache.commons.logging.LogFactory; * @author Neil McErlean * @since 3.4 */ -public class RatingServiceImpl implements RatingService +public class RatingServiceImpl implements RatingService, Extensible { private static final Log log = LogFactory.getLog(RatingServiceImpl.class); private RatingSchemeRegistry schemeRegistry; @@ -57,6 +64,13 @@ public class RatingServiceImpl implements RatingService private NodeService nodeService; private BehaviourFilter behaviourFilter; + public final ExtendedTrait ratingServiceTrait; + + public RatingServiceImpl() + { + ratingServiceTrait=new ExtendedTrait(AJProxyTrait.create(this, RatingServiceTrait.class)); + } + private RatingNamingConventionsUtil ratingNamingConventions; public void setRatingSchemeRegistry(RatingSchemeRegistry schemeRegistry) @@ -84,12 +98,14 @@ public class RatingServiceImpl implements RatingService this.ratingNamingConventions = namingConventions; } + @Extend(traitAPI=RatingServiceTrait.class,extensionAPI=RatingServiceExtension.class) public Map getRatingSchemes() { // This is already an unmodifiable Map. return schemeRegistry.getRatingSchemes(); } + @Extend(traitAPI=RatingServiceTrait.class,extensionAPI=RatingServiceExtension.class) public RatingScheme getRatingScheme(String ratingSchemeName) { return schemeRegistry.getRatingSchemes().get(ratingSchemeName); @@ -99,6 +115,7 @@ public class RatingServiceImpl implements RatingService * (non-Javadoc) * @see org.alfresco.service.cmr.rating.RatingService#applyRating(org.alfresco.service.cmr.repository.NodeRef, float, java.lang.String) */ + @Extend(traitAPI=RatingServiceTrait.class,extensionAPI=RatingServiceExtension.class) public void applyRating(final NodeRef targetNode, final float rating, final String ratingSchemeName) throws RatingServiceException { @@ -273,6 +290,7 @@ public class RatingServiceImpl implements RatingService * (non-Javadoc) * @see org.alfresco.service.cmr.rating.RatingService#getRatingByCurrentUser(org.alfresco.service.cmr.repository.NodeRef, java.lang.String) */ + @Extend(traitAPI=RatingServiceTrait.class,extensionAPI=RatingServiceExtension.class) public Rating getRatingByCurrentUser(NodeRef targetNode, String ratingSchemeName) { String currentUser = AuthenticationUtil.getFullyAuthenticatedUser(); @@ -283,6 +301,7 @@ public class RatingServiceImpl implements RatingService * (non-Javadoc) * @see org.alfresco.service.cmr.rating.RatingService#getRatingsByCurrentUser(org.alfresco.service.cmr.repository.NodeRef) */ + @Extend(traitAPI=RatingServiceTrait.class,extensionAPI=RatingServiceExtension.class) public List getRatingsByCurrentUser(NodeRef targetNode) { final String fullyAuthenticatedUser = AuthenticationUtil.getFullyAuthenticatedUser(); @@ -347,6 +366,7 @@ public class RatingServiceImpl implements RatingService * (non-Javadoc) * @see org.alfresco.service.cmr.rating.RatingService#removeRatingByCurrentUser(org.alfresco.service.cmr.repository.NodeRef, java.lang.String) */ + @Extend(traitAPI=RatingServiceTrait.class,extensionAPI=RatingServiceExtension.class) public Rating removeRatingByCurrentUser(NodeRef targetNode, String ratingScheme) { @@ -386,6 +406,7 @@ public class RatingServiceImpl implements RatingService * (non-Javadoc) * @see org.alfresco.service.cmr.rating.RatingService#getTotalRating(org.alfresco.service.cmr.repository.NodeRef, java.lang.String) */ + @Extend(traitAPI=RatingServiceTrait.class,extensionAPI=RatingServiceExtension.class) public float getTotalRating(NodeRef targetNode, String ratingSchemeName) { Serializable result = this.getRatingRollup(targetNode, ratingSchemeName, RatingTotalRollupAlgorithm.ROLLUP_NAME); @@ -397,6 +418,7 @@ public class RatingServiceImpl implements RatingService return (Float)result; } + @Extend(traitAPI=RatingServiceTrait.class,extensionAPI=RatingServiceExtension.class) public float getAverageRating(NodeRef targetNode, String ratingSchemeName) { float totalRating = getTotalRating(targetNode, ratingSchemeName); @@ -405,6 +427,7 @@ public class RatingServiceImpl implements RatingService return ratingCount == 0 ? -1 : Float.valueOf(totalRating / (float)ratingCount); } + @Extend(traitAPI=RatingServiceTrait.class,extensionAPI=RatingServiceExtension.class) public int getRatingsCount(NodeRef targetNode, String ratingSchemeName) { Serializable result = this.getRatingRollup(targetNode, ratingSchemeName, RatingCountRollupAlgorithm.ROLLUP_NAME); @@ -420,6 +443,7 @@ public class RatingServiceImpl implements RatingService * (non-Javadoc) * @see org.alfresco.service.cmr.rating.RatingService#getRatingRollup(org.alfresco.service.cmr.repository.NodeRef, java.lang.String, java.lang.String) */ + @Extend(traitAPI=RatingServiceTrait.class,extensionAPI=RatingServiceExtension.class) public Serializable getRatingRollup(NodeRef targetNode, String ratingSchemeName, String ratingRollupName) { RatingScheme scheme = schemeRegistry.getRatingSchemes().get(ratingSchemeName); @@ -481,4 +505,10 @@ public class RatingServiceImpl implements RatingService Rating result = new Rating(scheme, score, appliedBy, ratedAt); return result; } + + @Override + public ExtendedTrait getTrait(Class traitAPI) + { + return (ExtendedTrait) ratingServiceTrait; + } } diff --git a/source/java/org/alfresco/repo/rating/traitextender/RatingServiceExtension.java b/source/java/org/alfresco/repo/rating/traitextender/RatingServiceExtension.java new file mode 100644 index 0000000000..ca4328aaff --- /dev/null +++ b/source/java/org/alfresco/repo/rating/traitextender/RatingServiceExtension.java @@ -0,0 +1,26 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ +package org.alfresco.repo.rating.traitextender; + +import org.alfresco.service.cmr.rating.RatingService; + +public interface RatingServiceExtension extends RatingService +{ + +} diff --git a/source/java/org/alfresco/repo/rating/traitextender/RatingServiceTrait.java b/source/java/org/alfresco/repo/rating/traitextender/RatingServiceTrait.java new file mode 100644 index 0000000000..30d5a78a60 --- /dev/null +++ b/source/java/org/alfresco/repo/rating/traitextender/RatingServiceTrait.java @@ -0,0 +1,27 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ +package org.alfresco.repo.rating.traitextender; + +import org.alfresco.service.cmr.rating.RatingService; +import org.alfresco.traitextender.Trait; + +public interface RatingServiceTrait extends Trait, RatingService +{ + +} diff --git a/source/java/org/alfresco/repo/security/permissions/impl/PermissionServiceImpl.java b/source/java/org/alfresco/repo/security/permissions/impl/PermissionServiceImpl.java index 934d0a20e4..8a7a8d6749 100644 --- a/source/java/org/alfresco/repo/security/permissions/impl/PermissionServiceImpl.java +++ b/source/java/org/alfresco/repo/security/permissions/impl/PermissionServiceImpl.java @@ -33,6 +33,7 @@ import net.sf.acegisecurity.providers.dao.User; import org.alfresco.model.ContentModel; import org.alfresco.repo.cache.SimpleCache; import org.alfresco.repo.domain.permissions.AclDAO; +import org.alfresco.repo.node.db.traitextender.NodeServiceTrait; import org.alfresco.repo.policy.JavaBehaviour; import org.alfresco.repo.policy.PolicyComponent; import org.alfresco.repo.security.authentication.AuthenticationUtil; @@ -47,6 +48,8 @@ import org.alfresco.repo.security.permissions.NodePermissionEntry; import org.alfresco.repo.security.permissions.PermissionEntry; import org.alfresco.repo.security.permissions.PermissionReference; import org.alfresco.repo.security.permissions.PermissionServiceSPI; +import org.alfresco.repo.security.permissions.impl.traitextender.PermissionServiceExtension; +import org.alfresco.repo.security.permissions.impl.traitextender.PermissionServiceTrait; import org.alfresco.repo.tenant.TenantService; import org.alfresco.repo.transaction.AlfrescoTransactionSupport; import org.alfresco.repo.version.Version2Model; @@ -65,6 +68,12 @@ import org.alfresco.service.cmr.security.PermissionContext; import org.alfresco.service.cmr.security.PermissionService; import org.alfresco.service.namespace.NamespaceService; import org.alfresco.service.namespace.QName; +import org.alfresco.traitextender.AJExtender; +import org.alfresco.traitextender.Extend; +import org.alfresco.traitextender.ExtendedTrait; +import org.alfresco.traitextender.Extensible; +import org.alfresco.traitextender.AJProxyTrait; +import org.alfresco.traitextender.Trait; import org.alfresco.util.EqualsHelper; import org.alfresco.util.Pair; import org.alfresco.util.PropertyCheck; @@ -79,7 +88,7 @@ import org.springframework.extensions.surf.util.AbstractLifecycleBean; * * @author andyh */ -public class PermissionServiceImpl extends AbstractLifecycleBean implements PermissionServiceSPI +public class PermissionServiceImpl extends AbstractLifecycleBean implements PermissionServiceSPI,Extensible { static SimplePermissionReference OLD_ALL_PERMISSIONS_REFERENCE = new SimplePermissionReference( QName.createQName("", PermissionService.ALL_PERMISSIONS), @@ -141,6 +150,8 @@ public class PermissionServiceImpl extends AbstractLifecycleBean implements Perm protected PermissionReference allPermissionReference; protected boolean anyDenyDenies = false; + + private final ExtendedTrait permissionServiceTrait; /** * Standard spring construction. @@ -148,6 +159,7 @@ public class PermissionServiceImpl extends AbstractLifecycleBean implements Perm public PermissionServiceImpl() { super(); + permissionServiceTrait=new ExtendedTrait(AJProxyTrait.create(this, PermissionServiceTrait.class)); } // @@ -366,26 +378,36 @@ public class PermissionServiceImpl extends AbstractLifecycleBean implements Perm // Permissions Service // + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public String getOwnerAuthority() { return OWNER_AUTHORITY; } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public String getAllAuthorities() { return ALL_AUTHORITIES; } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public String getAllPermission() { return ALL_PERMISSIONS; } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public Set getPermissions(NodeRef nodeRef) { return getAllPermissionsImpl(nodeRef, true, true); } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public Set getAllSetPermissions(NodeRef nodeRef) { HashSet accessPermissions = new HashSet(); @@ -397,6 +419,8 @@ public class PermissionServiceImpl extends AbstractLifecycleBean implements Perm return accessPermissions; } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public Set getAllSetPermissions(StoreRef storeRef) { HashSet accessPermissions = new HashSet(); @@ -429,6 +453,8 @@ public class PermissionServiceImpl extends AbstractLifecycleBean implements Perm return accessPermissions; } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public Set getSettablePermissions(NodeRef nodeRef) { Set settable = getSettablePermissionReferences(nodeRef); @@ -440,6 +466,8 @@ public class PermissionServiceImpl extends AbstractLifecycleBean implements Perm return strings; } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public Set getSettablePermissions(QName type) { Set settable = getSettablePermissionReferences(type); @@ -451,16 +479,22 @@ public class PermissionServiceImpl extends AbstractLifecycleBean implements Perm return strings; } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public NodePermissionEntry getSetPermissions(NodeRef nodeRef) { return permissionsDaoComponent.getPermissions(tenantService.getName(nodeRef)); } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public NodePermissionEntry getSetPermissions(StoreRef storeRef) { return permissionsDaoComponent.getPermissions(storeRef); } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public AccessStatus hasPermission(NodeRef passedNodeRef, final PermissionReference permIn) { // If the node ref is null there is no sensible test to do - and there @@ -603,6 +637,8 @@ public class PermissionServiceImpl extends AbstractLifecycleBean implements Perm } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public AccessStatus hasPermission(Long aclID, PermissionContext context, String permission) { return hasPermission(aclID, context, getPermissionReference(permission)); @@ -873,18 +909,24 @@ public class PermissionServiceImpl extends AbstractLifecycleBean implements Perm return dynAuths; } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public NodePermissionEntry explainPermission(NodeRef nodeRef, PermissionReference perm) { // TODO Auto-generated method stub return null; } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public void clearPermission(StoreRef storeRef, String authority) { permissionsDaoComponent.deletePermissions(storeRef, authority); accessCache.clear(); } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public void deletePermission(StoreRef storeRef, String authority, String perm) { deletePermission(storeRef, authority, getPermissionReference(perm)); @@ -896,12 +938,16 @@ public class PermissionServiceImpl extends AbstractLifecycleBean implements Perm accessCache.clear(); } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public void deletePermissions(StoreRef storeRef) { permissionsDaoComponent.deletePermissions(storeRef); accessCache.clear(); } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public void setPermission(StoreRef storeRef, String authority, String perm, boolean allow) { setPermission(storeRef, authority, getPermissionReference(perm), allow); @@ -913,12 +959,16 @@ public class PermissionServiceImpl extends AbstractLifecycleBean implements Perm accessCache.clear(); } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public void deletePermissions(NodeRef nodeRef) { permissionsDaoComponent.deletePermissions(tenantService.getName(nodeRef)); accessCache.clear(); } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public void deletePermissions(NodePermissionEntry nodePermissionEntry) { permissionsDaoComponent.deletePermissions(tenantService.getName(nodePermissionEntry.getNodeRef())); @@ -928,6 +978,8 @@ public class PermissionServiceImpl extends AbstractLifecycleBean implements Perm /** * @see #deletePermission(NodeRef, String, PermissionReference) */ + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public void deletePermission(PermissionEntry permissionEntry) { NodeRef nodeRef = permissionEntry.getNodeRef(); @@ -942,6 +994,8 @@ public class PermissionServiceImpl extends AbstractLifecycleBean implements Perm accessCache.clear(); } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public void clearPermission(NodeRef nodeRef, String authority) { permissionsDaoComponent.deletePermissions(tenantService.getName(nodeRef), authority); @@ -954,6 +1008,8 @@ public class PermissionServiceImpl extends AbstractLifecycleBean implements Perm accessCache.clear(); } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public void setPermission(PermissionEntry permissionEntry) { // TODO - not MT-enabled nodeRef - currently only used by tests @@ -961,6 +1017,8 @@ public class PermissionServiceImpl extends AbstractLifecycleBean implements Perm accessCache.clear(); } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public void setPermission(NodePermissionEntry nodePermissionEntry) { // TODO - not MT-enabled nodeRef- currently only used by tests @@ -968,6 +1026,8 @@ public class PermissionServiceImpl extends AbstractLifecycleBean implements Perm accessCache.clear(); } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public void setInheritParentPermissions(NodeRef nodeRef, boolean inheritParentPermissions) { NodeRef actualRef = tenantService.getName(nodeRef); @@ -978,21 +1038,29 @@ public class PermissionServiceImpl extends AbstractLifecycleBean implements Perm /** * @see org.alfresco.service.cmr.security.PermissionService#getInheritParentPermissions(org.alfresco.service.cmr.repository.NodeRef) */ + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public boolean getInheritParentPermissions(NodeRef nodeRef) { return permissionsDaoComponent.getInheritParentPermissions(tenantService.getName(nodeRef)); } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public PermissionReference getPermissionReference(QName qname, String permissionName) { return modelDAO.getPermissionReference(qname, permissionName); } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public PermissionReference getAllPermissionReference() { return allPermissionReference; } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public String getPermission(PermissionReference permissionReference) { if (modelDAO.isUnique(permissionReference)) @@ -1005,36 +1073,50 @@ public class PermissionServiceImpl extends AbstractLifecycleBean implements Perm } } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public PermissionReference getPermissionReference(String permissionName) { return modelDAO.getPermissionReference(null, permissionName); } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public Set getSettablePermissionReferences(QName type) { return modelDAO.getExposedPermissions(type); } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public Set getSettablePermissionReferences(NodeRef nodeRef) { return modelDAO.getExposedPermissions(tenantService.getName(nodeRef)); } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public void deletePermission(NodeRef nodeRef, String authority, String perm) { deletePermission(nodeRef, authority, getPermissionReference(perm)); } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public AccessStatus hasPermission(NodeRef nodeRef, String perm) { return hasPermission(nodeRef, getPermissionReference(perm)); } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public void setPermission(NodeRef nodeRef, String authority, String perm, boolean allow) { setPermission(nodeRef, authority, getPermissionReference(perm), allow); } + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public void deletePermissions(String recipient) { permissionsDaoComponent.deletePermissions(recipient); @@ -1048,6 +1130,8 @@ public class PermissionServiceImpl extends AbstractLifecycleBean implements Perm * doesn't take into account node types/aspects for permissions * */ + @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public AccessStatus hasReadPermission(NodeRef nodeRef) { AccessStatus status = AccessStatus.DENIED; @@ -1167,6 +1251,7 @@ public class PermissionServiceImpl extends AbstractLifecycleBean implements Perm * {@inheritDoc} */ @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public Set getReaders(Long aclId) { AccessControlList acl = aclDaoComponent.getAccessControlList(aclId); @@ -1208,6 +1293,7 @@ public class PermissionServiceImpl extends AbstractLifecycleBean implements Perm * @return set of authorities denied permission on the ACL */ @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public Set getReadersDenied(Long aclId) { AccessControlList acl = aclDaoComponent.getAccessControlList(aclId); @@ -2713,6 +2799,7 @@ public class PermissionServiceImpl extends AbstractLifecycleBean implements Perm * {@inheritDoc} */ @Override + @Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class) public Set getAuthorisations() { // Use TX cache @@ -2733,4 +2820,10 @@ public class PermissionServiceImpl extends AbstractLifecycleBean implements Perm } return Collections.unmodifiableSet(auths); } + + @Override + public ExtendedTrait getTrait(Class traitAPI) + { + return (ExtendedTrait) permissionServiceTrait; + } } diff --git a/source/java/org/alfresco/repo/security/permissions/impl/traitextender/PermissionServiceExtension.java b/source/java/org/alfresco/repo/security/permissions/impl/traitextender/PermissionServiceExtension.java new file mode 100644 index 0000000000..a126527665 --- /dev/null +++ b/source/java/org/alfresco/repo/security/permissions/impl/traitextender/PermissionServiceExtension.java @@ -0,0 +1,9 @@ + +package org.alfresco.repo.security.permissions.impl.traitextender; + +import org.alfresco.repo.security.permissions.PermissionServiceSPI; + +public interface PermissionServiceExtension extends PermissionServiceSPI +{ + +} diff --git a/source/java/org/alfresco/repo/security/permissions/impl/traitextender/PermissionServiceTrait.java b/source/java/org/alfresco/repo/security/permissions/impl/traitextender/PermissionServiceTrait.java new file mode 100644 index 0000000000..a3289857aa --- /dev/null +++ b/source/java/org/alfresco/repo/security/permissions/impl/traitextender/PermissionServiceTrait.java @@ -0,0 +1,10 @@ + +package org.alfresco.repo.security.permissions.impl.traitextender; + +import org.alfresco.repo.security.permissions.PermissionServiceSPI; +import org.alfresco.traitextender.Trait; + +public interface PermissionServiceTrait extends Trait,PermissionServiceSPI +{ + +} diff --git a/source/java/org/alfresco/repo/version/Version2ServiceImpl.java b/source/java/org/alfresco/repo/version/Version2ServiceImpl.java index 0830925cce..46e1c707a2 100644 --- a/source/java/org/alfresco/repo/version/Version2ServiceImpl.java +++ b/source/java/org/alfresco/repo/version/Version2ServiceImpl.java @@ -40,6 +40,8 @@ import org.alfresco.repo.version.common.VersionHistoryImpl; import org.alfresco.repo.version.common.VersionImpl; import org.alfresco.repo.version.common.VersionUtil; import org.alfresco.repo.version.common.versionlabel.SerialVersionLabelPolicy; +import org.alfresco.repo.version.traitextender.VersionServiceExtension; +import org.alfresco.repo.version.traitextender.VersionServiceTrait; import org.alfresco.service.cmr.dictionary.AspectDefinition; import org.alfresco.service.cmr.dictionary.TypeDefinition; import org.alfresco.service.cmr.repository.AspectMissingException; @@ -56,6 +58,11 @@ import org.alfresco.service.cmr.version.VersionServiceException; import org.alfresco.service.namespace.NamespaceService; import org.alfresco.service.namespace.QName; import org.alfresco.service.namespace.RegexQNamePattern; +import org.alfresco.traitextender.AJProxyTrait; +import org.alfresco.traitextender.Extend; +import org.alfresco.traitextender.ExtendedTrait; +import org.alfresco.traitextender.Extensible; +import org.alfresco.traitextender.Trait; import org.alfresco.util.Pair; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -65,11 +72,18 @@ import org.springframework.extensions.surf.util.ParameterCheck; /** * Version2 Service - implements version2Store (a lighter implementation of the lightWeightVersionStore) */ -public class Version2ServiceImpl extends VersionServiceImpl implements VersionService, Version2Model +public class Version2ServiceImpl extends VersionServiceImpl implements VersionService, Version2Model,Extensible { private static Log logger = LogFactory.getLog(Version2ServiceImpl.class); private PermissionService permissionService; + + private ExtendedTrait versionServiceTrait; + + public Version2ServiceImpl() + { + versionServiceTrait=new ExtendedTrait(AJProxyTrait.create(this, VersionServiceTrait.class)); + } public void setPermissionService(PermissionService permissionService) { @@ -87,6 +101,7 @@ public class Version2ServiceImpl extends VersionServiceImpl implements VersionSe @Override + @Extend(extensionAPI=VersionServiceExtension.class,traitAPI=VersionServiceTrait.class) public StoreRef getVersionStoreReference() { if (logger.isDebugEnabled()) @@ -99,6 +114,7 @@ public class Version2ServiceImpl extends VersionServiceImpl implements VersionSe } @Override + @Extend(extensionAPI=VersionServiceExtension.class,traitAPI=VersionServiceTrait.class) public Version createVersion( NodeRef nodeRef, Map versionProperties) @@ -126,6 +142,7 @@ public class Version2ServiceImpl extends VersionServiceImpl implements VersionSe } @Override + @Extend(extensionAPI=VersionServiceExtension.class,traitAPI=VersionServiceTrait.class) public Collection createVersion( Collection nodeRefs, Map versionProperties) @@ -361,6 +378,7 @@ public class Version2ServiceImpl extends VersionServiceImpl implements VersionSe } @Override + @Extend(extensionAPI=VersionServiceExtension.class,traitAPI=VersionServiceTrait.class) public VersionHistory getVersionHistory(NodeRef nodeRef) { if (logger.isDebugEnabled()) @@ -381,6 +399,7 @@ public class Version2ServiceImpl extends VersionServiceImpl implements VersionSe } @Override + @Extend(extensionAPI=VersionServiceExtension.class,traitAPI=VersionServiceTrait.class) public Version getCurrentVersion(NodeRef nodeRef) { if (logger.isDebugEnabled()) @@ -940,6 +959,7 @@ public class Version2ServiceImpl extends VersionServiceImpl implements VersionSe } @Override + @Extend(extensionAPI=VersionServiceExtension.class,traitAPI=VersionServiceTrait.class) public void revert(NodeRef nodeRef) { if (logger.isDebugEnabled()) @@ -952,6 +972,7 @@ public class Version2ServiceImpl extends VersionServiceImpl implements VersionSe } @Override + @Extend(extensionAPI=VersionServiceExtension.class,traitAPI=VersionServiceTrait.class) public void revert(NodeRef nodeRef, boolean deep) { if (logger.isDebugEnabled()) @@ -964,6 +985,7 @@ public class Version2ServiceImpl extends VersionServiceImpl implements VersionSe } @Override + @Extend(extensionAPI=VersionServiceExtension.class,traitAPI=VersionServiceTrait.class) public void revert(NodeRef nodeRef, Version version) { if (logger.isDebugEnabled()) @@ -976,6 +998,7 @@ public class Version2ServiceImpl extends VersionServiceImpl implements VersionSe } @Override + @Extend(extensionAPI=VersionServiceExtension.class,traitAPI=VersionServiceTrait.class) public void revert(NodeRef nodeRef, Version version, boolean deep) { if (logger.isDebugEnabled()) @@ -1263,6 +1286,7 @@ public class Version2ServiceImpl extends VersionServiceImpl implements VersionSe } @Override + @Extend(extensionAPI=VersionServiceExtension.class,traitAPI=VersionServiceTrait.class) public NodeRef restore( NodeRef nodeRef, NodeRef parentNodeRef, @@ -1273,6 +1297,7 @@ public class Version2ServiceImpl extends VersionServiceImpl implements VersionSe } @Override + @Extend(extensionAPI=VersionServiceExtension.class,traitAPI=VersionServiceTrait.class) public NodeRef restore( NodeRef nodeRef, NodeRef parentNodeRef, @@ -1358,6 +1383,7 @@ public class Version2ServiceImpl extends VersionServiceImpl implements VersionSe } @Override + @Extend(extensionAPI=VersionServiceExtension.class,traitAPI=VersionServiceTrait.class) public void deleteVersionHistory(NodeRef nodeRef) throws AspectMissingException { @@ -1396,6 +1422,7 @@ public class Version2ServiceImpl extends VersionServiceImpl implements VersionSe } @Override + @Extend(extensionAPI=VersionServiceExtension.class,traitAPI=VersionServiceTrait.class) public void deleteVersion(NodeRef nodeRef, Version version) { if (logger.isDebugEnabled()) @@ -1432,6 +1459,7 @@ public class Version2ServiceImpl extends VersionServiceImpl implements VersionSe } @Override + @Extend(extensionAPI=VersionServiceExtension.class,traitAPI=VersionServiceTrait.class) public boolean isAVersion(NodeRef nodeRef) { if (logger.isDebugEnabled()) @@ -1449,6 +1477,7 @@ public class Version2ServiceImpl extends VersionServiceImpl implements VersionSe } @Override + @Extend(extensionAPI=VersionServiceExtension.class,traitAPI=VersionServiceTrait.class) public boolean isVersioned(NodeRef nodeRef) { if (logger.isDebugEnabled()) @@ -1464,4 +1493,10 @@ public class Version2ServiceImpl extends VersionServiceImpl implements VersionSe } return this.dbNodeService.hasAspect(realNodeRef, ContentModel.ASPECT_VERSIONABLE); } + + @Override + public ExtendedTrait getTrait(Class traitAPI) + { + return (ExtendedTrait) versionServiceTrait; + } } diff --git a/source/java/org/alfresco/repo/version/VersionServiceImpl.java b/source/java/org/alfresco/repo/version/VersionServiceImpl.java index b0c4b0c55c..69c2a70d4e 100644 --- a/source/java/org/alfresco/repo/version/VersionServiceImpl.java +++ b/source/java/org/alfresco/repo/version/VersionServiceImpl.java @@ -41,6 +41,8 @@ import org.alfresco.repo.version.common.AbstractVersionServiceImpl; import org.alfresco.repo.version.common.VersionHistoryImpl; import org.alfresco.repo.version.common.VersionImpl; import org.alfresco.repo.version.common.VersionUtil; +import org.alfresco.repo.version.traitextender.VersionServiceExtension; +import org.alfresco.repo.version.traitextender.VersionServiceTrait; import org.alfresco.service.cmr.dictionary.AspectDefinition; import org.alfresco.service.cmr.dictionary.AssociationDefinition; import org.alfresco.service.cmr.dictionary.ClassDefinition; @@ -61,6 +63,7 @@ import org.alfresco.service.cmr.version.VersionType; import org.alfresco.service.namespace.NamespaceService; import org.alfresco.service.namespace.QName; import org.alfresco.service.namespace.RegexQNamePattern; +import org.alfresco.traitextender.Extend; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.extensions.surf.util.ParameterCheck; @@ -165,6 +168,7 @@ public abstract class VersionServiceImpl extends AbstractVersionServiceImpl impl * @param typeQName QName * @param policy CalculateVersionLabelPolicy */ + @Extend(extensionAPI=VersionServiceExtension.class,traitAPI=VersionServiceTrait.class) public void registerVersionLabelPolicy(QName typeQName, CalculateVersionLabelPolicy policy) { // Register the serial version label behaviour @@ -236,6 +240,7 @@ public abstract class VersionServiceImpl extends AbstractVersionServiceImpl impl * ensure that the child version references in the version node will point to the version history nodes * for the (possibly) newly created version histories. */ + @Extend(extensionAPI=VersionServiceExtension.class,traitAPI=VersionServiceTrait.class) public Collection createVersion( NodeRef nodeRef, Map versionProperties, @@ -951,6 +956,7 @@ public abstract class VersionServiceImpl extends AbstractVersionServiceImpl impl /** * @see VersionService#ensureVersioningEnabled(NodeRef,Map) */ + @Extend(extensionAPI=VersionServiceExtension.class,traitAPI=VersionServiceTrait.class) public void ensureVersioningEnabled(NodeRef nodeRef, Map versionProperties) { if (logger.isDebugEnabled()) diff --git a/source/java/org/alfresco/repo/version/traitextender/VersionServiceExtension.java b/source/java/org/alfresco/repo/version/traitextender/VersionServiceExtension.java new file mode 100644 index 0000000000..05120def00 --- /dev/null +++ b/source/java/org/alfresco/repo/version/traitextender/VersionServiceExtension.java @@ -0,0 +1,26 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ +package org.alfresco.repo.version.traitextender; + +import org.alfresco.service.cmr.version.VersionService; + +public interface VersionServiceExtension extends VersionService +{ + +} diff --git a/source/java/org/alfresco/repo/version/traitextender/VersionServiceTrait.java b/source/java/org/alfresco/repo/version/traitextender/VersionServiceTrait.java new file mode 100644 index 0000000000..c1158cf599 --- /dev/null +++ b/source/java/org/alfresco/repo/version/traitextender/VersionServiceTrait.java @@ -0,0 +1,27 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ +package org.alfresco.repo.version.traitextender; + +import org.alfresco.service.cmr.version.VersionService; +import org.alfresco.traitextender.Trait; + +public interface VersionServiceTrait extends VersionService,Trait +{ + +} diff --git a/source/java/org/alfresco/repo/workflow/WorkflowPackageImpl.java b/source/java/org/alfresco/repo/workflow/WorkflowPackageImpl.java index fc31328be0..01954de88d 100644 --- a/source/java/org/alfresco/repo/workflow/WorkflowPackageImpl.java +++ b/source/java/org/alfresco/repo/workflow/WorkflowPackageImpl.java @@ -29,6 +29,8 @@ import org.alfresco.repo.importer.ImporterBootstrap; import org.alfresco.repo.node.SystemNodeUtils; import org.alfresco.repo.policy.BehaviourFilter; import org.alfresco.repo.tenant.TenantService; +import org.alfresco.repo.workflow.traitextender.WorkflowPackageExtension; +import org.alfresco.repo.workflow.traitextender.WorkflowPackageTrait; import org.alfresco.service.cmr.repository.ChildAssociationRef; import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeService; @@ -38,6 +40,11 @@ import org.alfresco.service.cmr.workflow.WorkflowException; import org.alfresco.service.cmr.workflow.WorkflowInstance; import org.alfresco.service.namespace.NamespaceService; import org.alfresco.service.namespace.QName; +import org.alfresco.traitextender.AJProxyTrait; +import org.alfresco.traitextender.Extend; +import org.alfresco.traitextender.ExtendedTrait; +import org.alfresco.traitextender.Extensible; +import org.alfresco.traitextender.Trait; import org.alfresco.util.GUID; import org.springframework.extensions.surf.util.ParameterCheck; @@ -47,7 +54,7 @@ import org.springframework.extensions.surf.util.ParameterCheck; * * @author davidc */ -public class WorkflowPackageImpl implements WorkflowPackageComponent +public class WorkflowPackageImpl implements WorkflowPackageComponent,Extensible { private final static String PACKAGE_FOLDER = "packages"; private static final String ERR_PACKAGE_ALREADY_ASSOCIATED = "workflow.package.already.associated.error"; @@ -62,7 +69,13 @@ public class WorkflowPackageImpl implements WorkflowPackageComponent private TenantService tenantService; private MessageService messageService; private BehaviourFilter policyBehaviourFilter; + private final ExtendedTrait workflowPackageTrait; + public WorkflowPackageImpl() + { + workflowPackageTrait=new ExtendedTrait(AJProxyTrait.create(this, WorkflowPackageTrait.class)); + } + /** * @param bootstrap the importer bootstrap for the store to place workflow * items into @@ -127,6 +140,7 @@ public class WorkflowPackageImpl implements WorkflowPackageComponent /** * {@inheritDoc} */ + @Extend(traitAPI=WorkflowPackageTrait.class,extensionAPI=WorkflowPackageExtension.class) public NodeRef createPackage(NodeRef container) { // create a container, if one is not specified @@ -204,6 +218,7 @@ public class WorkflowPackageImpl implements WorkflowPackageComponent /** * {@inheritDoc} */ + @Extend(traitAPI=WorkflowPackageTrait.class,extensionAPI=WorkflowPackageExtension.class) public void deletePackage(NodeRef container) { if (container != null && nodeService.exists(container) @@ -225,6 +240,7 @@ public class WorkflowPackageImpl implements WorkflowPackageComponent /** * {@inheritDoc} */ + @Extend(traitAPI=WorkflowPackageTrait.class,extensionAPI=WorkflowPackageExtension.class) public List getWorkflowIdsForContent(NodeRef packageItem) { ParameterCheck.mandatory("packageItem", packageItem); @@ -353,6 +369,7 @@ public class WorkflowPackageImpl implements WorkflowPackageComponent /** * {@inheritDoc} */ + @Extend(traitAPI=WorkflowPackageTrait.class,extensionAPI=WorkflowPackageExtension.class) public boolean setWorkflowForPackage(WorkflowInstance instance) { NodeRef packageNode = instance.getWorkflowPackage(); @@ -385,4 +402,10 @@ public class WorkflowPackageImpl implements WorkflowPackageComponent return true; } + @Override + public ExtendedTrait getTrait(Class traitAPI) + { + return (ExtendedTrait) workflowPackageTrait; + } + } diff --git a/source/java/org/alfresco/repo/workflow/traitextender/WorkflowPackageExtension.java b/source/java/org/alfresco/repo/workflow/traitextender/WorkflowPackageExtension.java new file mode 100644 index 0000000000..eae5690ddf --- /dev/null +++ b/source/java/org/alfresco/repo/workflow/traitextender/WorkflowPackageExtension.java @@ -0,0 +1,26 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ +package org.alfresco.repo.workflow.traitextender; + +import org.alfresco.repo.workflow.WorkflowPackageComponent; + +public interface WorkflowPackageExtension extends WorkflowPackageComponent +{ + +} diff --git a/source/java/org/alfresco/repo/workflow/traitextender/WorkflowPackageTrait.java b/source/java/org/alfresco/repo/workflow/traitextender/WorkflowPackageTrait.java new file mode 100644 index 0000000000..8db5704dc1 --- /dev/null +++ b/source/java/org/alfresco/repo/workflow/traitextender/WorkflowPackageTrait.java @@ -0,0 +1,27 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ +package org.alfresco.repo.workflow.traitextender; + +import org.alfresco.repo.workflow.WorkflowPackageComponent; +import org.alfresco.traitextender.Trait; + +public interface WorkflowPackageTrait extends Trait, WorkflowPackageComponent +{ + +} diff --git a/source/test-java/org/alfresco/AllUnitTestsSuite.java b/source/test-java/org/alfresco/AllUnitTestsSuite.java index 9da4397a3b..7a6453ebde 100644 --- a/source/test-java/org/alfresco/AllUnitTestsSuite.java +++ b/source/test-java/org/alfresco/AllUnitTestsSuite.java @@ -101,5 +101,7 @@ public class AllUnitTestsSuite extends TestSuite suite.addTest(new JUnit4TestAdapter(org.alfresco.util.BeanExtenderUnitTest.class)); suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.search.impl.solr.SpellCheckDecisionManagerTest.class)); suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.search.impl.solr.SolrStoreMappingWrapperTest.class)); - } + + suite.addTest(org.alfresco.traitextender.TraitExtenderUnitTestSuite.suite()); + suite.addTest(org.alfresco.repo.virtual.VirtualizationUnitTestSuite.suite()); } } diff --git a/source/test-java/org/alfresco/Repository01TestSuite.java b/source/test-java/org/alfresco/Repository01TestSuite.java index 37b5b106bd..80e160bc58 100644 --- a/source/test-java/org/alfresco/Repository01TestSuite.java +++ b/source/test-java/org/alfresco/Repository01TestSuite.java @@ -18,9 +18,9 @@ */ package org.alfresco; +import junit.framework.JUnit4TestAdapter; import junit.framework.Test; import junit.framework.TestSuite; -import junit.framework.JUnit4TestAdapter; /** * All Repository project test classes and test suites as a sequence of Repository<NN>TestSuite @@ -48,7 +48,7 @@ public class Repository01TestSuite extends TestSuite { suite.addTestSuite(org.alfresco.RepositoryStartStopTest.class); } - + static void tests3(TestSuite suite) // tests="76" time="82.566" { suite.addTestSuite(org.alfresco.email.server.EmailServiceImplTest.class); @@ -57,32 +57,32 @@ public class Repository01TestSuite extends TestSuite suite.addTestSuite(org.alfresco.filesys.repo.CifsIntegrationTest.class); suite.addTestSuite(org.alfresco.filesys.repo.ContentDiskDriverTest.class); } - + static void tests4(TestSuite suite) // tests="2" time="92.624" { suite.addTestSuite(org.alfresco.filesys.repo.LockKeeperImplTest.class); } - + static void tests6(TestSuite suite) { suite.addTest(new JUnit4TestAdapter(org.alfresco.opencmis.CMISTest.class)); } - + static void tests7(TestSuite suite) // tests="3" time="7.644" { suite.addTestSuite(org.alfresco.opencmis.OpenCmisLocalTest.class); // fails if with OpenCmisQueryTest } - + static void tests8(TestSuite suite) { suite.addTestSuite(org.alfresco.opencmis.search.OpenCmisQueryTest.class); } - + static void tests9(TestSuite suite) { suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.action.ActionTestSuite.class)); } - + static void tests10(TestSuite suite) { suite.addTestSuite(org.alfresco.repo.activities.ActivityServiceImplTest.class); @@ -93,12 +93,12 @@ public class Repository01TestSuite extends TestSuite suite.addTestSuite(org.alfresco.repo.admin.registry.RegistryServiceImplTest.class); suite.addTestSuite(org.alfresco.repo.attributes.AttributeServiceTest.class); } - + static void tests11(TestSuite suite) { suite.addTest(org.alfresco.repo.audit.AuditTestSuite.suite()); } - + static void tests13(TestSuite suite) { suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.blog.BlogServiceImplTest.class)); @@ -113,27 +113,27 @@ public class Repository01TestSuite extends TestSuite suite.addTestSuite(org.alfresco.repo.coci.CheckOutCheckInServiceImplTest.class); suite.addTestSuite(org.alfresco.repo.configuration.ConfigurableServiceImplTest.class); } - + static void tests15(TestSuite suite) { suite.addTest(org.alfresco.repo.content.ContentFullContextTestSuite.suite()); } - + static void tests16(TestSuite suite) { suite.addTest(org.alfresco.repo.content.ContentMinimalContextTestSuite.suite()); } - + static void tests17(TestSuite suite) { suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.content.caching.CachingContentStoreTestSuite.class)); } - + static void tests18(TestSuite suite) { suite.addTestSuite(org.alfresco.repo.copy.CopyServiceImplTest.class); } - + static void tests21(TestSuite suite) { suite.addTestSuite(org.alfresco.repo.descriptor.DescriptorServiceTest.class); @@ -144,30 +144,30 @@ public class Repository01TestSuite extends TestSuite suite.addTestSuite(org.alfresco.repo.dictionary.types.period.PeriodTest.class); suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.discussion.DiscussionServiceImplTest.class)); } - + static void tests22(TestSuite suite) { suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.domain.DomainTestSuite.class)); } - + static void tests23(TestSuite suite) { suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.download.DownloadServiceIntegrationTest.class)); suite.addTestSuite(org.alfresco.repo.exporter.ExporterComponentTest.class); suite.addTestSuite(org.alfresco.repo.exporter.RepositoryExporterComponentTest.class); } - + static void tests24(TestSuite suite) { suite.addTestSuite(org.alfresco.repo.forms.FormServiceImplTest.class); suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.forms.processor.action.ActionFormProcessorTest.class)); } - - static void tests27(TestSuite suite) // + + static void tests27(TestSuite suite) // { suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.forum.CommentsTest.class)); } - + static void tests28(TestSuite suite) // tests="53" time="178.25" { suite.addTestSuite(org.alfresco.repo.i18n.MessageServiceImplTest.class); // fails if with previous tests @@ -178,7 +178,7 @@ public class Repository01TestSuite extends TestSuite suite.addTestSuite(org.alfresco.repo.importer.ImporterComponentTest.class); suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.invitation.InvitationCleanupTest.class)); } - + static void tests29(TestSuite suite) // tests="12" time="93.965" { suite.addTestSuite(org.alfresco.repo.jscript.PeopleTest.class); // fails if with previous tests @@ -186,7 +186,7 @@ public class Repository01TestSuite extends TestSuite suite.addTestSuite(org.alfresco.repo.jscript.ScriptBehaviourTest.class); suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.jscript.ScriptNodeTest.class)); } - + static void tests30(TestSuite suite) // tests="70" time="62.041" failures="1" { suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.links.LinksServiceImplTest.class)); // fails if run more than once // fails if with previous tests @@ -197,12 +197,12 @@ public class Repository01TestSuite extends TestSuite suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.lock.mem.LockableAspectInterceptorTest.class)); suite.addTestSuite(org.alfresco.repo.management.JmxDumpUtilTest.class); } - + static void tests31(TestSuite suite) { suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.model.ModelTestSuite.class)); } - + static void tests32(TestSuite suite) { suite.addTestSuite(org.alfresco.repo.module.ComponentsTest.class); @@ -212,18 +212,18 @@ public class Repository01TestSuite extends TestSuite suite.addTestSuite(org.alfresco.repo.node.FullNodeServiceTest.class); suite.addTestSuite(org.alfresco.repo.node.NodeRefPropertyMethodInterceptorTest.class); } - + static void tests33(TestSuite suite) { suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.node.NodeServiceTest.class)); // moved to next test } - + static void tests34(TestSuite suite) { suite.addTestSuite(org.alfresco.repo.node.PerformanceNodeServiceTest.class); suite.addTestSuite(org.alfresco.repo.node.archive.ArchiveAndRestoreTest.class); } - + static void tests35(TestSuite suite) // tests="86" time="553.462" { suite.addTestSuite(org.alfresco.repo.node.archive.LargeArchiveAndRestoreTest.class); @@ -231,19 +231,19 @@ public class Repository01TestSuite extends TestSuite suite.addTestSuite(org.alfresco.repo.node.db.DbNodeServiceImplTest.class); suite.addTestSuite(org.alfresco.repo.node.db.DbNodeServiceImplPropagationTest.class); } - + static void tests36(TestSuite suite) // Fails with previous tests { suite.addTestSuite(org.alfresco.repo.node.getchildren.GetChildrenCannedQueryTest.class); suite.addTestSuite(org.alfresco.repo.node.index.FullIndexRecoveryComponentTest.class); suite.addTestSuite(org.alfresco.repo.node.index.IndexTransactionTrackerTest.class); } - + static void tests37(TestSuite suite) // Hangs with the previous 4 tests { suite.addTestSuite(org.alfresco.repo.node.index.MissingContentReindexComponentTest.class); } - + static void tests38(TestSuite suite) { suite.addTestSuite(org.alfresco.repo.node.integrity.IncompleteNodeTaggerTest.class); @@ -253,12 +253,12 @@ public class Repository01TestSuite extends TestSuite suite.addTestSuite(org.alfresco.repo.policy.PolicyComponentTransactionTest.class); suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.preference.PreferenceServiceImplTest.class)); } - + static void tests39(TestSuite suite) { suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.publishing.WebPublishingTestSuite.class)); } - + static void tests40(TestSuite suite) { suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.quickshare.QuickShareServiceIntegrationTest.class)); @@ -268,13 +268,13 @@ public class Repository01TestSuite extends TestSuite suite.addTestSuite(org.alfresco.repo.rendition.RenditionServiceIntegrationTest.class); suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.rendition.RenditionServicePermissionsTest.class)); } - + static void tests41(TestSuite suite) // tests="6" time="120.585" { suite.addTestSuite(org.alfresco.repo.rendition.StandardRenditionLocationResolverTest.class); suite.addTestSuite(org.alfresco.repo.rendition.executer.HTMLRenderingEngineTest.class); } - + static void tests42(TestSuite suite) // tests="27" time="134.585" { suite.addTestSuite(org.alfresco.repo.rendition.executer.XSLTFunctionsTest.class); // fails if with previous tests @@ -282,78 +282,78 @@ public class Repository01TestSuite extends TestSuite suite.addTestSuite(org.alfresco.repo.replication.ReplicationServiceIntegrationTest.class); suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.rule.MiscellaneousRulesTest.class)); } - + static void tests43(TestSuite suite) // tests="53" time="113.999" { suite.addTestSuite(org.alfresco.repo.rule.RuleLinkTest.class); // fails if with previous tests suite.addTestSuite(org.alfresco.repo.rule.RuleServiceCoverageTest.class); suite.addTestSuite(org.alfresco.repo.rule.RuleServiceImplTest.class); } - + static void tests44(TestSuite suite) // tests="2" time="104.636" errors="1" { suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.rule.RuleServiceIntegrationTest.class)); // fails locally even on its own } - + static void tests45(TestSuite suite) // tests="13" time="97.186" { suite.addTestSuite(org.alfresco.repo.rule.RuleTypeImplTest.class); suite.addTestSuite(org.alfresco.repo.rule.ruletrigger.RuleTriggerTest.class); } - + static void tests46(TestSuite suite) { suite.addTest(org.alfresco.repo.search.SearchTestSuite.suite()); } - + static void tests47(TestSuite suite) { suite.addTest(org.alfresco.repo.security.SecurityTestSuite.suite()); } - + static void tests48(TestSuite suite) { suite.addTestSuite(org.alfresco.repo.security.sync.ChainingUserRegistrySynchronizerTest.class); // failed on agent - split from following tests? } - + static void tests49(TestSuite suite) // Not sure this break is needed { suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.site.SiteServiceImplMoreTest.class)); suite.addTestSuite(org.alfresco.repo.site.SiteServiceImplTest.class); } - + static void tests50(TestSuite suite) { suite.addTestSuite(org.alfresco.repo.solr.SOLRTrackingComponentTest.class); } - + static void tests51(TestSuite suite) { suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.subscriptions.SubscriptionServiceActivitiesTest.class)); } - + static void tests52(TestSuite suite) { suite.addTestSuite(org.alfresco.repo.subscriptions.SubscriptionServiceImplTest.class); } - + static void tests53(TestSuite suite) { suite.addTestSuite(org.alfresco.repo.tagging.TaggingServiceImplTest.class); suite.addTestSuite(org.alfresco.repo.tagging.UpdateTagScopesActionExecuterTest.class); } - + static void tests55(TestSuite suite) { suite.addTestSuite(org.alfresco.repo.template.TemplateServiceImplTest.class); } - + static void tests56(TestSuite suite) { suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.tenant.MultiTServiceImplTest.class)); suite.addTestSuite(org.alfresco.repo.tenant.MultiTDemoTest.class); } - + static void tests57(TestSuite suite) { suite.addTestSuite(org.alfresco.repo.tenant.MultiTNodeServiceInterceptorTest.class); @@ -364,7 +364,7 @@ public class Repository01TestSuite extends TestSuite suite.addTestSuite(org.alfresco.repo.transaction.RetryingTransactionHelperTest.class); suite.addTestSuite(org.alfresco.repo.transaction.TransactionAwareSingletonTest.class); suite.addTestSuite(org.alfresco.repo.transaction.TransactionServiceImplTest.class); - suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.transaction.ConnectionPoolOverloadTest.class)); + suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.transaction.ConnectionPoolOverloadTest.class)); suite.addTestSuite(org.alfresco.repo.transfer.NodeCrawlerTest.class); suite.addTestSuite(org.alfresco.repo.transfer.RepoTransferReceiverImplTest.class); suite.addTestSuite(org.alfresco.repo.transfer.TransferServiceCallbackTest.class); @@ -375,22 +375,22 @@ public class Repository01TestSuite extends TestSuite suite.addTestSuite(org.alfresco.repo.transfer.script.ScriptTransferServiceTest.class); suite.addTestSuite(org.alfresco.repo.action.scheduled.CronScheduledQueryBasedTemplateActionDefinitionTest.class); } - + static void tests58(TestSuite suite) { suite.addTest(org.alfresco.repo.usage.UsageTestSuite.suite()); } - + static void tests59(TestSuite suite) { suite.addTest(org.alfresco.repo.version.VersionTestSuite.suite()); } - + static void tests61(TestSuite suite) { suite.addTest(org.alfresco.repo.workflow.WorkflowTestSuite.suite()); } - + static void tests63(TestSuite suite) // tests="187" time="364.334" { suite.addTest(new JUnit4TestAdapter(org.alfresco.util.schemacomp.DbToXMLTest.class)); @@ -439,4 +439,9 @@ public class Repository01TestSuite extends TestSuite { suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.policy.annotation.QNameTypeEditorTest.class)); } + + static void tests70(TestSuite suite) + { + suite.addTest(org.alfresco.repo.virtual.VirtualizationIntegrationTestSuite.suite()); + } } diff --git a/source/test-java/org/alfresco/Repository70TestSuite.java b/source/test-java/org/alfresco/Repository70TestSuite.java new file mode 100644 index 0000000000..df10f2e9c7 --- /dev/null +++ b/source/test-java/org/alfresco/Repository70TestSuite.java @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco; + +import junit.framework.Test; +import junit.framework.TestSuite; + +/** + * All Repository project UNIT test classes should be added to this test suite. + */ +public class Repository70TestSuite extends TestSuite +{ + public static Test suite() + { + TestSuite suite = new TestSuite(); + Repository01TestSuite.tests70(suite); + return suite; + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/TypeAndAspectsFormProcessor.java b/source/test-java/org/alfresco/repo/virtual/TypeAndAspectsFormProcessor.java new file mode 100644 index 0000000000..642c57a390 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/TypeAndAspectsFormProcessor.java @@ -0,0 +1,445 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual; + +import static org.alfresco.repo.forms.processor.node.FormFieldConstants.PROP_DATA_PREFIX; + +import java.io.InputStream; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.alfresco.model.ContentModel; +import org.alfresco.repo.forms.Form; +import org.alfresco.repo.forms.FormData; +import org.alfresco.repo.forms.FormData.FieldData; +import org.alfresco.repo.forms.FormException; +import org.alfresco.repo.forms.Item; +import org.alfresco.repo.forms.processor.node.TypeFormProcessor; +import org.alfresco.repo.model.Repository; +import org.alfresco.service.cmr.dictionary.AspectDefinition; +import org.alfresco.service.cmr.dictionary.PropertyDefinition; +import org.alfresco.service.cmr.dictionary.TypeDefinition; +import org.alfresco.service.cmr.repository.ContentData; +import org.alfresco.service.cmr.repository.ContentWriter; +import org.alfresco.service.cmr.repository.MimetypeService; +import org.alfresco.service.cmr.repository.NodeRef; +import org.alfresco.service.namespace.InvalidQNameException; +import org.alfresco.service.namespace.NamespaceService; +import org.alfresco.service.namespace.QName; +import org.alfresco.util.GUID; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class TypeAndAspectsFormProcessor extends TypeFormProcessor +{ + + /** Logger */ + private static Log logger = LogFactory.getLog(TypeAndAspectsFormProcessor.class); + + private Item typeItem = null; + + private List aspectsItems = new ArrayList(); + + private MimetypeService mimetypeService; + + private Repository repository; + + private static final String PHYSICAL_STRUCTURE = "physical_structure"; + + public void setMimetypeService(MimetypeService mimetypeService) + { + this.mimetypeService = mimetypeService; + } + + public void setRepository(Repository repository) + { + this.repository = repository; + } + + @Override + public Form generate(Item item, List fields, List forcedFields, Map context) + { + parseItems(item); + return super.generate(typeItem, + fields, + forcedFields, + context); + } + + @Override + public Object persist(Item item, FormData data) + { + parseItems(item); + return super.persist(typeItem, + data); + } + + /* + * @see + * org.alfresco.repo.forms.processor.node.ContentModelFormProcessor#getLogger + * () + */ + @Override + protected Log getLogger() + { + return logger; + } + + @Override + protected Set getAspectNames(TypeDefinition item) + { + Set requestedAspects = new HashSet(); + // default aspects from type definition + requestedAspects.addAll(super.getAspectNames(item)); + // additional requested aspects + requestedAspects.addAll(getRequestedAspects()); + return requestedAspects; + } + + private Set getRequestedAspects() + { + Set requestedAspects = new HashSet(); + for (String aspectItem : aspectsItems) + { + QName aspectQname = getAspectQname(aspectItem); + requestedAspects.add(aspectQname); + } + return requestedAspects; + } + + private List parseIds(String id) + { + String[] ids = id.split(","); + List parsedIds = new ArrayList(Arrays.asList(ids)); + return parsedIds; + } + + private void parseItems(Item item) + { + typeItem = null; + aspectsItems = new ArrayList(); + String id = item.getId(); + List parsedIds = parseIds(id); + // typeItem + typeItem = new Item("type", + parsedIds.get(0)); + Iterator iterator = parsedIds.iterator(); + iterator.next(); + while (iterator.hasNext()) + { + String nextAspect = iterator.next(); + aspectsItems.add(nextAspect); + } + } + + private QName getAspectQname(String aspectName) + { + AspectDefinition aspectDef = null; + QName aspect = null; + + try + { + // the itemId could either be the full form qname i.e. + // {http://www.alfresco.org/model/content/1.0}content + // or it could be the prefix form i.e. cm:name + + if (aspectName.startsWith("{")) + { + // item id looks like a full qname + aspect = QName.createQName(aspectName); + } + else + { + // try and create the QName using the item id as is + aspect = QName.createQName(aspectName, + this.namespaceService); + } + + // retrieve the aspect from the dictionary + aspectDef = this.dictionaryService.getAspect(aspect); + + if (aspectDef == null) + { + throw new FormException(aspectName, + new IllegalArgumentException("Aspect does not exist: " + aspectName)); + } + } + catch (InvalidQNameException iqne) + { + throw new FormException(aspectName, + iqne); + } + + // return the QName object for the requested aspect + return aspect; + + } + + @Override + protected void persistNode(NodeRef nodeRef, FormData data) + { + super.persistNode(nodeRef, + data); + + QName type = this.nodeService.getType(nodeRef); + Set aspectNames = getAspectNames(getTypedItem(typeItem)); + TypeDefinition typeDef = this.dictionaryService.getAnonymousType(type, + aspectNames); + Map propDefs = typeDef.getProperties(); + Map propsToPersist = new HashMap(); + + for (FieldData fieldData : data) + { + String fieldName = fieldData.getName(); + if (fieldName.startsWith(PROP_DATA_PREFIX)) + { + processPropertyPersist(nodeRef, + propDefs, + fieldData, + propsToPersist, + data); + } + } + + this.nodeService.addProperties(nodeRef, + propsToPersist); + + } + + @Override + protected void processContentPropertyPersist(NodeRef nodeRef, FieldData fieldData, + Map propsToPersist, FormData data) + { + + if (fieldData.isFile() == true) + { + ContentWriter writer = this.contentService.getWriter(nodeRef, + ContentModel.PROP_CONTENT, + true); + ContentData contentData = null; + + if (writer != null) + { + // determine whether there is any content for the node yet i.e. + // it's a create + boolean defaultMimetypeRequired = (this.nodeService.getProperty(nodeRef, + ContentModel.PROP_CONTENT) == null); + + // write the content + InputStream inputStream = fieldData.getInputStream(); + writer.putContent(inputStream); + + // if there was no content set a sensible default mimetype if + // necessary + if (defaultMimetypeRequired) + { + // if the transient mimetype property has already set the + // mimetype don't do anything + contentData = (ContentData) propsToPersist.get(ContentModel.PROP_CONTENT); + if (contentData != null) + { + String mimetype = contentData.getMimetype(); + if (mimetype == null) + { + contentData = ContentData.setMimetype(contentData, + determineDefaultMimetype(data)); + } + } + else + { + // content data has not been persisted yet so get it + // from the node + contentData = (ContentData) this.nodeService.getProperty(nodeRef, + ContentModel.PROP_CONTENT); + if (contentData != null) + { + String fileName = (String) fieldData.getValue(); + contentData = ContentData + .setMimetype(contentData, + mimetypeService.getMimetype(fileName.substring(fileName + .lastIndexOf(".") + 1))); + } + } + + } + else + { + contentData = (ContentData) this.nodeService.getProperty(nodeRef, + ContentModel.PROP_CONTENT); + + if (contentData != null) + { + // if the ContentData object already exists in + // propsToPersist extract the mimetype + // and encoding and set on the ContentData object just + // retrieved + if (propsToPersist.containsKey(ContentModel.PROP_CONTENT)) + { + ContentData mimetypeEncoding = (ContentData) propsToPersist.get(ContentModel.PROP_CONTENT); + contentData = ContentData.setMimetype(contentData, + mimetypeEncoding.getMimetype()); + contentData = ContentData.setEncoding(contentData, + mimetypeEncoding.getEncoding()); + } + } + } + + // add the potentially changed content data object back to + // property map for persistence + if (contentData != null) + { + propsToPersist.put(ContentModel.PROP_CONTENT, + contentData); + } + } + } + else + { + super.processContentPropertyPersist(nodeRef, + fieldData, + propsToPersist, + data); + } + } + + @SuppressWarnings("unchecked") + @Override + protected NodeRef createNode(TypeDefinition typeDef, FormData data) + { + NodeRef nodeRef = null; + + if (data != null) + { + // firstly, ensure we have a destination to create the node in + NodeRef parentRef = null; + FieldData destination = data.getFieldData(DESTINATION); + if (destination == null) + { + throw new FormException("Failed to persist form for '" + + typeDef.getName().toPrefixString(this.namespaceService) + "' as '" + DESTINATION + + "' data was not provided."); + } + + // create the parent NodeRef + String destinationValue = (String) destination.getValue(); + parentRef = getParentNodeRef(destinationValue); + if (parentRef == null) + { + throw new FormException("Failed to persist form for '" + + typeDef.getName().toPrefixString(this.namespaceService) + "' as '" + destinationValue + + "' does not exist as path or NodeRef in the system."); + } + + data.removeFieldData(DESTINATION); + + // if a name property is present in the form data use it as the node + // name, + // otherwise generate a guid + String nodeName = null; + FieldData nameData = data.getFieldData(NAME_PROP_DATA); + if (nameData != null) + { + nodeName = (String) nameData.getValue(); + + // remove the name data otherwise 'rename' gets called in + // persistNode + data.removeFieldData(NAME_PROP_DATA); + } + if (nodeName == null || nodeName.length() == 0) + { + nodeName = GUID.generate(); + } + + // create the node + Map nodeProps = new HashMap(1); + nodeProps.put(ContentModel.PROP_NAME, + nodeName); + nodeRef = this.nodeService.createNode(parentRef, + ContentModel.ASSOC_CONTAINS, + QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, + QName.createValidLocalName(nodeName)), + typeDef.getName(), + nodeProps).getChildRef(); + // adding additional aspects for now with empty properties...this + // will not be needed anymore when we'll use form processor for + // generating the form + for (QName qname : getRequestedAspects()) + { + this.nodeService.addAspect(nodeRef, + qname, + new HashMap()); + } + // if the physical structure is configured we'll create for now + // simple folders + FieldData physicalStructure = data.getFieldData(PHYSICAL_STRUCTURE); + if (physicalStructure != null) + { + List folderPhysicalStructure = (List) physicalStructure.getValue(); + createPhysicalStructure(nodeRef, + folderPhysicalStructure); + data.removeFieldData(PHYSICAL_STRUCTURE); + } + } + + return nodeRef; + } + + private void createPhysicalStructure(NodeRef nodeRef, List folderNames) + { + for (String folderName : folderNames) + { + Map nodeProps = new HashMap(1); + nodeProps.put(ContentModel.PROP_NAME, + folderName); + this.nodeService.createNode(nodeRef, + ContentModel.ASSOC_CONTAINS, + QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, + QName.createValidLocalName(folderName)), + ContentModel.TYPE_FOLDER, + nodeProps); + } + } + + private NodeRef getParentNodeRef(String destination) + { + NodeRef parentRef = null; + if (destination.contains("://")) + { + String node = destination.replace("://", + "/"); + parentRef = repository.findNodeRef("node", + node.split("/")); + } + else + { + String path = "workspace/SpacesStore/Company Home/" + destination; + parentRef = repository.findNodeRef("path", + path.split("/")); + } + return parentRef; + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/VirtualizationConfigTestBootstrap.java b/source/test-java/org/alfresco/repo/virtual/VirtualizationConfigTestBootstrap.java new file mode 100644 index 0000000000..de74d3cb71 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/VirtualizationConfigTestBootstrap.java @@ -0,0 +1,98 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual; + +import org.alfresco.repo.virtual.config.NodeRefExpression; + +public class VirtualizationConfigTestBootstrap +{ + private NodeRefExpression typeTemplatesPath; + + private NodeRefExpression systemTemplatesPath; + + private String systemTemplateType; + + private boolean virtualFoldersEnabled = true; + + private NodeRefExpression downloadAssocaiationsFolder; + + + private String typeTemplatesQNameFilterRegexp; + + public void setTypeTemplatesQNameFilterRegexp(String typeTemplatesQNameFilterRegexp) + { + this.typeTemplatesQNameFilterRegexp = typeTemplatesQNameFilterRegexp; + } + + public String getTypeTemplatesQNameFilterRegexp() + { + return this.typeTemplatesQNameFilterRegexp; + } + + public void setTypeTemplatesPath(NodeRefExpression typeTemplatesPath) + { + this.typeTemplatesPath = typeTemplatesPath; + } + + public NodeRefExpression getTypeTemplatesPath() + { + return this.typeTemplatesPath; + } + + public NodeRefExpression getDownloadAssocaiationsFolder() + { + return this.downloadAssocaiationsFolder; + } + + public void setDownloadAssocaiationsFolder(NodeRefExpression downloadAssocaiationsFolder) + { + this.downloadAssocaiationsFolder = downloadAssocaiationsFolder; + } + + public void setVirtualFoldersEnabled(boolean virtualFoldersEnabled) + { + this.virtualFoldersEnabled = virtualFoldersEnabled; + } + + public boolean areVirtualFoldersEnabled() + { + return this.virtualFoldersEnabled; + } + + public void setSystemTemplatesPath(NodeRefExpression systemTemplatesPath) + { + this.systemTemplatesPath = systemTemplatesPath; + } + + public NodeRefExpression getSystemTemplatesPath() + { + return this.systemTemplatesPath; + } + + public void setSystemTemplateType(String systemTemplateType) + { + this.systemTemplateType = systemTemplateType; + } + + public String getSystemTemplateType() + { + return this.systemTemplateType; + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/VirtualizationConfigurationTest.java b/source/test-java/org/alfresco/repo/virtual/VirtualizationConfigurationTest.java new file mode 100644 index 0000000000..dd0a3c6996 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/VirtualizationConfigurationTest.java @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual; + +import junit.framework.TestCase; + +import org.alfresco.util.ApplicationContextHelper; +import org.junit.Test; +import org.springframework.context.ApplicationContext; + +/** + * Checks test configurations. + * + * @author Bogdan Horje + */ +public class VirtualizationConfigurationTest extends TestCase implements VirtualizationTest +{ + + protected static final ApplicationContext ctx = ApplicationContextHelper.getApplicationContext(CONFIG_LOCATIONS); + + private VirtualizationConfigTestBootstrap virtualizationConfigTestBootstrap; + + @Override + protected void setUp() throws Exception + { + virtualizationConfigTestBootstrap = (VirtualizationConfigTestBootstrap) ctx + .getBean(VIRTUALIZATION_CONFIG_TEST_BOOTSTRAP_BEAN_ID, + VirtualizationConfigTestBootstrap.class); + } + + @Test + public void testVirtualizationEnabled() throws Exception + { + assertTrue("Virtual folders are disabled!", + virtualizationConfigTestBootstrap.areVirtualFoldersEnabled()); + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/VirtualizationIntegrationTest.java b/source/test-java/org/alfresco/repo/virtual/VirtualizationIntegrationTest.java new file mode 100644 index 0000000000..85bd771976 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/VirtualizationIntegrationTest.java @@ -0,0 +1,415 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual; + +import java.io.InputStream; +import java.io.Serializable; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import javax.transaction.UserTransaction; + +import junit.framework.TestCase; + +import org.alfresco.model.ContentModel; +import org.alfresco.repo.forms.FormData; +import org.alfresco.repo.forms.Item; +import org.alfresco.repo.model.Repository; +import org.alfresco.repo.node.integrity.IntegrityChecker; +import org.alfresco.repo.security.authentication.AuthenticationComponent; +import org.alfresco.repo.security.authentication.AuthenticationUtil; +import org.alfresco.repo.transaction.RetryingTransactionHelper; +import org.alfresco.repo.virtual.model.SystemTemplateLocationsConstraint; +import org.alfresco.repo.virtual.ref.Reference; +import org.alfresco.service.ServiceRegistry; +import org.alfresco.service.cmr.model.FileFolderService; +import org.alfresco.service.cmr.model.FileInfo; +import org.alfresco.service.cmr.repository.ChildAssociationRef; +import org.alfresco.service.cmr.repository.ContentService; +import org.alfresco.service.cmr.repository.ContentWriter; +import org.alfresco.service.cmr.repository.NodeRef; +import org.alfresco.service.cmr.repository.NodeService; +import org.alfresco.service.cmr.repository.StoreRef; +import org.alfresco.service.cmr.security.PermissionService; +import org.alfresco.service.namespace.NamespaceService; +import org.alfresco.service.namespace.QName; +import org.alfresco.service.transaction.TransactionService; +import org.alfresco.util.ApplicationContextHelper; +import org.junit.Ignore; +import org.springframework.context.ApplicationContext; + +@Ignore +public abstract class VirtualizationIntegrationTest extends TestCase implements VirtualizationTest +{ + + private static final String PROP_VM_TEMPLATE_CLASSPATH = "prop_vm_system-template-location"; + + protected static final String VIRTUAL_FOLDER_1_NAME = "VirtualFolder1"; + + protected static final String VIRTUAL_FOLDER_2_NAME = "VirtualFolder2"; + + protected static final String TEST_ROOT_FOLDER_NAME = "TestFolder"; + + protected static final String TEST_TEMPLATE_CLASSPATH = "/org/alfresco/repo/virtual/template/"; + + protected static final String TEST_TEMPLATE_1_JS_NAME = "testTemplate1.js"; + + protected static final String TEST_TEMPLATE_1_JSON_NAME = "testTemplate1.json"; + + protected static final String TEST_TEMPLATE_2_JSON_NAME = "testTemplate2.json"; + + protected static final String TEST_TEMPLATE_3_JSON_NAME = "testTemplate3.json"; + + protected static final String TEST_TEMPLATE_4_JSON_NAME = "testTemplate4.json"; + + protected static final String TEST_TEMPLATE_5_JSON_NAME = "testTemplate5.json"; + + protected static final String TEST_TEMPLATE_6_JSON_NAME = "testTemplate6.json"; + + protected static final String TEST_TEMPLATE_1_JS_CLASSPATH = TEST_TEMPLATE_CLASSPATH + TEST_TEMPLATE_1_JS_NAME; + + protected static final String TEST_TEMPLATE_1_JSON_CLASSPATH = TEST_TEMPLATE_CLASSPATH + TEST_TEMPLATE_1_JSON_NAME; + + protected static final String TEST_TEMPLATE_2_JSON_CLASSPATH = TEST_TEMPLATE_CLASSPATH + TEST_TEMPLATE_2_JSON_NAME; + + protected static final String TEST_TEMPLATE_3_JSON_CLASSPATH = TEST_TEMPLATE_CLASSPATH + TEST_TEMPLATE_3_JSON_NAME; + + protected static final String TEST_TEMPLATE_4_JSON_CLASSPATH = TEST_TEMPLATE_CLASSPATH + TEST_TEMPLATE_4_JSON_NAME; + + protected static final String TEST_TEMPLATE_5_JSON_CLASSPATH = TEST_TEMPLATE_CLASSPATH + TEST_TEMPLATE_5_JSON_NAME; + + protected static final String TEST_TEMPLATE_6_JSON_CLASSPATH = TEST_TEMPLATE_CLASSPATH + TEST_TEMPLATE_6_JSON_NAME; + + protected static final String TEST_TEMPLATE_1_JSON_SYS_PATH = "C" + TEST_TEMPLATE_1_JSON_CLASSPATH; + + protected static final String TEST_TEMPLATE_2_JSON_SYS_PATH = "C" + TEST_TEMPLATE_2_JSON_CLASSPATH; + + protected static final String TEST_TEMPLATE_3_JSON_SYS_PATH = "C" + TEST_TEMPLATE_3_JSON_CLASSPATH; + + protected static final String TEST_TEMPLATE_4_JSON_SYS_PATH = "C" + TEST_TEMPLATE_4_JSON_CLASSPATH; + + protected static final String TEST_TEMPLATE_5_JSON_SYS_PATH = "C" + TEST_TEMPLATE_5_JSON_CLASSPATH; + + protected static final String TEST_TEMPLATE_6_JSON_SYS_PATH = "C" + TEST_TEMPLATE_6_JSON_CLASSPATH; + + protected static final String TEST_TEMPLATE_1_JS_SYS_PATH = "C" + TEST_TEMPLATE_1_JS_CLASSPATH; + + public static final String VANILLA_PROCESSOR_JS_CLASSPATH = "/org/alfresco/repo/virtual/node/vanilla.js"; + + protected static final String FORM_DATA_PROP_NAME = "prop_cm_name"; + + protected static final String FORM_DATA_PROP_ALF_DEF = "alf_destination"; + + protected static final ApplicationContext ctx = ApplicationContextHelper.getApplicationContext(CONFIG_LOCATIONS); + + protected ContentService contentService; + + private TransactionService transactionService; + + protected FileInfo testRootFolder; + + protected FileFolderService fileAndFolderService; + + protected ActualEnvironment environment; + + protected NodeRef virtualFolder1NodeRef; + + protected NodeService nodeService; + + protected RetryingTransactionHelper retryingTransactionHelper; + + protected TypeAndAspectsFormProcessor typeAndAspectsFormProcessor; + + private UserTransaction txn; + + protected AuthenticationComponent authenticationComponent; + + protected PermissionService permissionService; + + /** The root node reference */ + protected NodeRef rootNodeRef; + + protected VirtualizationConfigTestBootstrap virtualizationConfigTestBootstrap; + + protected String configuredTemplatesClassPath = null; + + protected SystemTemplateLocationsConstraint constraints; + @Override + protected void setUp() throws Exception + { + virtualizationConfigTestBootstrap = ctx.getBean(VIRTUALIZATION_CONFIG_TEST_BOOTSTRAP_BEAN_ID, + VirtualizationConfigTestBootstrap.class); + + // Get the required services + ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean("ServiceRegistry"); + transactionService = serviceRegistry.getTransactionService(); + authenticationComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent"); + retryingTransactionHelper = (RetryingTransactionHelper) ctx.getBean("retryingTransactionHelper"); + this.authenticationComponent.setSystemUserAsCurrentUser(); + permissionService = (PermissionService) ctx.getBean("PermissionService"); + + contentService = ctx.getBean("contentService", + ContentService.class); + environment = ctx.getBean("actualEnvironment", + ActualEnvironment.class); + + fileAndFolderService = serviceRegistry.getFileFolderService(); + + Repository repository = ctx.getBean("repositoryHelper", + Repository.class); + + // start the transaction + txn = transactionService.getUserTransaction(); + txn.begin(); + + AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName()); + NodeRef root = repository.getCompanyHome(); + testRootFolder = fileAndFolderService.create(root, + TEST_ROOT_FOLDER_NAME, + ContentModel.TYPE_FOLDER); + nodeService = ctx.getBean("nodeService", + NodeService.class); + typeAndAspectsFormProcessor = ctx.getBean("typeAndAspectsFormProcessor", + TypeAndAspectsFormProcessor.class); + constraints = ctx.getBean("systemTemplateLocations", + SystemTemplateLocationsConstraint.class); + + virtualFolder1NodeRef = createVirtualizedFolder(testRootFolder.getNodeRef(), + VIRTUAL_FOLDER_1_NAME, + TEST_TEMPLATE_1_JSON_SYS_PATH); + rootNodeRef = nodeService.getRootNode(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE); + + } + + public void tearDown() throws Exception + { + if (configuredTemplatesClassPath != null) + { + constraints.setTemplatesParentClasspath(configuredTemplatesClassPath); + configuredTemplatesClassPath = null; + } + authenticationComponent.clearCurrentSecurityContext(); + txn.rollback(); + super.tearDown(); + } + + /** + * @param parent + * @param name + * @param templateSysPath system path of the template to be applied. If + * null the property is not set - this should + * trigger default predefined settings behavior. + * @return the {@link NodeRef} of a newly created folder that has the + * predefined virtualization method aspect applied + */ + protected NodeRef createVirtualizedFolder(NodeRef parent, String name, String templateSysPath) + { + Item testItem = new Item("typeAndAspects", + "cm:folder,vm:system-virtualization"); + FormData testFormData = new FormData(); + + testFormData.addFieldData(FORM_DATA_PROP_NAME, + name); + if (templateSysPath != null) + { + testFormData.addFieldData(PROP_VM_TEMPLATE_CLASSPATH, + templateSysPath); + } + // alf_destination is mandatory + testFormData.addFieldData(FORM_DATA_PROP_ALF_DEF, + parent.toString()); + + return (NodeRef) typeAndAspectsFormProcessor.persist(testItem, + testFormData); + + } + + protected void assertVirtualNode(NodeRef nodeRef) + { + assertVirtualNode(nodeRef, + Collections. emptyMap()); + } + + protected void assertVirtualNode(NodeRef nodeRef, Map expectedProperties) + { + assertTrue(Reference.isReference(nodeRef)); + + assertTrue(nodeService.hasAspect(nodeRef, + VirtualContentModel.ASPECT_VIRTUAL)); + Set aspects = nodeService.getAspects(nodeRef); + assertTrue(aspects.contains(VirtualContentModel.ASPECT_VIRTUAL)); + + Map nodeProperties = nodeService.getProperties(nodeRef); + + List mandatoryProperties = Arrays.asList(ContentModel.PROP_STORE_IDENTIFIER, + ContentModel.PROP_STORE_PROTOCOL, + ContentModel.PROP_LOCALE, + ContentModel.PROP_TITLE, + ContentModel.PROP_MODIFIED, + ContentModel.PROP_MODIFIER, + ContentModel.PROP_CREATED, + ContentModel.PROP_CREATOR, + ContentModel.PROP_NODE_DBID, + ContentModel.PROP_DESCRIPTION); + + Set missingPropreties = new HashSet<>(mandatoryProperties); + missingPropreties.removeAll(nodeProperties.keySet()); + + assertTrue("Mandatory properties are missing" + missingPropreties, + missingPropreties.isEmpty()); + + Set> epEntries = expectedProperties.entrySet(); + StringBuilder unexpectedBuilder = new StringBuilder(); + for (Entry entry : epEntries) + { + Serializable actualValue = nodeProperties.get(entry.getKey()); + Serializable expectedValue = expectedProperties.get(entry.getKey()); + boolean fail = false; + String expectedValueStr = null; + + if (expectedValue != null) + { + expectedValueStr = expectedValue.toString(); + + if (!expectedValue.equals(actualValue)) + { + fail = true; + } + + } + else if (actualValue != null) + { + fail = true; + expectedValueStr = ""; + } + + if (fail) + { + unexpectedBuilder.append("\n"); + unexpectedBuilder.append(entry.getKey()); + unexpectedBuilder.append(" expected["); + unexpectedBuilder.append(expectedValueStr); + unexpectedBuilder.append("] != actua["); + unexpectedBuilder.append(actualValue); + unexpectedBuilder.append("]"); + } + } + String unexpectedStr = unexpectedBuilder.toString(); + assertTrue("Unexpected property values : " + unexpectedStr, + unexpectedStr.isEmpty()); + } + + protected ChildAssociationRef createTypedNode(NodeRef parent, final String name, QName type) + { + return createTypedNode(parent, + name, + type, + new HashMap()); + } + + protected ChildAssociationRef createTypedNode(NodeRef parent, final String name, QName type, + HashMap properties) + { + final HashMap newProperties = new HashMap(properties); + newProperties.put(ContentModel.PROP_NAME, + name); + QName assocQName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, + QName.createValidLocalName(name)); + return nodeService.createNode(parent, + ContentModel.ASSOC_CONTAINS, + assocQName, + type, + newProperties); + } + + protected ChildAssociationRef createFolder(NodeRef parent, final String name) + { + return createTypedNode(parent, + name, + ContentModel.TYPE_FOLDER); + } + + protected ChildAssociationRef createFolder(NodeRef parent, final String name, + HashMap properties) + { + return createTypedNode(parent, + name, + ContentModel.TYPE_FOLDER, + properties); + } + + protected ChildAssociationRef createContent(NodeRef parent, final String name) + { + return createTypedNode(parent, + name, + ContentModel.TYPE_CONTENT); + } + + protected ChildAssociationRef createContent(NodeRef parent, final String name, InputStream stream, String mimeType, + String encoding) + { + return createContent(parent, + name, + stream, + mimeType, + encoding, + ContentModel.TYPE_CONTENT); + } + + protected ChildAssociationRef createContent(NodeRef parent, final String name, InputStream stream, String mimeType, + String encoding, QName nodeType) + { + ChildAssociationRef nodeAssoc = createTypedNode(parent, + name, + nodeType); + NodeRef child = nodeAssoc.getChildRef(); + ContentWriter writer = contentService.getWriter(child, + ContentModel.PROP_CONTENT, + true); + + writer.setMimetype(mimeType); + writer.setEncoding(encoding); + writer.putContent(stream); + return nodeAssoc; + } + + protected ChildAssociationRef createContent(NodeRef parent, final String name, String contentString, + String mimeType, String encoding) + { + ChildAssociationRef nodeAssoc = createTypedNode(parent, + name, + ContentModel.TYPE_CONTENT); + NodeRef child = nodeAssoc.getChildRef(); + ContentWriter writer = contentService.getWriter(child, + ContentModel.PROP_CONTENT, + true); + + writer.setMimetype(mimeType); + writer.setEncoding(encoding); + writer.putContent(contentString); + return nodeAssoc; + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/VirtualizationIntegrationTestSuite.java b/source/test-java/org/alfresco/repo/virtual/VirtualizationIntegrationTestSuite.java new file mode 100644 index 0000000000..ce8730ed7e --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/VirtualizationIntegrationTestSuite.java @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual; + +import junit.framework.JUnit4TestAdapter; +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.alfresco.repo.virtual.bundle.VirtualCheckOutCheckInServiceExtensionTest; +import org.alfresco.repo.virtual.bundle.VirtualFileFolderServiceExtensionTest; +import org.alfresco.repo.virtual.bundle.VirtualLockableAspectInterceptorExtensionTest; +import org.alfresco.repo.virtual.bundle.VirtualNodeServiceExtensionTest; +import org.alfresco.repo.virtual.bundle.VirtualPermissionServiceExtensionTest; +import org.alfresco.repo.virtual.bundle.VirtualRatingServiceExtensionTest; +import org.alfresco.repo.virtual.bundle.VirtualVersionServiceExtensionTest; +import org.alfresco.repo.virtual.config.NodeRefPathExpressionTest; +import org.alfresco.repo.virtual.model.SystemTemplateLocationsConstraintTest; +import org.alfresco.repo.virtual.store.SystemVirtualizationMethodTest; +import org.alfresco.repo.virtual.store.TypeVirtualizationMethodTest; +import org.alfresco.repo.virtual.store.VirtualStoreImplTest; +import org.alfresco.repo.virtual.template.ApplyTemplateMethodTest; +import org.alfresco.repo.virtual.template.TemplateFilingRuleTest; +import org.alfresco.repo.virtual.template.TemplateResourceProcessorTest; +import org.alfresco.util.ApplicationContextHelper; +import org.springframework.context.ApplicationContext; + +/** + * + * + * @author Bogdan Horje + */ +public class VirtualizationIntegrationTestSuite extends TestSuite implements VirtualizationTest +{ + protected static final ApplicationContext ctx = ApplicationContextHelper.getApplicationContext(CONFIG_LOCATIONS); + + public static Test suite() + { + VirtualizationConfigTestBootstrap virtualizationConfigTestBootstrap = ctx + .getBean(VIRTUALIZATION_CONFIG_TEST_BOOTSTRAP_BEAN_ID, + VirtualizationConfigTestBootstrap.class); + + TestSuite suite = new TestSuite(); + + suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.virtual.VirtualizationConfigurationTest.class)); + + if (virtualizationConfigTestBootstrap.areVirtualFoldersEnabled()) + { + suite.addTest(new JUnit4TestAdapter(VirtualLockableAspectInterceptorExtensionTest.class)); + suite.addTest(new JUnit4TestAdapter(VirtualVersionServiceExtensionTest.class)); + suite.addTest(new JUnit4TestAdapter(VirtualRatingServiceExtensionTest.class)); + suite.addTest(new JUnit4TestAdapter(VirtualCheckOutCheckInServiceExtensionTest.class)); + suite.addTest(new JUnit4TestAdapter(VirtualPermissionServiceExtensionTest.class)); + suite.addTest(new JUnit4TestAdapter(VirtualNodeServiceExtensionTest.class)); + suite.addTest(new JUnit4TestAdapter(VirtualFileFolderServiceExtensionTest.class)); + suite.addTest(new JUnit4TestAdapter(ApplyTemplateMethodTest.class)); + suite.addTest(new JUnit4TestAdapter(SystemTemplateLocationsConstraintTest.class)); + suite.addTest(new JUnit4TestAdapter(SystemVirtualizationMethodTest.class)); + suite.addTest(new JUnit4TestAdapter(TypeVirtualizationMethodTest.class)); + suite.addTest(new JUnit4TestAdapter(TemplateResourceProcessorTest.class)); + suite.addTest(new JUnit4TestAdapter(VirtualStoreImplTest.class)); + suite.addTest(new JUnit4TestAdapter(NodeRefPathExpressionTest.class)); + suite.addTest(new JUnit4TestAdapter(TemplateFilingRuleTest.class)); + } + + return suite; + + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/VirtualizationTest.java b/source/test-java/org/alfresco/repo/virtual/VirtualizationTest.java new file mode 100644 index 0000000000..b47d78a96d --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/VirtualizationTest.java @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual; + +import org.alfresco.util.ApplicationContextHelper; + +/** + * Virtualization tests constant interface. + * + * @author Bogdan Horje + */ +public interface VirtualizationTest +{ + static String VIRTUALIZATION_CONFIG_TEST_BOOTSTRAP_BEAN_ID = "virtualizationConfigTestBootstrap"; + + static final String[] CONFIG_LOCATIONS = new String[] { ApplicationContextHelper.CONFIG_LOCATIONS[0], + "classpath:**/virtualization-test-context.xml" }; +} diff --git a/source/test-java/org/alfresco/repo/virtual/VirtualizationUnitTestSuite.java b/source/test-java/org/alfresco/repo/virtual/VirtualizationUnitTestSuite.java new file mode 100644 index 0000000000..559213c5c7 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/VirtualizationUnitTestSuite.java @@ -0,0 +1,47 @@ + +package org.alfresco.repo.virtual; + +import junit.framework.JUnit4TestAdapter; +import junit.framework.Test; +import junit.framework.TestSuite; + +public class VirtualizationUnitTestSuite +{ + /** + * Creates the test suite + * + * @return the test suite + */ + public static Test suite() + { + TestSuite suite = new TestSuite(); + unitTests(suite); + return suite; + } + + static void unitTests(TestSuite suite) + { + suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.virtual.page.PageCollatorTest.class)); + suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.virtual.ref.GetChildByIdMethodTest.class)); + suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.virtual.ref.GetParentReferenceMethodTest.class)); + suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.virtual.ref.NewVirtualReferenceMethodTest.class)); + suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.virtual.ref.PlainReferenceParserTest.class)); + suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.virtual.ref.PlainStringifierTest.class)); + suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.virtual.ref.ProtocolTest.class)); + suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.virtual.ref.ReferenceTest.class)); + suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.virtual.ref.ResourceParameterTest.class)); + suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.virtual.ref.StringParameterTest.class)); + suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.virtual.ref.VirtualProtocolTest.class)); + suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.virtual.store.ReferenceComparatorTest.class)); + + suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.virtual.ref.ZeroReferenceParserTest.class)); + suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.virtual.ref.ZeroStringifierTest.class)); + + suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.virtual.ref.HashStringifierTest.class)); + suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.virtual.ref.NodeRefRadixHasherTest.class)); + suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.virtual.ref.NumericPathHasherTest.class)); + suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.virtual.ref.StoredPathHasherTest.class)); + + suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.virtual.template.VirtualQueryImplTest.class)); + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/bundle/VirtualCheckOutCheckInServiceExtensionTest.java b/source/test-java/org/alfresco/repo/virtual/bundle/VirtualCheckOutCheckInServiceExtensionTest.java new file mode 100644 index 0000000000..e629eeeeff --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/bundle/VirtualCheckOutCheckInServiceExtensionTest.java @@ -0,0 +1,378 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ +package org.alfresco.repo.virtual.bundle; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.alfresco.model.ContentModel; +import org.alfresco.repo.coci.CheckOutCheckInServiceImpl; +import org.alfresco.repo.content.MimetypeMap; +import org.alfresco.repo.version.VersionModel; +import org.alfresco.repo.virtual.VirtualizationIntegrationTest; +import org.alfresco.service.cmr.coci.CheckOutCheckInService; +import org.alfresco.service.cmr.repository.AssociationRef; +import org.alfresco.service.cmr.repository.ChildAssociationRef; +import org.alfresco.service.cmr.repository.ContentReader; +import org.alfresco.service.cmr.repository.ContentWriter; +import org.alfresco.service.cmr.repository.NodeRef; +import org.alfresco.service.cmr.version.Version; +import org.alfresco.service.cmr.version.VersionService; +import org.alfresco.service.cmr.version.VersionType; +import org.junit.Test; +import org.springframework.extensions.surf.util.I18NUtil; + +public class VirtualCheckOutCheckInServiceExtensionTest extends VirtualizationIntegrationTest +{ + private static final String PROP_VERSION_LABEL_3 = "1.0"; + + private static final String PROP_VERSION_LABEL_2 = "0.2"; + + private static final String PROP_VERSION_LABEL_1 = "0.1"; + + private static final String PROP_VERSION_DESCRIPTION_3 = "dd2"; + + private static final String PROP_VERSION_DESCRIPTION_2 = "dd1"; + + private static final String PROP_VERSION_DESCRIPTION_1 = "dd"; + + private static final String TEST_CONTENT_3 = "2"; + + private static final String TEST_CONTENT_2 = "1"; + + private static final String TEST_CONTENT_1 = "0"; + + private static final String PROP_FILE_NAME = "originalFile"; + + private static final String PROP_WORKING_COPY_NAME = CheckOutCheckInServiceImpl + .createWorkingCopyName(PROP_FILE_NAME, + I18NUtil.getMessage("coci_service.working_copy_label")); + + private CheckOutCheckInService checkOutCheckInService; + + private VersionService versionService; + + private NodeRef originalContentNodeRef; + + private NodeRef node; + + private NodeRef physicalFileNodeRef; + + @Override + protected void setUp() throws Exception + { + super.setUp(); + checkOutCheckInService = VirtualCheckOutCheckInServiceExtensionTest.ctx.getBean("checkOutCheckInService", + CheckOutCheckInService.class); + versionService = VirtualCheckOutCheckInServiceExtensionTest.ctx.getBean("versionService", + VersionService.class); + + node = nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + "Node1"); + originalContentNodeRef = createContent(node, + PROP_FILE_NAME, + TEST_CONTENT_1, + MimetypeMap.MIMETYPE_TEXT_PLAIN, + "UTF-8").getChildRef(); + nodeService.addAspect(originalContentNodeRef, + ContentModel.ASPECT_VERSIONABLE, + null); + physicalFileNodeRef = nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + PROP_FILE_NAME); + } + + @Override + public void tearDown() throws Exception + { + super.tearDown(); + } + + @Test + public void testCheckOut() throws Exception + { + // method1 + NodeRef workingCopy = checkOutCheckInService.checkout(originalContentNodeRef); + assertNotNull(workingCopy); + assertTrue(checkOutCheckInService.isCheckedOut(physicalFileNodeRef)); + + assertEquals(checkOutCheckInService.getWorkingCopy(originalContentNodeRef), + workingCopy); + checkOutCheckInService.cancelCheckout(workingCopy); + + // method2 + ChildAssociationRef childAssocRef = nodeService.getPrimaryParent(node); + NodeRef workingCopy1 = checkOutCheckInService.checkout(originalContentNodeRef, + childAssocRef.getParentRef(), + childAssocRef.getTypeQName(), + childAssocRef.getQName()); + + assertNotNull(workingCopy1); + assertTrue(checkOutCheckInService.isCheckedOut(physicalFileNodeRef)); + + assertEquals(checkOutCheckInService.getWorkingCopy(physicalFileNodeRef), + workingCopy1); + checkOutCheckInService.cancelCheckout(workingCopy1); + + } + + @Test + public void testCheckIn() throws Exception + { + checkOutCheckInService.checkout(originalContentNodeRef); + NodeRef workingCopyVirtualContext = nodeService.getChildByName(node, + ContentModel.ASSOC_CONTAINS, + PROP_WORKING_COPY_NAME); + + Map versionProperties = new HashMap(); + versionProperties.put(VersionModel.PROP_DESCRIPTION, + PROP_VERSION_DESCRIPTION_1); + versionProperties.put(VersionModel.PROP_VERSION_TYPE, + VersionType.MINOR); + NodeRef origNodeRef = checkOutCheckInService.checkin(workingCopyVirtualContext, + versionProperties); + + assertNotNull(origNodeRef); + assertEquals(originalContentNodeRef, + origNodeRef); + assertFalse(checkOutCheckInService.isCheckedOut(physicalFileNodeRef)); + + // Check that the version history is correct + Version version = this.versionService.getCurrentVersion(origNodeRef); + assertNotNull(version); + assertEquals(PROP_VERSION_DESCRIPTION_1, + version.getDescription()); + assertEquals(VersionType.MINOR, + version.getVersionType()); + assertEquals(PROP_VERSION_LABEL_1, + version.getVersionLabel()); + + // method2 + + checkOutCheckInService.checkout(originalContentNodeRef); + workingCopyVirtualContext = nodeService.getChildByName(node, + ContentModel.ASSOC_CONTAINS, + PROP_WORKING_COPY_NAME); + + versionProperties = new HashMap(); + versionProperties.put(VersionModel.PROP_DESCRIPTION, + PROP_VERSION_DESCRIPTION_2); + versionProperties.put(VersionModel.PROP_VERSION_TYPE, + VersionType.MINOR); + + ContentWriter tempWriter = this.contentService.getWriter(workingCopyVirtualContext, + ContentModel.PROP_CONTENT, + false); + assertNotNull(tempWriter); + tempWriter.putContent(TEST_CONTENT_2); + + String contentUrl = tempWriter.getContentUrl(); + origNodeRef = checkOutCheckInService.checkin(workingCopyVirtualContext, + versionProperties, + contentUrl); + assertNotNull(origNodeRef); + assertEquals(originalContentNodeRef, + origNodeRef); + assertFalse(checkOutCheckInService.isCheckedOut(physicalFileNodeRef)); + + // Check the checked in content + ContentReader contentReader = this.contentService.getReader(origNodeRef, + ContentModel.PROP_CONTENT); + assertNotNull(contentReader); + assertEquals(TEST_CONTENT_2, + contentReader.getContentString()); + + // Check that the version history is correct + + version = this.versionService.getCurrentVersion(origNodeRef); + assertNotNull(version); + assertEquals(PROP_VERSION_DESCRIPTION_2, + version.getDescription()); + assertEquals(VersionType.MINOR, + version.getVersionType()); + assertEquals(PROP_VERSION_LABEL_2, + version.getVersionLabel()); + + // method3 + + checkOutCheckInService.checkout(originalContentNodeRef); + workingCopyVirtualContext = nodeService.getChildByName(node, + ContentModel.ASSOC_CONTAINS, + PROP_WORKING_COPY_NAME); + + versionProperties = new HashMap(); + versionProperties.put(VersionModel.PROP_DESCRIPTION, + PROP_VERSION_DESCRIPTION_3); + versionProperties.put(VersionModel.PROP_VERSION_TYPE, + VersionType.MAJOR); + + tempWriter = this.contentService.getWriter(workingCopyVirtualContext, + ContentModel.PROP_CONTENT, + false); + assertNotNull(tempWriter); + tempWriter.putContent(TEST_CONTENT_3); + + contentUrl = tempWriter.getContentUrl(); + origNodeRef = checkOutCheckInService.checkin(workingCopyVirtualContext, + versionProperties, + contentUrl, + false); + assertNotNull(origNodeRef); + assertEquals(originalContentNodeRef, + origNodeRef); + assertFalse(checkOutCheckInService.isCheckedOut(physicalFileNodeRef)); + + // Check the checked in content + contentReader = this.contentService.getReader(origNodeRef, + ContentModel.PROP_CONTENT); + assertNotNull(contentReader); + assertEquals(TEST_CONTENT_3, + contentReader.getContentString()); + + // Check that the version history is correct + + version = this.versionService.getCurrentVersion(origNodeRef); + assertNotNull(version); + assertEquals(PROP_VERSION_DESCRIPTION_3, + version.getDescription()); + assertEquals(VersionType.MAJOR, + version.getVersionType()); + assertEquals(PROP_VERSION_LABEL_3, + version.getVersionLabel()); + } + + @Test + public void testCancelCheckout() throws Exception + { + checkOutCheckInService.checkout(originalContentNodeRef); + assertTrue(checkOutCheckInService.isCheckedOut(physicalFileNodeRef)); + + NodeRef workingCopyVirtualContext = nodeService.getChildByName(node, + ContentModel.ASSOC_CONTAINS, + PROP_WORKING_COPY_NAME); + assertNotNull(workingCopyVirtualContext); + checkOutCheckInService.cancelCheckout(workingCopyVirtualContext); + + assertFalse(checkOutCheckInService.isCheckedOut(physicalFileNodeRef)); + workingCopyVirtualContext = nodeService.getChildByName(node, + ContentModel.ASSOC_CONTAINS, + PROP_WORKING_COPY_NAME); + assertNull(workingCopyVirtualContext); + + } + + @Test + public void testGetWorkingCopy() throws Exception + { + NodeRef checkedOut = checkOutCheckInService.checkout(originalContentNodeRef); + + NodeRef workingCopy = checkOutCheckInService.getWorkingCopy(originalContentNodeRef); + assertNotNull(workingCopy); + assertEquals(checkedOut, + workingCopy); + + checkOutCheckInService.cancelCheckout(workingCopy); + + workingCopy = checkOutCheckInService.getWorkingCopy(originalContentNodeRef); + assertNull(workingCopy); + assertNull(checkOutCheckInService.getWorkingCopy(physicalFileNodeRef)); + + } + + @Test + public void testGetCheckedOut() throws Exception + { + checkOutCheckInService.checkout(originalContentNodeRef); + NodeRef workingCopyVirtualContext = nodeService.getChildByName(node, + ContentModel.ASSOC_CONTAINS, + PROP_WORKING_COPY_NAME); + assertNotNull(workingCopyVirtualContext); + + NodeRef checkedOut = checkOutCheckInService.getCheckedOut(workingCopyVirtualContext); + assertNotNull(checkedOut); + assertEquals(originalContentNodeRef, + checkedOut); + + checkOutCheckInService.cancelCheckout(workingCopyVirtualContext); + + NodeRef checkedOut2 = checkOutCheckInService.getCheckedOut(originalContentNodeRef); + assertNull(checkedOut2); + + } + + @Test + public void testIsWorkingCopy() throws Exception + { + checkOutCheckInService.checkout(originalContentNodeRef); + NodeRef workingCopyVirtualContext = nodeService.getChildByName(node, + ContentModel.ASSOC_CONTAINS, + PROP_WORKING_COPY_NAME); + assertNotNull(workingCopyVirtualContext); + + assertTrue(checkOutCheckInService.isWorkingCopy(workingCopyVirtualContext)); + + checkOutCheckInService.cancelCheckout(workingCopyVirtualContext); + } + + @Test + public void testIsCheckedOut() throws Exception + { + NodeRef workingCopy = checkOutCheckInService.checkout(originalContentNodeRef); + assertNotNull(workingCopy); + + boolean checkedOut = checkOutCheckInService.isCheckedOut(originalContentNodeRef); + assertTrue(checkedOut); + + checkOutCheckInService.cancelCheckout(workingCopy); + checkedOut = checkOutCheckInService.isCheckedOut(originalContentNodeRef); + assertFalse(checkedOut); + + } + + @Test + public void testAssocsReferences() throws Exception + { + checkOutCheckInService.checkout(originalContentNodeRef); + NodeRef workingCopyVirtualContext = nodeService.getChildByName(node, + ContentModel.ASSOC_CONTAINS, + PROP_WORKING_COPY_NAME); + + //test target association reference + List targetAssocs = nodeService.getTargetAssocs(originalContentNodeRef, + ContentModel.ASSOC_WORKING_COPY_LINK); + assertNotNull(targetAssocs); + assertEquals(1, + targetAssocs.size()); + assertEquals(workingCopyVirtualContext, + targetAssocs.get(0).getTargetRef()); + + //test source association reference + List sourceAssocs = nodeService.getSourceAssocs(workingCopyVirtualContext, + ContentModel.ASSOC_WORKING_COPY_LINK); + assertNotNull(sourceAssocs); + assertEquals(1, + sourceAssocs.size()); + assertEquals(originalContentNodeRef, + sourceAssocs.get(0).getSourceRef()); + checkOutCheckInService.cancelCheckout(workingCopyVirtualContext); + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/bundle/VirtualFileFolderServiceExtensionTest.java b/source/test-java/org/alfresco/repo/virtual/bundle/VirtualFileFolderServiceExtensionTest.java new file mode 100644 index 0000000000..927b114dc0 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/bundle/VirtualFileFolderServiceExtensionTest.java @@ -0,0 +1,450 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.bundle; + +import java.io.File; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Set; + +import org.alfresco.model.ContentModel; +import org.alfresco.query.PagingRequest; +import org.alfresco.query.PagingResults; +import org.alfresco.repo.virtual.VirtualizationIntegrationTest; +import org.alfresco.service.cmr.coci.CheckOutCheckInService; +import org.alfresco.service.cmr.model.FileInfo; +import org.alfresco.service.cmr.repository.NodeRef; +import org.alfresco.service.namespace.NamespaceService; +import org.alfresco.service.namespace.QName; +import org.alfresco.util.Pair; +import org.alfresco.util.TempFileProvider; +import org.junit.Test; + +public class VirtualFileFolderServiceExtensionTest extends VirtualizationIntegrationTest +{ + + private static final String NEW_FILE_NAME_2 = "RenameTest2"; + private static final String NEW_FILE_NAME_1 = "RenamedTest"; + + @Test + public void testListOne() throws Exception + { + NodeRef node2 = nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CHILDREN, + "Node2"); + final String folderName = "Node2_1"; + final String testFileName = "testfile.txt"; + createContent(node2, + testFileName); + + List node2Contents = fileAndFolderService.list(node2); + + assertEquals(2, + node2Contents.size()); + FileInfo testFolderFileInfo = node2Contents.get(0); + assertEquals(folderName, + testFolderFileInfo.getName()); + FileInfo testFileFileInfo = node2Contents.get(1); + assertEquals(testFileName, + testFileFileInfo.getName()); + } + + @Test + public void testListActualFolders() throws Exception + { + createFolder(virtualFolder1NodeRef, + "Actual1"); + List contents = fileAndFolderService.list(virtualFolder1NodeRef); + assertEquals(3, + contents.size()); + assertContainsNames(contents, + "Node1", + "Node2", + "Actual1"); + } + + private void assertContainsNames(List contents, String... names) + { + List fileNames = new ArrayList<>(); + for (FileInfo fileInfo : contents) + { + fileNames.add(fileInfo.getName()); + } + assertTrue(fileNames.containsAll(Arrays.asList(names))); + } + + private void assertMissesNames(List contents, String... names) + { + List fileNames = new ArrayList<>(); + for (FileInfo fileInfo : contents) + { + fileNames.add(fileInfo.getName()); + } + List missedNames = new ArrayList<>(Arrays.asList(names)); + assertFalse(missedNames.removeAll(fileNames)); + } + + @Test + public void testListNonVirtualizable() throws Exception + { + NodeRef nv = createVirtualizedFolder(testRootFolder.getNodeRef(), + "TestVirtualFileFolderService_testListNonVirtualizable", + null); + List emptyList = fileAndFolderService.list(nv); + + assertTrue(emptyList.isEmpty()); + } + + @Test + public void testSearch() throws Exception + { + NodeRef node1 = nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + "Node1"); + NodeRef node2 = nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + "Node2"); + + HashMap properties = new HashMap(); + properties.put(ContentModel.PROP_NAME, + "testfile.txt"); + QName assocQName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, + QName.createValidLocalName("testfile.txt")); + + nodeService.createNode(node1, + ContentModel.ASSOC_CONTAINS, + assocQName, + ContentModel.TYPE_CONTENT, + properties); + nodeService.createNode(node2, + ContentModel.ASSOC_CONTAINS, + assocQName, + ContentModel.TYPE_CONTENT, + properties); + + List search = fileAndFolderService.search(virtualFolder1NodeRef, + "testfile.txt", + true, + false, + true); + // one physical file and one from node1 + assertEquals(2, + search.size()); + + search = fileAndFolderService.search(virtualFolder1NodeRef, + "testfile-1.txt", + true, + false, + true); + // one physical file and one from node2 + assertEquals(2, + search.size()); + + search = fileAndFolderService.search(virtualFolder1NodeRef, + "testfile.txt", + true, + false, + false); + + assertEquals(1, + search.size()); + + search = fileAndFolderService.search(virtualFolder1NodeRef, + null, + true, + false, + true); + assertEquals(4, + search.size()); + + search = fileAndFolderService.search(virtualFolder1NodeRef, + null, + true, + false, + false); + + assertEquals(2, + search.size()); + + search = fileAndFolderService.search(virtualFolder1NodeRef, + null, + false, + true, + false); + + assertEquals(2, + search.size()); + + search = fileAndFolderService.search(virtualFolder1NodeRef, + null, + false, + true, + true); + + assertEquals(3, + search.size()); + + } + + /** + * List the contents of a virtualized folder retrieved as a virtual child. + * + * @throws Exception + */ + @Test + public void testListVirtualizedVirtualChild() throws Exception + { + NodeRef vf = createVirtualizedFolder(testRootFolder.getNodeRef(), + "TestVirtualFileFolderService_testVirtualFolderVirtualChild", + TEST_TEMPLATE_3_JSON_SYS_PATH); + NodeRef node1 = nodeService.getChildByName(vf, + ContentModel.ASSOC_CHILDREN, + "Node1"); + + final String virtualizedChildFolderName = "TestVirtualFileFolderService_testVirtualFolderVirtualChild_CVF"; + // CM-533 Suppress options to create folders in a virtual folder (repo) + // we programmatically replicate the process + NodeRef virtulizedFolder = createVirtualizedFolder(vf, + virtualizedChildFolderName, + TEST_TEMPLATE_3_JSON_SYS_PATH); + nodeService.setProperty(virtulizedFolder, + ContentModel.PROP_DESCRIPTION, + "Node1_content_FR"); + + NodeRef vfchildvf = nodeService.getChildByName(node1, + ContentModel.ASSOC_CHILDREN, + virtualizedChildFolderName); + + assertNotNull("Virtual child expected.", + vfchildvf); + + { + List vfchildvfList = fileAndFolderService.list(vfchildvf); + assertContainsNames(vfchildvfList, + "Node1", + "Node2"); + } + + { + PagingResults vfchildvfResults = fileAndFolderService.list(vfchildvf, + null, + null, + null, + new PagingRequest(100)); + List page = vfchildvfResults.getPage(); + assertContainsNames(page, + "Node1", + "Node2"); + } + + { + PagingResults vfchildvfResults = fileAndFolderService.list(vfchildvf, + true, + true, + null, + null, + null, + new PagingRequest(100)); + List page = vfchildvfResults.getPage(); + assertContainsNames(page, + "Node1", + "Node2"); + } + } + + @Test + public void testListFileFolderDisjunction() throws Exception + { + NodeRef vf = createVirtualizedFolder(testRootFolder.getNodeRef(), + "TestVirtualFileFolderService_testVirtualFolderVirtualChild", + TEST_TEMPLATE_3_JSON_SYS_PATH); + NodeRef node2 = nodeService.getChildByName(vf, + ContentModel.ASSOC_CHILDREN, + "Node2"); + + final String folderName = "FolderVirtualChild"; + // CM-533 Suppress options to create folders in a virtual folder (repo) + // we programmatically replicate the process + final HashMap properties = new HashMap(); + properties.put(ContentModel.PROP_DESCRIPTION, + "Node2_folder_FR"); + createFolder(vf, + folderName, + properties); + + final String contentName = "ContentVirtualChild"; + createContent(node2, + contentName); + + { + PagingResults folderChildren = fileAndFolderService + .list(node2, + false, + true, + "*", + Collections. emptySet(), + Collections.> emptyList(), + new PagingRequest(100)); + List page = folderChildren.getPage(); + assertContainsNames(page, + folderName); + assertMissesNames(page, + contentName); + } + + { + PagingResults contentChildren = fileAndFolderService + .list(node2, + true, + false, + "*", + Collections. emptySet(), + Collections.> emptyList(), + new PagingRequest(100)); + List page = contentChildren.getPage(); + assertMissesNames(page, + folderName); + assertContainsNames(page, + contentName); + } + + } + + @Test + public void testListWithIgnores() throws Exception + { + NodeRef vf = createVirtualizedFolder(testRootFolder.getNodeRef(), + "TestVirtualFileFolderService_testVirtualFolderVirtualChild", + TEST_TEMPLATE_3_JSON_SYS_PATH); + NodeRef node2 = nodeService.getChildByName(vf, + ContentModel.ASSOC_CHILDREN, + "Node2"); + + final String contentName = "ContentVirtualChild"; + NodeRef contentNodeRef = createContent(node2, + contentName).getChildRef(); + + CheckOutCheckInService checkOutCheckInService = ctx.getBean("checkOutCheckInService", + CheckOutCheckInService.class); + + checkOutCheckInService.checkout(contentNodeRef); + + Set searchTypeQNames = Collections.emptySet(); + Set ignoreAspectQNames = Collections.singleton(ContentModel.ASPECT_CHECKED_OUT); + List> sortProps = Collections.> emptyList(); + PagingRequest pagingRequest = new PagingRequest(100); + PagingResults node2List = fileAndFolderService.list(node2, + searchTypeQNames, + ignoreAspectQNames, + sortProps, + pagingRequest); + + assertEquals(1, + node2List.getPage().size()); + + } + + @Test + public void testCreateTempFile() throws Exception + { + NodeRef vf = createVirtualizedFolder(testRootFolder.getNodeRef(), + "TestVirtualFileFolderService_testVirtualFolderVirtualChild", + TEST_TEMPLATE_3_JSON_SYS_PATH); + NodeRef node2 = nodeService.getChildByName(vf, + ContentModel.ASSOC_CHILDREN, + "Node2"); + String contentName = "ContentVirtualChild"; + createContent(node2, + contentName); + NodeRef childByName = nodeService.getChildByName(node2, + ContentModel.ASSOC_CHILDREN, + contentName); + + // TODO to test with minimized nodeRef id when minimisation is finished + File file = File.createTempFile("dedededede", + ".tmp", + TempFileProvider.getTempDir()); + assertNotNull(file); + } + + @Test + public void testRename() throws Exception + { + NodeRef vf = createVirtualizedFolder(testRootFolder.getNodeRef(), + "TestVirtualFileFolderService_testVirtualFolderVirtualChild", + TEST_TEMPLATE_3_JSON_SYS_PATH); + NodeRef node2 = nodeService.getChildByName(vf, + ContentModel.ASSOC_CONTAINS, + "Node2"); + String contentName = "ContentVirtualChild"; + createContent(node2, + contentName); + NodeRef childByName = nodeService.getChildByName(node2, + ContentModel.ASSOC_CONTAINS, + contentName); + //rename file in virtual context + FileInfo renamedFileInfo = fileAndFolderService.rename(childByName, + NEW_FILE_NAME_1); + assertNotNull(renamedFileInfo); + assertEquals(NEW_FILE_NAME_1, + nodeService.getProperty(childByName, + ContentModel.PROP_NAME)); + assertNull(nodeService.getChildByName(node2, + ContentModel.ASSOC_CONTAINS, + contentName)); + assertNull(nodeService.getChildByName(vf, + ContentModel.ASSOC_CONTAINS, + contentName)); + assertNotNull(nodeService.getChildByName(node2, + ContentModel.ASSOC_CONTAINS, + NEW_FILE_NAME_1)); + assertNotNull(nodeService.getChildByName(vf, + ContentModel.ASSOC_CONTAINS, + NEW_FILE_NAME_1)); + + //rename physical file + childByName = nodeService.getChildByName(vf, + ContentModel.ASSOC_CONTAINS, + NEW_FILE_NAME_1); + renamedFileInfo = fileAndFolderService.rename(childByName, + NEW_FILE_NAME_2); + assertNotNull(renamedFileInfo); + assertEquals(NEW_FILE_NAME_2, + nodeService.getProperty(childByName, + ContentModel.PROP_NAME)); + assertNull(nodeService.getChildByName(node2, + ContentModel.ASSOC_CONTAINS, + NEW_FILE_NAME_1)); + assertNull(nodeService.getChildByName(vf, + ContentModel.ASSOC_CONTAINS, + NEW_FILE_NAME_1)); + assertNotNull(nodeService.getChildByName(node2, + ContentModel.ASSOC_CONTAINS, + NEW_FILE_NAME_2)); + assertNotNull(nodeService.getChildByName(vf, + ContentModel.ASSOC_CONTAINS, + NEW_FILE_NAME_2)); + + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/bundle/VirtualLockableAspectInterceptorExtensionTest.java b/source/test-java/org/alfresco/repo/virtual/bundle/VirtualLockableAspectInterceptorExtensionTest.java new file mode 100644 index 0000000000..185294710d --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/bundle/VirtualLockableAspectInterceptorExtensionTest.java @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.bundle; + +import org.alfresco.model.ContentModel; +import org.alfresco.repo.content.MimetypeMap; +import org.alfresco.repo.lock.mem.Lifetime; +import org.alfresco.repo.virtual.VirtualizationIntegrationTest; +import org.alfresco.service.cmr.lock.LockService; +import org.alfresco.service.cmr.lock.LockType; +import org.alfresco.service.cmr.repository.NodeRef; +import org.junit.Test; + +public class VirtualLockableAspectInterceptorExtensionTest extends VirtualizationIntegrationTest +{ + private LockService lockService; + + private NodeRef originalContentNodeRef; + + @Override + protected void setUp() throws Exception + { + super.setUp(); + lockService = ctx.getBean("lockService", + LockService.class); + NodeRef node = nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + "Node1"); + originalContentNodeRef = createContent(node, + "originalContentName", + "0", + MimetypeMap.MIMETYPE_TEXT_PLAIN, + "UTF-8").getChildRef(); + } + + @Test + public void testHasLockableAspect() throws Exception + { + assertFalse("Node should not be reported as lockable", + nodeService.hasAspect(originalContentNodeRef, + ContentModel.ASPECT_LOCKABLE)); + + lockService.lock(originalContentNodeRef, + LockType.WRITE_LOCK, + 10, + Lifetime.EPHEMERAL, + null); + + assertTrue("Node should be reported as lockable", + nodeService.hasAspect(originalContentNodeRef, + ContentModel.ASPECT_LOCKABLE)); + } + + @Test + public void testGetAspectsHasLockableAspect() throws Exception + { + assertFalse("Node should not contain lockable aspect", + nodeService.getAspects(originalContentNodeRef).contains(ContentModel.ASPECT_LOCKABLE)); + + lockService.lock(originalContentNodeRef, + LockType.WRITE_LOCK, + 10, + Lifetime.EPHEMERAL, + null); + + assertTrue("Node should contain lockable aspect", + nodeService.getAspects(originalContentNodeRef).contains(ContentModel.ASPECT_LOCKABLE)); + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/bundle/VirtualNodeServiceExtensionTest.java b/source/test-java/org/alfresco/repo/virtual/bundle/VirtualNodeServiceExtensionTest.java new file mode 100644 index 0000000000..2472fd54e5 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/bundle/VirtualNodeServiceExtensionTest.java @@ -0,0 +1,1208 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.bundle; + +import static org.junit.Assert.*; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.alfresco.model.ContentModel; +import org.alfresco.model.RenditionModel; +import org.alfresco.repo.content.MimetypeMap; +import org.alfresco.repo.download.DownloadModel; +import org.alfresco.repo.download.DownloadStorage; +import org.alfresco.repo.node.integrity.IntegrityChecker; +import org.alfresco.repo.security.authentication.AuthenticationUtil; +import org.alfresco.repo.virtual.VirtualContentModel; +import org.alfresco.repo.virtual.VirtualizationIntegrationTest; +import org.alfresco.repo.virtual.config.NodeRefExpression; +import org.alfresco.repo.virtual.ref.GetActualNodeRefMethod; +import org.alfresco.repo.virtual.ref.GetParentReferenceMethod; +import org.alfresco.repo.virtual.ref.Protocols; +import org.alfresco.repo.virtual.ref.Reference; +import org.alfresco.repo.virtual.ref.ReferenceEncodingException; +import org.alfresco.repo.virtual.ref.VirtualProtocol; +import org.alfresco.repo.virtual.store.VirtualStore; +import org.alfresco.service.cmr.repository.AssociationRef; +import org.alfresco.service.cmr.repository.ChildAssociationRef; +import org.alfresco.service.cmr.repository.CopyService; +import org.alfresco.service.cmr.repository.InvalidNodeRefException; +import org.alfresco.service.cmr.repository.NodeRef; +import org.alfresco.service.cmr.repository.Path; +import org.alfresco.service.namespace.NamespaceService; +import org.alfresco.service.namespace.QName; +import org.alfresco.service.namespace.QNamePattern; +import org.alfresco.service.namespace.RegexQNamePattern; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Ignore; +import org.junit.Test; + +public class VirtualNodeServiceExtensionTest extends VirtualizationIntegrationTest +{ + private static final String NODE2TEST1_2_TXT = "NODE2test1_2.txt"; + + private static Log logger = LogFactory.getLog(VirtualNodeServiceExtensionTest.class); + + private VirtualStore virtualStore; + + private DownloadStorage downloadStorage; + + private QName[] node2ChildrenQNames; + + private QName[] rootChildrenQNames; + + private QName[] node2_1ChildrenQNames; + + private NodeRef node2Test1_2_TXTNodeRef; + + @Override + protected void setUp() throws Exception + { + // TODO:is the store really needed when testing node service ? why ? + super.setUp(); + virtualStore = ctx.getBean("virtualStore", + VirtualStore.class); + downloadStorage = ctx.getBean("downloadStorage", + DownloadStorage.class); + } + + @Test + public void testCreateNode_withFilingRuleAspects() throws Exception + { + NodeRef assocNode2 = nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + "Node2"); + NodeRef assocNode2_1 = nodeService.getChildByName(assocNode2, + ContentModel.ASSOC_CONTAINS, + "Node2_1"); + ChildAssociationRef childAssocRef = createContent(assocNode2_1, + "ContentWithAspects"); + assertNewVirtualChildAssocRef(assocNode2_1, + childAssocRef); + + nodeService.hasAspect(childAssocRef.getChildRef(), + ContentModel.ASPECT_AUTHOR); + + nodeService.hasAspect(childAssocRef.getChildRef(), + ContentModel.ASPECT_DUBLINCORE); + } + + @Test + public void testCreateNode_noFilingRule() throws Exception + { + NodeRef testTemplate2 = createVirtualizedFolder(testRootFolder.getNodeRef(), + "aVFTestTemplate2", + TEST_TEMPLATE_2_JSON_SYS_PATH); + NodeRef testTemplate2Node2 = nodeService.getChildByName(testTemplate2, + ContentModel.ASSOC_CONTAINS, + "Node2"); + + try + { + createContent(testTemplate2Node2, + "shouldNotBeCreated"); + fail("Should not be able to create node in a readonly context."); + } + catch (InvalidNodeRefException e) + { + logger.info("Succesfully denied creation in readonl", + e); + } + } + + @Test + public void testCreate_NodeProtocolParent() throws Exception + { + NodeRef assocNode2 = nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + "Node2"); + NodeRef assocNode2_1 = nodeService.getChildByName(assocNode2, + ContentModel.ASSOC_CONTAINS, + "Node2_1"); + ChildAssociationRef childAssocRef = createContent(assocNode2_1, + "Content"); + NodeRef node = childAssocRef.getChildRef(); + assertTrue(Reference.isReference(node)); + assertTrue(Reference.fromNodeRef(node).getProtocol().equals(Protocols.NODE.protocol)); + + QName nodeTypeQName = ContentModel.TYPE_THUMBNAIL; + QName assocQName = QName.createQName("cm", "contentThumbnail", environment.getNamespacePrefixResolver()); + QName assocTypeQName = RenditionModel.ASSOC_RENDITION; + ChildAssociationRef assoc = nodeService.createNode(node, + assocTypeQName, + assocQName, + nodeTypeQName); + NodeRef virtualRenditionNode = assoc.getChildRef(); + NodeRef virtualRenditionParent = assoc.getParentRef(); + assertEquals(node, virtualRenditionParent); + + Reference child = Reference.fromNodeRef(virtualRenditionNode); + Reference parent = Reference.fromNodeRef(virtualRenditionParent); + NodeRef physicalRenditionNode = child.execute(new GetActualNodeRefMethod(environment)); + NodeRef physicalRenditionParent = parent.execute(new GetActualNodeRefMethod(environment)); + List refs = nodeService.getChildAssocs(physicalRenditionParent); + assertEquals(physicalRenditionNode, refs.get(0).getChildRef()); // the association exists for the physical nodes + + List virtualRefs = nodeService.getChildAssocs(virtualRenditionParent); + assertEquals(physicalRenditionNode, virtualRefs.get(0).getChildRef()); // the association exists for the virtual nodes + } + + @Test + public void testCreateNode_CM_528_folder_filing_type() throws Exception + { + NodeRef testTemplate5 = createVirtualizedFolder(testRootFolder.getNodeRef(), + "aVFTestTemplate5", + TEST_TEMPLATE_5_JSON_SYS_PATH); + NodeRef folderFilingTypeNode = nodeService.getChildByName(testTemplate5, + ContentModel.ASSOC_CONTAINS, + "FolderFilingType"); + + ChildAssociationRef forcedCmContentAssocRef = createContent(folderFilingTypeNode, + "forcedCmContent"); + NodeRef forcedCmContent = forcedCmContentAssocRef.getChildRef(); + + QName actualType = nodeService.getType(forcedCmContent); + assertEquals(ContentModel.TYPE_CONTENT, + actualType); + } + + @Test + public void testCreateNode() throws Exception + { + + assertTrue(virtualStore.canVirtualize(virtualFolder1NodeRef)); + + Reference semiVirtualFolder = virtualStore.virtualize(virtualFolder1NodeRef); + assertNotNull(semiVirtualFolder); + assertTrue(semiVirtualFolder.getProtocol() instanceof VirtualProtocol); + + Reference firstChild = virtualStore.getChildByName(semiVirtualFolder, + ContentModel.ASSOC_CONTAINS, + "Node1"); + assertNotNull(firstChild); + + Reference secondChild = virtualStore.getChildByName(semiVirtualFolder, + ContentModel.ASSOC_CONTAINS, + "Node2"); + assertNotNull(secondChild); + + HashMap properties = new HashMap(); + properties.put(ContentModel.PROP_NAME, + "testfile.txt"); + QName assocQName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, + QName.createValidLocalName("testfile.txt")); + authenticationComponent.setCurrentUser(AuthenticationUtil.getAdminUserName()); + // add testfile.txt to first virtual child + + createNode(firstChild, + assocQName, + properties); + assertNotNull(nodeService.getChildByName(firstChild.toNodeRef(), + ContentModel.ASSOC_CONTAINS, + "testfile.txt")); + createNode(firstChild, + assocQName, + properties); + assertNotNull(nodeService.getChildByName(firstChild.toNodeRef(), + ContentModel.ASSOC_CONTAINS, + "testfile-1.txt")); + + // add testfile.txt to second virtual child + createNode(secondChild, + assocQName, + properties); + assertNotNull(nodeService.getChildByName(secondChild.toNodeRef(), + ContentModel.ASSOC_CONTAINS, + "testfile-2.txt")); + createNode(secondChild, + assocQName, + properties); + assertNotNull(nodeService.getChildByName(secondChild.toNodeRef(), + ContentModel.ASSOC_CONTAINS, + "testfile-3.txt")); + + // add again to first virtual child starting from the last index found + // (this is the index that comes from + // upload-post.js) + properties.put(ContentModel.PROP_NAME, + "testfile-2.txt"); + assocQName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, + QName.createValidLocalName("testfile-2.txt")); + createNode(firstChild, + assocQName, + properties); + assertNotNull(nodeService.getChildByName(firstChild.toNodeRef(), + ContentModel.ASSOC_CONTAINS, + "testfile-4.txt")); + + // test create node for actual node starting from the last index found + // (this is the index that comes from + // upload-post.js) + properties.put(ContentModel.PROP_NAME, + "testfile-5.txt"); + assocQName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, + QName.createValidLocalName("testfile-5.txt")); + nodeService.createNode(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + assocQName, + ContentModel.TYPE_CONTENT, + properties).getChildRef(); + assertNotNull(nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + "testfile-5.txt")); + + properties.put(ContentModel.PROP_NAME, + "testfile-6.txt"); + assocQName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, + QName.createValidLocalName("testfile-6.txt")); + nodeService.createNode(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + assocQName, + ContentModel.TYPE_CONTENT, + properties).getChildRef(); + assertNotNull(nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + "testfile-6.txt")); + + // add again to second child starting from the last index found (this is + // the index that comes from + // upload-post.js) + properties.put(ContentModel.PROP_NAME, + "testfile-4.txt"); + assocQName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, + QName.createValidLocalName("testfile-4.txt")); + nodeService.createNode(secondChild.toNodeRef(), + ContentModel.ASSOC_CONTAINS, + assocQName, + ContentModel.TYPE_CONTENT, + properties).getChildRef(); + assertNotNull(nodeService.getChildByName(secondChild.toNodeRef(), + ContentModel.ASSOC_CONTAINS, + "testfile-7.txt")); + + // test situation when file name is of form testfile1-1.txt + properties.put(ContentModel.PROP_NAME, + "testfile1-1.txt"); + assocQName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, + QName.createValidLocalName("testfile1-1.txt")); + nodeService.createNode(secondChild.toNodeRef(), + ContentModel.ASSOC_CONTAINS, + assocQName, + ContentModel.TYPE_CONTENT, + properties).getChildRef(); + assertNotNull(nodeService.getChildByName(secondChild.toNodeRef(), + ContentModel.ASSOC_CONTAINS, + "testfile1-1.txt")); + + nodeService.createNode(secondChild.toNodeRef(), + ContentModel.ASSOC_CONTAINS, + assocQName, + ContentModel.TYPE_CONTENT, + properties).getChildRef(); + assertNotNull(nodeService.getChildByName(secondChild.toNodeRef(), + ContentModel.ASSOC_CONTAINS, + "testfile1-1-1.txt")); + + } + + @Test + @Ignore("CM-533 Suppress options to create folders in a virtual folder (repo)") + public void ignore_testCreateFilingIrregularNode() throws Exception + { + NodeRef vf = createVirtualizedFolder(testRootFolder.getNodeRef(), + "testCreateFolderOnContentFilingRule", + TEST_TEMPLATE_3_JSON_SYS_PATH); + { + NodeRef node1 = nodeService.getChildByName(vf, + ContentModel.ASSOC_CHILDREN, + "Node1"); + HashMap properties = new HashMap(); + properties.put(ContentModel.PROP_NAME, + "Folder1"); + QName assocQName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, + QName.createValidLocalName("Folder1")); + + ChildAssociationRef folderChilAssoc = nodeService.createNode(node1, + ContentModel.ASSOC_CONTAINS, + assocQName, + ContentModel.TYPE_FOLDER, + properties); + NodeRef folderChildRef = folderChilAssoc.getChildRef(); + assertEquals(ContentModel.TYPE_FOLDER, + environment.getType(folderChildRef)); + assertEquals("Node1_content_FR", + environment.getProperties(folderChildRef).get(ContentModel.PROP_DESCRIPTION)); + } + + { + NodeRef node2 = nodeService.getChildByName(vf, + ContentModel.ASSOC_CHILDREN, + "Node2"); + HashMap properties = new HashMap(); + properties.put(ContentModel.PROP_NAME, + "Content2"); + QName assocQName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, + QName.createValidLocalName("Content2")); + + ChildAssociationRef folderChilAssoc = nodeService.createNode(node2, + ContentModel.ASSOC_CONTAINS, + assocQName, + ContentModel.TYPE_CONTENT, + properties); + NodeRef folderChildRef = folderChilAssoc.getChildRef(); + assertEquals(ContentModel.TYPE_CONTENT, + environment.getType(folderChildRef)); + assertEquals("Node2_folder_FR", + environment.getProperties(folderChildRef).get(ContentModel.PROP_DESCRIPTION)); + } + } + + private void createNode(Reference reference, final QName assocQName, HashMap properties) + throws ReferenceEncodingException + { + ChildAssociationRef childAssocsRef = nodeService.createNode(reference.toNodeRef(), + ContentModel.ASSOC_CONTAINS, + assocQName, + ContentModel.TYPE_CONTENT, + properties); + assertNewVirtualChildAssocRef(reference, + childAssocsRef); + } + + /** + * Assets that the given {@link ChildAssociationRef} was created within the + * given virtualizable nodeRef container reference. + * + * @param nodeRef + * @param childAssocsRef + */ + private void assertNewVirtualChildAssocRef(NodeRef nodeRef, ChildAssociationRef childAssocsRef) + { + assertTrue(Reference.isReference(nodeRef)); + assertNewVirtualChildAssocRef(Reference.fromNodeRef(nodeRef), + childAssocsRef); + } + + /** + * Assets that the given {@link ChildAssociationRef} was created within the + * given container {@link Reference}. + * + * @param nodeRef + * @param childAssocsRef + */ + private void assertNewVirtualChildAssocRef(Reference reference, ChildAssociationRef childAssocsRef) + { + assertNotNull(childAssocsRef); + NodeRef childNodeRef = childAssocsRef.getChildRef(); + NodeRef parentNodeRef = childAssocsRef.getParentRef(); + + assertTrue(Reference.isReference(parentNodeRef)); + assertEquals(reference, + Reference.fromNodeRef(parentNodeRef)); + + assertTrue(Reference.isReference(childNodeRef)); + Reference.fromNodeRef(childNodeRef); + Reference childReference = Reference.fromNodeRef(childNodeRef); + Reference parent = childReference.execute(new GetParentReferenceMethod()); + assertEquals(reference, + parent); + } + + @Test + public void testGetPath() throws Exception + { + NodeRef node2 = nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CHILDREN, + "Node2"); + assertNotNull(node2); + Path node2Path = nodeService.getPath(node2); + assertNotNull(node2Path); + assertEquals("/app:company_home/cm:TestFolder/cm:VirtualFolder1/vm:Node2", + node2Path.toPrefixString(environment.getNamespacePrefixResolver())); + } + + @Test + public void testNodeProtocolReferencePath() throws Exception + { + NodeRef node2 = nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + "Node2"); + + HashMap properties = new HashMap(); + properties.put(ContentModel.PROP_NAME, + "testfile.txt"); + QName assocQName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, + QName.createValidLocalName("testfile.txt")); + + // add testfile.txt to first virtual child + nodeService.createNode(node2, + ContentModel.ASSOC_CONTAINS, + assocQName, + ContentModel.TYPE_CONTENT, + properties); + + NodeRef childRef = nodeService.getChildByName(node2, + ContentModel.ASSOC_CONTAINS, + "testfile.txt"); + Path path = nodeService.getPath(childRef); + assertEquals("/app:company_home/cm:TestFolder/cm:VirtualFolder1/vm:Node2/cm:testfile.txt", + path.toPrefixString(environment.getNamespacePrefixResolver())); + + NodeRef physicalNode = nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + "testfile.txt"); + assertNotNull(physicalNode); + + Path physicalPath = nodeService.getPath(physicalNode); + + assertEquals("/app:company_home/cm:TestFolder/cm:VirtualFolder1/cm:testfile.txt", + physicalPath.toPrefixString(environment.getNamespacePrefixResolver())); + + NodeRef node2_1 = nodeService.getChildByName(node2, + ContentModel.ASSOC_CONTAINS, + "Node2_1"); + assertNotNull(node2_1); + + nodeService.createNode(node2_1, + ContentModel.ASSOC_CONTAINS, + assocQName, + ContentModel.TYPE_CONTENT, + properties); + + NodeRef childRef_1 = nodeService.getChildByName(node2_1, + ContentModel.ASSOC_CONTAINS, + "testfile-1.txt"); + Path path_1 = nodeService.getPath(childRef_1); + assertEquals("/app:company_home/cm:TestFolder/cm:VirtualFolder1/vm:Node2/vm:Node2_1/cm:testfile-1.txt", + path_1.toPrefixString(environment.getNamespacePrefixResolver())); + } + + private void setUpTestAssociations(NodeRef actualNodeRef) + { + rootChildrenQNames = new QName[13]; + rootChildrenQNames[0] = QName.createQNameWithValidLocalName(VirtualContentModel.VIRTUAL_CONTENT_MODEL_1_0_URI, + "Node2"); + rootChildrenQNames[1] = QName.createQNameWithValidLocalName(VirtualContentModel.VIRTUAL_CONTENT_MODEL_1_0_URI, + "Node1"); + + NodeRef node2 = nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + "Node2"); + + String node2ChildNameString = "test1_2.txt"; + ChildAssociationRef node2ChildAssoc = createContent(node2, + node2ChildNameString); + node2Test1_2_TXTNodeRef = node2ChildAssoc.getChildRef(); + rootChildrenQNames[2] = QName.createQNameWithValidLocalName(NamespaceService.CONTENT_MODEL_1_0_URI, + node2ChildNameString); + + nodeService.setProperty(node2ChildAssoc.getChildRef(), + ContentModel.PROP_TITLE, + NODE2TEST1_2_TXT); + + node2ChildrenQNames = new QName[2]; + node2ChildrenQNames[0] = QName.createQNameWithValidLocalName(VirtualContentModel.VIRTUAL_CONTENT_MODEL_1_0_URI, + "Node2_1"); + node2ChildrenQNames[1] = node2ChildAssoc.getQName(); + + NodeRef node2_1 = nodeService.getChildByName(node2, + ContentModel.ASSOC_CONTAINS, + "Node2_1"); + + node2_1ChildrenQNames = new QName[10]; + for (int i = 1; i <= 10; i++) + { + ChildAssociationRef childAssoc = createContent(node2_1, + "test" + i + "_2_1.txt"); + rootChildrenQNames[2 + i] = QName.createQNameWithValidLocalName(NamespaceService.CONTENT_MODEL_1_0_URI, + childAssoc.getQName().getLocalName()); + node2_1ChildrenQNames[i - 1] = childAssoc.getQName(); + } + } + + protected QName[] copyOf(QName[] from, int count) + { + QName[] tmp = new QName[count]; + + if (count < from.length) + { + System.arraycopy(from, + 0, + tmp, + 0, + count); + } + else + { + System.arraycopy(from, + 0, + tmp, + 0, + from.length); + } + + return tmp; + } + + private ChildAssociationRef findActualAssocPeer(ChildAssociationRef virtualAssoc, NodeRef actualParentNodeRef) + { + List actualAssocs = nodeService.getChildAssocs(actualParentNodeRef); + NodeRef virtualChildNodeRef = virtualAssoc.getChildRef(); + assertTrue(Reference.isReference(virtualChildNodeRef)); + NodeRef materialNodeRef = virtualStore.materialize(Reference.fromNodeRef(virtualChildNodeRef)); + + for (ChildAssociationRef actualAssocRef : actualAssocs) + { + if (materialNodeRef.equals(actualAssocRef.getChildRef())) + { + if (virtualAssoc.getQName().getLocalName().equals(actualAssocRef.getQName().getLocalName()) + && virtualAssoc.getTypeQName().equals(actualAssocRef.getTypeQName())) + { + return actualAssocRef; + } + } + } + + return null; + } + + @Test + public void testRemoveChildAssoc_1() throws Exception + { + NodeRef node2 = nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + "Node2"); + + ChildAssociationRef node2ChildAssoc = createContent(node2, + "TestPresentation4_pdf_removeAssoc"); + + assertNotNull(findActualAssocPeer(node2ChildAssoc, + virtualFolder1NodeRef)); + + boolean removed = nodeService.removeChildAssociation(node2ChildAssoc); + + assertTrue("No association", + removed); + + assertNull(findActualAssocPeer(node2ChildAssoc, + virtualFolder1NodeRef)); + } + + @Test + public void testGetChildAssocs_1() throws Exception + { + // semi-virtual folder with 2 virtual folder nodes + List childAssocs = nodeService.getChildAssocs(virtualFolder1NodeRef); + assertEquals(2, + childAssocs.size()); + + setUpTestAssociations(virtualFolder1NodeRef); + + NodeRef node2 = nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + "Node2"); + + NodeRef node2_1 = nodeService.getChildByName(node2, + ContentModel.ASSOC_CONTAINS, + "Node2_1"); + + childAssocs = nodeService.getChildAssocs(virtualFolder1NodeRef); + assertEquals(13, + childAssocs.size()); + assertAssocNames(childAssocs, + rootChildrenQNames); + + // one virtual folder with a virtual folder child and a virtual node + // reference child + if (logger.isDebugEnabled()) + { + logger.debug("Getting children of node2 " + node2); + } + childAssocs = nodeService.getChildAssocs(node2); + if (logger.isDebugEnabled()) + { + logger.debug("Got children of node2 " + childAssocs); + } + assertEquals(2, + childAssocs.size()); + + // one virtual folder with a virtual node reference child + childAssocs = nodeService.getChildAssocs(node2_1); + assertEquals(10, + childAssocs.size()); + assertAssocNames(childAssocs, + node2_1ChildrenQNames); + + } + + protected void assertAssocNames(List assocs, QName... expectedNames) + { + List actualNames = new LinkedList<>(); + for (ChildAssociationRef childAssociationRef : assocs) + { + actualNames.add(childAssociationRef.getQName()); + } + + assertEquals(expectedNames.length, + actualNames.size()); + for (int i = 0; i < expectedNames.length; i++) + { + assertTrue(expectedNames[i] + " assoc name was expected within " + actualNames, + actualNames.contains(expectedNames[i])); + actualNames.remove(expectedNames[i]); + } + } + + @Test + public void testGetChildAssocs_2() throws Exception + { + // semi-virtual folder with 2 virtual folder nodes + List childAssocs = nodeService.getChildAssocs(virtualFolder1NodeRef); + assertEquals(2, + childAssocs.size()); + + setUpTestAssociations(virtualFolder1NodeRef); + + NodeRef node2 = nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + "Node2"); + + NodeRef node2_1 = nodeService.getChildByName(node2, + ContentModel.ASSOC_CONTAINS, + "Node2_1"); + + childAssocs = nodeService.getChildAssocs(node2, + ContentModel.ASSOC_ARCHIVED_LINK, + ContentModel.ASSOC_ARCHIVED_LINK, + 7, + true); + + assertTrue(childAssocs.isEmpty()); + + childAssocs = nodeService.getChildAssocs(node2, + RegexQNamePattern.MATCH_ALL, + RegexQNamePattern.MATCH_ALL, + 7, + true); + assertEquals(2, + childAssocs.size()); + + assertAssocNames(childAssocs, + copyOf(node2ChildrenQNames, + 2)); + + childAssocs = nodeService.getChildAssocs(virtualFolder1NodeRef, + + RegexQNamePattern.MATCH_ALL, + new QNamePattern() + { + + @Override + public boolean isMatch(QName qname) + { + return qname.getLocalName().startsWith("test") + && qname.getLocalName().endsWith("txt"); + } + }, + 15, + true); + + assertEquals(11, + childAssocs.size()); + + // one virtual folder with a virtual folder child and a virtual node + // reference child + if (logger.isDebugEnabled()) + { + logger.debug("Getting children of node2 " + node2); + } + childAssocs = nodeService.getChildAssocs(node2, + RegexQNamePattern.MATCH_ALL, + RegexQNamePattern.MATCH_ALL, + 2, + true); + if (logger.isDebugEnabled()) + { + logger.debug("Got children of node2 " + childAssocs); + } + assertEquals(2, + childAssocs.size()); + + // one virtual folder with a virtual node reference child + childAssocs = nodeService.getChildAssocs(node2_1, + RegexQNamePattern.MATCH_ALL, + RegexQNamePattern.MATCH_ALL, + 10, + true); + assertEquals(10, + childAssocs.size()); + + assertAssocNames(childAssocs, + copyOf(node2_1ChildrenQNames, + 10)); + + } + + @Test + public void testGetChildAssocs_3() throws Exception + { + // semi-virtual folder with 2 virtual folder nodes + List childAssocs = nodeService.getChildAssocs(virtualFolder1NodeRef); + assertEquals(2, + childAssocs.size()); + + setUpTestAssociations(virtualFolder1NodeRef); + + List folderAssocs = nodeService + .getChildAssocs(virtualFolder1NodeRef, + new HashSet<>(Arrays.asList(ContentModel.TYPE_FOLDER))); + + assertEquals(2, + folderAssocs.size()); + + List contentAssocs = nodeService + .getChildAssocs(virtualFolder1NodeRef, + new HashSet<>(Arrays.asList(ContentModel.TYPE_CONTENT))); + + assertEquals(11, + contentAssocs.size()); + } + + @Test + public void testGetChildAssocsByPropertyValue() throws Exception + { + setUpTestAssociations(virtualFolder1NodeRef); + + NodeRef node2 = nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + "Node2"); + { + List children = nodeService.getChildAssocsByPropertyValue(node2, + ContentModel.PROP_TITLE, + NODE2TEST1_2_TXT); + assertNotNull(children); + assertEquals(1, + children.size()); + assertEquals(node2Test1_2_TXTNodeRef, + children.get(0).getChildRef()); + + } + + { + List children = nodeService.getChildAssocsByPropertyValue(node2, + ContentModel.PROP_TITLE, + "non" + NODE2TEST1_2_TXT); + assertTrue(children.isEmpty()); + } + } + + @Test + public void testGetProperties() throws Exception + { + NodeRef template2VF = createVirtualizedFolder(testRootFolder.getNodeRef(), + VIRTUAL_FOLDER_2_NAME, + TEST_TEMPLATE_2_JSON_SYS_PATH); + + final String expectedDescription = "ParentDescription"; + nodeService.setProperty(template2VF, + ContentModel.PROP_DESCRIPTION, + expectedDescription); + + NodeRef node1 = nodeService.getChildByName(template2VF, + ContentModel.ASSOC_CONTAINS, + "Node1"); + + assertVirtualNode(node1); + + NodeRef node2 = nodeService.getChildByName(template2VF, + ContentModel.ASSOC_CONTAINS, + "Node2"); + + Map expectedProperties = new HashMap<>(); + expectedProperties.put(ContentModel.PROP_DESCRIPTION, + expectedDescription); + assertVirtualNode(node2, + expectedProperties); + } + + @Test + public void testCreateAssociation() throws Exception + { + NodeRef createDownloadNode = createDownloadNode(); + NodeRef node2 = nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + "Node2"); + nodeService.createAssociation(createDownloadNode, + node2, + DownloadModel.ASSOC_REQUESTED_NODES); + + } + + @Test + public void testGetParentAssocs() throws Exception + { + NodeRef node2 = nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + "Node2"); + + { + List node2Parents = nodeService.getParentAssocs(node2); + assertNotNull(node2Parents); + assertTrue(!node2Parents.isEmpty()); + ChildAssociationRef firstAssoc = node2Parents.get(0); + NodeRef child = firstAssoc.getChildRef(); + NodeRef parent = firstAssoc.getParentRef(); + + assertEquals(ContentModel.ASSOC_CONTAINS, + firstAssoc.getTypeQName()); + assertEquals(node2, + child); + assertEquals(virtualFolder1NodeRef, + parent); + assertNotNull(firstAssoc.getQName()); + assertEquals(QName.createQNameWithValidLocalName(VirtualContentModel.VIRTUAL_CONTENT_MODEL_1_0_URI, + "Node2"), + firstAssoc.getQName()); + } + + { + List node2Parents = nodeService + .getParentAssocs(node2, + RegexQNamePattern.MATCH_ALL, + new RegexQNamePattern(VirtualContentModel.VIRTUAL_CONTENT_MODEL_1_0_URI, + "Node.")); + assertNotNull(node2Parents); + assertTrue(!node2Parents.isEmpty()); + ChildAssociationRef firstAssoc = node2Parents.get(0); + NodeRef child = firstAssoc.getChildRef(); + NodeRef parent = firstAssoc.getParentRef(); + + assertEquals(ContentModel.ASSOC_CONTAINS, + firstAssoc.getTypeQName()); + assertEquals(node2, + child); + assertEquals(virtualFolder1NodeRef, + parent); + assertNotNull(firstAssoc.getQName()); + assertEquals(QName.createQName(VirtualContentModel.VIRTUAL_CONTENT_MODEL_1_0_URI, + "Node2"), + firstAssoc.getQName()); + } + + { + List node2Parents = nodeService + .getParentAssocs(node2, + RegexQNamePattern.MATCH_ALL, + new RegexQNamePattern(VirtualContentModel.VIRTUAL_CONTENT_MODEL_1_0_URI, + "Foo.")); + assertNotNull(node2Parents); + assertTrue(node2Parents.isEmpty()); + } + + } + + @Test + public void testGetSourceAssocs_download() throws Exception + { + NodeRef node2 = nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + "Node2"); + + List sourceAssocs = null; + sourceAssocs = nodeService.getSourceAssocs(node2, + RegexQNamePattern.MATCH_ALL); + assertEquals(0, + sourceAssocs.size()); + + sourceAssocs = nodeService.getSourceAssocs(node2, + DownloadModel.ASSOC_REQUESTED_NODES); + assertEquals(0, + sourceAssocs.size()); + + // one virtual noderef + NodeRef createDownloadNode = createDownloadNode(); + nodeService.createAssociation(createDownloadNode, + node2, + DownloadModel.ASSOC_REQUESTED_NODES); + sourceAssocs = nodeService.getSourceAssocs(node2, + DownloadModel.ASSOC_REQUESTED_NODES); + + // sources are deliberately not virtualized due to performance and + // complexity issues + assertEquals(0, + sourceAssocs.size()); + + } + + @Test + public void testGetTargetAssocs_download() throws Exception + { + + NodeRef node2 = nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + "Node2"); + + List targetAssocs = nodeService.getTargetAssocs(node2, + DownloadModel.ASSOC_REQUESTED_NODES); + assertEquals(0, + targetAssocs.size()); + + // one virtual noderef + NodeRef createDownloadNode = createDownloadNode(); + nodeService.createAssociation(createDownloadNode, + node2, + DownloadModel.ASSOC_REQUESTED_NODES); + targetAssocs = nodeService.getTargetAssocs(createDownloadNode, + ContentModel.ASSOC_CONTAINS); + assertEquals(0, + targetAssocs.size()); + targetAssocs = nodeService.getTargetAssocs(createDownloadNode, + DownloadModel.ASSOC_REQUESTED_NODES); + assertEquals(1, + targetAssocs.size()); + + // 2 virtual node ref ...associations have to be created again since + // they are removed after they are obtained in + // order to cleanup temp node refs from repository. + NodeRef node2_1 = nodeService.getChildByName(node2, + ContentModel.ASSOC_CONTAINS, + "Node2_1"); + nodeService.createAssociation(createDownloadNode, + node2, + DownloadModel.ASSOC_REQUESTED_NODES); + nodeService.createAssociation(createDownloadNode, + node2_1, + DownloadModel.ASSOC_REQUESTED_NODES); + targetAssocs = nodeService.getTargetAssocs(createDownloadNode, + ContentModel.ASSOC_CONTAINS); + assertEquals(0, + targetAssocs.size()); + for (int i = 0; i < 2; i++) + { + targetAssocs = nodeService.getTargetAssocs(createDownloadNode, + DownloadModel.ASSOC_REQUESTED_NODES); + assertEquals("Try # " + (i + 1), + 2, + targetAssocs.size()); + } + + List targets = new LinkedList<>(); + for (AssociationRef assocs : targetAssocs) + { + targets.add(assocs.getTargetRef()); + } + + assertTrue(targets.contains(node2)); + + assertTrue(targets.contains(node2_1)); + + NodeRefExpression downloadAsocsFolderExpr = virtualizationConfigTestBootstrap.getDownloadAssocaiationsFolder(); + NodeRef downloadAssocsFolder = downloadAsocsFolderExpr.resolve(); + + NodeRef tempDownloadSourceAssocs = nodeService.getChildByName(downloadAssocsFolder, + ContentModel.ASSOC_CONTAINS, + createDownloadNode.getId()); + + assertNotNull(tempDownloadSourceAssocs); + + downloadStorage.delete(createDownloadNode); + + assertFalse("Association information was not removed when removing the source.", + nodeService.exists(tempDownloadSourceAssocs)); + } + + @Test + public void testGetChildByName() + { + + NodeRef virtualFolder = createVirtualizedFolder(testRootFolder.getNodeRef(), + VIRTUAL_FOLDER_2_NAME, + TEST_TEMPLATE_4_JSON_SYS_PATH); + + assertTrue(virtualStore.canVirtualize(virtualFolder)); + Reference semiVirtualFolder = virtualStore.virtualize(virtualFolder); + assertNotNull(semiVirtualFolder); + + // access virtual entry + NodeRef virtualChild = nodeService.getChildByName(semiVirtualFolder.toNodeRef(), + ContentModel.ASSOC_CONTAINS, + "All My Content"); + assertNotNull(virtualChild); + assertVirtualNode(virtualChild); + + // access physical child on first level + NodeRef phys1 = nodeService.getChildByName(virtualChild, + ContentModel.ASSOC_CONTAINS, + "Company Home"); + assertNotNull(phys1); + assertVirtualNode(virtualChild); + + // access physical child on second level + NodeRef phys2 = nodeService.getChildByName(phys1, + ContentModel.ASSOC_CONTAINS, + "Data Dictionary"); + assertNotNull(phys2); + assertVirtualNode(virtualChild); + } + + @Test + public void testGetPrimaryParent() throws Exception + { + // check that the primary parent node of level 1 virtual folder is + // actual folder and not the root node from json template + NodeRef node2 = nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + "Node2"); + assertNotNull(node2); + ChildAssociationRef primaryParent = nodeService.getPrimaryParent(node2); + assertNotNull(primaryParent); + NodeRef parentRef = primaryParent.getParentRef(); + assertEquals(virtualFolder1NodeRef, + parentRef); + + // check that the primary parent node of level 2 virtual folder is his + // virtual folder parent + NodeRef node2_1 = nodeService.getChildByName(node2, + ContentModel.ASSOC_CONTAINS, + "Node2_1"); + assertNotNull(node2_1); + primaryParent = nodeService.getPrimaryParent(node2_1); + assertNotNull(primaryParent); + parentRef = primaryParent.getParentRef(); + assertEquals(node2, + parentRef); + } + + @Test + public void testGetAssocs_CM_673() throws Exception + { + NodeRef createFolder = createFolder(testRootFolder.getNodeRef(), + "FOLDER").getChildRef(); + createContent(createFolder, + "testFile1", + "0", + MimetypeMap.MIMETYPE_TEXT_PLAIN, + "UTF-8"); + NodeRef virtualFolder = createVirtualizedFolder(testRootFolder.getNodeRef(), + VIRTUAL_FOLDER_2_NAME, + TEST_TEMPLATE_6_JSON_SYS_PATH); + NodeRef node1 = nodeService.getChildByName(virtualFolder, + ContentModel.ASSOC_CONTAINS, + "Node1"); + assertNotNull(node1); + + NodeRef physicalFolderInVirtualContext = nodeService.getChildByName(node1, + ContentModel.ASSOC_CONTAINS, + "FOLDER"); + assertNotNull(physicalFolderInVirtualContext); + + List childAssocs = nodeService.getChildAssocs(physicalFolderInVirtualContext); + assertNotNull(childAssocs); + assertEquals(1, + childAssocs.size()); + assertEquals("testFile1", + nodeService.getProperty(childAssocs.get(0).getChildRef(), + ContentModel.PROP_NAME)); + } + + @Test + public void testCopySemivirtualFolder() throws Exception + { + configuredTemplatesClassPath = constraints.getTemplatesParentClasspath(); + constraints.setTemplatesParentClasspath("/org/alfresco/repo/virtual/template"); + IntegrityChecker integrityChecker = (IntegrityChecker) ctx.getBean("integrityChecker"); + NodeRef childRef = createFolder(testRootFolder.getNodeRef(), + "TT").getChildRef(); + CopyService copyService = ctx.getBean("copyService", + CopyService.class); + copyService.copyAndRename(virtualFolder1NodeRef, + childRef, + ContentModel.ASSOC_CONTAINS, + null, + true); + NodeRef copiedNodeRef = nodeService.getChildByName(childRef, + ContentModel.ASSOC_CONTAINS, + VIRTUAL_FOLDER_1_NAME); + assertNotNull(copiedNodeRef); + NodeRef node2 = nodeService.getChildByName(copiedNodeRef, + ContentModel.ASSOC_CONTAINS, + "Node2"); + assertNotNull(node2); + + NodeRef node2_1 = nodeService.getChildByName(node2, + ContentModel.ASSOC_CONTAINS, + "Node2_1"); + assertNotNull(node2_1); + + integrityChecker.checkIntegrity(); + } + + @Test + public void testCreateFileAndFolderInFolderInVirtualContext() throws Exception + { + NodeRef physicalFolder = createFolder(testRootFolder.getNodeRef(), + "FOLDER").getChildRef(); + NodeRef virtualFolder = createVirtualizedFolder(testRootFolder.getNodeRef(), + VIRTUAL_FOLDER_2_NAME, + TEST_TEMPLATE_6_JSON_SYS_PATH); + NodeRef node1 = nodeService.getChildByName(virtualFolder, + ContentModel.ASSOC_CONTAINS, + "Node1"); + assertNotNull(node1); + + NodeRef physicalFolderInVirtualContext = nodeService.getChildByName(node1, + ContentModel.ASSOC_CONTAINS, + "FOLDER"); + assertNotNull(physicalFolderInVirtualContext); + + createContent(physicalFolderInVirtualContext, + "testFile1", + "0", + MimetypeMap.MIMETYPE_TEXT_PLAIN, + "UTF-8"); + + NodeRef childFileNodeRef = nodeService.getChildByName(physicalFolderInVirtualContext,ContentModel.ASSOC_CONTAINS, "testFile1"); + assertNotNull(childFileNodeRef); + + childFileNodeRef = nodeService.getChildByName(physicalFolder,ContentModel.ASSOC_CONTAINS, "testFile1"); + assertNotNull(childFileNodeRef); + + createFolder(physicalFolderInVirtualContext, "testFolder1"); + + NodeRef childFolderNodeRef = nodeService.getChildByName(physicalFolderInVirtualContext,ContentModel.ASSOC_CONTAINS, "testFolder1"); + assertNotNull(childFolderNodeRef); + + childFolderNodeRef = nodeService.getChildByName(physicalFolder,ContentModel.ASSOC_CONTAINS, "testFolder1"); + assertNotNull(childFolderNodeRef); + } + + private NodeRef createDownloadNode() + { + NodeRef createDownloadNode = downloadStorage.createDownloadNode(true); + return createDownloadNode; + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/bundle/VirtualPermissionServiceExtensionTest.java b/source/test-java/org/alfresco/repo/virtual/bundle/VirtualPermissionServiceExtensionTest.java new file mode 100644 index 0000000000..eb0723a33f --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/bundle/VirtualPermissionServiceExtensionTest.java @@ -0,0 +1,623 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.bundle; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.alfresco.model.ContentModel; +import org.alfresco.repo.jscript.ScriptNode; +import org.alfresco.repo.security.authentication.AuthenticationUtil; +import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork; +import org.alfresco.repo.security.permissions.NodePermissionEntry; +import org.alfresco.repo.security.permissions.PermissionEntry; +import org.alfresco.repo.security.permissions.PermissionServiceSPI; +import org.alfresco.repo.virtual.VirtualizationIntegrationTest; +import org.alfresco.repo.virtual.store.VirtualStoreImpl; +import org.alfresco.repo.virtual.store.VirtualUserPermissions; +import org.alfresco.service.ServiceRegistry; +import org.alfresco.service.cmr.repository.ChildAssociationRef; +import org.alfresco.service.cmr.repository.NodeRef; +import org.alfresco.service.cmr.repository.Path; +import org.alfresco.service.cmr.security.AccessPermission; +import org.alfresco.service.cmr.security.AccessStatus; +import org.alfresco.service.cmr.security.PermissionService; +import org.junit.Test; + +public class VirtualPermissionServiceExtensionTest extends VirtualizationIntegrationTest +{ + private PermissionServiceSPI permissionService; + + private String user1; + + private String user2; + + private NodeRef vf1Node2; + + private NodeRef virtualContent; + + private VirtualStoreImpl virtualStore; + + /** original user permissions to be restored on tear down */ + private VirtualUserPermissions savedUserPermissions; + + @Override + protected void setUp() throws Exception + { + super.setUp(); + // we set our own virtual user permissions in order to be context xml + // independent + virtualStore = VirtualPermissionServiceExtensionTest.ctx.getBean("virtualStore", + VirtualStoreImpl.class); + + permissionService = VirtualPermissionServiceExtensionTest.ctx.getBean("permissionServiceImpl", + PermissionServiceSPI.class); + + user1 = "user1"; + + user2 = "user2"; + + vf1Node2 = nodeService.getChildByName(this.virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + "Node2"); + + virtualContent = createContent(vf1Node2, + "virtualContent").getChildRef(); + + this.permissionService.setPermission(this.virtualFolder1NodeRef, + user1, + PermissionService.DELETE_CHILDREN, + true); + + this.permissionService.setPermission(this.virtualFolder1NodeRef, + user2, + PermissionService.DELETE_CHILDREN, + false); + + this.permissionService.setPermission(this.virtualFolder1NodeRef, + user1, + PermissionService.READ_PROPERTIES, + true); + + this.permissionService.setPermission(this.virtualFolder1NodeRef, + user1, + PermissionService.CREATE_CHILDREN, + false); + + this.permissionService.setPermission(this.virtualFolder1NodeRef, + user1, + PermissionService.DELETE, + true); + + } + + protected void setUpTestPermissions() + { + // we save the original permissions + savedUserPermissions = virtualStore.getUserPermissions(); + + VirtualUserPermissions testPermissions = new VirtualUserPermissions(savedUserPermissions); + Set allowVirtualNodes = new HashSet<>(savedUserPermissions.getAllowVirtualNodes()); + + // we force create children on virtual nodes + allowVirtualNodes.add(PermissionService.CREATE_CHILDREN); + + testPermissions.setAllowVirtualNodes(allowVirtualNodes); + + testPermissions.init(); + + virtualStore.setUserPermissions(testPermissions); + } + + @Override + public void tearDown() throws Exception + { + if (savedUserPermissions != null) + { + virtualStore.setUserPermissions(savedUserPermissions); + savedUserPermissions = null; + } + + super.tearDown(); + } + + private AccessStatus hasPermissionAs(final NodeRef nodeRef, final String permission, String asUser) + { + RunAsWork hasPermissionAs = new RunAsWork() + { + + @Override + public AccessStatus doWork() throws Exception + { + return permissionService.hasPermission(nodeRef, + permission); + } + + }; + return AuthenticationUtil.runAs(hasPermissionAs, + asUser); + } + + @Test + public void testHasPermissionAdherence_actualPath() throws Exception + { + + // virtual nodes should adhere to actual node permission if no filing + // or the actual path is specified + + assertEquals(AccessStatus.ALLOWED, + hasPermissionAs(this.virtualFolder1NodeRef, + PermissionService.DELETE_CHILDREN, + user1)); + + assertEquals(AccessStatus.DENIED, + hasPermissionAs(this.virtualFolder1NodeRef, + PermissionService.DELETE_CHILDREN, + user2)); + + assertEquals(AccessStatus.ALLOWED, + hasPermissionAs(vf1Node2, + PermissionService.DELETE_CHILDREN, + user1)); + + assertEquals(AccessStatus.ALLOWED, + hasPermissionAs(virtualContent, + PermissionService.DELETE_CHILDREN, + user1)); + + assertEquals(AccessStatus.DENIED, + hasPermissionAs(vf1Node2, + PermissionService.DELETE_CHILDREN, + user2)); + + assertEquals(AccessStatus.DENIED, + hasPermissionAs(virtualContent, + PermissionService.DELETE_CHILDREN, + user2)); + + this.permissionService.setPermission(this.virtualFolder1NodeRef, + user1, + PermissionService.DELETE_CHILDREN, + false); + + assertEquals(AccessStatus.DENIED, + hasPermissionAs(vf1Node2, + PermissionService.DELETE_CHILDREN, + user1)); + + assertEquals(AccessStatus.DENIED, + hasPermissionAs(virtualContent, + PermissionService.DELETE_CHILDREN, + user1)); + + } + + @Test + public void testHasPermissionAdherence_missingFolderPath() throws Exception + { + + NodeRef virtualFolderT5 = createVirtualizedFolder(testRootFolder.getNodeRef(), + "VirtualFolderT5", + TEST_TEMPLATE_5_JSON_SYS_PATH); + + NodeRef filingFolderVirtualNodeRef = nodeService.getChildByName(virtualFolderT5, + ContentModel.ASSOC_CONTAINS, + "FilingFolder_filing_path"); + + + + + assertEquals(AccessStatus.DENIED, + hasPermissionAs(filingFolderVirtualNodeRef, + PermissionService.DELETE, + user1)); + + assertEquals(AccessStatus.DENIED, + hasPermissionAs(filingFolderVirtualNodeRef, + asTypedPermission(PermissionService.DELETE), + user1) ); + + assertEquals(AccessStatus.DENIED, + hasPermissionAs(filingFolderVirtualNodeRef, + PermissionService.CREATE_CHILDREN, + user1)); + + assertEquals(AccessStatus.DENIED, + hasPermissionAs(filingFolderVirtualNodeRef, + asTypedPermission(PermissionService.CREATE_CHILDREN), + user1)); + + } + + @Test + public void testHasPermissionAdherence_folderPath() throws Exception + { + + // virtual nodes should adhere to node permission of the node indicated + // by the filing path is specified -with virtual permission overriding + // when specified + + NodeRef virtualFolderT5 = createVirtualizedFolder(testRootFolder.getNodeRef(), + "VirtualFolderT5", + TEST_TEMPLATE_5_JSON_SYS_PATH); + + NodeRef filingFolderVirtualNodeRef = nodeService.getChildByName(virtualFolderT5, + ContentModel.ASSOC_CONTAINS, + "FilingFolder_filing_path"); + + ChildAssociationRef filingFolderChildAssoc = createFolder(rootNodeRef, + "FilingFolder"); + + NodeRef filingFolderNodeRef = filingFolderChildAssoc.getChildRef(); + + this.permissionService.setPermission(filingFolderNodeRef, + user1, + PermissionService.CREATE_CHILDREN, + true); + + this.permissionService.setPermission(filingFolderNodeRef, + user2, + PermissionService.CREATE_CHILDREN, + false); + + assertEquals(AccessStatus.DENIED, + hasPermissionAs(filingFolderNodeRef, + PermissionService.DELETE, + user1)); + + assertEquals(AccessStatus.ALLOWED, + hasPermissionAs(filingFolderNodeRef, + PermissionService.CREATE_CHILDREN, + user1)); + + assertEquals(AccessStatus.DENIED, + hasPermissionAs(filingFolderNodeRef, + PermissionService.CREATE_CHILDREN, + user2)); + + assertEquals(AccessStatus.DENIED, + hasPermissionAs(filingFolderVirtualNodeRef, + PermissionService.DELETE, + user1)); + + assertEquals(AccessStatus.DENIED, + hasPermissionAs(filingFolderVirtualNodeRef, + asTypedPermission(PermissionService.DELETE), + user1)); + + assertEquals(AccessStatus.ALLOWED, + hasPermissionAs(filingFolderVirtualNodeRef, + PermissionService.CREATE_CHILDREN, + user1)); + + assertEquals(AccessStatus.ALLOWED, + hasPermissionAs(filingFolderVirtualNodeRef, + asTypedPermission(PermissionService.CREATE_CHILDREN), + user1)); + + this.permissionService.setPermission(filingFolderNodeRef, + user1, + PermissionService.DELETE_CHILDREN, + true); + + this.permissionService.setPermission(filingFolderNodeRef, + user2, + PermissionService.DELETE_CHILDREN, + false); + + this.permissionService.setPermission(filingFolderNodeRef, + user1, + PermissionService.READ_PROPERTIES, + true); + + this.permissionService.setPermission(filingFolderNodeRef, + user1, + PermissionService.CREATE_CHILDREN, + false); + + this.permissionService.setPermission(filingFolderNodeRef, + user1, + PermissionService.DELETE, + true); + + assertEquals(AccessStatus.ALLOWED, + hasPermissionAs(filingFolderNodeRef, + PermissionService.DELETE, + user1)); + + assertEquals(AccessStatus.DENIED, + hasPermissionAs(filingFolderNodeRef, + PermissionService.CREATE_CHILDREN, + user1)); + + assertEquals(AccessStatus.DENIED, + hasPermissionAs(filingFolderVirtualNodeRef, + PermissionService.DELETE, + user1)); + + assertEquals(AccessStatus.DENIED, + hasPermissionAs(filingFolderVirtualNodeRef, + asTypedPermission(PermissionService.DELETE), + user1)); + + assertEquals(AccessStatus.DENIED, + hasPermissionAs(filingFolderVirtualNodeRef, + PermissionService.CREATE_CHILDREN, + user1)); + + assertEquals(AccessStatus.DENIED, + hasPermissionAs(filingFolderVirtualNodeRef, + asTypedPermission(PermissionService.CREATE_CHILDREN), + user1)); + + } + + @Test + public void testHasPermission() throws Exception + { + setUpTestPermissions(); + + // virtual permission should override actual permissions + + assertEquals(AccessStatus.ALLOWED, + hasPermissionAs(this.virtualFolder1NodeRef, + PermissionService.DELETE, + user1)); + + assertEquals(AccessStatus.DENIED, + hasPermissionAs(this.virtualFolder1NodeRef, + PermissionService.CREATE_CHILDREN, + user1)); + + assertEquals(AccessStatus.DENIED, + hasPermissionAs(vf1Node2, + PermissionService.DELETE, + user1)); + + assertEquals(AccessStatus.DENIED, + hasPermissionAs(vf1Node2, + asTypedPermission(PermissionService.DELETE), + user1)); + + assertEquals(AccessStatus.ALLOWED, + hasPermissionAs(vf1Node2, + PermissionService.CREATE_CHILDREN, + user1)); + + assertEquals(AccessStatus.ALLOWED, + hasPermissionAs(vf1Node2, + asTypedPermission(PermissionService.CREATE_CHILDREN), + user1)); + + } + + @Test + public void testReadonlyNodeHasPermission() throws Exception + { + + // virtual permission should override actual permissions + NodeRef aVFTestTemplate2 = createVirtualizedFolder(testRootFolder.getNodeRef(), + "aVFTestTemplate2", + TEST_TEMPLATE_2_JSON_SYS_PATH); + NodeRef vf2Node2 = nodeService.getChildByName(aVFTestTemplate2, + ContentModel.ASSOC_CONTAINS, + "Node2"); + + final String[] deniedReadOnly = new String[] { PermissionService.UNLOCK, PermissionService.CANCEL_CHECK_OUT, + PermissionService.CHANGE_PERMISSIONS, PermissionService.CREATE_CHILDREN, PermissionService.DELETE, + PermissionService.WRITE, PermissionService.DELETE_NODE, PermissionService.WRITE_PROPERTIES, + PermissionService.WRITE_CONTENT, PermissionService.CREATE_ASSOCIATIONS }; + + StringBuilder nonDeniedTrace = new StringBuilder(); + for (int i = 0; i < deniedReadOnly.length; i++) + { + AccessStatus accessStatus = hasPermissionAs(vf2Node2, + deniedReadOnly[i], + user1); + if (!AccessStatus.DENIED.equals(accessStatus)) + { + if (nonDeniedTrace.length() > 0) + { + nonDeniedTrace.append(","); + } + nonDeniedTrace.append(deniedReadOnly[i]); + } + } + + assertTrue("Non-denied permissions on RO virtual nodes : " + nonDeniedTrace, + nonDeniedTrace.length() == 0); + } + + @SuppressWarnings("unchecked") + private Map> mapPermissionsByName(List entries) + { + Map> nameMap = new HashMap<>(); + for (PermissionEntry permissionEntry : entries) + { + String name = permissionEntry.getPermissionReference().getName(); + List permissions = (List) nameMap.get(name); + if (permissions == null) + { + permissions = new ArrayList<>(); + nameMap.put(name, + permissions); + } + permissions.add(permissionEntry); + } + + return nameMap; + } + + private Map> mapAccessPermissionsByName(Set accessPermissions) + { + Map> nameMap = new HashMap<>(); + for (AccessPermission accessPermission : accessPermissions) + { + String name = accessPermission.getPermission(); + List permissions = (List) nameMap.get(name); + if (permissions == null) + { + permissions = new ArrayList<>(); + nameMap.put(name, + permissions); + } + permissions.add(accessPermission); + } + + return nameMap; + } + + /** + * Asserts that the permission with the given name uniquely found in the + * given permission entries list has the given access status for the given + * authority. + * + * @param permissionName + * @param accessStatus + * @param authority + * @param permissionEntries + */ + protected void assertUniquePermission(String permissionName, AccessStatus accessStatus, String authority, + List permissionEntries) + { + Map> entriesByName = mapPermissionsByName((List) permissionEntries); + assertNotNull("Not null permission " + permissionName + " expected.", + entriesByName.get(permissionName)); + assertEquals(1, + entriesByName.get(permissionName).size()); + + PermissionEntry permission = entriesByName.get(permissionName).get(0); + assertEquals(accessStatus, + permission.getAccessStatus()); + assertEquals(authority, + permission.getAuthority()); + } + + /** + * Asserts that the permission with the given name uniquely found in the + * given permission entries list has the given access status for the given + * authority. + * + * @param permissionName + * @param accessStatus + * @param authority + * @param permissionEntries + */ + protected void assertUniqueAccessPermission(String permissionName, AccessStatus accessStatus, String authority, + Set accessPermissions) + { + Map> apByName = mapAccessPermissionsByName(accessPermissions); + assertNotNull("Not null permission " + permissionName + " expected.", + apByName.get(permissionName)); + List oneAccessPermission = apByName.get(permissionName); + assertEquals("Expected single AccessPermission but found " + oneAccessPermission, + 1, + oneAccessPermission.size()); + + AccessPermission permission = apByName.get(permissionName).get(0); + assertEquals(accessStatus, + permission.getAccessStatus()); + assertEquals(authority, + permission.getAuthority()); + } + + @Test + public void testGetAllSetPermissions() throws Exception + { + setUpTestPermissions(); + + Set allVf1SetPermissions = permissionService.getAllSetPermissions(this.virtualFolder1NodeRef); + + AccessPermission vf1ReadProperties = mapAccessPermissionsByName(allVf1SetPermissions) + .get(PermissionService.READ_PROPERTIES) + .get(0); + + assertUniqueAccessPermission(PermissionService.DELETE, + AccessStatus.ALLOWED, + user1, + allVf1SetPermissions); + assertUniqueAccessPermission(PermissionService.CREATE_CHILDREN, + AccessStatus.DENIED, + user1, + allVf1SetPermissions); + + Set allNode2SetPermissions = permissionService.getAllSetPermissions(vf1Node2); + + assertUniqueAccessPermission(PermissionService.DELETE, + AccessStatus.DENIED, + PermissionService.ALL_AUTHORITIES, + allNode2SetPermissions); + assertUniqueAccessPermission(PermissionService.CREATE_CHILDREN, + AccessStatus.ALLOWED, + PermissionService.ALL_AUTHORITIES, + allNode2SetPermissions); + // adhere to actual node + assertUniqueAccessPermission(PermissionService.READ_PROPERTIES, + vf1ReadProperties.getAccessStatus(), + vf1ReadProperties.getAuthority(), + allNode2SetPermissions); + + } + + @Test + public void testGetSetPermissions() throws Exception + { + setUpTestPermissions(); + + NodePermissionEntry vf1SetPermissions = permissionService.getSetPermissions(this.virtualFolder1NodeRef); + assertEquals(virtualFolder1NodeRef, + vf1SetPermissions.getNodeRef()); + List vf1Entries = vf1SetPermissions.getPermissionEntries(); + assertUniquePermission(PermissionService.DELETE, + AccessStatus.ALLOWED, + user1, + vf1Entries); + assertUniquePermission(PermissionService.CREATE_CHILDREN, + AccessStatus.DENIED, + user1, + vf1Entries); + + NodePermissionEntry node2SetPermissions = permissionService.getSetPermissions(vf1Node2); + + assertEquals(vf1Node2, + node2SetPermissions.getNodeRef()); + + List node2Entries = node2SetPermissions.getPermissionEntries(); + assertUniquePermission(PermissionService.DELETE, + AccessStatus.DENIED, + PermissionService.ALL_AUTHORITIES, + node2Entries); + assertUniquePermission(PermissionService.CREATE_CHILDREN, + AccessStatus.ALLOWED, + PermissionService.ALL_AUTHORITIES, + node2Entries); + + } + + private String asTypedPermission(String perm) + { + return virtualStore.getUserPermissions().getPermissionTypeQName() + "." + perm; + } + +} diff --git a/source/test-java/org/alfresco/repo/virtual/bundle/VirtualRatingServiceExtensionTest.java b/source/test-java/org/alfresco/repo/virtual/bundle/VirtualRatingServiceExtensionTest.java new file mode 100644 index 0000000000..b84dab2feb --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/bundle/VirtualRatingServiceExtensionTest.java @@ -0,0 +1,138 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.bundle; + +import org.alfresco.model.ContentModel; +import org.alfresco.repo.security.authentication.AuthenticationUtil; +import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork; +import org.alfresco.repo.virtual.VirtualizationIntegrationTest; +import org.alfresco.repo.virtual.ref.GetActualNodeRefMethod; +import org.alfresco.repo.virtual.ref.Reference; +import org.alfresco.service.cmr.rating.RatingService; +import org.alfresco.service.cmr.rating.RatingServiceException; +import org.alfresco.service.cmr.repository.NodeRef; +import org.alfresco.service.cmr.security.AccessStatus; +import org.junit.Test; + +public class VirtualRatingServiceExtensionTest extends VirtualizationIntegrationTest +{ + private final static String LIKES_RATING_SCHEME = "likesRatingScheme"; + + private final static String FIVE_STAR_RATING_SCHEME = "fiveStarRatingScheme"; + + private RatingService ratingService; + + private NodeRef vf1Node2; + + private NodeRef virtualContent; + + private String user1; + + private String user2; + + @Override + protected void setUp() throws Exception + { + super.setUp(); + + ratingService = VirtualPermissionServiceExtensionTest.ctx.getBean("ratingService", + RatingService.class); + + user1 = "user1"; + + user2 = "user2"; + + vf1Node2 = nodeService.getChildByName(this.virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + "Node2"); + + virtualContent = createContent(vf1Node2, + "virtualContent").getChildRef(); + } + + private void applyRatingAs(final NodeRef targetNode, final float rating, final String ratingSchemeName, + String asUser) throws RatingServiceException + { + + String fau = AuthenticationUtil.getFullyAuthenticatedUser(); + try + { + AuthenticationUtil.setFullyAuthenticatedUser(asUser); + RunAsWork applyRatingsAsWork = new RunAsWork() + { + + @Override + public Void doWork() throws Exception + { + ratingService.applyRating(targetNode, + rating, + ratingSchemeName); + return null; + } + + }; + AuthenticationUtil.runAs(applyRatingsAsWork, + asUser); + } + finally + { + AuthenticationUtil.setFullyAuthenticatedUser(fau); + } + } + + @Test + public void testApplyRatings() throws Exception + { + assertTrue(Reference.isReference(virtualContent)); + NodeRef actualNodeRef = Reference.fromNodeRef(virtualContent).execute(new GetActualNodeRefMethod(environment)); + + applyRatingAs(virtualContent, + 1f, + LIKES_RATING_SCHEME, + user1); + + applyRatingAs(virtualContent, + 1f, + LIKES_RATING_SCHEME, + user2); + + assertEquals(1f, + ratingService.getAverageRating(virtualContent, + LIKES_RATING_SCHEME)); + assertEquals(1f, + ratingService.getAverageRating(actualNodeRef, + LIKES_RATING_SCHEME)); + + applyRatingAs(virtualContent, + 1f, + FIVE_STAR_RATING_SCHEME, + user1); + applyRatingAs(virtualContent, + 3f, + FIVE_STAR_RATING_SCHEME, + user2); + assertEquals(2f, + ratingService.getAverageRating(virtualContent, + FIVE_STAR_RATING_SCHEME)); + assertEquals(2f, + ratingService.getAverageRating(actualNodeRef, + FIVE_STAR_RATING_SCHEME)); + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/bundle/VirtualVersionServiceExtensionTest.java b/source/test-java/org/alfresco/repo/virtual/bundle/VirtualVersionServiceExtensionTest.java new file mode 100644 index 0000000000..c0475f16bc --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/bundle/VirtualVersionServiceExtensionTest.java @@ -0,0 +1,238 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.bundle; + +import java.util.Collection; +import java.util.Set; + +import org.alfresco.model.ApplicationModel; +import org.alfresco.model.ContentModel; +import org.alfresco.repo.virtual.VirtualizationIntegrationTest; +import org.alfresco.repo.virtual.ref.GetActualNodeRefMethod; +import org.alfresco.repo.virtual.ref.Reference; +import org.alfresco.service.cmr.repository.ChildAssociationRef; +import org.alfresco.service.cmr.repository.ContentReader; +import org.alfresco.service.cmr.repository.ContentWriter; +import org.alfresco.service.cmr.repository.NodeRef; +import org.alfresco.service.cmr.version.Version; +import org.alfresco.service.cmr.version.VersionHistory; +import org.alfresco.service.cmr.version.VersionService; +import org.alfresco.service.namespace.QName; +import org.junit.Test; + +public class VirtualVersionServiceExtensionTest extends VirtualizationIntegrationTest +{ + + private VersionService versionService; + + private NodeRef node2; + + private NodeRef node2_1; + + @Override + protected void setUp() throws Exception + { + super.setUp(); + + versionService = ctx.getBean("VersionService", + VersionService.class); + + node2 = nodeService.getChildByName(virtualFolder1NodeRef, + ContentModel.ASSOC_CONTAINS, + "Node2"); + node2_1 = nodeService.getChildByName(node2, + ContentModel.ASSOC_CONTAINS, + "Node2_1"); + } + + @Test + public void testGetCurrentVersion() throws Exception + { + ChildAssociationRef contentWithVersionsAssocRef = createContent(node2_1, + "ContentWithVersions"); + NodeRef contentWithVersionsNodeRef = contentWithVersionsAssocRef.getChildRef(); + + Version currentVersion = versionService.getCurrentVersion(contentWithVersionsNodeRef); + assertNull(currentVersion); + + Version newVersion = versionService.createVersion(contentWithVersionsNodeRef, + null); + assertNotNull(newVersion); + + Version newCurrentVersion = versionService.getCurrentVersion(contentWithVersionsNodeRef); + assertNotNull(newCurrentVersion); + + assertSameVersion(newVersion, + newCurrentVersion); + + } + + private void assertSameVersion(Version expectedVersion, Version actualVersion) + { + assertEquals("FrozenStateNodeRefs are not the same", + expectedVersion.getFrozenStateNodeRef(), + actualVersion.getFrozenStateNodeRef()); + assertEquals("VersionedNodeRefs are not the same", + expectedVersion.getVersionedNodeRef(), + actualVersion.getVersionedNodeRef()); + assertEquals("Versionlabels are not the same", + expectedVersion.getVersionLabel(), + actualVersion.getVersionLabel()); + } + + @Test + public void testCreateVersion() throws Exception + { + + ChildAssociationRef contentWithVersionsAssocRef = createContent(node2_1, + "ContentWithVersions"); + NodeRef contentWithVersionsNodeRef = contentWithVersionsAssocRef.getChildRef(); + assertTrue(Reference.isReference(contentWithVersionsNodeRef)); + NodeRef actualContentWithVersionsNodeRef = Reference + .fromNodeRef(contentWithVersionsNodeRef) + .execute(new GetActualNodeRefMethod(environment)); + + VersionHistory versionHistory = versionService.getVersionHistory(contentWithVersionsNodeRef); + assertNull(versionHistory); + VersionHistory actualVersionHistory = versionService.getVersionHistory(actualContentWithVersionsNodeRef); + assertNull(actualVersionHistory); + + Version newVersion = versionService.createVersion(contentWithVersionsNodeRef, + null); + + NodeRef newVersionNodeRef = newVersion.getVersionedNodeRef(); + assertTrue(Reference.isReference(newVersionNodeRef)); + + versionHistory = versionService.getVersionHistory(newVersionNodeRef); + assertNotNull(versionHistory); + + Collection allVersions = versionHistory.getAllVersions(); + assertEquals(1, + allVersions.size()); + + actualVersionHistory = versionService.getVersionHistory(actualContentWithVersionsNodeRef); + assertNotNull(actualVersionHistory); + + Collection allActualVersions = versionHistory.getAllVersions(); + assertEquals(1, + allActualVersions.size()); + + Version actualVersion = actualVersionHistory.getHeadVersion(); + + NodeRef newActualVersionNodeRef = actualVersion.getVersionedNodeRef(); + assertTrue(!Reference.isReference(newActualVersionNodeRef)); + + assertEquals(newActualVersionNodeRef, + actualContentWithVersionsNodeRef); + } + + @Test + public void testRevert() throws Exception + { + ChildAssociationRef contentWithVersionsAssocRef = createContent(node2_1, + "ContentWithVersions"); + // Create a versionable node + NodeRef versionableNode = contentWithVersionsAssocRef.getChildRef(); + + // Create the initial version + Version version1 = versionService.createVersion(versionableNode, + null); + + // Check the history is correct + VersionHistory history = versionService.getVersionHistory(versionableNode); + assertEquals(version1.getVersionLabel(), + history.getHeadVersion().getVersionLabel()); + assertEquals(version1.getVersionedNodeRef(), + history.getHeadVersion().getVersionedNodeRef()); + assertEquals(1, + history.getAllVersions().size()); + Version[] versions = history.getAllVersions().toArray(new Version[1]); + assertEquals("0.1", + versions[0].getVersionLabel()); + assertEquals("0.1", + nodeService.getProperty(versionableNode, + ContentModel.PROP_VERSION_LABEL)); + + ContentWriter contentWriter = this.contentService.getWriter(versionableNode, + ContentModel.PROP_CONTENT, + true); + assertNotNull(contentWriter); + + // Record this as a new version + Version version2 = versionService.createVersion(versionableNode, + null); + + // Check we're now seeing both versions in the history + history = versionService.getVersionHistory(versionableNode); + // assertEquals(version2.getVersionLabel(), + // history.getHeadVersion().getVersionLabel()); + assertEquals(version2.getVersionedNodeRef(), + history.getHeadVersion().getVersionedNodeRef()); + assertEquals(2, + history.getAllVersions().size()); + + versions = history.getAllVersions().toArray(new Version[2]); + assertEquals("0.2", + versions[0].getVersionLabel()); + assertEquals("0.1", + versions[1].getVersionLabel()); + assertEquals("0.2", + nodeService.getProperty(versionableNode, + ContentModel.PROP_VERSION_LABEL)); + + // Change the property and content values + ContentWriter contentWriter2 = this.contentService.getWriter(versionableNode, + ContentModel.PROP_CONTENT, + true); + assertNotNull(contentWriter2); + + // Revert to the previous version, which will loose these changes + this.versionService.revert(versionableNode); + + // Check that the history is back how it was + history = versionService.getVersionHistory(versionableNode); + assertEquals(version2.getVersionedNodeRef(), + history.getHeadVersion().getVersionedNodeRef()); + assertEquals(2, + history.getAllVersions().size()); + + versions = history.getAllVersions().toArray(new Version[2]); + assertEquals("0.2", + versions[0].getVersionLabel()); + assertEquals("0.1", + versions[1].getVersionLabel()); + assertEquals("0.2", + nodeService.getProperty(versionableNode, + ContentModel.PROP_VERSION_LABEL)); + + // Revert to the first version + this.versionService.revert(versionableNode, + version1); + + // Check the history still has 2 versions + history = versionService.getVersionHistory(versionableNode); + assertEquals(2, + history.getAllVersions().size()); + + assertEquals("0.1", + history.getHeadVersion().getVersionLabel()); + + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/config/NodeRefPathExpressionTest.java b/source/test-java/org/alfresco/repo/virtual/config/NodeRefPathExpressionTest.java new file mode 100644 index 0000000000..e04450e85e --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/config/NodeRefPathExpressionTest.java @@ -0,0 +1,131 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.config; + +import java.io.Serializable; + +import javax.transaction.UserTransaction; + +import junit.framework.TestCase; + +import org.alfresco.model.ContentModel; +import org.alfresco.repo.virtual.VirtualizationTest; +import org.alfresco.service.ServiceRegistry; +import org.alfresco.service.cmr.repository.NodeRef; +import org.alfresco.service.cmr.repository.NodeService; +import org.alfresco.service.transaction.TransactionService; +import org.alfresco.util.ApplicationContextHelper; +import org.junit.Test; +import org.springframework.context.ApplicationContext; + +public class NodeRefPathExpressionTest extends TestCase implements VirtualizationTest +{ + private static final String NODE_REF_PATH_EXPRESSION_FACTORY_ID = "config.NodeRefPathExpressionFactory"; + + protected static final ApplicationContext ctx = ApplicationContextHelper.getApplicationContext(CONFIG_LOCATIONS); + + private UserTransaction txn; + + private ServiceRegistry serviceRegistry; + + private NodeService nodeService; + + private NodeRefPathExpressionFactory nodeRefPathExpressionFactory; + + @Override + protected void setUp() throws Exception + { + super.setUp(); + + serviceRegistry = (ServiceRegistry) ctx.getBean("ServiceRegistry"); + + nodeService = (NodeService) ctx.getBean("nodeService"); + + nodeRefPathExpressionFactory = (NodeRefPathExpressionFactory) ctx.getBean(NODE_REF_PATH_EXPRESSION_FACTORY_ID); + + TransactionService transactionService = serviceRegistry.getTransactionService(); + + // start the transaction + txn = transactionService.getUserTransaction(); + txn.begin(); + } + + @Override + protected void tearDown() throws Exception + { + txn.rollback(); + super.tearDown(); + } + + protected void assertResolvablePath(String path, String toName) + { + NodeRefPathExpression pathExpression = nodeRefPathExpressionFactory.createInstance(); + + pathExpression.setPath(path); + + NodeRef nodeRef = pathExpression.resolve(); + assertNotNull(nodeRef); + Serializable theName = nodeService.getProperty(nodeRef, + ContentModel.PROP_NAME); + assertEquals("Unexpected name for path " + pathExpression, + toName, + theName); + } + + @Test + public void testResolveNamePath() throws Exception + { + assertResolvablePath("/Data Dictionary", + "Data Dictionary"); + assertResolvablePath("/Data Dictionary//Messages", + "Messages"); + assertResolvablePath("", + "Company Home"); + assertResolvablePath("//", + "Company Home"); + } + + @Test + public void testResolveQNamePath() throws Exception + { + assertResolvablePath("", + "Company Home"); + assertResolvablePath("app:dictionary", + "Data Dictionary"); + assertResolvablePath("/app:dictionary/app:messages", + "Messages"); + } + + @Test + public void testNonSingleton() throws Exception + { + NodeRefPathExpression spe1 = nodeRefPathExpressionFactory.createInstance(); + NodeRefPathExpression spe2 = nodeRefPathExpressionFactory.createInstance(); + assertNotSame(spe1, + spe2); + spe1.setPath("Data Dictionary"); + spe2.setPath("/Data Dictionary//Messages"); + NodeRef nr = spe1.resolve(); + Serializable theName = nodeService.getProperty(nr, + ContentModel.PROP_NAME); + assertEquals("Data Dictionary", + theName); + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/model/SystemTemplateLocationsConstraintTest.java b/source/test-java/org/alfresco/repo/virtual/model/SystemTemplateLocationsConstraintTest.java new file mode 100644 index 0000000000..01936c2355 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/model/SystemTemplateLocationsConstraintTest.java @@ -0,0 +1,165 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.model; + +import java.io.InputStream; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +import org.alfresco.model.ContentModel; +import org.alfresco.query.PagingRequest; +import org.alfresco.query.PagingResults; +import org.alfresco.repo.virtual.VirtualContentModel; +import org.alfresco.repo.virtual.VirtualizationIntegrationTest; +import org.alfresco.repo.virtual.config.NodeRefExpression; +import org.alfresco.repo.virtual.config.NodeRefPathExpression; +import org.alfresco.repo.virtual.config.NodeRefPathExpressionFactory; +import org.alfresco.service.ServiceRegistry; +import org.alfresco.service.cmr.model.FileInfo; +import org.alfresco.service.cmr.repository.ChildAssociationRef; +import org.alfresco.service.cmr.repository.NodeRef; +import org.alfresco.service.namespace.QName; +import org.junit.Test; + +public class SystemTemplateLocationsConstraintTest extends VirtualizationIntegrationTest +{ + private ServiceRegistry serviceRegistry; + + private NodeRefPathExpressionFactory nrPathExpressionFactory; + + private NodeRefExpression templatesParentRepositoryPath; + + @Override + protected void setUp() throws Exception + { + super.setUp(); + serviceRegistry = (ServiceRegistry) ctx.getBean("ServiceRegistry"); + nrPathExpressionFactory = (NodeRefPathExpressionFactory) ctx.getBean("config.NodeRefPathExpressionFactory"); + + } + + @Override + public void tearDown() throws Exception + { + if (templatesParentRepositoryPath != null) + { + constraints.setTemplatesParentRepositoryPath(templatesParentRepositoryPath); + templatesParentRepositoryPath = null; + } + super.tearDown(); + } + + @Test + public void testNullConstraints() throws Exception + { + configuredTemplatesClassPath = constraints.getTemplatesParentClasspath(); + constraints.setTemplatesParentClasspath("/org/alfresco/repo/virtual"); + + templatesParentRepositoryPath = constraints.getTemplatesParentRepositoryPath(); + NodeRefPathExpression aNewPath = nrPathExpressionFactory.createInstance(); + constraints.setTemplatesParentRepositoryPath(aNewPath); + + List rawAllowedValues = constraints.getRawAllowedValues(); + assertEquals(1, + rawAllowedValues.size()); + assertEquals(SystemTemplateLocationsConstraint.NULL_SYSTEM_TEMPLATE, + rawAllowedValues.get(0)); + + } + + @Test + public void testConfiguredConstraints() throws Exception + { + List rawAllowedValues = constraints.getRawAllowedValues(); + NodeRefExpression sysTemplatesPath = virtualizationConfigTestBootstrap.getSystemTemplatesPath(); + + NodeRef templatesLocation = sysTemplatesPath.resolve(true); + + PagingResults templates = fileAndFolderService + .list(templatesLocation, + Collections.singleton(VirtualContentModel.TYPE_VIRTUAL_FOLDER_TEMPLATE), + null, + null, + new PagingRequest(1000)); + + List templatesPage = templates.getPage(); + if (!templatesPage.isEmpty()) + { + assertEquals(templatesPage.size(), + rawAllowedValues.size()); + + List expectedSysPaths = new LinkedList<>(); + for (FileInfo fi : templatesPage) + { + expectedSysPaths.add("N" + fi.getNodeRef().toString()); + } + + assertTrue(rawAllowedValues.containsAll(expectedSysPaths)); + } + + } + + @Test + public void testAllConstraints() throws Exception + { + configuredTemplatesClassPath = constraints.getTemplatesParentClasspath(); + constraints.setTemplatesParentClasspath("/org/alfresco/repo/virtual/template"); + + NodeRefExpression sysTemplatesPath = virtualizationConfigTestBootstrap.getSystemTemplatesPath(); + + NodeRef templatesLocation = sysTemplatesPath.resolve(true); + + assertNotNull(templatesLocation); + + InputStream testTemplsteJsonIS = getClass().getResourceAsStream(TEST_TEMPLATE_1_JSON_CLASSPATH); + ChildAssociationRef templateAssoc = createContent(templatesLocation, + TEST_TEMPLATE_1_JSON_NAME, + testTemplsteJsonIS, + "application/json", + "UTF-8", + QName.createQName(virtualizationConfigTestBootstrap + .getSystemTemplateType(), + serviceRegistry.getNamespaceService())); + testTemplsteJsonIS = getClass().getResourceAsStream(TEST_TEMPLATE_1_JSON_CLASSPATH); + createContent(templatesLocation, + "non" + TEST_TEMPLATE_1_JSON_NAME, + testTemplsteJsonIS, + "application/json", + "UTF-8", + ContentModel.TYPE_CONTENT); + + List rawAllowedValues = constraints.getRawAllowedValues(); + + assertTrue(rawAllowedValues.size() >= 5); + + assertTrue("Invalid values " + rawAllowedValues, + rawAllowedValues.contains(TEST_TEMPLATE_1_JSON_SYS_PATH)); + assertTrue("Invalid values " + rawAllowedValues, + rawAllowedValues.contains(TEST_TEMPLATE_2_JSON_SYS_PATH)); + assertTrue("Invalid values " + rawAllowedValues, + rawAllowedValues.contains(TEST_TEMPLATE_3_JSON_SYS_PATH)); + assertTrue("Invalid values " + rawAllowedValues, + rawAllowedValues.contains(TEST_TEMPLATE_4_JSON_SYS_PATH)); + + assertTrue("Invalid values " + rawAllowedValues, + rawAllowedValues.contains("N" + templateAssoc.getChildRef())); + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/page/PageCollatorTest.java b/source/test-java/org/alfresco/repo/virtual/page/PageCollatorTest.java new file mode 100644 index 0000000000..9333a53758 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/page/PageCollatorTest.java @@ -0,0 +1,585 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.page; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import junit.framework.TestCase; + +import org.alfresco.query.ListBackedPagingResults; +import org.alfresco.query.PagingRequest; +import org.alfresco.query.PagingResults; +import org.alfresco.repo.virtual.page.PageCollator.PagingResultsSource; +import org.alfresco.util.Pair; +import org.apache.commons.lang.ArrayUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Test; +import org.springframework.util.comparator.ComparableComparator; + +public class PageCollatorTest extends TestCase +{ + private static Log logger = LogFactory.getLog(PageCollatorTest.class); + + @Override + protected void setUp() throws Exception + { + super.setUp(); + } + + private int[] createMergedPage(int skip, int count, List s1, Integer[] s2) + { + return createMergedPage(skip, + count, + s1, + ArrayUtils.toPrimitive(s2)); + } + + private int[] createMergedPage(int skip, int count, List s1, int[] s2) + { + int[] s1Primitive = (s1 == null || s1.isEmpty()) ? new int[] {} : ArrayUtils.toPrimitive((Integer[]) s1 + .toArray()); + + return createMergedPage(skip, + count, + s1Primitive, + s2); + } + + /** + * Creates an page-array by concatenating the given arrays than skipping and + * trimming the resulted array. + * + * @param skip + * @param count + * @param s1 + * @param s2 + * @return a page-array obtained by merging s1 and + * s2, sorting the result than copying + * count elements from the concatenation starting with + * the element at index skip into the returned array of + * size count. If skip value is out of + * bounds an empty array is returned. + */ + private int[] createMergedPage(int skip, int count, int[] s1, int[] s2) + { + final int[] m = Arrays.copyOf(s1, + s1.length + s2.length); + System.arraycopy(s2, + 0, + m, + s1.length, + s2.length); + Arrays.sort(m); + + final int zeroCount = (count == 0 ? m.length : count); + + final int len = Math.min(m.length - skip, + zeroCount); + if (len > 0) + { + int[] p = new int[len]; + + System.arraycopy(m, + skip, + p, + 0, + len); + + return p; + } + else + { + return new int[] {}; + } + } + + private void assertEqualPages(int[] expected, int[] actual) + { + assertEqualPages(Arrays.toString(expected) + " vs " + Arrays.toString(actual), + expected, + actual); + } + + private void assertEqualPages(String message, int[] expected, int[] actual) + { + assertTrue(message, + Arrays.equals(expected, + actual)); + } + + private void assertEqualPages(String message, int[] expected, List page) + { + assertEqualPages(message, + expected, + ArrayUtils.toPrimitive((Integer[]) page.toArray(new Integer[] {}))); + } + + @Test + public void testCreateMergedPage() throws Exception + { + // { 0, 1, 2, 3, 4, 7, 8, 9, 10 } + final int[] s1 = new int[] { 0, 1, 3, 7, 8 }; + final int[] s2 = new int[] { 2, 4, 9, 10 }; + + assertEqualPages(new int[] { 2, 3, 4 }, + createMergedPage(2, + 3, + s1, + s2)); + + assertEqualPages(new int[] { 9, 10 }, + createMergedPage(7, + 2, + s1, + s2)); + + assertEqualPages(new int[] { 0, 1, 2, 3, 4 }, + createMergedPage(0, + 5, + s1, + s2)); + + assertEqualPages(new int[] { 0, 1, 2, 3, 4 }, + createMergedPage(0, + 5, + s1, + s2)); + + assertEqualPages(new int[] { 4, 7, 8, 9 }, + createMergedPage(4, + 4, + s1, + s2)); + + assertEqualPages(new int[] {}, + createMergedPage(10, + 4, + s1, + s2)); + + assertEqualPages(new int[] {}, + createMergedPage(9, + 1, + s1, + s2)); + + assertEqualPages(new int[] {}, + createMergedPage(9, + 1, + s1, + s2)); + + assertEqualPages(new int[] {}, + createMergedPage(11, + 3, + s1, + s2)); + + final int[] s3 = new int[] { 2, 3 }; + final int[] s4 = new int[] { 7, 10, 13, 11 }; + + assertEqualPages(new int[] { 13 }, + createMergedPage(5, + 2, + s3, + s4)); + + final int[] s5 = new int[] { 1, 2, 3 }; + final int[] s6 = new int[] { 5 }; + + assertEqualPages(new int[] { 5 }, + createMergedPage(3, + 1, + s5, + s6)); + + assertEqualPages(new int[] { 1, 2, 3, 5 }, + createMergedPage(0, + 0, + s5, + s6)); + } + + /** + * A page source that uses a generic array for the entire possible page + * range. + * + * @author Bogdan Horje + * @param + */ + class ArrayPageSource implements PagingResultsSource + { + private R[] array; + + private boolean boundsError; + + public ArrayPageSource(R[] array) + { + this(array, + true); + } + + public ArrayPageSource(R[] array, boolean boundsError) + { + super(); + this.array = array; + this.boundsError = boundsError; + } + + @Override + public PagingResults retrieve(PagingRequest pr) throws PageCollationException + { + final int skip = pr.getSkipCount(); + final int pageSize = pr.getMaxItems(); + if (skip < 0 || pageSize < 0) + { + throw new PageCollationException("Invalid page!"); + } + + if (boundsError && (skip >= array.length)) + { + throw new InvalidPageBounds("Out of bounds " + skip + ">=" + array.length); + } + + return new ListBackedPagingResults(Arrays.asList(array), + pr); + } + + } + + public void assertCollate(List results, Integer[] source, int skip, int pageSize) throws Exception + { + assertCollate(results, + source, + skip, + pageSize, + false); + } + + public void assertCollate(List results, Integer[] source, int skip, int pageSize, boolean boundsError) + throws Exception + { + Arrays.sort(source); + Collections.sort(results); + int[] expected = createMergedPage(skip, + pageSize, + results, + source); + PagingResults actualResults = new PageCollator().collate(results, + new ArrayPageSource(source), + new PagingRequest(skip, + pageSize), + new ComparableComparator()); + List actualPage = actualResults.getPage(); + + final String message = "[" + results + " + " + Arrays.toString(source) + " ] -> " + Arrays.toString(expected) + + " != " + actualPage; + assertEqualPages(message, + expected, + actualPage); + assertEquals("Invalid moreItems info!", + (pageSize != 0) && (skip + pageSize < results.size() + source.length), + actualResults.hasMoreItems()); + assertTrue(message, + (pageSize == 0) || actualPage.size() <= pageSize); + final int expectedTotal = source.length + results.size(); + if (boundsError && !new Pair(null, + null).equals(actualResults.getTotalResultCount())) + { + assertEquals("Invalid total info", + new Pair(expectedTotal, + expectedTotal), + actualResults.getTotalResultCount()); + } + logger.info(actualPage); + } + + @Test + public void testCollate() throws Exception + { + final List s1 = Arrays.asList(2, + 4, + 9, + 10); + final Integer[] s2 = new Integer[] { 0, 1, 3, 5, 7, 8 }; + + assertCollate(s1, + s2, + 0, + 3); + assertCollate(s1, + s2, + 2, + 3); + + final List s3 = Arrays.asList(2, + 4, + 9, + 10, + 12, + 15, + 17, + 18); + final Integer[] s4 = new Integer[] { 0, 1, 3, 8, 16, 19 }; + + assertCollate(s3, + s4, + 0, + 3); + assertCollate(s3, + s4, + 2, + 3); + assertCollate(s3, + s4, + 6, + 3); + assertCollate(s3, + s4, + 7, + 3); + + final List s5 = Arrays.asList(2, + 3, + 6, + 8); + final Integer[] s6 = new Integer[] { 7, 10, 13, 11, 17, 19 }; + + assertCollate(s5, + s6, + 0, + 1); + assertCollate(s5, + s6, + 1, + 2); + + } + + public void testCollateBoundary1() throws Exception + { + final List s1 = Arrays.asList(2, + 3); + final Integer[] s2 = new Integer[] { 7, 10, 13, 11 }; + + assertCollate(s1, + s2, + 6, + 1, + true); + } + + public void testCollateBoundary2() throws Exception + { + final List s1 = Arrays.asList(2, + 3); + final Integer[] s2 = new Integer[] { 7, 10, 13, 11 }; + + assertCollate(s1, + s2, + 5, + 2, + true); + } + + public void testCollateBoundary3() throws Exception + { + final List s1 = Arrays.asList(1, + 2, + 3); + final Integer[] s2 = new Integer[] { 5, 6, 7, 8 }; + + assertCollate(s1, + s2, + 6, + 1, + true); + } + + public void testCollateBoundary4() throws Exception + { + final List s1 = Arrays.asList(1, + 2, + 3); + final Integer[] s2 = new Integer[] { 5 }; + + assertCollate(s1, + s2, + 3, + 1, + false); + } + + public void testCollateBoundary5() throws Exception + { + final List s1 = Arrays.asList(2, + 3); + final Integer[] s2 = new Integer[] { 7, 10, 13 }; + + assertCollate(s1, + s2, + 10, + 2, + true); + } + + public void testCollateBoundary6() throws Exception + { + final List s1 = Arrays.asList(2, + 3); + final Integer[] s2 = new Integer[] { 7, 10, 13 }; + + assertCollate(s1, + s2, + 0, + 0, + true); + } + + public void testCollateBoundary7() throws Exception + { + final List s1 = Arrays.asList(10); + final Integer[] s2 = new Integer[] { 1, 2, 3 }; + + assertCollate(s1, + s2, + 6, + 1, + true); + } + + public void testCollateBoundary8() throws Exception + { + final List s1 = Arrays.asList(1); + final Integer[] s2 = new Integer[] { 5, 6, 7 }; + + assertCollate(s1, + s2, + 5, + 1, + true); + } + + public void testCollateBoundary9() throws Exception + { + final List s1 = Arrays.asList(1); + final Integer[] s2 = new Integer[] { 5 }; + + assertCollate(s1, + s2, + 0, + 2, + true); + } + + public void testCollateBoundary10() throws Exception + { + final List s1 = Arrays.asList(); + final Integer[] s2 = new Integer[] { 5 }; + + assertCollate(s1, + s2, + 0, + 2, + true); + } + + public void testCollateBoundary11() throws Exception + { + final List s1 = Arrays.asList(1); + final Integer[] s2 = new Integer[] {}; + + assertCollate(s1, + s2, + 0, + 1, + false); + } + + public void testCollateBoundary12() throws Exception + { + final List s1 = Arrays.asList(); + final Integer[] s2 = new Integer[] {}; + + assertCollate(s1, + s2, + 0, + 1, + false); + } + + public void testCollateBoundary13() throws Exception + { + final List s1 = Arrays.asList(6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14); + final Integer[] s2 = new Integer[] { 1 }; + + assertCollate(s1, + s2, + 3, + 5, + false); + } + + public void testCollateFalsePositive1() throws Exception + { + final List s1 = Arrays.asList(2, + 3); + final Integer[] s2 = new Integer[] { 7, 10, 13 }; + + try + { + new PageCollator().collate(s1, + new ArrayPageSource(s2), + new PagingRequest(-1, + 1), + new ComparableComparator()); + fail("Invalid page data."); + } + catch (PageCollationException e) + { + logger.info(e.getMessage()); + } + + try + { + new PageCollator().collate(s1, + new ArrayPageSource(s2), + new PagingRequest(1, + -1), + new ComparableComparator()); + fail("Invalid page data."); + } + catch (PageCollationException e) + { + logger.info(e.getMessage()); + } + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/ref/AbstractReferenceParserTest.java b/source/test-java/org/alfresco/repo/virtual/ref/AbstractReferenceParserTest.java new file mode 100644 index 0000000000..8951128cf8 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/ref/AbstractReferenceParserTest.java @@ -0,0 +1,53 @@ +package org.alfresco.repo.virtual.ref; + +import java.util.Arrays; +import java.util.List; + +import junit.framework.TestCase; + +import org.alfresco.service.cmr.repository.NodeRef; +import org.junit.Test; + +public abstract class AbstractReferenceParserTest extends TestCase +{ + @Test + public void assertRecursiveReferenceParser(Encoding encoding) throws Exception + { + List params0 = Arrays + . asList(new StringParameter("/6"), + new ResourceParameter(new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/67c8f11d-0936-4295-88a0-12b85764c76f"))))); + + Reference innerRef0 = new Reference(Encodings.ZERO.encoding, + Protocols.VANILLA.protocol, + new ClasspathResource("/some/cp.json"), + params0); + + List params1 = Arrays. asList(new StringParameter("/6"), + new ReferenceParameter(innerRef0)); + + Reference innerRef1 = new Reference(Encodings.ZERO.encoding, + Protocols.VANILLA.protocol, + new ClasspathResource("/some/cp.json"), + params1); + + List params2 = Arrays. asList(new ReferenceParameter(innerRef1)); + + Reference innerRef2 = new Reference(Encodings.ZERO.encoding, + Protocols.VANILLA.protocol, + new ClasspathResource("/some/cp.json"), + params2); + + List params = Arrays. asList(new ReferenceParameter(innerRef2),new ReferenceParameter(innerRef1),new StringParameter("AString")); + + Reference stringifiedReference = new Reference(Encodings.ZERO.encoding, + Protocols.NODE.protocol, + new RepositoryResource(new RepositoryPath("/A/repository/path/")), + params); + + String refString = encoding.stringifier.stringify(stringifiedReference); + Reference parsedReference = encoding.parser.parse(refString); + + assertEquals(stringifiedReference, + parsedReference); + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/ref/GetChildByIdMethodTest.java b/source/test-java/org/alfresco/repo/virtual/ref/GetChildByIdMethodTest.java new file mode 100644 index 0000000000..fbdd8791e0 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/ref/GetChildByIdMethodTest.java @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.ref; + +import java.util.Arrays; + +import junit.framework.TestCase; + +import org.junit.Test; + +public class GetChildByIdMethodTest extends TestCase +{ + + private String toChildPath(final String parentPath, String childName) throws ProtocolMethodException + { + StringParameter path = new StringParameter(parentPath); + + Reference ref = new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + new ClasspathResource("/a/class/path.js"), + Arrays.asList(path)); + GetChildByIdMethod method = new GetChildByIdMethod(childName); + + Reference childRef = ref.execute(method); + + assertEquals(ref.getResource(), + childRef.getResource()); + assertEquals(ref.getProtocol(), + childRef.getProtocol()); + + return childRef.execute(new GetTemplatePathMethod()); + } + + @Test + public void testExecute() throws Exception + { + final String parentPath = "/root"; + final String childName = "aChid"; + String childPath = toChildPath(parentPath, + childName); + + assertEquals(parentPath + "/" + childName, + childPath); + } + + @Test + public void testTrailingPath() throws Exception + { + String childPath = toChildPath(" /root/ ", + "child"); + + assertEquals("/root/child", + childPath); + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/ref/GetParentReferenceMethodTest.java b/source/test-java/org/alfresco/repo/virtual/ref/GetParentReferenceMethodTest.java new file mode 100644 index 0000000000..d05dbeac1c --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/ref/GetParentReferenceMethodTest.java @@ -0,0 +1,96 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.ref; + +import java.util.Arrays; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Test; + +public class GetParentReferenceMethodTest extends TestCase +{ + private GetParentReferenceMethod method; + + @Override + protected void setUp() throws Exception + { + method = new GetParentReferenceMethod(); + } + + @Test + public void testSpacePath() throws Exception + { + final String path = "/Media types/Images"; + assertEquals("/Media types", + toParentPath(path)); + } + + @Test + public void testTrailingPath() throws Exception + { + final String path = "/Media types/Images/"; + assertEquals("/Media types", + toParentPath(path)); + } + + @Test + public void testFirsLevelPath() throws Exception + { + final String path = "/Media types"; + assertEquals("/", + toParentPath(path)); + } + + @Test + public void testTrailingRoot() throws Exception + { + final String path = "/ "; + assertNull(toParentPath(path)); + } + + @Test + public void testRootPath() throws Exception + { + final String path = "/"; + assertNull(toParentPath(path)); + } + + private String toParentPath(final String path) throws ProtocolMethodException + { + List params = Arrays. asList(new StringParameter(path)); + Reference ref = new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + new ClasspathResource("/some/class/path.js"), + params); + Reference parent = ref.execute(method); + if (parent == null) + { + return null; + } + else + { + StringParameter parentPath = (StringParameter) parent.getParameters().get(0); + return parentPath.getValue(); + } + } + +} diff --git a/source/test-java/org/alfresco/repo/virtual/ref/HashStringifierTest.java b/source/test-java/org/alfresco/repo/virtual/ref/HashStringifierTest.java new file mode 100644 index 0000000000..922d93ba79 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/ref/HashStringifierTest.java @@ -0,0 +1,180 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.ref; + +import java.util.Collections; + +import junit.framework.TestCase; + +import org.alfresco.service.cmr.repository.NodeRef; +import org.junit.Test; + +public class HashStringifierTest extends TestCase +{ + private HashStore cpHashStore; + + public void setUp() + { + + cpHashStore = HashStoreConfiguration.getInstance().getClasspathHashStore(); + cpHashStore.put("/com/alfresco", + "1"); + + } + + private Reference stringifyParse(Reference reference) + { + String encodedReferenceString = new HashStringifier().stringify(reference); + Reference paresedReference = new HashReferenceParser().parse(encodedReferenceString); + + return paresedReference; + } + + @Test + public void testStringifyVirtualReference_nodeRef() + { + NodeRef templateNodeRef = new NodeRef("workspace://SpacesStore/0d3b26ff-c4c1-4680-8622-8608ea7ab4b2"); + NodeRef actualNode = new NodeRef("workspace://SpacesStore/67c8f11d-0936-4295-88a0-12b85764c76f"); + + Reference virtualReference = ((VirtualProtocol) Protocols.VIRTUAL.protocol).newReference(templateNodeRef, + "/1/2/3", + actualNode); + Reference spReference = stringifyParse(virtualReference); + + assertEquals(virtualReference, + spReference); + + } + + @Test + public void testStringifyVirtualReference_classpath() + { + ClasspathResource classpathTemplate = new ClasspathResource("/com/alfresco/template.js"); + NodeRef actualNode = new NodeRef("workspace://SpacesStore/67c8f11d-0936-4295-88a0-12b85764c76f"); + RepositoryResource actualNodeResource = new RepositoryResource(new RepositoryNodeRef(actualNode)); + Reference virtualReference = ((VirtualProtocol) Protocols.VIRTUAL.protocol) + .newReference(Encodings.PLAIN.encoding, + classpathTemplate, + "/1/2/3", + actualNodeResource, + Collections. emptyList()); + Reference spReference = stringifyParse(virtualReference); + + assertEquals(virtualReference, + spReference); + + } + + @Test + public void testStringifyVirtualReference_actualRepositoryPath() + { + ClasspathResource classpathTemplate = new ClasspathResource("/com/alfresco/template.js"); + RepositoryResource actualNodeResource = new RepositoryResource(new RepositoryPath("/app:company_home/cm:aVirtualFolder")); + Reference virtualReference = ((VirtualProtocol) Protocols.VIRTUAL.protocol) + .newReference(Encodings.PLAIN.encoding, + classpathTemplate, + "/1/2/3", + actualNodeResource, + Collections. emptyList()); + Reference spReference = stringifyParse(virtualReference); + + assertEquals(virtualReference, + spReference); + + } + + @Test + public void testStringifyVirtualReference_root() + { + NodeRef templateNodeRef = new NodeRef("workspace://SpacesStore/0d3b26ff-c4c1-4680-8622-8608ea7ab4b2"); + NodeRef actualNode = new NodeRef("workspace://SpacesStore/67c8f11d-0936-4295-88a0-12b85764c76f"); + + Reference virtualReference = ((VirtualProtocol) Protocols.VIRTUAL.protocol).newReference(templateNodeRef, + "/", + actualNode); + Reference spReference = stringifyParse(virtualReference); + + assertEquals(virtualReference, + spReference); + + } + + @Test + public void testStringifyNodeReference_actualRepositoryPath() + { + NodeRef templateNodeRef = new NodeRef("workspace://SpacesStore/0d3b26ff-c4c1-4680-8622-8608ea7ab4b2"); + NodeRef actualTemplateNode = new NodeRef("workspace://SpacesStore/67c8f11d-0936-4295-88a0-12b85764c76f"); + + Reference virtualReference = ((VirtualProtocol) Protocols.VIRTUAL.protocol).newReference(templateNodeRef, + "/1/2/3", + actualTemplateNode); + RepositoryResource actualNodeResource = new RepositoryResource(new RepositoryPath("/app:company_home/cm:aVirtualFolder")); + Reference nodeReference = NodeProtocol.newReference(Encodings.PLAIN.encoding, + actualNodeResource, + virtualReference); + Reference spReference = stringifyParse(nodeReference); + + assertEquals(nodeReference, + spReference); + } + + @Test + public void testStringifyNodeReference_actualNodeRef() + { + NodeRef templateNodeRef = new NodeRef("workspace://SpacesStore/0d3b26ff-c4c1-4680-8622-8608ea7ab4b2"); + NodeRef actualTemplateNode = new NodeRef("workspace://SpacesStore/67c8f11d-0936-4295-88a0-12b85764c76f"); + + Reference virtualReference = ((VirtualProtocol) Protocols.VIRTUAL.protocol).newReference(templateNodeRef, + "/1/2/3", + actualTemplateNode); + NodeRef actualNode = new NodeRef("workspace://SpacesStore/00c8f11d-0936-4295-88a0-12b85764c76f"); + Reference nodeReference = NodeProtocol.newReference(actualNode, + virtualReference); + Reference spReference = stringifyParse(nodeReference); + + assertEquals(nodeReference, + spReference); + + } + + @Test + public void testStringifyVanillaReference_classpath() + { + ClasspathResource virtualClasspathTemplate = new ClasspathResource("/com/alfresco/template.js"); + NodeRef actualNode = new NodeRef("workspace://SpacesStore/67c8f11d-0936-4295-88a0-12b85764c76f"); + RepositoryResource actualNodeResource = new RepositoryResource(new RepositoryNodeRef(actualNode)); + ClasspathResource vanillaClasspathTemplate = new ClasspathResource("/com/alfresco/vanilla-template.js"); + + Reference vanillaReference = ((VanillaProtocol) Protocols.VANILLA.protocol) + .newReference(Encodings.PLAIN.encoding, + virtualClasspathTemplate, + "/1/2/3", + actualNodeResource, + vanillaClasspathTemplate, + Collections. emptyList()); + + Reference spReference = stringifyParse(vanillaReference); + + assertEquals(vanillaReference, + spReference); + + } + +} diff --git a/source/test-java/org/alfresco/repo/virtual/ref/NewVirtualReferenceMethodTest.java b/source/test-java/org/alfresco/repo/virtual/ref/NewVirtualReferenceMethodTest.java new file mode 100644 index 0000000000..89e067020d --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/ref/NewVirtualReferenceMethodTest.java @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.ref; + +import java.util.Arrays; +import java.util.List; + +import junit.framework.TestCase; + +import org.alfresco.service.cmr.repository.NodeRef; +import org.junit.Test; + +public class NewVirtualReferenceMethodTest extends TestCase +{ + @Test + public void testExecute() throws Exception + { + final NodeRef templateRef = new NodeRef("workspace://SpacesStore/0029-2222-333-4424"); + final String templatePath = "/new/ref/path"; + final NodeRef actualNodeRef = new NodeRef("workspace://SpacesStore/2229-1234-5678-9012"); + NewVirtualReferenceMethod newVirtualReferenceMethod = new NewVirtualReferenceMethod(templateRef, + templatePath, + actualNodeRef, + null); + Reference ref = Protocols.VIRTUAL.protocol.dispatch(newVirtualReferenceMethod, + null); + final List expectedParams = Arrays + . asList(new StringParameter(templatePath), + new ResourceParameter(new RepositoryResource(new RepositoryNodeRef(actualNodeRef)))); + final Reference expectedRef = new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + new RepositoryResource(new RepositoryNodeRef(templateRef)), + expectedParams); + + assertEquals(expectedRef, + ref); + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/ref/NodeRefRadixHasherTest.java b/source/test-java/org/alfresco/repo/virtual/ref/NodeRefRadixHasherTest.java new file mode 100644 index 0000000000..effeb458ac --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/ref/NodeRefRadixHasherTest.java @@ -0,0 +1,137 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.ref; + +import junit.framework.TestCase; + +import org.alfresco.repo.version.Version2Model; +import org.alfresco.repo.version.VersionModel; +import org.alfresco.service.cmr.repository.NodeRef; +import org.alfresco.service.cmr.repository.StoreRef; +import org.alfresco.service.cmr.version.VersionService; +import org.alfresco.util.Pair; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Test; + +public class NodeRefRadixHasherTest extends TestCase +{ + private static Log logger = LogFactory.getLog(NodeRefRadixHasherTest.class); + + @Test + public void testSupportedStores() throws Exception + { + NodeRefRadixHasher h = NodeRefRadixHasher.RADIX_36_HASHER; + + String[] storeProtocols = new String[] { StoreRef.PROTOCOL_WORKSPACE, StoreRef.PROTOCOL_ARCHIVE, + StoreRef.PROTOCOL_AVM, StoreRef.PROTOCOL_DELETED, VersionService.VERSION_STORE_PROTOCOL }; + String[] storeIds = new String[] { "SpacesStore", VersionModel.STORE_ID, Version2Model.STORE_ID }; + + for (int i = 0; i < storeProtocols.length; i++) + { + for (int j = 0; j < storeIds.length; j++) + { + NodeRef nr = new NodeRef(storeProtocols[i], + storeIds[j], + "0d3b26ff-c4c1-4680-8622-8608ea7ab4b2"); + Pair nh = h.hash(nr); + NodeRef nr2 = h.lookup(nh); + assertEquals("Could match hash-lookup " + nr, + nr, + nr2); + } + } + } + + @Test + public void testZeroPaddedNodeId() throws Exception + { + NodeRefRadixHasher h = NodeRefRadixHasher.RADIX_36_HASHER; + NodeRef nr = new NodeRef("workspace://SpacesStore/0d3b26ff-c4c1-4680-8622-8608ea7ab4b2"); + Pair nh = h.hash(nr); + NodeRef nr2 = h.lookup(nh); + assertEquals(nr, + nr2); + } + + @Test + public void testInvalidStoreId() throws Exception + { + NodeRefRadixHasher h = NodeRefRadixHasher.RADIX_36_HASHER; + NodeRef nr = new NodeRef("workspace://ASpacesStore/0d3b26ff-c4c1-4680-8622-8608ea7ab4b2"); + try + { + h.hash(nr); + fail("Should not be able to hash invalid store NodeRef " + nr); + } + catch (RuntimeException e) + { + logger.info("Caught invalid NodeRef " + e.getMessage()); + } + } + + @Test + public void testInvalidStoreProtocol() throws Exception + { + NodeRefRadixHasher h = NodeRefRadixHasher.RADIX_36_HASHER; + NodeRef nr = new NodeRef("Xworkspace://SpacesStore/0d3b26ff-c4c1-4680-8622-8608ea7ab4b2"); + try + { + h.hash(nr); + fail("Should not be able to hash invalid store NodeRef " + nr); + } + catch (RuntimeException e) + { + logger.info("Caught invalid NodeRef " + e.getMessage()); + } + } + + @Test + public void testInvalidNodeId1() throws Exception + { + NodeRefRadixHasher h = NodeRefRadixHasher.RADIX_36_HASHER; + NodeRef nr = new NodeRef("workspace://SpacesStore/0d3b26ff-c4c1-4680-8622-8608ea7ab4"); + try + { + h.hash(nr); + fail("Should not be able to hash invalid id (length) NodeRef " + nr); + } + catch (RuntimeException e) + { + logger.info("Caught invalid NodeRef " + e.getMessage()); + } + } + + @Test + public void testInvalidNodeId2() throws Exception + { + NodeRefRadixHasher h = NodeRefRadixHasher.RADIX_36_HASHER; + NodeRef nr = new NodeRef("workspace://SpacesStore/0d3b26ff-c4c14680-8622-8608ea7ab4b29"); + try + { + h.hash(nr); + fail("Should not be able to hash invalid id (format) NodeRef " + nr); + } + catch (RuntimeException e) + { + logger.info("Caught invalid NodeRef " + e.getMessage()); + } + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/ref/NumericPathHasherTest.java b/source/test-java/org/alfresco/repo/virtual/ref/NumericPathHasherTest.java new file mode 100644 index 0000000000..fd3f4546d1 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/ref/NumericPathHasherTest.java @@ -0,0 +1,118 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.ref; + +import junit.framework.TestCase; + +import org.alfresco.util.Pair; +import org.apache.commons.codec.binary.Base64; +import org.junit.Test; + +public class NumericPathHasherTest extends TestCase +{ + @Test + public void testHash() throws Exception + { + NumericPathHasher nph = new NumericPathHasher(); + + Pair h1 = nph.hash("/1/2/3"); + assertEquals(new Pair("123", + null), + h1); + + Pair h2 = nph.hash("/a/2/3"); + String xc2 = new String(Base64.encodeBase64("/a/2/3".getBytes(), + false)); + assertEquals(new Pair(null, + xc2), + h2); + + Pair h3 = nph.hash("/1/2/a/1/3"); + String xc3 = new String(Base64.encodeBase64("a/1/3".getBytes(), + false)); + assertEquals(new Pair("12", + xc3), + h3); + + } + + @Test + public void testHashRoot() throws Exception + { + NumericPathHasher nph = new NumericPathHasher(); + + Pair h1 = nph.hash("/"); + assertEquals(new Pair(null, + ""), + h1); + } + + @Test + public void testLookupRoot() throws Exception + { + NumericPathHasher nph = new NumericPathHasher(); + + String p = nph.lookup(new Pair(null, + "")); + assertEquals("/", + p); + } + + @Test + public void testLookup() throws Exception + { + NumericPathHasher nph = new NumericPathHasher(); + Pair h = nph.hash("/1/2/3"); + + assertEquals(new Pair("123", + null), + h); + + String xc2 = new String(Base64.encodeBase64("/a/2/3".getBytes(), + false)); + String p2 = nph.lookup(new Pair(null, + xc2)); + assertEquals("/a/2/3", + p2); + + String xc3 = new String(Base64.encodeBase64("a/1/3".getBytes(), + false)); + String p3 = nph.lookup(new Pair("12", + xc3)); + assertEquals("/1/2/a/1/3", + p3); + } + + @Test + public void testHashEmpty() throws Exception + { + NumericPathHasher nph = new NumericPathHasher(); + + try + { + nph.hash(""); + fail("Should not be able to hash empty String"); + } + catch (IllegalArgumentException e) + { + // as expected + } + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/ref/PlainReferenceParserTest.java b/source/test-java/org/alfresco/repo/virtual/ref/PlainReferenceParserTest.java new file mode 100644 index 0000000000..63260b723d --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/ref/PlainReferenceParserTest.java @@ -0,0 +1,249 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.ref; + +import java.util.Arrays; +import java.util.List; + +import org.alfresco.service.cmr.repository.NodeRef; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Test; + +public class PlainReferenceParserTest extends AbstractReferenceParserTest +{ + + private static Log logger = LogFactory.getLog(PlainReferenceParserTest.class); + + @Test + public void testRecursiveReferenceParser() throws Exception + { + assertRecursiveReferenceParser(Encodings.PLAIN.encoding); + } + + @Test + public void testParseClasspathResource() throws Exception + { + { + Reference pr = new PlainReferenceParser().parse("virtual:classpath:/org/alfresco/"); + Reference r = new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + new ClasspathResource("/org/alfresco/")); + assertEquals(r, + pr); + } + + { + Reference prp1 = new PlainReferenceParser() + .parse("virtual:classpath:/org/alfresco/:r:repository:node:workspace:SpacesStore:0029-222-333-444"); + RepositoryResource rr1 = new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/0029-222-333-444"))); + List params1 = Arrays. asList(new ResourceParameter(rr1)); + Reference rp1 = new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + new ClasspathResource("/org/alfresco/"), + params1); + assertEquals(rp1, + prp1); + } + { + Reference prp2 = new PlainReferenceParser() + .parse("virtual:classpath:/org/alfresco/:r:repository:node:workspace:SpacesStore:0029-222-333-444:r:repository:path:/Data Dictionary/Virtual Folders/claim.json"); + RepositoryResource rr21 = new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/0029-222-333-444"))); + RepositoryResource rr22 = new RepositoryResource(new RepositoryPath("/Data Dictionary/Virtual Folders/claim.json")); + List params2 = Arrays. asList(new ResourceParameter(rr21), + new ResourceParameter(rr22)); + Reference rp2 = new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + new ClasspathResource("/org/alfresco/"), + params2); + assertEquals(rp2, + prp2); + } + } + + @Test + public void testParseRepositoryNodeRef() throws Exception + { + Reference reference = new PlainReferenceParser() + .parse("virtual:repository:node:workspace:SpacesStore:0029-222-333-444"); + + assertEquals(reference, + new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/0029-222-333-444"))))); + + } + + @Test + public void testParseRepositoryPath() throws Exception + { + Reference reference = new PlainReferenceParser().parse("virtual:repository:path:/Foo/Bar"); + + assertEquals(reference, + new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + new RepositoryResource(new RepositoryPath("/Foo/Bar")))); + + } + + @Test + public void testParseNodeProtocol() throws Exception + { + // testing parse for node protocol with an repository node as reference + // parameter + Reference reference = new PlainReferenceParser() + .parse("node:repository:node:workspace:SpacesStore:0029-222-333-444:r:repository:node:workspace:SpacesStore:0029-122-333-0023:ref:node:repository:node:workspace:SpacesStore:0029-222-333-444:r:repository:path:/Foo/Bar:s:vm_virtual:*"); + + RepositoryResource rr = new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/0029-122-333-0023"))); + List params = Arrays. asList(new ResourceParameter(rr), + new ReferenceParameter(reference)); + /* + * assertEquals(reference, new Reference(Encodings.PLAIN.encoding, + * Protocols.NODE.protocol, new RepositoryResource(new + * RepositoryNodeRef(new + * NodeRef("workspace://SpacesStore/0029-222-333-444"))), params)); + */ + + // testing parse for node protocol with an repository path as reference + // parameter + reference = new PlainReferenceParser() + .parse("node:repository:node:workspace:SpacesStore:0029-222-333-444:r:repository:path:/Foo/Bar"); + + rr = new RepositoryResource(new RepositoryPath("/Foo/Bar")); + params = Arrays. asList(new ResourceParameter(rr)); + assertEquals(reference, + new Reference(Encodings.PLAIN.encoding, + Protocols.NODE.protocol, + new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/0029-222-333-444"))), + params)); + + // testing parse for node protocol with an repository path and a string + // as reference parameters + reference = new PlainReferenceParser() + .parse("node:repository:node:workspace:SpacesStore:0029-222-333-444:r:repository:path:/Foo/Bar:s:vm_virtual"); + + rr = new RepositoryResource(new RepositoryPath("/Foo/Bar")); + params = Arrays. asList(new ResourceParameter(rr), + new StringParameter("vm_virtual")); + assertEquals(reference, + new Reference(Encodings.PLAIN.encoding, + Protocols.NODE.protocol, + new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/0029-222-333-444"))), + params)); + } + + @Test + public void testReferenceDelimiter() + { + Reference parsedRef = new PlainReferenceParser() + .parse("vanilla:repository:path:/Company Home/Data Dictionary/:ref:vanilla:classpath:/org/alfresco/repo/virtual/node/vanilla.js:s:/Images/ JPG images/:r:repository:node:workspace:SpacesStore:67c8f11d-0936-4295-88a0-12b85764c76f:r:repository:node:workspace:SpacesStore:6428d7cc-feaa-4e32-a983-0b357439a994:*"); + List params = Arrays + . asList(new StringParameter("/Images/ JPG images/"), + new ResourceParameter(new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/67c8f11d-0936-4295-88a0-12b85764c76f")))), + new ResourceParameter(new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/6428d7cc-feaa-4e32-a983-0b357439a994"))))); + Reference innerRef = new Reference(Encodings.PLAIN.encoding, + Protocols.VANILLA.protocol, + new ClasspathResource("/org/alfresco/repo/virtual/node/vanilla.js"), + params); + + List prms = Arrays. asList(new ReferenceParameter(innerRef)); + Reference createdRef = new Reference(Encodings.PLAIN.encoding, + Protocols.VANILLA.protocol, + new RepositoryResource(new RepositoryPath("/Company Home/Data Dictionary/")), + prms); + assertEquals(parsedRef, + createdRef); + + + + Reference parsedRef1 = new PlainReferenceParser() + .parse("node:repository:path:/Company Home/Data Dictionary/:ref:vanilla:classpath:/org/alfresco/repo/virtual/node/vanilla.js:s:/My Documents:r:repository:node:workspace:SpacesStore:67c8f11d-0936-4295-88a0-12b85764c76f:r:repository:node:workspace:SpacesStore:6428d7cc-feaa-4e32-a983-0b357439a994:*:ref:vanilla:classpath:/org/alfresco/repo/virtual/node/vanilla.js:s:/My Documents:r:repository:node:workspace:SpacesStore:67c8f11d-0936-4295-88a0-12b85764c76f:r:repository:node:workspace:SpacesStore:6428d7cc-feaa-4e32-a983-0b357439a994:*"); + List params1 = Arrays + . asList(new StringParameter("/My Documents"), + new ResourceParameter(new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/67c8f11d-0936-4295-88a0-12b85764c76f")))), + new ResourceParameter(new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/6428d7cc-feaa-4e32-a983-0b357439a994"))))); + Reference innerRef1 = new Reference(Encodings.PLAIN.encoding, + Protocols.VANILLA.protocol, + new ClasspathResource("/org/alfresco/repo/virtual/node/vanilla.js"), + params1); + Reference innerRef2 = new Reference(Encodings.PLAIN.encoding, + Protocols.VANILLA.protocol, + new ClasspathResource("/org/alfresco/repo/virtual/node/vanilla.js"), + params1); + + List prms1 = Arrays. asList(new ReferenceParameter(innerRef1), + new ReferenceParameter(innerRef2)); + Reference createdRef1 = new Reference(Encodings.PLAIN.encoding, + Protocols.NODE.protocol, + new RepositoryResource(new RepositoryPath("/Company Home/Data Dictionary/")), + prms1); + assertEquals(parsedRef1, + createdRef1); + + + Reference parsedRef2 = new PlainReferenceParser() + .parse("virtual:classpath:/Company Home/:ref:vanilla:classpath:/org/alfresco/repo/virtual/node/vanilla.js:s:/My Documents/+=?Folder:r:repository:path:/this/ repo/ path/:r:classpath:/org/alfresco/repo/virtual/template.js:*:ref:vanilla:classpath:virtual.js:*"); + List params2 = Arrays + . asList(new StringParameter("/My Documents/+=?Folder"), + new ResourceParameter(new RepositoryResource(new RepositoryPath("/this/ repo/ path/"))), + new ResourceParameter(new ClasspathResource("/org/alfresco/repo/virtual/template.js"))); + Reference innerRef3 = new Reference(Encodings.PLAIN.encoding, + Protocols.VANILLA.protocol, + new ClasspathResource("/org/alfresco/repo/virtual/node/vanilla.js"), + params2); + Reference innerRef4 = new Reference(Encodings.PLAIN.encoding, + Protocols.VANILLA.protocol, + new ClasspathResource("virtual.js")); + + List prms2 = Arrays. asList(new ReferenceParameter(innerRef3), + new ReferenceParameter(innerRef4)); + Reference createdRef2 = new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + new ClasspathResource("/Company Home/"), + prms2); + assertEquals(parsedRef2, + createdRef2); + } + + protected void assertReferenceParseException(String reference) + { + try + { + new PlainReferenceParser().parse(reference); + fail("\"" + reference + "\" should not be parsed!"); + } + catch (ReferenceParseException e) + { + logger.info(e); + } + + } + + @Test + public void testParseError1() throws Exception + { + assertReferenceParseException("x:folder:classpath:/org/alfresco/"); + assertReferenceParseException("plain:folder:classpath:/org/alfresco/"); + assertReferenceParseException("folder:x:/org/alfresco/"); + assertReferenceParseException("folder:classpath:"); + assertReferenceParseException("folder:classpath:/org/alfresco/:x:u"); + + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/ref/PlainStringifierTest.java b/source/test-java/org/alfresco/repo/virtual/ref/PlainStringifierTest.java new file mode 100644 index 0000000000..51088104a1 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/ref/PlainStringifierTest.java @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.ref; + +import junit.framework.TestCase; + +import org.alfresco.service.cmr.repository.NodeRef; +import org.junit.Test; + +public class PlainStringifierTest extends TestCase +{ + @Test + public void testEncode1() throws Exception + { + Reference r = new Reference(Encodings.ZERO.encoding, + Protocols.VIRTUAL.protocol, + new ClasspathResource("/org/alfresco/")); + assertEquals("virtual:classpath:/org/alfresco/", + r.encode(Encodings.PLAIN.encoding)); + } + + @Test + public void testStringifyReference() throws Exception + { + Reference r = new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + new ClasspathResource("/org/alfresco/")); + + } + + public void testStringifyRepositoryNodeRef() throws Exception + { + + RepositoryResource rr1 = new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/0029-222-333-444"))); + Reference r = new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + rr1); + assertEquals("virtual:repository:node:workspace:SpacesStore:0029-222-333-444", + r.encode(Encodings.PLAIN.encoding)); + + } + + public void testStringifyRepositoryPath() throws Exception + { + RepositoryResource rr2 = new RepositoryResource(new RepositoryPath("/Data Dictionary/Virtual Folders/claim.json")); + Reference r = new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + rr2); + assertEquals("virtual:repository:path:/Data Dictionary/Virtual Folders/claim.json", + r.encode(Encodings.PLAIN.encoding)); + + } + +} diff --git a/source/test-java/org/alfresco/repo/virtual/ref/ProtocolTest.java b/source/test-java/org/alfresco/repo/virtual/ref/ProtocolTest.java new file mode 100644 index 0000000000..5f23afcbb8 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/ref/ProtocolTest.java @@ -0,0 +1,168 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.ref; + +import java.util.Arrays; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Test; + +public class ProtocolTest extends TestCase +{ + + private StringParameter p1; + + private ResourceParameter p2; + + private List> parameters; + + private Reference r; + + private Protocol protocol = new Protocol("unitTest"); + + @Override + protected void setUp() throws Exception + { + p1 = new StringParameter("sp1"); + p2 = new ResourceParameter(new ClasspathResource("/r/p.js")); + + parameters = Arrays.asList(p1, + p2); + r = new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + new ClasspathResource("/a/b/c.class"), + parameters); + } + + @Test + public void testGetParameter() throws Exception + { + Parameter tp1 = protocol.getParameter(r, + 0); + assertEquals(p1, + tp1); + Parameter tp2 = protocol.getParameter(r, + 1); + assertEquals(p2, + tp2); + + try + { + protocol.getParameter(r, + -1); + fail("Out of bounds!"); + } + catch (IndexOutOfBoundsException e) + { + e.printStackTrace(); + } + + try + { + protocol.getParameter(r, + 2); + fail("Out of bounds!"); + } + catch (IndexOutOfBoundsException e) + { + e.printStackTrace(); + } + } + + @Test + public void testReplaceParameter() throws Exception + { + final StringParameter newParameter = new StringParameter("rep1"); + Reference rr1 = protocol.replaceParameter(r, + 0, + newParameter); + assertEquals(newParameter, + protocol.getParameter(rr1, + 0)); + + try + { + protocol.replaceParameter(r, + 2, + newParameter); + fail("Out of bounds!"); + } + catch (IndexOutOfBoundsException e) + { + e.printStackTrace(); + } + } + + @Test + public void testAddParameter() throws Exception + { + final StringParameter newParameter = new StringParameter("rep1"); + Reference rr1 = protocol.addParameter(r, + newParameter); + assertEquals(newParameter, + protocol.getParameter(rr1, + 2)); + + } + + @Test + public void testDispatch() throws Exception + { + boolean sccess = protocol.dispatch(new ProtocolMethod() + { + + @Override + public Boolean execute(VanillaProtocol vanillaProtocol, + Reference reference) throws ProtocolMethodException + { + fail("Invalid dispatch"); + return false; + } + + @Override + public Boolean execute(VirtualProtocol virtualProtocol, + Reference reference) throws ProtocolMethodException + { + fail("Invalid dispatch"); + return false; + } + + @Override + public Boolean execute(NodeProtocol protocol, Reference reference) + throws ProtocolMethodException + { + fail("Invalid dispatch"); + return false; + } + + @Override + public Boolean execute(Protocol protocol, Reference reference) + throws ProtocolMethodException + { + return true; + } + }, + r); + + assertTrue(sccess); + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/ref/ReferenceTest.java b/source/test-java/org/alfresco/repo/virtual/ref/ReferenceTest.java new file mode 100644 index 0000000000..306e70de7c --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/ref/ReferenceTest.java @@ -0,0 +1,154 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.ref; + +import java.util.Arrays; +import java.util.List; + +import junit.framework.TestCase; + +import org.alfresco.service.cmr.repository.NodeRef; +import org.junit.Test; + +public class ReferenceTest extends TestCase +{ + private static final String TEST_CLASSPATH = "/org/alfresco/"; + + private static final String TEST_PLAIN_REFERENCE = "virtual:classpath:" + TEST_CLASSPATH; + + private static final String TEST_NODE_REF = "workspace://SpacesStore/vpdmlydHVhbDpjbGFzc3BhdGg6L29yZy9hbGZyZXNjby8="; + + private static final String TEST_NODE_REF_1 = "workspace://SpacesStore/vpdmFuaWxsYTpjbGFzc3BhdGg6L29yZy9hbGZyZXNjby9yZXBvL3ZpcnR1YWwvbm9kZS92YW5pbGxhLmpzOnM6LzAxIENvcnJlc3BvbmRlbmNlOnI6cmVwb3NpdG9yeTpub2RlOndvcmtzcGFjZTpTcGFjZXNTdG9yZTo2NWM2NjliMS00N2IzLTQzMmUtYjk0Zi1lZmU4YTcyYWEyMjA6cjpjbGFzc3BhdGg6L29yZy9hbGZyZXNjby9yZXBvL3ZpcnR1YWwvbm9kZS9jbGFpbXNEZW1vLmpzb24"; + + private static final Reference TEST_REFERENCE = new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + new ClasspathResource(TEST_CLASSPATH)); + + @Test + public void testToNodeRef() throws Exception + { + Reference r = new PlainReferenceParser().parse(TEST_PLAIN_REFERENCE); + NodeRef nodeRef = r.toNodeRef(); + assertEquals(new NodeRef(TEST_NODE_REF), + nodeRef); + } + + @Test + public void testFromNodeRef() throws Exception + { + Reference r = Reference.fromNodeRef(new NodeRef(TEST_NODE_REF)); + Reference expectedReference = TEST_REFERENCE; + + assertEquals(expectedReference, + r); + + String expected = "vanilla:classpath:/org/alfresco/repo/virtual/node/vanilla.js:s:/01 Correspondence:r:repository:node:workspace:SpacesStore:65c669b1-47b3-432e-b94f-efe8a72aa220:r:classpath:/org/alfresco/repo/virtual/node/claimsDemo.json"; + Reference fromNodeRef = Reference.fromNodeRef(new NodeRef(TEST_NODE_REF_1)); + assertNotNull(fromNodeRef); + assertEquals(expected, + fromNodeRef.toString()); + } + + @Test + public void testExecute() throws Exception + { + boolean sccess = TEST_REFERENCE.execute(new ProtocolMethod() + { + + @Override + public Boolean execute(VanillaProtocol vanillaProtocol, Reference reference) throws ProtocolMethodException + { + fail("Invalid dispatch"); + return false; + } + + @Override + public Boolean execute(VirtualProtocol virtualProtocol, Reference reference) throws ProtocolMethodException + { + return reference == TEST_REFERENCE; + } + + @Override + public Boolean execute(NodeProtocol protocol, Reference reference) throws ProtocolMethodException + { + fail("Invalid dispatch"); + return false; + } + + @Override + public Boolean execute(Protocol protocol, Reference reference) throws ProtocolMethodException + { + fail("Invalid dispatch"); + return false; + } + }); + + assertTrue("Invalid method execution result!", + sccess); + } + + @Test + public void testEncode() throws Exception + { + Reference r = TEST_REFERENCE; + assertEquals(TEST_PLAIN_REFERENCE, + r.encode()); + } + + @Test + public void testEquals() throws Exception + { + assertTrue(TEST_REFERENCE.equals(TEST_REFERENCE)); + assertFalse(TEST_REFERENCE.equals(null)); + Reference testResourceReplica = new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + new ClasspathResource(TEST_CLASSPATH)); + + assertTrue(TEST_REFERENCE.equals(testResourceReplica)); + Reference nullResRef = new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + null); + Reference nullResRefReplica = new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + null); + assertFalse(TEST_REFERENCE.equals(nullResRef)); + assertFalse(nullResRef.equals(TEST_REFERENCE)); + assertTrue(nullResRef.equals(nullResRefReplica)); + + List params1 = Arrays. asList(new StringParameter("P1")); + List params2 = Arrays. asList(new StringParameter("P1"), + new StringParameter("P2")); + Reference testParams1Ref = new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + new ClasspathResource(TEST_CLASSPATH), + params1); + Reference testParams1RefReplica = new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + new ClasspathResource(TEST_CLASSPATH), + params1); + Reference testParams2Ref = new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + new ClasspathResource(TEST_CLASSPATH), + params2); + assertTrue(testParams1Ref.equals(testParams1RefReplica)); + assertFalse(testParams2Ref.equals(testParams1Ref)); + } + +} diff --git a/source/test-java/org/alfresco/repo/virtual/ref/ResourceParameterTest.java b/source/test-java/org/alfresco/repo/virtual/ref/ResourceParameterTest.java new file mode 100644 index 0000000000..83451722f4 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/ref/ResourceParameterTest.java @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.ref; + +import org.alfresco.service.cmr.repository.NodeRef; +import org.junit.Test; + +import junit.framework.TestCase; + +public class ResourceParameterTest extends TestCase +{ + @Test + public void testResourceParameter() throws Exception + { + RepositoryResource repoNodeRefResource = new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/0029-222-333-444"))); + RepositoryResource repoPathResource = new RepositoryResource(new RepositoryPath("/Foo/Bar")); + ClasspathResource classpathResource = new ClasspathResource("/org/alfresco/"); + ResourceParameter repoNodeRefResourceParam = new ResourceParameter(repoNodeRefResource); + ResourceParameter repoPathResourceParam = new ResourceParameter(repoPathResource); + ResourceParameter classpathResourceParam = new ResourceParameter(classpathResource); + + // + assertEquals(repoNodeRefResource, + repoNodeRefResourceParam.getValue()); + + String repoNodeRefResourceParamStrRepresentation = repoNodeRefResourceParam.stringify(new PlainStringifier()); + + assertEquals("r:repository:node:workspace:SpacesStore:0029-222-333-444", + repoNodeRefResourceParamStrRepresentation); + + // + assertEquals(repoPathResource, + repoPathResourceParam.getValue()); + + String repoPathResourceParamStrRepresentation = repoPathResourceParam.stringify(new PlainStringifier()); + + assertEquals("r:repository:path:/Foo/Bar", + repoPathResourceParamStrRepresentation); + + // + + assertEquals(classpathResource, + classpathResourceParam.getValue()); + + String classpathResourceParamStrRepresentation = classpathResourceParam.stringify(new PlainStringifier()); + + assertEquals("r:classpath:/org/alfresco/", + classpathResourceParamStrRepresentation); + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/ref/StoredPathHasherTest.java b/source/test-java/org/alfresco/repo/virtual/ref/StoredPathHasherTest.java new file mode 100644 index 0000000000..c157e22659 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/ref/StoredPathHasherTest.java @@ -0,0 +1,118 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.ref; + +import junit.framework.TestCase; + +import org.alfresco.util.Pair; +import org.apache.commons.codec.binary.Base64; +import org.junit.Test; + +public class StoredPathHasherTest extends TestCase +{ + private HashStore hashStore; + + public void setUp() + { + hashStore = new HashStore(); + hashStore.put("/com/alfresco", + "1"); + } + + @Test + public void testHash() throws Exception + { + + hashStore.put("/org/alfresco", + "2"); + + StoredPathHasher hasher = new StoredPathHasher(hashStore); + + assertEquals(new Pair("1", + null), + hasher.hash("/com/alfresco/")); + + assertEquals(new Pair("1", + null), + hasher.hash("/com/alfresco")); + + assertEquals(new Pair(null, + Base64.encodeBase64String("/com".getBytes())), + hasher.hash("/com")); + + assertEquals(new Pair(null, + Base64.encodeBase64String("/com".getBytes())), + hasher.hash("/com/")); + + assertEquals(new Pair("1", + Base64.encodeBase64String("foo/bar".getBytes())), + hasher.hash("/com/alfresco/foo/bar")); + + assertEquals(new Pair("2", + Base64.encodeBase64String("foo/bar".getBytes())), + hasher.hash("/org/alfresco/foo/bar")); + } + + @Test + public void testHashRoot() throws Exception + { + StoredPathHasher hasher = new StoredPathHasher(hashStore); + + assertEquals(new Pair(null, + ""), + hasher.hash("/")); + } + + @Test + public void testNullPaths() throws Exception + { + + { + + StoredPathHasher hasher = new StoredPathHasher(hashStore); + + try + { + hasher.hash(""); + fail("Shold not be able to hash empty paths."); + } + catch (IllegalArgumentException e) + { + // as expected + } + } + + { + + StoredPathHasher hasher = new StoredPathHasher(hashStore); + + try + { + hasher.hash(null); + fail("Shold not be able to hash null paths."); + } + catch (IllegalArgumentException e) + { + // as expected + } + } + } + +} diff --git a/source/test-java/org/alfresco/repo/virtual/ref/StringParameterTest.java b/source/test-java/org/alfresco/repo/virtual/ref/StringParameterTest.java new file mode 100644 index 0000000000..eeebd3c374 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/ref/StringParameterTest.java @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.ref; + +import org.junit.Test; + +import junit.framework.TestCase; + +public class StringParameterTest extends TestCase +{ + @Test + public void testStringParameter() throws Exception + { + StringParameter strParam1 = new StringParameter("value1"); + assertEquals("value1", + strParam1.getValue()); + + String strRepresentation = strParam1.stringify(new PlainStringifier()); + + assertEquals("s:value1", + strRepresentation); + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/ref/VirtualProtocolTest.java b/source/test-java/org/alfresco/repo/virtual/ref/VirtualProtocolTest.java new file mode 100644 index 0000000000..1dec848db4 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/ref/VirtualProtocolTest.java @@ -0,0 +1,152 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.ref; + +import java.util.Arrays; +import java.util.List; + +import junit.framework.TestCase; + +import org.alfresco.service.cmr.repository.NodeRef; +import org.junit.Test; + +public class VirtualProtocolTest extends TestCase +{ + private static final String TEST_ACTUAL_NODE_REF_1 = "workspace://SpacesStore/0001-0002-0003-0004"; + + private static final String TEST_TEAMPLATE_CP_1 = "/org/alfresco/repo/test.js"; + + private ClasspathResource template1; + + private RepositoryResource actual1; + + private StringParameter templatePath1; + + private List> parameters1; + + private Reference r1; + + private VirtualProtocol virtualProtocol; + + @Override + protected void setUp() throws Exception + { + templatePath1 = new StringParameter("/root/child"); + template1 = new ClasspathResource(TEST_TEAMPLATE_CP_1); + actual1 = new RepositoryResource(new RepositoryNodeRef(new NodeRef(TEST_ACTUAL_NODE_REF_1))); + + parameters1 = Arrays.asList(templatePath1, + new ResourceParameter(actual1)); + r1 = new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + template1, + parameters1); + virtualProtocol = new VirtualProtocol(); + } + + @Test + public void testGetTemplatePath() throws Exception + { + String tp = virtualProtocol.getTemplatePath(r1); + assertEquals(templatePath1.getValue(), + tp); + } + + @Test + public void testGetActualNodeLocation() throws Exception + { + RepositoryLocation al = virtualProtocol.getActualNodeLocation(r1); + assertEquals(actual1.getLocation(), + al); + } + + @Test + public void testReplaceTemplatePath() throws Exception + { + final String newPath = "/root/child/anotherChild"; + Reference r = virtualProtocol.replaceTemplatePath(r1, + newPath); + String templatePath = virtualProtocol.getTemplatePath(r); + assertEquals(newPath, + templatePath); + } + + @Test + public void testNewReference() throws Exception + { + final String repoPath = "/a/repo/path"; + Reference nr1 = virtualProtocol.newReference(VirtualProtocol.NODE_TEMPLATE_PATH_TOKEN + repoPath, + "/root/child", + new NodeRef(TEST_ACTUAL_NODE_REF_1)); + final Resource repoResource = new RepositoryResource(new RepositoryPath(repoPath)); + assertEquals(repoResource, + nr1.getResource()); + + final String classpath = "/a/class/path"; + Reference nr2 = virtualProtocol.newReference(VirtualProtocol.CLASS_TEMPLATE_PATH_TOKEN + classpath, + "/root/child", + new NodeRef(TEST_ACTUAL_NODE_REF_1)); + final Resource classpathResource = new ClasspathResource(classpath); + assertEquals(classpathResource, + nr2.getResource()); + } + + @Test + public void testDispatch() throws Exception + { + boolean sccess = virtualProtocol.dispatch(new ProtocolMethod() + { + + @Override + public Boolean execute(VanillaProtocol vanillaProtocol, + Reference reference) throws ProtocolMethodException + { + fail("Invalid dispatch"); + return false; + } + + @Override + public Boolean execute(VirtualProtocol virtualProtocol, + Reference reference) throws ProtocolMethodException + { + return true; + } + + @Override + public Boolean execute(NodeProtocol protocol, Reference reference) + throws ProtocolMethodException + { + fail("Invalid dispatch"); + return false; + } + + @Override + public Boolean execute(Protocol protocol, Reference reference) + throws ProtocolMethodException + { + fail("Invalid dispatch"); + return false; + } + }, + r1); + + assertTrue(sccess); + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/ref/ZeroReferenceParserTest.java b/source/test-java/org/alfresco/repo/virtual/ref/ZeroReferenceParserTest.java new file mode 100644 index 0000000000..073f840af5 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/ref/ZeroReferenceParserTest.java @@ -0,0 +1,230 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.ref; + +import java.util.Arrays; +import java.util.List; + +import org.alfresco.service.cmr.repository.NodeRef; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Test; + +public class ZeroReferenceParserTest extends AbstractReferenceParserTest +{ + + private static Log logger = LogFactory.getLog(ZeroReferenceParserTest.class); + + private double compressionRatio(Reference ref, Encoding uncompressedEnc, Encoding compressedEnc) throws Exception + { + double ratio = (double) ref.encode(compressedEnc).length() / (double) ref.encode(uncompressedEnc).length() + * 100; + return ratio; + } + + private void compress(String referenceString, Encoding uncompressedEnc, Encoding compressedEnc, String trueMessage, + String debugMessage) throws Exception + { + Reference ref = new ZeroReferenceParser().parse(referenceString); + double testRatio = this.compressionRatio(ref, + uncompressedEnc, + compressedEnc); + if (logger.isDebugEnabled()) + { + logger.debug(testRatio + debugMessage); + } + assertTrue(trueMessage, + testRatio < 100); + } + + @Test + public void testCompressionRatio() throws Exception + { + String trueMessage = "Compression ratio should be lower than 100."; + String debugMessage = " % of initial size"; + Encoding uncompressedEnc = Encodings.PLAIN.encoding, compressedEnc = Encodings.ZERO.encoding; + this + .compress("2:/org/alfresco/repo/virtual/node/vanilla.js:s:/:1:0d3b26ff-c4c1-4680-8622-8608ea7ab4b2:1:b6843991-e06f-4ca6-9fe5-51105e2af99f", + uncompressedEnc, + compressedEnc, + trueMessage, + debugMessage); + this + .compress("7:1a0b110f-1e09-4ca2-b367-fe25e4964a4e:r:2:/org/alfresco/repo/virtual/node/vanilla.js:s:/7/8:1:872d6250-913d-460e-9c88-e695f247d81c:1:b6843991-e06f-4ca6-9fe5-51105e2af99f", + uncompressedEnc, + compressedEnc, + trueMessage, + debugMessage); + + this + .compress("2:/org/alfresco/repo/virtual/node/vanilla.js:s:/6:1:872d6250-913d-460e-9c88-e695f247d81c:1:6869da5d-35a8-493a-91b5-a79c6f422122", + uncompressedEnc, + compressedEnc, + trueMessage, + debugMessage); + + this + .compress("7:7d71e00b-1838-4a3f-aff5-be24def2663c:r:2:/org/alfresco/repo/virtual/node/vanilla.js:s:/6:1:67c8f11d-0936-4295-88a0-12b85764c76f:1:6428d7cc-feaa-4e32-a983-0b357439a994", + uncompressedEnc, + compressedEnc, + trueMessage, + debugMessage); + + this + .compress("6:/Company Home/Data Dictionary/:r:2:/org/alfresco/repo/virtual/node/vanilla.js:s:/6:1:67c8f11d-0936-4295-88a0-12b85764c76f:1:6428d7cc-feaa-4e32-a983-0b357439a994", + uncompressedEnc, + compressedEnc, + trueMessage, + debugMessage); + + } + + @Test + public void testReferenceDelimiter() + { + Reference parsedRef = new ZeroReferenceParser() + .parse("6:/Company Home/Data Dictionary/:r:2:/org/alfresco/repo/virtual/node/vanilla.js:s:/6:1:67c8f11d-0936-4295-88a0-12b85764c76f:1:6428d7cc-feaa-4e32-a983-0b357439a994:*"); + List params = Arrays + . asList(new StringParameter("/6"), + new ResourceParameter(new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/67c8f11d-0936-4295-88a0-12b85764c76f")))), + new ResourceParameter(new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/6428d7cc-feaa-4e32-a983-0b357439a994"))))); + Reference innerRef = new Reference(Encodings.ZERO.encoding, + Protocols.VANILLA.protocol, + new ClasspathResource("/org/alfresco/repo/virtual/node/vanilla.js"), + params); + + List prms = Arrays. asList(new ReferenceParameter(innerRef)); + Reference createdRef = new Reference(Encodings.ZERO.encoding, + Protocols.NODE.protocol, + new RepositoryResource(new RepositoryPath("/Company Home/Data Dictionary/")), + prms); + assertEquals(parsedRef, + createdRef); + + Reference parsedRef1 = new ZeroReferenceParser() + .parse("6:/Company Home/Data Dictionary/:r:2:/org/alfresco/repo/virtual/node/vanilla.js:s:/6:1:67c8f11d-0936-4295-88a0-12b85764c76f:1:6428d7cc-feaa-4e32-a983-0b357439a994:*:r:2:/org/alfresco/repo/virtual/node/vanilla.js:s:/6:1:67c8f11d-0936-4295-88a0-12b85764c76f:1:6428d7cc-feaa-4e32-a983-0b357439a994:*"); + List params1 = Arrays + . asList(new StringParameter("/6"), + new ResourceParameter(new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/67c8f11d-0936-4295-88a0-12b85764c76f")))), + new ResourceParameter(new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/6428d7cc-feaa-4e32-a983-0b357439a994"))))); + Reference innerRef1 = new Reference(Encodings.ZERO.encoding, + Protocols.VANILLA.protocol, + new ClasspathResource("/org/alfresco/repo/virtual/node/vanilla.js"), + params1); + Reference innerRef2 = new Reference(Encodings.ZERO.encoding, + Protocols.VANILLA.protocol, + new ClasspathResource("/org/alfresco/repo/virtual/node/vanilla.js"), + params1); + + List prms1 = Arrays. asList(new ReferenceParameter(innerRef1), + new ReferenceParameter(innerRef2)); + Reference createdRef1 = new Reference(Encodings.ZERO.encoding, + Protocols.NODE.protocol, + new RepositoryResource(new RepositoryPath("/Company Home/Data Dictionary/")), + prms1); + assertEquals(parsedRef1, + createdRef1); + + Reference parsedRef2 = new ZeroReferenceParser() + .parse("6:/Company Home/Data Dictionary/:r:2:/org/alfresco/repo/virtual/node/vanilla.js:s:/6:1:67c8f11d-0936-4295-88a0-12b85764c76f:1:6428d7cc-feaa-4e32-a983-0b357439a994:*:s:test:s:exit:r:2:/org/alfresco/repo/virtual/node/vanilla.js:s:/6:1:67c8f11d-0936-4295-88a0-12b85764c76f:1:6428d7cc-feaa-4e32-a983-0b357439a994:*:s:roro"); + List prms2 = Arrays. asList(new ReferenceParameter(innerRef1), + new StringParameter("test"), + new StringParameter("exit"), + new ReferenceParameter(innerRef2), + new StringParameter("roro")); + Reference createdRef2 = new Reference(Encodings.ZERO.encoding, + Protocols.NODE.protocol, + new RepositoryResource(new RepositoryPath("/Company Home/Data Dictionary/")), + prms2); + assertEquals(parsedRef2, + createdRef2); + + } + + @Test + public void testParseRepositoryNodeRef() throws Exception + { + Reference reference = new ZeroReferenceParser().parse("4:0029-222-333-444"); + assertEquals(reference, + new Reference(Encodings.ZERO.encoding, + Protocols.VIRTUAL.protocol, + new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/0029-222-333-444"))))); + + } + + @Test + public void testParseRepositoryPath() throws Exception + { + Reference reference = new ZeroReferenceParser().parse("3:/Foo/Bar"); + assertEquals(reference, + new Reference(Encodings.ZERO.encoding, + Protocols.VIRTUAL.protocol, + new RepositoryResource(new RepositoryPath("/Foo/Bar")))); + + } + + @Test + public void testParseNodeProtocol() throws Exception + { + // testing parse for node protocol with an repository node as Resource + // parameter + Reference reference = new ZeroReferenceParser().parse("7:0029-222-333-444:1:0029-122-333-0023"); + + RepositoryResource rr = new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/0029-122-333-0023"))); + List params = Arrays. asList(new ResourceParameter(rr)); + assertEquals(reference, + new Reference(Encodings.ZERO.encoding, + Protocols.NODE.protocol, + new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/0029-222-333-444"))), + params)); + + // testing parse for node protocol with an repository path as Resource + // parameter + reference = new ZeroReferenceParser().parse("7:0029-222-333-444:0:/Foo/Bar"); + + rr = new RepositoryResource(new RepositoryPath("/Foo/Bar")); + params = Arrays. asList(new ResourceParameter(rr)); + assertEquals(reference, + new Reference(Encodings.ZERO.encoding, + Protocols.NODE.protocol, + new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/0029-222-333-444"))), + params)); + + // testing parse for node protocol with an repository path and a string + // as resource and respectively String parameters + reference = new ZeroReferenceParser().parse("7:0029-222-333-444:0:/Foo/Bar:s:vm_virtual"); + + rr = new RepositoryResource(new RepositoryPath("/Foo/Bar")); + params = Arrays. asList(new ResourceParameter(rr), + new StringParameter("vm_virtual")); + assertEquals(reference, + new Reference(Encodings.ZERO.encoding, + Protocols.NODE.protocol, + new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/0029-222-333-444"))), + params)); + + } + + @Test + public void testRecursiveReferenceParser() throws Exception + { + assertRecursiveReferenceParser(Encodings.ZERO.encoding); + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/ref/ZeroStringifierTest.java b/source/test-java/org/alfresco/repo/virtual/ref/ZeroStringifierTest.java new file mode 100644 index 0000000000..b9ebbe08b2 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/ref/ZeroStringifierTest.java @@ -0,0 +1,171 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.ref; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.alfresco.service.cmr.repository.NodeRef; +import org.junit.Test; + +public class ZeroStringifierTest +{ + +// @Test +// public void testStringifyNodeReference() throws Exception +// { +// { +// NodeRef templateNodeRef = new NodeRef("workspace://SpacesStore/0d3b26ff-c4c1-4680-8622-8608ea7ab4b2"); +// NodeRef actualTemplateNode = new NodeRef("workspace://SpacesStore/b6843991-e06f-4ca6-9fe5-51105e2af99f"); +// NodeRef actualNode = new NodeRef("workspace://SpacesStore/67c8f11d-0936-4295-88a0-12b85764c76f"); +// +// Reference templateParentReference = ((VirtualProtocol) Protocols.VIRTUAL.protocol) +// .newReference(templateNodeRef, +// "/1/2/3", +// actualTemplateNode); +// +// Reference templateNodeRefence = NodeProtocol.newReference(actualNode, +// templateParentReference); +// +// String encoding = new ZeroNodeStringifier().stringify(templateNodeRefence); +// +// System.err.println(encoding); +// +// Reference ref = new ZeroNodeReferenceParser().parse(encoding); +// System.out.println(ref.encode(Encodings.PLAIN.encoding)); +// } +// { +// NodeRef templateNodeRef = new NodeRef("workspace://SpacesStore/0d3b26ff-c4c1-4680-8622-8608ea7ab4b2"); +// NodeRef actualTemplateNode = new NodeRef("workspace://SpacesStore/b6843991-e06f-4ca6-9fe5-51105e2af99f"); +// NodeRef actualNode = new NodeRef("workspace://SpacesStore/67c8f11d-0936-4295-88a0-12b85764c76f"); +// +// Reference templateParentReference = ((VirtualProtocol) Protocols.VIRTUAL.protocol) +// .newReference(new ClasspathResource("/com/alfresco/someTemplate.js"), +// "/1/2/3", +// actualTemplateNode, +// Collections. emptyList()); +// +// Reference templateNodeRefence = NodeProtocol.newReference(actualNode, +// templateParentReference); +// +// ZeroConfiguredClasspathHasher.addHash("/com/alfresco/", +// "1"); +// String encoding = new ZeroNodeStringifier().stringify(templateNodeRefence); +// +// System.err.println(encoding); +// +// Reference ref = new ZeroNodeReferenceParser().parse(encoding); +// System.out.println(ref.encode(Encodings.PLAIN.encoding)); +// +// } +// } + + @Test + public void testStringifyReference() throws Exception + { + { + Reference r = new Reference(Encodings.ZERO.encoding, + Protocols.VIRTUAL.protocol, + new ClasspathResource("/org/alfresco/")); + assertEquals("5:/org/alfresco/", + r.encode(Encodings.ZERO.encoding)); + } + + { + + RepositoryResource rr1 = new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/0d3b26ff-c4c1-4680-8622-8608ea7ab4b2"))); + RepositoryResource rr2 = new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/b6843991-e06f-4ca6-9fe5-51105e2af99f"))); + List params = Arrays. asList(new StringParameter("/"), + new ResourceParameter(rr1), + new ResourceParameter(rr2)); + + Reference r = new Reference(Encodings.ZERO.encoding, + Protocols.VANILLA.protocol, + new ClasspathResource("/org/alfresco/repo/virtual/node/vanilla.js"), + params); + assertEquals("2:/org/alfresco/repo/virtual/node/vanilla.js:s:/:1:0d3b26ff-c4c1-4680-8622-8608ea7ab4b2:1:b6843991-e06f-4ca6-9fe5-51105e2af99f", + r.encode(Encodings.ZERO.encoding)); + } + } + + @Test + public void testReferenceDelimiter() + { + List params1 = Arrays + . asList(new StringParameter("/6"), + new ResourceParameter(new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/67c8f11d-0936-4295-88a0-12b85764c76f")))), + new ResourceParameter(new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/6428d7cc-feaa-4e32-a983-0b357439a994"))))); + Reference innerRef1 = new Reference(Encodings.ZERO.encoding, + Protocols.VANILLA.protocol, + new ClasspathResource("/org/alfresco/repo/virtual/node/vanilla.js"), + params1); + Reference innerRef2 = new Reference(Encodings.ZERO.encoding, + Protocols.VANILLA.protocol, + new ClasspathResource("/org/alfresco/repo/virtual/node/vanilla.js"), + params1); + + List prms1 = Arrays. asList(new ReferenceParameter(innerRef1), + new ReferenceParameter(innerRef2)); + Reference createdRef1 = new Reference(Encodings.ZERO.encoding, + Protocols.NODE.protocol, + new RepositoryResource(new RepositoryPath("/Company Home/Data Dictionary/")), + prms1); + assertEquals("6:/Company Home/Data Dictionary/:r:2:/org/alfresco/repo/virtual/node/vanilla.js:s:/6:1:67c8f11d-0936-4295-88a0-12b85764c76f:1:6428d7cc-feaa-4e32-a983-0b357439a994:*:r:2:/org/alfresco/repo/virtual/node/vanilla.js:s:/6:1:67c8f11d-0936-4295-88a0-12b85764c76f:1:6428d7cc-feaa-4e32-a983-0b357439a994:*", + createdRef1.encode()); + + List prms2 = Arrays + . asList(new StringParameter("ado+8"), + new ReferenceParameter(innerRef1), + new ReferenceParameter(innerRef2), + new ResourceParameter(new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/67c8f11d-0936-4295-88a0-12b85764c76f"))))); + Reference createdRef2 = new Reference(Encodings.ZERO.encoding, + Protocols.NODE.protocol, + new RepositoryResource(new RepositoryPath("/Company Home/Data Dictionary/")), + prms2); + assertEquals("6:/Company Home/Data Dictionary/:s:ado+8:r:2:/org/alfresco/repo/virtual/node/vanilla.js:s:/6:1:67c8f11d-0936-4295-88a0-12b85764c76f:1:6428d7cc-feaa-4e32-a983-0b357439a994:*:r:2:/org/alfresco/repo/virtual/node/vanilla.js:s:/6:1:67c8f11d-0936-4295-88a0-12b85764c76f:1:6428d7cc-feaa-4e32-a983-0b357439a994:*:1:67c8f11d-0936-4295-88a0-12b85764c76f", + createdRef2.encode()); + + } + + @Test + public void testStringifyRepositoryNodeRef() throws Exception + { + + RepositoryResource rr1 = new RepositoryResource(new RepositoryNodeRef(new NodeRef("workspace://SpacesStore/0029-222-333-444"))); + Reference r = new Reference(Encodings.ZERO.encoding, + Protocols.VIRTUAL.protocol, + rr1); + assertEquals("4:0029-222-333-444", + r.encode(Encodings.ZERO.encoding)); + } + + public void testStringifyRepositoryPath() throws Exception + { + RepositoryResource rr2 = new RepositoryResource(new RepositoryPath("/Data Dictionary/Virtual Folders/claim.json")); + Reference r = new Reference(Encodings.ZERO.encoding, + Protocols.VIRTUAL.protocol, + rr2); + assertEquals("3:/Data Dictionary/Virtual Folders/claim.json", + r.encode(Encodings.ZERO.encoding)); + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/store/ReferenceComparatorTest.java b/source/test-java/org/alfresco/repo/virtual/store/ReferenceComparatorTest.java new file mode 100644 index 0000000000..86d41dc5fc --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/store/ReferenceComparatorTest.java @@ -0,0 +1,150 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.store; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import junit.framework.TestCase; + +import org.alfresco.query.PagingRequest; +import org.alfresco.query.PagingResults; +import org.alfresco.repo.security.permissions.NodePermissionEntry; +import org.alfresco.repo.security.permissions.PermissionReference; +import org.alfresco.repo.virtual.VirtualizationException; +import org.alfresco.repo.virtual.ref.ClasspathResource; +import org.alfresco.repo.virtual.ref.Encodings; +import org.alfresco.repo.virtual.ref.Protocols; +import org.alfresco.repo.virtual.ref.Reference; +import org.alfresco.repo.virtual.template.FilingData; +import org.alfresco.service.cmr.repository.ChildAssociationRef; +import org.alfresco.service.cmr.repository.InvalidNodeRefException; +import org.alfresco.service.cmr.repository.NodeRef; +import org.alfresco.service.cmr.repository.Path; +import org.alfresco.service.cmr.security.AccessPermission; +import org.alfresco.service.cmr.security.AccessStatus; +import org.alfresco.service.namespace.QName; +import org.alfresco.service.namespace.QNamePattern; +import org.alfresco.util.Pair; +import org.junit.Test; +import org.mockito.Mockito; + +public class ReferenceComparatorTest extends TestCase +{ + private static QName PROP_BOOLEAN_1 = QName.createQName("tst:bool1"); + + private static QName PROP_BOOLEAN_2 = QName.createQName("tst:bool2"); + + private static QName PROP_INTEGER_1 = QName.createQName("tst:int1"); + + private static QName PROP_INTEGER_2 = QName.createQName("tst:int2"); + + private static final Reference TEST_REFERENCE_1 = new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + new ClasspathResource("/some/class/path.js")); + + private static final Reference TEST_REFERENCE_2 = new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + new ClasspathResource("/some/other/class/path.js")); + + private static final Reference TEST_REFERENCE_3 = new Reference(Encodings.PLAIN.encoding, + Protocols.VIRTUAL.protocol, + new ClasspathResource("/and/an/other/class/path.js")); + + private VirtualStore testPropertiesStore = null; + + @Override + protected void setUp() throws Exception + { + + testPropertiesStore = Mockito.mock(VirtualStore.class); + { + final Map ref1Props = new HashMap<>(); + + ref1Props.put(PROP_INTEGER_1, + 1); + ref1Props.put(PROP_INTEGER_2, + 2); + ref1Props.put(PROP_BOOLEAN_1, + true); + ref1Props.put(PROP_BOOLEAN_2, + false); + + Mockito.when(testPropertiesStore.getProperties(TEST_REFERENCE_1)).thenReturn(ref1Props); + } + { + final Map ref2Props = new HashMap<>(); + + ref2Props.put(PROP_INTEGER_1, + 1); + ref2Props.put(PROP_INTEGER_2, + 3); + ref2Props.put(PROP_BOOLEAN_1, + false); + ref2Props.put(PROP_BOOLEAN_2, + true); + + Mockito.when(testPropertiesStore.getProperties(TEST_REFERENCE_2)).thenReturn(ref2Props); + } + { + final Map ref3Props = new HashMap<>(); + + ref3Props.put(PROP_INTEGER_1, + 4); + ref3Props.put(PROP_INTEGER_2, + 5); + ref3Props.put(PROP_BOOLEAN_1, + true); + ref3Props.put(PROP_BOOLEAN_2, + false); + + Mockito.when(testPropertiesStore.getProperties(TEST_REFERENCE_3)).thenReturn(ref3Props); + } + + } + + @Test + public void testCompare1() throws Exception + { + ReferenceComparator c = new ReferenceComparator(testPropertiesStore, + Arrays.asList(new Pair(PROP_INTEGER_1, + true), + new Pair(PROP_BOOLEAN_1, + true))); + + assertEquals(0, + c.compare(TEST_REFERENCE_1, + TEST_REFERENCE_1)); + assertEquals(1, + c.compare(TEST_REFERENCE_1, + TEST_REFERENCE_2)); + assertEquals(-1, + c.compare(TEST_REFERENCE_2, + TEST_REFERENCE_1)); + assertEquals(-1, + c.compare(TEST_REFERENCE_1, + TEST_REFERENCE_3)); + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/store/SystemVirtualizationMethodTest.java b/source/test-java/org/alfresco/repo/virtual/store/SystemVirtualizationMethodTest.java new file mode 100644 index 0000000000..49722a0b60 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/store/SystemVirtualizationMethodTest.java @@ -0,0 +1,145 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.store; + +import java.io.InputStream; + +import org.alfresco.model.ContentModel; +import org.alfresco.repo.virtual.VirtualizationIntegrationTest; +import org.alfresco.repo.virtual.VirtualContentModel; +import org.alfresco.repo.virtual.VirtualizationException; +import org.alfresco.repo.virtual.ref.Reference; +import org.alfresco.service.cmr.repository.ContentWriter; +import org.alfresco.service.cmr.repository.NodeRef; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Test; + +public class SystemVirtualizationMethodTest extends VirtualizationIntegrationTest +{ + + private static Log logger = LogFactory.getLog(VirtualStoreImplTest.class); + + private SystemVirtualizationMethod systemVirtualizationMethod; + + @Override + protected void setUp() throws Exception + { + super.setUp(); + systemVirtualizationMethod = ctx.getBean("systemVirtualizationMethod", + SystemVirtualizationMethod.class); + + } + + @Test + public void testDefaultSyspath() throws Exception + { + NodeRef vf = createVirtualizedFolder(testRootFolder.getNodeRef(), + "SystemVirtualizationMethodTest_testDefaultSyspath", + null); + assertFalse(systemVirtualizationMethod.canVirtualize(environment, + vf)); + try + { + systemVirtualizationMethod.virtualize(environment, + vf); + fail("Should not be able to virtualize non-virtualizable nodes."); + } + catch (VirtualizationException e) + { + logger.info(e); + } + } + + @Test + public void testNonExistentClassPathResource() throws Exception + { + NodeRef vf = createVirtualizedFolder(testRootFolder.getNodeRef(), + "SystemVirtualizationMethodTest_testNonExistentClassPathResource", + "C/org/alfresco/repo/virtual/template/nonExistetJsonTemplate.json"); + assertFalse(systemVirtualizationMethod.canVirtualize(environment, + vf)); + } + + @Test + public void testNonExistentRepoResource() throws Exception + { + NodeRef vf = createVirtualizedFolder(testRootFolder.getNodeRef(), + "SystemVirtualizationMethodTest_testNonExistentRepoResource", + "Nworkspace://SpacesStore/nonExistentRepoNode"); + assertFalse(systemVirtualizationMethod.canVirtualize(environment, + vf)); + } + + @Test + public void testTemplateFromRepository() throws Exception + { + InputStream openContentStream = environment.openContentStream(TEST_TEMPLATE_1_JSON_CLASSPATH); + NodeRef repositoryTemplate = fileAndFolderService + .create(testRootFolder.getNodeRef(), + "test1.json", + VirtualContentModel.TYPE_VIRTUAL_FOLDER_TEMPLATE) + .getNodeRef(); + ContentWriter writer = contentService.getWriter(repositoryTemplate, + ContentModel.PROP_CONTENT, + true); + writer.setMimetype("application/json"); + writer.putContent(openContentStream); + + NodeRef vf = createVirtualizedFolder(testRootFolder.getNodeRef(), + "repositoryVirtualizedFolder", + "N" + repositoryTemplate.toString()); + assertTrue(systemVirtualizationMethod.canVirtualize(environment, + vf)); + + Reference ref = systemVirtualizationMethod.virtualize(environment, + vf); + assertNotNull(ref); + + assertNotNull(nodeService.getChildByName(ref.toNodeRef(), + ContentModel.ASSOC_CONTAINS, + "Node1")); + assertNotNull(nodeService.getChildByName(ref.toNodeRef(), + ContentModel.ASSOC_CONTAINS, + "Node2")); + } + + @Test + public void testTemplateFromClassPath() throws Exception + { + NodeRef vf = createVirtualizedFolder(testRootFolder.getNodeRef(), + "classpathVirtualizedFolder", + TEST_TEMPLATE_1_JSON_SYS_PATH); + assertTrue(systemVirtualizationMethod.canVirtualize(environment, + vf)); + + Reference ref = systemVirtualizationMethod.virtualize(environment, + vf); + assertNotNull(ref); + + assertNotNull(nodeService.getChildByName(ref.toNodeRef(), + ContentModel.ASSOC_CONTAINS, + "Node1")); + assertNotNull(nodeService.getChildByName(ref.toNodeRef(), + ContentModel.ASSOC_CONTAINS, + "Node2")); + + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/store/TypeVirtualizationMethodTest.java b/source/test-java/org/alfresco/repo/virtual/store/TypeVirtualizationMethodTest.java new file mode 100644 index 0000000000..265358ad4d --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/store/TypeVirtualizationMethodTest.java @@ -0,0 +1,240 @@ + +package org.alfresco.repo.virtual.store; + +import java.io.InputStream; +import java.io.Serializable; +import java.util.Collections; +import java.util.List; + +import org.alfresco.model.ContentModel; +import org.alfresco.repo.site.SiteModel; +import org.alfresco.repo.virtual.VirtualizationIntegrationTest; +import org.alfresco.repo.virtual.config.NodeRefExpression; +import org.alfresco.repo.virtual.ref.ClasspathResource; +import org.alfresco.repo.virtual.ref.Parameter; +import org.alfresco.repo.virtual.ref.Protocols; +import org.alfresco.repo.virtual.ref.Reference; +import org.alfresco.repo.virtual.ref.RepositoryLocation; +import org.alfresco.repo.virtual.ref.RepositoryResource; +import org.alfresco.repo.virtual.ref.Resource; +import org.alfresco.repo.virtual.ref.ResourceParameter; +import org.alfresco.repo.virtual.ref.ResourceProcessingError; +import org.alfresco.repo.virtual.ref.ResourceProcessor; +import org.alfresco.repo.virtual.ref.VanillaProtocol; +import org.alfresco.service.cmr.repository.ChildAssociationRef; +import org.alfresco.service.cmr.repository.NodeRef; +import org.alfresco.service.namespace.QName; +import org.junit.Test; + +public class TypeVirtualizationMethodTest extends VirtualizationIntegrationTest +{ + private static final QName TEST_FOLDER_TYPE = SiteModel.TYPE_SITE; + + private static final QName TEST_ASPECT = SiteModel.ASPECT_SITE_CONTAINER; + + private TypeVirtualizationMethod typeVirtualizationMethod; + + @Override + protected void setUp() throws Exception + { + super.setUp(); + typeVirtualizationMethod = ctx.getBean("typeVirtualizationMethod", + TypeVirtualizationMethod.class); + } + + @Override + public void tearDown() throws Exception + { + super.tearDown(); + typeVirtualizationMethod.setQnameFilterRegexp(virtualizationConfigTestBootstrap + .getTypeTemplatesQNameFilterRegexp()); + } + + @Test + public void testRegExpFiltering() throws Exception + { + typeVirtualizationMethod.setQnameFilterRegexp("\\{.*site/1\\.0\\}site"); + + ChildAssociationRef typedNodeAssocRef = createTypedNode(testRootFolder.getNodeRef(), + "TypeVirtualized", + TEST_FOLDER_TYPE); + assertFalse(typeVirtualizationMethod.canVirtualize(environment, + typedNodeAssocRef.getChildRef())); + + addTypeTemplate(TEST_FOLDER_TYPE, + TEST_TEMPLATE_1_JS_CLASSPATH); + + assertTrue(typeVirtualizationMethod.canVirtualize(environment, + typedNodeAssocRef.getChildRef())); + + + typeVirtualizationMethod.setQnameFilterRegexp("\\{.*site/2\\.0\\}site"); + + assertFalse(typeVirtualizationMethod.canVirtualize(environment, + typedNodeAssocRef.getChildRef())); + + //invalid regexp + typeVirtualizationMethod.setQnameFilterRegexp("{.*site/1\\.0\\}site"); + + assertFalse(typeVirtualizationMethod.canVirtualize(environment, + typedNodeAssocRef.getChildRef())); + + } + + public void testVirtualizeCmFolder_recusive() throws Exception + { + ChildAssociationRef templateContentChildRef = addTypeTemplate(ContentModel.TYPE_FOLDER, + TEST_TEMPLATE_1_JS_CLASSPATH); + virtualize(templateContentChildRef.getChildRef(), + ContentModel.TYPE_FOLDER); + } + + public void testCanVirtualize() throws Exception + { + ChildAssociationRef typedNodeAssocRef = createTypedNode(testRootFolder.getNodeRef(), + "TypeVirtualized", + TEST_FOLDER_TYPE); + NodeRef typeNode = typedNodeAssocRef.getChildRef(); + + assertFalse(typeVirtualizationMethod.canVirtualize(environment, + typeNode)); + + addTypeTemplate(TEST_FOLDER_TYPE, + TEST_TEMPLATE_1_JS_CLASSPATH); + + assertTrue(typeVirtualizationMethod.canVirtualize(environment, + typeNode)); + + } + + public void testCanVirtualizeAspect() throws Exception + { + ChildAssociationRef aspectNodeAssocRef = createTypedNode(testRootFolder.getNodeRef(), + "TypeVirtualized", + ContentModel.TYPE_FOLDER); + NodeRef aspectNode = aspectNodeAssocRef.getChildRef(); + + nodeService.addAspect(aspectNode, + TEST_ASPECT, + Collections. emptyMap()); + + assertFalse(typeVirtualizationMethod.canVirtualize(environment, + aspectNode)); + + addTypeTemplate(TEST_ASPECT, + TEST_TEMPLATE_1_JS_CLASSPATH); + + assertTrue(typeVirtualizationMethod.canVirtualize(environment, + aspectNode)); + + } + + public void testVirtualizeAspect() throws Exception + { + ChildAssociationRef templateContentChildRef = addTypeTemplate(TEST_ASPECT, + TEST_TEMPLATE_1_JS_CLASSPATH); + virtualize(templateContentChildRef.getChildRef(), + ContentModel.TYPE_FOLDER, + TEST_ASPECT); + } + + public void testVirtualizeType() throws Exception + { + ChildAssociationRef templateContentChildRef = addTypeTemplate(TEST_FOLDER_TYPE, + TEST_TEMPLATE_1_JS_CLASSPATH); + + virtualize(templateContentChildRef.getChildRef(), + TEST_FOLDER_TYPE); + } + + private void virtualize(NodeRef expectedTemplateNodeRef, QName fodlerType, QName... aspects) throws Exception + { + + ChildAssociationRef typedNodeAssocRef = createTypedNode(testRootFolder.getNodeRef(), + "TypeVirtualized", + fodlerType); + NodeRef typeNode = typedNodeAssocRef.getChildRef(); + + for (QName aspect : aspects) + { + nodeService.addAspect(typeNode, + aspect, + Collections. emptyMap()); + } + + assertTrue(typeVirtualizationMethod.canVirtualize(environment, + typeNode)); + + Reference theVirtualizedNode = typeVirtualizationMethod.virtualize(environment, + typeNode); + assertEquals(Protocols.VANILLA.protocol, + theVirtualizedNode.getProtocol()); + + List parameters = theVirtualizedNode.getParameters(); + ResourceParameter vanillaResourceParameter = (ResourceParameter) parameters + .get(VanillaProtocol.VANILLA_TEMPLATE_PARAM_INDEX); + Resource vanillaResource = vanillaResourceParameter.getValue(); + + NodeRef resourceNodeRef = vanillaResource.processWith(new ResourceProcessor() + { + + @Override + public NodeRef process(Resource resource) throws ResourceProcessingError + { + fail("Inavlid resource type"); + return null; + } + + @Override + public NodeRef process(ClasspathResource classpath) throws ResourceProcessingError + { + fail("Inavlid resource type"); + return null; + } + + @Override + public NodeRef process(RepositoryResource repository) throws ResourceProcessingError + { + RepositoryLocation location = repository.getLocation(); + return location.asNodeRef(environment); + } + }); + + assertEquals(expectedTemplateNodeRef, + resourceNodeRef); + } + + private synchronized ChildAssociationRef addTypeTemplate(QName theType, String cp) + { + NodeRefExpression templatesLocationExpr = virtualizationConfigTestBootstrap.getTypeTemplatesPath(); + NodeRef templatesLocation = templatesLocationExpr.resolve(); + + assertNotNull(templatesLocation); + + final String prefixedType = theType.toPrefixString(environment.getNamespacePrefixResolver()); + String contentName = prefixedType; + contentName = contentName.replaceAll(":", + "_") + ".json"; + + InputStream testTemplsteJsonIS = getClass().getResourceAsStream(cp); + ChildAssociationRef templateContentChildRef = createContent(templatesLocation, + contentName, + testTemplsteJsonIS, + "application/json", + "UTF-8", + ContentModel.TYPE_CONTENT); + + String regexp = theType.toString(); + regexp = regexp.replaceAll("\\{", + "\\\\{"); + regexp = regexp.replaceAll("\\}", + "\\\\}"); + regexp = regexp.replaceAll("\\:", + "\\\\:"); + regexp = regexp.replaceAll("\\.", + "\\\\."); + typeVirtualizationMethod.setQnameFilterRegexp(regexp); + + return templateContentChildRef; + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/store/VirtualStoreImplTest.java b/source/test-java/org/alfresco/repo/virtual/store/VirtualStoreImplTest.java new file mode 100644 index 0000000000..d4c379192e --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/store/VirtualStoreImplTest.java @@ -0,0 +1,116 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.store; + +import org.alfresco.repo.virtual.VirtualizationIntegrationTest; +import org.alfresco.repo.virtual.VirtualizationException; +import org.alfresco.service.cmr.repository.NodeRef; +import org.alfresco.service.cmr.security.AccessStatus; +import org.alfresco.service.cmr.security.PermissionService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Test; + +public class VirtualStoreImplTest extends VirtualizationIntegrationTest +{ + private static Log logger = LogFactory.getLog(VirtualStoreImplTest.class); + + private VirtualStoreImpl virtualStore; + + @Override + protected void setUp() throws Exception + { + super.setUp(); + + virtualStore = ctx.getBean("virtualStore", + VirtualStoreImpl.class); + + } + + @Test + public void testNonVirtualizable() throws Exception + { + NodeRef aNodeRef = createVirtualizedFolder(testRootFolder.getNodeRef(), + "TestVirtualStoreImpl_createVirtualizedFolder", + null); + assertFalse(virtualStore.canVirtualize(aNodeRef)); + + try + { + virtualStore.virtualize(aNodeRef); + fail("Should not be able to virtualize non-virtualizable nodes."); + } + catch (VirtualizationException e) + { + logger.info(e); + } + } + + @Test + public void testCanVirtualize() throws Exception + { + NodeRef solrFacetsNodeRef = new NodeRef("workspace://SpacesStore/solr_facets_root_space"); + boolean canVirtualize = virtualStore.canVirtualize(solrFacetsNodeRef); + assertEquals(false, + canVirtualize); + } + + private String asTypedPermission(String perm) + { + return virtualStore.getUserPermissions().getPermissionTypeQName()+"."+perm; + } + + private void assertHasQueryNodePermission(AccessStatus accessStatus,String perm) + { + VirtualUserPermissions virtualUserPermissions = virtualStore.getUserPermissions(); + + assertEquals(AccessStatus.DENIED,virtualUserPermissions.hasQueryNodePermission(perm)); + assertEquals(AccessStatus.DENIED,virtualUserPermissions.hasQueryNodePermission(asTypedPermission(perm))); + } + + private void assertHasVirtualNodePermission(AccessStatus accessStatus,String perm,boolean readonly) + { + VirtualUserPermissions virtualUserPermissions = virtualStore.getUserPermissions(); + + assertEquals(AccessStatus.DENIED,virtualUserPermissions.hasVirtualNodePermission(perm,readonly)); + assertEquals(AccessStatus.DENIED,virtualUserPermissions.hasVirtualNodePermission(asTypedPermission(perm),readonly)); + } + + @Test + public void testConfiguredUserPermissions() throws Exception + { + assertHasQueryNodePermission(AccessStatus.DENIED,PermissionService.DELETE); + assertHasQueryNodePermission(AccessStatus.DENIED,PermissionService.DELETE_NODE); + assertHasQueryNodePermission(AccessStatus.DENIED,PermissionService.CHANGE_PERMISSIONS); + + assertHasVirtualNodePermission(AccessStatus.DENIED,PermissionService.CREATE_ASSOCIATIONS,true); + assertHasVirtualNodePermission(AccessStatus.DENIED,PermissionService.UNLOCK,true); + assertHasVirtualNodePermission(AccessStatus.DENIED,PermissionService.CANCEL_CHECK_OUT,true); + assertHasVirtualNodePermission(AccessStatus.DENIED,PermissionService.DELETE,true); + assertHasVirtualNodePermission(AccessStatus.DENIED,PermissionService.DELETE_NODE,true); + assertHasVirtualNodePermission(AccessStatus.DENIED,PermissionService.CHANGE_PERMISSIONS,true); + assertHasVirtualNodePermission(AccessStatus.DENIED,PermissionService.WRITE_CONTENT,true); + assertHasVirtualNodePermission(AccessStatus.DENIED,PermissionService.WRITE,true); + assertHasVirtualNodePermission(AccessStatus.DENIED,PermissionService.WRITE_PROPERTIES,true); + assertHasVirtualNodePermission(AccessStatus.DENIED,PermissionService.WRITE,false); + assertHasVirtualNodePermission(AccessStatus.DENIED,PermissionService.WRITE_PROPERTIES,false); + + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/template/ApplyTemplateMethodTest.java b/source/test-java/org/alfresco/repo/virtual/template/ApplyTemplateMethodTest.java new file mode 100644 index 0000000000..769f415c6d --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/template/ApplyTemplateMethodTest.java @@ -0,0 +1,108 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.template; + +import java.nio.charset.StandardCharsets; +import java.util.List; + +import org.alfresco.repo.content.MimetypeMap; +import org.alfresco.repo.virtual.VirtualizationIntegrationTest; +import org.alfresco.repo.virtual.ref.NewVirtualReferenceMethod; +import org.alfresco.repo.virtual.ref.Protocols; +import org.alfresco.repo.virtual.ref.Reference; +import org.alfresco.service.cmr.repository.ChildAssociationRef; +import org.junit.Test; + +public class ApplyTemplateMethodTest extends VirtualizationIntegrationTest +{ + + @Test + public void testExecuteSysClasspath() throws Exception + { + ApplyTemplateMethod applyTemplateMethod = new ApplyTemplateMethod(environment); + + NewVirtualReferenceMethod newVirtualReferenceMethod = new NewVirtualReferenceMethod(TEST_TEMPLATE_1_JS_SYS_PATH, + "/", + rootNodeRef, + null); + Reference ref = Protocols.VIRTUAL.protocol.dispatch(newVirtualReferenceMethod, + null); + VirtualFolderDefinition structure = ref.execute(applyTemplateMethod); + + String templateName = structure.getName(); + assertEquals("template1_name", + templateName); + + List children = structure.getChildren(); + assertEquals(3, + children.size()); + + VirtualFolderDefinition child1 = structure.findChildByName("My Documents"); + assertTrue(child1 != null); + + VirtualFolderDefinition child2 = structure.findChildByName("Recent Documents"); + assertTrue(child2 != null); + + VirtualFolderDefinition child3 = structure.findChildByName("Other Documents"); + assertTrue(child3 != null); + + } + + @Test + public void testExecuteRepositoryJSON() throws Exception + { + ChildAssociationRef templateAssoc = createContent(testRootFolder.getNodeRef(), + "template1.json", + ApplyTemplateMethodTest.class + .getResourceAsStream(TEST_TEMPLATE_1_JSON_NAME), + MimetypeMap.MIMETYPE_JSON, + StandardCharsets.UTF_8.name()); + ApplyTemplateMethod applyTemplateMethod = new ApplyTemplateMethod(environment); + + NewVirtualReferenceMethod newVirtualReferenceMethod = new NewVirtualReferenceMethod(templateAssoc.getChildRef(), + "/", + virtualFolder1NodeRef, + VANILLA_PROCESSOR_JS_CLASSPATH); + Reference ref = Protocols.VANILLA.protocol.dispatch(newVirtualReferenceMethod, + null); + VirtualFolderDefinition structure = ref.execute(applyTemplateMethod); + + String templateName = structure.getName(); + assertEquals("Test", + templateName); + + List children = structure.getChildren(); + assertEquals(2, + children.size()); + + VirtualFolderDefinition child1 = structure.findChildByName("Node1"); + assertTrue(child1 != null); + + VirtualFolderDefinition child2 = structure.findChildByName("Node2"); + assertTrue(child2 != null); + + } + + @Test + public void testExecuteRepositoryJS() throws Exception + { + // TODO: + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/template/TemplateFilingRuleTest.java b/source/test-java/org/alfresco/repo/virtual/template/TemplateFilingRuleTest.java new file mode 100644 index 0000000000..cf282a392f --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/template/TemplateFilingRuleTest.java @@ -0,0 +1,80 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.template; + +import org.alfresco.model.ContentModel; +import org.alfresco.repo.virtual.VirtualizationIntegrationTest; +import org.alfresco.repo.virtual.ref.Reference; +import org.alfresco.service.cmr.repository.NodeRef; +import org.junit.Test; + +public class TemplateFilingRuleTest extends VirtualizationIntegrationTest +{ + @Test + public void testISO9075FilingSubPath() throws Exception + { + NodeRef vfNodeRef = createVirtualizedFolder(testRootFolder.getNodeRef(), + "Template 6 With Spaces", + TEST_TEMPLATE_5_JSON_SYS_PATH); + + NodeRef sfpNodeRef = nodeService.getChildByName(vfNodeRef, + ContentModel.ASSOC_CONTAINS, + "SpecialFilingPath5"); + + Reference sfpReference = Reference.fromNodeRef(sfpNodeRef); + ApplyTemplateMethod applyTemplateMethod = new ApplyTemplateMethod(environment); + + VirtualFolderDefinition structure = sfpReference.execute(applyTemplateMethod); + + FilingRule filingRule = structure.getFilingRule(); + + assertTrue(filingRule instanceof TemplateFilingRule); + + NodeRef fn = filingRule.filingNodeRefFor(new FilingParameters(sfpReference)); + assertNull(fn); + createFolder(vfNodeRef, + "Space Sub Folder"); + fn = filingRule.filingNodeRefFor(new FilingParameters(sfpReference)); + assertNotNull(fn); + } + + @Test + public void testISO9075FilingPath() throws Exception + { + NodeRef vfNodeRef = createVirtualizedFolder(testRootFolder.getNodeRef(), + "Template 6 With Spaces", + TEST_TEMPLATE_5_JSON_SYS_PATH); + + NodeRef sfpNodeRef = nodeService.getChildByName(vfNodeRef, + ContentModel.ASSOC_CONTAINS, + "SpecialFilingPath4"); + + Reference sfpReference = Reference.fromNodeRef(sfpNodeRef); + ApplyTemplateMethod applyTemplateMethod = new ApplyTemplateMethod(environment); + + VirtualFolderDefinition structure = sfpReference.execute(applyTemplateMethod); + + FilingRule filingRule = structure.getFilingRule(); + assertTrue(filingRule instanceof TemplateFilingRule); + + NodeRef fn = filingRule.filingNodeRefFor(new FilingParameters(sfpReference)); + assertNotNull(fn); + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/template/TemplateResourceProcessorTest.java b/source/test-java/org/alfresco/repo/virtual/template/TemplateResourceProcessorTest.java new file mode 100644 index 0000000000..6a0ff1c2d2 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/template/TemplateResourceProcessorTest.java @@ -0,0 +1,106 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.template; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Map; + +import org.alfresco.model.ContentModel; +import org.alfresco.repo.virtual.VirtualizationIntegrationTest; +import org.alfresco.repo.virtual.VirtualContext; +import org.alfresco.repo.virtual.ref.ClasspathResource; +import org.apache.commons.io.IOUtils; +import org.junit.Test; + +public class TemplateResourceProcessorTest extends VirtualizationIntegrationTest +{ + + private VirtualFolderDefinition testTemplate2Definition; + + @Override + protected void setUp() throws Exception + { + super.setUp(); + + VirtualContext context = new VirtualContext(environment, + virtualFolder1NodeRef); + nodeService.setProperty(virtualFolder1NodeRef, ContentModel.PROP_DESCRIPTION,"AContextDescription"); + InputStream vanillaIS = getClass().getResourceAsStream(TEST_TEMPLATE_2_JSON_CLASSPATH); + String vanillaJSON = IOUtils.toString(vanillaIS, + StandardCharsets.UTF_8); + context.setParameter(ApplyTemplateMethod.VANILLA_JSON_PARAM_NAME, + vanillaJSON); + TemplateResourceProcessor processor = new TemplateResourceProcessor(context); + + testTemplate2Definition = processor.process(new ClasspathResource(VANILLA_PROCESSOR_JS_CLASSPATH)); + } + + protected void assertReadonly(VirtualFolderDefinition vf) + { + FilingRule fr = vf.getFilingRule(); + assertNotNull(fr); + assertTrue(fr.isNullFilingRule()); + } + + @Test + public void testBasicNodeInfo() throws Exception + { + assertNotNull(testTemplate2Definition); + assertNotNull(testTemplate2Definition.getChildren()); + assertEquals(4, + testTemplate2Definition.getChildren().size()); + + assertEquals("Test", + testTemplate2Definition.getName()); + + VirtualFolderDefinition node2 = testTemplate2Definition.findChildByName("Node2"); + + assertEquals("Node2", + node2.getName()); + assertEquals("The2ndNode", + node2.getDescription()); + assertEquals("2", + node2.getId()); + + VirtualQuery node2Query = node2.getQuery(); + assertNotNull(node2Query); + + Map node2Properties = node2.getProperties(); + assertTrue(node2Properties.keySet().containsAll(Arrays.asList("cm:modifier", + "cm:description", + "sys:node-dbid"))); + + assertEquals("admin",node2Properties.get("cm:modifier")); + //there is no node so values with property placeholder remain as they are + assertEquals("AContextDescription",node2Properties.get("cm:description")); + assertEquals("34567",node2Properties.get("sys:node-dbid")); + } + + @Test + public void testReadOnly() throws Exception + { + assertReadonly(testTemplate2Definition); + assertReadonly(testTemplate2Definition.findChildByName("Node2")); + assertReadonly(testTemplate2Definition.findChildByName("Node3")); + assertReadonly(testTemplate2Definition.findChildByName("Node4")); + } +} diff --git a/source/test-java/org/alfresco/repo/virtual/template/VirtualQueryImplTest.java b/source/test-java/org/alfresco/repo/virtual/template/VirtualQueryImplTest.java new file mode 100644 index 0000000000..a3d456a1b9 --- /dev/null +++ b/source/test-java/org/alfresco/repo/virtual/template/VirtualQueryImplTest.java @@ -0,0 +1,218 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.repo.virtual.template; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; + +import junit.framework.TestCase; + +import org.alfresco.repo.search.EmptyResultSet; +import org.alfresco.repo.virtual.ActualEnvironment; +import org.alfresco.repo.virtual.ref.Protocols; +import org.alfresco.repo.virtual.ref.Reference; +import org.alfresco.repo.virtual.ref.VirtualProtocol; +import org.alfresco.service.cmr.repository.NodeRef; +import org.alfresco.service.cmr.repository.StoreRef; +import org.alfresco.service.cmr.search.SearchParameters; +import org.alfresco.service.cmr.search.SearchParameters.SortDefinition; +import org.alfresco.service.cmr.search.SearchService; +import org.alfresco.service.namespace.NamespacePrefixResolver; +import org.alfresco.service.namespace.QName; +import org.alfresco.util.Pair; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; + +public class VirtualQueryImplTest extends TestCase +{ + + private static final String QUERY_TEST_STRING_QUERY = "QUERY_TEST_STRING_QUERY"; + + private static final String TEST_LOCAL_NAME_1 = "testQName1"; + + private static final String TEST_LOCAL_NAME_2 = "testQName2"; + + private static final String TEST_URI = "http://test/uri"; + + private static final String TST_PREFIX = "tst"; + + private VirtualQueryImpl query; + + private ActualEnvironment mockitoActualEnvironment; + + private NamespacePrefixResolver mockitoPrefixResolver; + + private QName testQName1; + + private QName testQName2; + + private Reference nodeOneReference; + + @Override + protected void setUp() throws Exception + { + super.setUp(); + + query = new VirtualQueryImpl(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.toString(), + SearchService.LANGUAGE_FTS_ALFRESCO, + QUERY_TEST_STRING_QUERY); + + mockitoActualEnvironment = Mockito.mock(ActualEnvironment.class); + Mockito.when(mockitoActualEnvironment.query(Mockito.any(SearchParameters.class))) + .thenReturn(new EmptyResultSet()); + + mockitoPrefixResolver = Mockito.mock(NamespacePrefixResolver.class); + Mockito.when(mockitoPrefixResolver.getNamespaceURI(TST_PREFIX)).thenReturn(TEST_URI); + Mockito.when(mockitoPrefixResolver.getPrefixes(TEST_URI)).thenReturn(Arrays.asList(TST_PREFIX)); + + Mockito.when(mockitoActualEnvironment.getNamespacePrefixResolver()).thenReturn(mockitoPrefixResolver); + + testQName1 = QName.createQName(TST_PREFIX, + TEST_LOCAL_NAME_1, + mockitoPrefixResolver); + + testQName2 = QName.createQName(TST_PREFIX, + TEST_LOCAL_NAME_2, + mockitoPrefixResolver); + + NodeRef n1 = new NodeRef("workspace://SpacesStore/17c8f11d-0936-4295-88a0-12b85764c76f"); + NodeRef n2 = new NodeRef("workspace://SpacesStore/27c8f11d-0936-4295-88a0-12b85764c76f"); + nodeOneReference = ((VirtualProtocol) Protocols.VIRTUAL.protocol).newReference(n1, + "/1", + n2); + } + + @Test + public void testPerform_1() throws Exception + { + Pair withSortDefinitions = new Pair(testQName2, + true); + + VirtualQueryConstraint constraint = BasicConstraint.INSTANCE; + constraint = new FilesFoldersConstraint(constraint, + true, + true); + constraint = new IgnoreConstraint(constraint, + Collections.singleton(testQName2), + Collections.singleton(testQName1)); + constraint = new SortConstraint(constraint, + Arrays.asList(withSortDefinitions)); + + query.perform(mockitoActualEnvironment, + constraint, + null, + nodeOneReference); + + assertPerform1Results(withSortDefinitions); + } + + public void testPerform_2() throws Exception + { + + VirtualQueryConstraint constraint = BasicConstraint.INSTANCE; + constraint = new FilesFoldersConstraint(constraint, + false, + true); + constraint = new IgnoreConstraint(constraint, + Collections.singleton(testQName2), + Collections.singleton(testQName1)); + + query.perform(mockitoActualEnvironment, + constraint, + null, + nodeOneReference); + + assertPerform2Results(); + } + + private void assertPerform1Results(Pair withSortDefinitions) + { + ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(SearchParameters.class); + Mockito.verify(mockitoActualEnvironment).query(queryCaptor.capture()); + + assertEquals("(QUERY_TEST_STRING_QUERY) and !ASPECT:'tst:testQName1' and !TYPE:'tst:testQName2'", + queryCaptor.getValue().getQuery()); + + ArrayList sortDefinitions = queryCaptor.getValue().getSortDefinitions(); + + assertNotNull(sortDefinitions); + assertEquals(1, + sortDefinitions.size()); + assertEquals(withSortDefinitions.getFirst().getLocalName(), + sortDefinitions.get(0).getField()); + + assertEquals(withSortDefinitions.getSecond(), + Boolean.valueOf(sortDefinitions.get(0).isAscending())); + } + + @Test + public void testPerform_deprecated_1() throws Exception + { + Pair withSortDefinitions = new Pair(testQName2, + true); + query.perform(mockitoActualEnvironment, + true, + true, + null, + Collections.singleton(testQName2), + Collections. emptySet(), + Collections.singleton(testQName1), + Arrays.asList(withSortDefinitions), + null, + nodeOneReference); + + assertPerform1Results(withSortDefinitions); + } + + @Test + public void testPerform_deprecated_2() throws Exception + { + query.perform(mockitoActualEnvironment, + false, + true, + null, + Collections.singleton(testQName2), + Collections. emptySet(), + Collections.singleton(testQName1), + Collections.> emptyList(), + null, + nodeOneReference); + + assertPerform2Results(); + + } + + private void assertPerform2Results() + { + ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(SearchParameters.class); + Mockito.verify(mockitoActualEnvironment).query(queryCaptor.capture()); + + assertEquals("((QUERY_TEST_STRING_QUERY) and TYPE:\"cm:folder\") and !ASPECT:'tst:testQName1' and !TYPE:'tst:testQName2'", + queryCaptor.getValue().getQuery()); + + ArrayList sortDefinitions = queryCaptor.getValue().getSortDefinitions(); + + assertNotNull(sortDefinitions); + assertEquals(0, + sortDefinitions.size()); + } +} diff --git a/source/test-java/org/alfresco/traitextender/AJExtensionsCompileTest.java b/source/test-java/org/alfresco/traitextender/AJExtensionsCompileTest.java new file mode 100644 index 0000000000..1979b2e58d --- /dev/null +++ b/source/test-java/org/alfresco/traitextender/AJExtensionsCompileTest.java @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2005-2015 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see http://www.gnu.org/licenses/. + */ + +package org.alfresco.traitextender; + +import java.util.HashSet; +import java.util.Set; + +import junit.framework.TestCase; + +import org.alfresco.traitextender.AJExtender.CompiledExtensible; +import org.junit.Test; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; +import org.springframework.core.type.filter.AssignableTypeFilter; + +public class AJExtensionsCompileTest extends TestCase +{ + protected void compile(Class extensible) throws AJExtensibleCompilingException + { + Set> extensiblesSet = new HashSet<>(); + extensiblesSet.add(extensible); + compile(extensiblesSet); + } + + protected void compile(Set> extensibles) throws AJExtensibleCompilingException + { + StringBuilder errorString = new StringBuilder(); + boolean errorsFound = false; + for (Class extensible : extensibles) + { + CompiledExtensible ce = AJExtender.compile(extensible); + if (ce.hasErrors()) + { + errorsFound = true; + errorString.append("Error compiling "); + errorString.append(extensible); + errorString.append(":\n"); + errorString.append(ce.getErrorsString()); + errorString.append(":\n"); + } + } + assertFalse(errorString.toString(), + errorsFound); + } + + @Test + public void testCompileExtendedServices() throws Exception + { + ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true); + provider.addIncludeFilter(new AssignableTypeFilter(Extensible.class)); + + Set components = provider.findCandidateComponents("org/alfresco/*"); + Set> extensibles = new HashSet<>(); + for (BeanDefinition component : components) + { + @SuppressWarnings("unchecked") + Class extensibleClass = (Class) Class.forName(component + .getBeanClassName()); + extensibles.add(extensibleClass); + + } + compile(extensibles); + } +}; diff --git a/source/test-java/org/alfresco/traitextender/RunTestExtensions.aj b/source/test-java/org/alfresco/traitextender/RunTestExtensions.aj new file mode 100644 index 0000000000..9e02315eea --- /dev/null +++ b/source/test-java/org/alfresco/traitextender/RunTestExtensions.aj @@ -0,0 +1,26 @@ + +package org.alfresco.traitextender; + +import org.alfresco.traitextender.AJExtender; +import org.alfresco.traitextender.Extend; +import org.alfresco.traitextender.ExtensionTargetException; +import org.alfresco.traitextender.RouteExtensions; + +public aspect RunTestExtensions +{ + declare precedence: RunTestExtensions,RouteExtensions; + + pointcut throwsTestException(Extend meAnnotation):execution(@org.alfresco.traitextender.Extend * *(..) throws TestException) && (@annotation(meAnnotation)); + + after(Extend meAnnotation) throwing(ExtensionTargetException ete) throws TestException :throwsTestException(meAnnotation){ + Throwable exception = AJExtender.asCheckThrowable(ete.getCause(), TestException.class); + if (exception instanceof TestException) + { + throw (TestException) exception; + } + else + { + throw ete; + } + } +} diff --git a/source/test-java/org/alfresco/traitextender/TestException.java b/source/test-java/org/alfresco/traitextender/TestException.java new file mode 100644 index 0000000000..b44108ee76 --- /dev/null +++ b/source/test-java/org/alfresco/traitextender/TestException.java @@ -0,0 +1,6 @@ +package org.alfresco.traitextender; + +public class TestException extends Exception +{ + +} diff --git a/source/test-java/org/alfresco/traitextender/TestExtension.java b/source/test-java/org/alfresco/traitextender/TestExtension.java new file mode 100644 index 0000000000..34bf5d66a4 --- /dev/null +++ b/source/test-java/org/alfresco/traitextender/TestExtension.java @@ -0,0 +1,14 @@ +package org.alfresco.traitextender; + +import java.util.List; + +public interface TestExtension +{ + String privateServiceMethod1(String s); + + String publicServiceMethod2(String s); + + String publicServiceMethod3(String s); + + void publicServiceMethod3(TestService s,List traitIdentities); +} diff --git a/source/test-java/org/alfresco/traitextender/TestExtensionImpl.java b/source/test-java/org/alfresco/traitextender/TestExtensionImpl.java new file mode 100644 index 0000000000..2b3ef82396 --- /dev/null +++ b/source/test-java/org/alfresco/traitextender/TestExtensionImpl.java @@ -0,0 +1,45 @@ + +package org.alfresco.traitextender; + +import java.util.List; + +import org.alfresco.traitextender.InstanceExtension; + +public class TestExtensionImpl extends InstanceExtension implements TestExtension +{ + + public TestExtensionImpl(TestTrait tarit) + { + super(tarit); + } + + @Override + public String privateServiceMethod1(String s) + { + return trait.traitImplOf_privateServiceMethod1(s) + " TestExtensionImpl.privateServiceMethod1(" + s + ")"; + } + + @Override + public String publicServiceMethod2(String s) + { + return trait.traitImplOf_publicServiceMethod2(s) + " TestExtensionImpl.privateServiceMethod1(" + s + ")"; + } + + @Override + public String publicServiceMethod3(String s) + { + return "EX" + trait.publicServiceMethod3("TestExtensionImpl.publicServiceMethod3(" + s + ")"); + } + + @Override + public void publicServiceMethod3(TestService s, List traitIdentities) + { + traitIdentities.add(System.identityHashCode(trait)); + if (s != null) + { + s.publicServiceMethod3(null, traitIdentities); + } + traitIdentities.add(System.identityHashCode(trait)); + trait.traitImplOf_publicServiceMethod3(s, traitIdentities); + } +} diff --git a/source/test-java/org/alfresco/traitextender/TestPublicExtension.java b/source/test-java/org/alfresco/traitextender/TestPublicExtension.java new file mode 100644 index 0000000000..3fe0999fae --- /dev/null +++ b/source/test-java/org/alfresco/traitextender/TestPublicExtension.java @@ -0,0 +1,13 @@ + +package org.alfresco.traitextender; + +public interface TestPublicExtension +{ + String publicMethod1(String s); + + String publicMethod2(String s); + + void publicMethod3(boolean throwException, boolean throwExException) throws TestException; + + void publicMethod4(boolean throwRuntimeException,boolean throwExRuntimeException); +} diff --git a/source/test-java/org/alfresco/traitextender/TestPublicExtensionImpl.java b/source/test-java/org/alfresco/traitextender/TestPublicExtensionImpl.java new file mode 100644 index 0000000000..847c535492 --- /dev/null +++ b/source/test-java/org/alfresco/traitextender/TestPublicExtensionImpl.java @@ -0,0 +1,46 @@ + +package org.alfresco.traitextender; + +import org.alfresco.traitextender.InstanceExtension; + +public class TestPublicExtensionImpl extends InstanceExtension implements TestPublicExtension +{ + + public TestPublicExtensionImpl(TestPublicTrait trait) + { + super(trait); + } + + @Override + public String publicMethod1(String s) + { + return "EPM1" + trait.publicMethod1(s); + } + + @Override + public String publicMethod2(String s) + { + return "EPM2" + trait.publicMethod2(s); + } + + @Override + public void publicMethod3(boolean throwException, boolean throwExException) throws TestException + { + if (throwExException) + { + throw new TestException(); + } + else + { + trait.publicMethod3(throwException, throwExException); + } + } + + @Override + public void publicMethod4(boolean throwRuntimeException, boolean throwExRuntimeException) + { + if (throwExRuntimeException) { throw new TestRuntimeException(); } + else { trait.publicMethod4(throwRuntimeException, throwExRuntimeException);} + } + +} diff --git a/source/test-java/org/alfresco/traitextender/TestPublicService.java b/source/test-java/org/alfresco/traitextender/TestPublicService.java new file mode 100644 index 0000000000..ff9495f2d1 --- /dev/null +++ b/source/test-java/org/alfresco/traitextender/TestPublicService.java @@ -0,0 +1,50 @@ + +package org.alfresco.traitextender; + +import org.alfresco.traitextender.Extend; +import org.alfresco.traitextender.ExtendedTrait; +import org.alfresco.traitextender.Extensible; +import org.alfresco.traitextender.AJProxyTrait; +import org.alfresco.traitextender.Trait; + +public class TestPublicService implements Extensible +{ + private final ExtendedTrait testPublicTrait; + + public TestPublicService() + { + this.testPublicTrait=new ExtendedTrait(AJProxyTrait.create(this, TestPublicTrait.class)); + } + + @Extend(traitAPI = TestPublicTrait.class, extensionAPI = TestPublicExtension.class) + public String publicMethod1(String s) + { + return "PM1" + s; + } + + @Extend(traitAPI = TestPublicTrait.class, extensionAPI = TestPublicExtension.class) + public String publicMethod2(String s) + { + return "PM2" + s; + } + + @Extend(traitAPI = TestPublicTrait.class, extensionAPI = TestPublicExtension.class) + public void publicMethod3(boolean throwException, boolean throwExException) throws TestException + { + if (throwException) { throw new TestException(); } + + } + + @Extend(traitAPI = TestPublicTrait.class, extensionAPI = TestPublicExtension.class) + public void publicMethod4(boolean throwRuntimeException, boolean throwExRuntimeException) + { + if (throwRuntimeException) { throw new TestRuntimeException(); } + } + + @Override + public ExtendedTrait getTrait(Class traitAPI) + { + return (ExtendedTrait) testPublicTrait; + } + +} diff --git a/source/test-java/org/alfresco/traitextender/TestPublicServiceExtension.java b/source/test-java/org/alfresco/traitextender/TestPublicServiceExtension.java new file mode 100644 index 0000000000..e4a67e74cb --- /dev/null +++ b/source/test-java/org/alfresco/traitextender/TestPublicServiceExtension.java @@ -0,0 +1,17 @@ +package org.alfresco.traitextender; + +public class TestPublicServiceExtension extends TestPublicService +{ + @Override + public String publicMethod1(String s) + { + return "X"+super.publicMethod1(s); + } + + @Override + public String publicMethod2(String s) + { + publicMethod1(s); + return "X"+super.publicMethod2(s); + } +} diff --git a/source/test-java/org/alfresco/traitextender/TestPublicTrait.java b/source/test-java/org/alfresco/traitextender/TestPublicTrait.java new file mode 100644 index 0000000000..8c32ec5874 --- /dev/null +++ b/source/test-java/org/alfresco/traitextender/TestPublicTrait.java @@ -0,0 +1,14 @@ +package org.alfresco.traitextender; + +import org.alfresco.traitextender.Trait; + +public interface TestPublicTrait extends Trait +{ + String publicMethod1(String s); + + String publicMethod2(String s); + + void publicMethod3(boolean throwException, boolean throwExException) throws TestException; + + void publicMethod4(boolean throwRuntimeException,boolean throwExRuntimeException); +} diff --git a/source/test-java/org/alfresco/traitextender/TestRuntimeException.java b/source/test-java/org/alfresco/traitextender/TestRuntimeException.java new file mode 100644 index 0000000000..51cd5a9318 --- /dev/null +++ b/source/test-java/org/alfresco/traitextender/TestRuntimeException.java @@ -0,0 +1,6 @@ +package org.alfresco.traitextender; + +public class TestRuntimeException extends RuntimeException +{ + +} diff --git a/source/test-java/org/alfresco/traitextender/TestService.java b/source/test-java/org/alfresco/traitextender/TestService.java new file mode 100644 index 0000000000..fd5439ad17 --- /dev/null +++ b/source/test-java/org/alfresco/traitextender/TestService.java @@ -0,0 +1,119 @@ + +package org.alfresco.traitextender; + +import java.util.List; + +import org.alfresco.traitextender.AJExtender; +import org.alfresco.traitextender.Extend; +import org.alfresco.traitextender.ExtendedTrait; +import org.alfresco.traitextender.Extensible; +import org.alfresco.traitextender.Trait; + +public class TestService implements Extensible +{ + + private String psmv2; + + private final ExtendedTrait testTrait; + + public TestService(String psmv2) + { + super(); + this.testTrait = new ExtendedTrait(AJProxyTrait.create(createTestTrait(), + TestTrait.class)); + this.psmv2 = psmv2; + } + + @Extend(traitAPI = TestTrait.class, extensionAPI = TestExtension.class) + private String privateServiceMethod1(String s) + { + return "TestService.privateServiceMethod1(" + s + ")"; + } + + public String publicServiceMethod1(String s) + { + return privateServiceMethod1(s); + } + + @Extend(traitAPI = TestTrait.class, extensionAPI = TestExtension.class) + public String publicServiceMethod3(String s) + { + return "PSM3" + privateServiceMethod1(s); + } + + @Extend(traitAPI = TestTrait.class, extensionAPI = TestExtension.class) + public String publicServiceMethod2(String s) + { + return this.psmv2; + } + + @Extend(traitAPI = TestTrait.class, extensionAPI = TestExtension.class) + public void publicServiceMethod3(TestService s, List traitIdentities) + { + traitIdentities.add(System.identityHashCode(this)); + } + + @Override + public ExtendedTrait getTrait(Class traitAPI) + { + return (ExtendedTrait) testTrait; + } + + private TestTrait createTestTrait() + { + return new TestTrait() + { + + @Override + public String traitImplOf_privateServiceMethod1(final String s) + { + return AJExtender.run(new AJExtender.ExtensionBypass() + { + + @Override + public String run() + { + return privateServiceMethod1(s); + }; + }); + } + + @Override + public String traitImplOf_publicServiceMethod2(final String s) + { + return AJExtender.run(new AJExtender.ExtensionBypass() + { + + @Override + public String run() + { + return publicServiceMethod2(s); + }; + }); + } + + @Override + public String publicServiceMethod3(final String s) + { + return publicServiceMethod3(s); + } + + @Override + public void traitImplOf_publicServiceMethod3(final TestService s, final List traitIdentities) + { + AJExtender.run(new AJExtender.ExtensionBypass() + { + + @Override + public Void run() + { + TestService.this.publicServiceMethod3(s, + traitIdentities); + return null; + }; + }); + } + + }; + } +} diff --git a/source/test-java/org/alfresco/traitextender/TestServiceExtension.java b/source/test-java/org/alfresco/traitextender/TestServiceExtension.java new file mode 100644 index 0000000000..a3922aac11 --- /dev/null +++ b/source/test-java/org/alfresco/traitextender/TestServiceExtension.java @@ -0,0 +1,16 @@ +package org.alfresco.traitextender; + +public class TestServiceExtension extends TestService +{ + + public TestServiceExtension(String psmv2) + { + super(psmv2); + } + + @Override + public String publicServiceMethod3(String s) + { + return "x"+super.publicServiceMethod3(s); + } +} diff --git a/source/test-java/org/alfresco/traitextender/TestSingletonExtensionImpl.java b/source/test-java/org/alfresco/traitextender/TestSingletonExtensionImpl.java new file mode 100644 index 0000000000..cf878ec3b5 --- /dev/null +++ b/source/test-java/org/alfresco/traitextender/TestSingletonExtensionImpl.java @@ -0,0 +1,54 @@ + +package org.alfresco.traitextender; + +import java.util.List; + +import org.alfresco.traitextender.SingletonExtension; + +public class TestSingletonExtensionImpl extends SingletonExtension implements TestExtension +{ + + private String singletonId; + + public TestSingletonExtensionImpl(String singletonId) + { + super(TestTrait.class); + this.singletonId = singletonId; + } + + @Override + public String privateServiceMethod1(String s) + { + return getTrait().traitImplOf_privateServiceMethod1(s) + " TestSingletonExtensionImpl.privateServiceMethod1(" + + s + ")@" + singletonId; + } + + @Override + public String publicServiceMethod2(String s) + { + return getTrait().traitImplOf_publicServiceMethod2(s) + " TestSingletonExtensionImpl.publicServiceMethod2(" + s + + ")@" + singletonId; + } + + @Override + public String publicServiceMethod3(String s) + { + return getTrait().publicServiceMethod3(s) + " TestSingletonExtensionImpl.publicServiceMethod3(" + s + + ")@" + singletonId; + } + + @Override + public void publicServiceMethod3(TestService s, List traitIdentities) + { + traitIdentities.add(System.identityHashCode(getTrait())); + if (s != null) + { + s.publicServiceMethod3(null, + traitIdentities); + } + traitIdentities.add(System.identityHashCode(getTrait())); + getTrait().traitImplOf_publicServiceMethod3(s, + traitIdentities); + } + +} diff --git a/source/test-java/org/alfresco/traitextender/TestTrait.java b/source/test-java/org/alfresco/traitextender/TestTrait.java new file mode 100644 index 0000000000..142cc1126a --- /dev/null +++ b/source/test-java/org/alfresco/traitextender/TestTrait.java @@ -0,0 +1,17 @@ +package org.alfresco.traitextender; + +import java.util.List; + +import org.alfresco.traitextender.Trait; + + +public interface TestTrait extends Trait +{ + String traitImplOf_privateServiceMethod1(String s); + + String traitImplOf_publicServiceMethod2(String s); + + String publicServiceMethod3(String s); + + void traitImplOf_publicServiceMethod3(TestService s,List traitIdentities); +} diff --git a/source/test-java/org/alfresco/traitextender/TraitExtenderIntegrationTest.java b/source/test-java/org/alfresco/traitextender/TraitExtenderIntegrationTest.java new file mode 100644 index 0000000000..7994401def --- /dev/null +++ b/source/test-java/org/alfresco/traitextender/TraitExtenderIntegrationTest.java @@ -0,0 +1,231 @@ + +package org.alfresco.traitextender; + +import java.util.ArrayList; +import java.util.List; + +import org.alfresco.traitextender.Extender; +import org.alfresco.traitextender.ExtensionPoint; +import org.alfresco.traitextender.InstanceExtensionFactory; +import org.alfresco.traitextender.RegistryExtensionBundle; +import org.alfresco.traitextender.SingletonExtensionFactory; + +import junit.framework.TestCase; + +public class TraitExtenderIntegrationTest extends TestCase +{ + private RegistryExtensionBundle extensionBundle; + + private RegistryExtensionBundle singletonExtensionBundle; + + private RegistryExtensionBundle publicExtensionBundle; + + @Override + protected void setUp() throws Exception + { + Extender.getInstance().stopAll(); + + extensionBundle = new RegistryExtensionBundle("extensionBundle"); + extensionBundle + .register(new ExtensionPoint(TestExtension.class, + TestTrait.class), + new InstanceExtensionFactory(TestExtensionImpl.class, + TestTrait.class, + TestExtension.class)); + + TestSingletonExtensionImpl sigletonExtension = new TestSingletonExtensionImpl("s1"); + + singletonExtensionBundle = new RegistryExtensionBundle("singletonExtensionBundle"); + singletonExtensionBundle + .register(new ExtensionPoint(TestExtension.class, + TestTrait.class), + new SingletonExtensionFactory(sigletonExtension, + TestExtension.class)); + + publicExtensionBundle = new RegistryExtensionBundle("publicExtensionBundle"); + publicExtensionBundle + .register(new ExtensionPoint(TestPublicExtension.class, + TestPublicTrait.class), + new InstanceExtensionFactory(TestPublicExtensionImpl.class, + TestPublicTrait.class, + TestPublicExtension.class)); + } + + public void testIntegration() + { + Extender.getInstance().start(extensionBundle); + + assertEquals("TestService.privateServiceMethod1(testIntegration) TestExtensionImpl.privateServiceMethod1(testIntegration)", + new TestService("psm1").publicServiceMethod1("testIntegration")); + } + + public void testIntegration_overrideExtensible_1() + { + Extender.getInstance().start(extensionBundle); + + String expectedSuffix = new TestService("psm1").publicServiceMethod3("testIntegration"); + assertEquals("x"+expectedSuffix, + new TestServiceExtension("psm1").publicServiceMethod3("testIntegration")); + } + + public void testIntegration_stoppedBundle() + { + final TestService preStopService = new TestService("psm1"); + Extender.getInstance().start(extensionBundle); + + assertEquals("TestService.privateServiceMethod1(testIntegration) TestExtensionImpl.privateServiceMethod1(testIntegration)", + preStopService.publicServiceMethod1("testIntegration")); + + Extender.getInstance().stop(extensionBundle); + final TestService postStopService = new TestService("psm1"); + + assertEquals("TestService.privateServiceMethod1(testIntegration)", + postStopService.publicServiceMethod1("testIntegration")); + assertEquals("TestService.privateServiceMethod1(testIntegration)", + preStopService.publicServiceMethod1("testIntegration")); + } + + public void testIntegration_singletonExtension() + { + Extender.getInstance().start(singletonExtensionBundle); + + assertEquals("psm1 TestSingletonExtensionImpl.publicServiceMethod2(testIntegration)@s1", + new TestService("psm1").publicServiceMethod2("testIntegration")); + + assertEquals("psm2 TestSingletonExtensionImpl.publicServiceMethod2(testIntegration)@s1", + new TestService("psm2").publicServiceMethod2("testIntegration")); + } + + public void testIntegration_publicTrait() + { + Extender.getInstance().start(publicExtensionBundle); + + assertEquals("EPM1PM1testIntegration", + new TestPublicService().publicMethod1("testIntegration")); + + assertEquals("EPM2PM2testIntegration", + new TestPublicService().publicMethod2("testIntegration")); + } + + public void testIntegration_publicOverridenExtensible_1() + { + Extender.getInstance().start(publicExtensionBundle); + + assertEquals("XEPM1PM1testIntegration", + new TestPublicServiceExtension().publicMethod1("testIntegration")); + } + + public void testIntegration_publicOverridenExtensible_2() + { + Extender.getInstance().start(publicExtensionBundle); + + assertEquals("XEPM2PM2testIntegration", + new TestPublicServiceExtension().publicMethod2("testIntegration")); + } + + public void testIntegration_bypass() + { + + Extender.getInstance().start(singletonExtensionBundle); + + assertEquals("PSM3TestService.privateServiceMethod1(bypass) TestSingletonExtensionImpl.privateServiceMethod1(bypass)@s1 TestSingletonExtensionImpl.publicServiceMethod3(bypass)@s1", + new TestService("SBP").publicServiceMethod3("bypass")); + } + + public void testIntegration_exceptionHandling() + { + Extender.getInstance().start(publicExtensionBundle); + + try + { + new TestPublicService().publicMethod3(true, + false); + fail("An exception was expected!"); + } + catch (TestException e) + { + // void - success + } + catch (Exception e) + { + fail(TestException.class + " wa expected but got " + e); + } + } + + public void testIntegration_runtimeExceptionHandling() + { + Extender.getInstance().start(publicExtensionBundle); + + try + { + new TestPublicService().publicMethod4(true, + false); + fail("An exception was expected!"); + } + catch (TestRuntimeException e) + { + // void - success + } + catch (Exception e) + { + e.printStackTrace(); + fail(TestRuntimeException.class + " wa expected but got " + e.getClass()); + } + + try + { + new TestPublicService().publicMethod4(false, + true); + fail("An exception was expected!"); + } + catch (TestRuntimeException e) + { + // void - success + } + catch (Exception e) + { + e.printStackTrace(); + fail(TestRuntimeException.class + " wa expected but got " + e.getClass()); + } + } + + private void assertNoThreadTraitSideEffect() + { + final TestService s1 = new TestService("psm1"); + final TestService s2 = new TestService("psm2"); + + final Integer s1Id = System.identityHashCode(s1); + final Integer s2Id = System.identityHashCode(s2); + + final List traitIdentities = new ArrayList(); + s1.publicServiceMethod3(s2, + traitIdentities); + + assertEquals(6, + traitIdentities.size()); + final Integer s1TraitId = traitIdentities.get(0); + final Integer s2TraitId = traitIdentities.get(1); + assertFalse(s1TraitId.equals(s2TraitId)); + assertEquals(s2TraitId, + traitIdentities.get(2)); + assertEquals(s2Id, + traitIdentities.get(3)); + assertEquals(s1TraitId, + traitIdentities.get(4)); + assertEquals(s1Id, + traitIdentities.get(5)); + } + + public void testIntegration_threadTraitSideEffect() + { + + Extender.getInstance().start(singletonExtensionBundle); + assertNoThreadTraitSideEffect(); + Extender.getInstance().stop(singletonExtensionBundle); + + Extender.getInstance().start(extensionBundle); + assertNoThreadTraitSideEffect(); + Extender.getInstance().stop(extensionBundle); + + } +} diff --git a/source/test-java/org/alfresco/traitextender/TraitExtenderUnitTestSuite.java b/source/test-java/org/alfresco/traitextender/TraitExtenderUnitTestSuite.java new file mode 100644 index 0000000000..8bb6b06482 --- /dev/null +++ b/source/test-java/org/alfresco/traitextender/TraitExtenderUnitTestSuite.java @@ -0,0 +1,27 @@ + +package org.alfresco.traitextender; + +import junit.framework.JUnit4TestAdapter; +import junit.framework.Test; +import junit.framework.TestSuite; + +public class TraitExtenderUnitTestSuite +{ + /** + * Creates the test suite + * + * @return the test suite + */ + public static Test suite() + { + TestSuite suite = new TestSuite(); + unitTests(suite); + return suite; + } + + static void unitTests(TestSuite suite) + { + suite.addTest(new JUnit4TestAdapter(org.alfresco.traitextender.TraitExtenderIntegrationTest.class)); + suite.addTest(new JUnit4TestAdapter(org.alfresco.traitextender.AJExtensionsCompileTest.class)); + } +} diff --git a/source/test-resources/org/alfresco/repo/virtual/template/testTemplate1.js b/source/test-resources/org/alfresco/repo/virtual/template/testTemplate1.js new file mode 100644 index 0000000000..8423dd4139 --- /dev/null +++ b/source/test-resources/org/alfresco/repo/virtual/template/testTemplate1.js @@ -0,0 +1,14 @@ +function applyTemplate(ctx) { + return { + name : 'template1_name', + nodes : [ { + name : 'My Documents' + }, { + name : 'Recent Documents' + }, { + name : 'Other Documents' + } ] + }; +} + +applyTemplate(context); \ No newline at end of file diff --git a/source/test-resources/org/alfresco/repo/virtual/template/testTemplate1.json b/source/test-resources/org/alfresco/repo/virtual/template/testTemplate1.json new file mode 100644 index 0000000000..89c6385b0a --- /dev/null +++ b/source/test-resources/org/alfresco/repo/virtual/template/testTemplate1.json @@ -0,0 +1,65 @@ +{ + "name":"Test", + "filing":{ + + }, + "nodes":[ + { + "id":"1", + "name":"Node1", + "search":{ + "language":"fts-alfresco", + "query":"=cm:description:'TheNode1'" + }, + "filing":{ + "path":"%ACTUAL_PATH%", + "classification":{ + "type":"cm:content" + }, + "properties":{ + "cm:description":"TheNode1" + } + } + }, + { + "id":"2", + "name":"Node2", + "search":{ + "language":"fts-alfresco", + "query":"=cm:description:'SomeNode2Desc'" + }, + "filing":{ + "path":"%ACTUAL_PATH%", + "classification":{ + "type":"cm:content" + }, + "properties":{ + "cm:description":"SomeNode2Desc" + } + }, + "nodes":[ + { + "id":"3", + "name":"Node2_1", + "search":{ + "language":"fts-alfresco", + "query":"=cm:description:'Node2_1Desc'" + }, + "filing":{ + "path":"%ACTUAL_PATH%", + "classification":{ + "type":"cm:content", + "aspects":[ + "cm:dublincore", + "cm:author" + ] + }, + "properties":{ + "cm:description":"Node2_1Desc" + } + } + } + ] + } + ] +} \ No newline at end of file diff --git a/source/test-resources/org/alfresco/repo/virtual/template/testTemplate2.json b/source/test-resources/org/alfresco/repo/virtual/template/testTemplate2.json new file mode 100644 index 0000000000..ab102e477b --- /dev/null +++ b/source/test-resources/org/alfresco/repo/virtual/template/testTemplate2.json @@ -0,0 +1,62 @@ +{ + "name":"Test", + "filing":{ + + }, + "nodes":[ + { + "id":"1", + "name":"Node1", + "search":{ + "language":"fts-alfresco", + "query":"=cm:description:'Node1'" + }, + "filing":{ + "path":"%ACTUAL_PATH%", + "classification":{ + "type":"cm:content" + }, + "properties":{ + "cm:description":"Node1" + } + } + }, + { + "id":"2", + "name":"Node2", + "description":"The2ndNode", + "search":{ + "language":"fts-alfresco", + "query":"=cm:description:'Node2'" + }, + "properties":{ + "cm:modifier":"%CURRENT_USER%", + "cm:description":"", + "sys:node-dbid":"34567" + } + }, + { + "id":"3", + "name":"Node3", + "search":{ + "language":"fts-alfresco", + "query":"=cm:description:'Node2'" + }, + "filing":{ + + } + }, + { + "id":"4", + "name":"Node4", + "search":{ + "language":"fts-alfresco", + "query":"=cm:description:'Node4'" + }, + "filing":{ + "readonly":"true" + } + + } + ] +} \ No newline at end of file diff --git a/source/test-resources/org/alfresco/repo/virtual/template/testTemplate3.json b/source/test-resources/org/alfresco/repo/virtual/template/testTemplate3.json new file mode 100644 index 0000000000..6f813140bb --- /dev/null +++ b/source/test-resources/org/alfresco/repo/virtual/template/testTemplate3.json @@ -0,0 +1,45 @@ +{ + "name":"Test", + "filing":{ + + }, + "nodes":[ + { + "name":"Node1", + "search":{ + "language":"fts-alfresco", + "query":"=cm:description:'Node1_content_FR'" + }, + "filing":{ + "path":"%ACTUAL_PATH%", + "classification":{ + "type":"cm:content" + }, + "properties":{ + "cm:description":"Node1_content_FR" + } + + } + + }, + { + "name":"Node2", + "search":{ + "language":"fts-alfresco", + "query":"=cm:description:'Node2_folder_FR'" + }, + "filing":{ + "path":"%ACTUAL_PATH%", + "classification":{ + "type":"cm:folder" + }, + "properties":{ + "cm:description":"Node2_folder_FR" + } + + } + + } + + ] +} \ No newline at end of file diff --git a/source/test-resources/org/alfresco/repo/virtual/template/testTemplate4.json b/source/test-resources/org/alfresco/repo/virtual/template/testTemplate4.json new file mode 100644 index 0000000000..0b8756b8f8 --- /dev/null +++ b/source/test-resources/org/alfresco/repo/virtual/template/testTemplate4.json @@ -0,0 +1,18 @@ +{ + "name":"Test", + "filing":{ + + }, + "nodes":[ + { + "id":"1", + "name":"All My Content", + "description":"My documents in this virtualized folder", + "search":{ + "language":"fts-alfresco", + "query":"=cm:name:'Company Home'" + } + + } + ] +} \ No newline at end of file diff --git a/source/test-resources/org/alfresco/repo/virtual/template/testTemplate5.json b/source/test-resources/org/alfresco/repo/virtual/template/testTemplate5.json new file mode 100644 index 0000000000..34f702a6f7 --- /dev/null +++ b/source/test-resources/org/alfresco/repo/virtual/template/testTemplate5.json @@ -0,0 +1,97 @@ +{ + "name":"Test", + "filing":{ + }, + "nodes":[ + { + "id":"1", + "name":"FilingFolder_filing_path", + "description":"V_FilingFolder_filing_path", + "search":{ + "language":"fts-alfresco", + "query":"=cm:description:'FilingFolder_filing_path'" + }, + "filing":{ + "path":"/cm:FilingFolder", + "classification":{ + "type":"cm:content" + }, + "properties":{ + "cm:description":"Node1_content_FR" + } + } + }, + { + "id":"2", + "name":"Actual_filing_path", + "description":"V_Actual_filing_path", + "search":{ + "language":"fts-alfresco", + "query":"=cm:description:'Actual_filing_path'" + }, + "filing":{ + "path":"%ACTUAL_PATH%", + "classification":{ + "type":"cm:content" + }, + "properties":{ + "cm:description":"Node1_content_FR" + } + } + }, + { + "id":"3", + "name":"FolderFilingType", + "description":"V_FolderFilingType", + "search":{ + "language":"fts-alfresco", + "query":"=cm:description:'FolderFilingType'" + }, + "filing":{ + "path":"%ACTUAL_PATH%", + "classification":{ + "type":"cm:folder" + }, + "properties":{ + "cm:description":"FolderFilingType" + } + } + }, + { + "id":"4", + "name":"SpecialFilingPath4", + "description":"SpecialFilingPath4", + "search":{ + "language":"fts-alfresco", + "query":"=cm:description:'SpecialFilingPath_4'" + }, + "filing":{ + "path":"%ACTUAL_PATH%", + "classification":{ + "type":"cm:folder" + }, + "properties":{ + "cm:description":"SpecialFilingPath_4" + } + } + }, + { + "id":"5", + "name":"SpecialFilingPath5", + "description":"SpecialFilingPath5", + "search":{ + "language":"fts-alfresco", + "query":"=cm:description:'SpecialFilingPath_5'" + }, + "filing":{ + "path":"%ACTUAL_PATH%/cm:Space_x0020_Sub_x0020_Folder", + "classification":{ + "type":"cm:folder" + }, + "properties":{ + "cm:description":"SpecialFilingPath_5" + } + } + } + ] +} \ No newline at end of file diff --git a/source/test-resources/org/alfresco/repo/virtual/template/testTemplate6.json b/source/test-resources/org/alfresco/repo/virtual/template/testTemplate6.json new file mode 100644 index 0000000000..899406f410 --- /dev/null +++ b/source/test-resources/org/alfresco/repo/virtual/template/testTemplate6.json @@ -0,0 +1,20 @@ +{ + "name":"Test", + "filing":{ + + }, + "nodes":[ + { + "id":"1", + "name":"Node1", + "description":"SUBFOLDERS", + "search":{ + "language":"fts-alfresco", + "query":"(PATH:'//app:company_home//cm:TestFolder//cm:FOLDER')" + }, + "filing":{ + "path":"%ACTUAL_PATH%" + } + } + ] +} \ No newline at end of file diff --git a/source/test-resources/virtualization-test-context.xml b/source/test-resources/virtualization-test-context.xml new file mode 100644 index 0000000000..3abdf94d02 --- /dev/null +++ b/source/test-resources/virtualization-test-context.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + typeAndAspects + + + + + + + + + + + + + + + + + + + + + + + + + + +