From 063dde5d8b076bb56307435946651401e08e982c Mon Sep 17 00:00:00 2001 From: Ancuta Morarasu Date: Fri, 19 Aug 2016 18:37:10 +0000 Subject: [PATCH] REPO-340 / REPO-1136 - V1 REST API: Unlock Node git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/BRANCHES/DEV/5.2.N/root@129716 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261 --- config/alfresco/public-rest-context.xml | 1 + source/java/org/alfresco/rest/api/Nodes.java | 10 + .../org/alfresco/rest/api/impl/NodesImpl.java | 671 +++++++++--------- .../alfresco/rest/api/model/UnlockInfo.java | 60 ++ .../rest/api/nodes/NodesEntityResource.java | 10 + .../rest/api/tests/AbstractBaseApiTest.java | 12 + .../alfresco/rest/api/tests/NodeApiTest.java | 171 ++++- 7 files changed, 593 insertions(+), 342 deletions(-) create mode 100644 source/java/org/alfresco/rest/api/model/UnlockInfo.java diff --git a/config/alfresco/public-rest-context.xml b/config/alfresco/public-rest-context.xml index 12835be9ce..1d24675c4a 100644 --- a/config/alfresco/public-rest-context.xml +++ b/config/alfresco/public-rest-context.xml @@ -154,6 +154,7 @@ + diff --git a/source/java/org/alfresco/rest/api/Nodes.java b/source/java/org/alfresco/rest/api/Nodes.java index 27deba6ec4..ee9e0a2aa4 100644 --- a/source/java/org/alfresco/rest/api/Nodes.java +++ b/source/java/org/alfresco/rest/api/Nodes.java @@ -36,6 +36,7 @@ import org.alfresco.rest.api.model.Document; import org.alfresco.rest.api.model.Folder; import org.alfresco.rest.api.model.LockInfo; import org.alfresco.rest.api.model.Node; +import org.alfresco.rest.api.model.UnlockInfo; import org.alfresco.rest.api.model.UserInfo; import org.alfresco.rest.framework.resource.content.BasicContentInfo; import org.alfresco.rest.framework.resource.content.BinaryResource; @@ -254,6 +255,15 @@ public interface Nodes * @return */ Node lock(String nodeId, LockInfo lockInfo, Parameters parameters); + + /** + * Unlock a node + * @param nodeId + * @param unlockInfo + * @param parameters + * @return + */ + Node unlock(String nodeId, UnlockInfo unlockInfo, Parameters parameters); /** * API Constants - query parameters, etc diff --git a/source/java/org/alfresco/rest/api/impl/NodesImpl.java b/source/java/org/alfresco/rest/api/impl/NodesImpl.java index 3e1f384d36..ecece7f332 100644 --- a/source/java/org/alfresco/rest/api/impl/NodesImpl.java +++ b/source/java/org/alfresco/rest/api/impl/NodesImpl.java @@ -22,9 +22,9 @@ * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see . * #L% - */ -package org.alfresco.rest.api.impl; - + */ +package org.alfresco.rest.api.impl; + import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -87,6 +87,7 @@ import org.alfresco.rest.api.model.Node; import org.alfresco.rest.api.model.PathInfo; import org.alfresco.rest.api.model.PathInfo.ElementInfo; import org.alfresco.rest.api.model.QuickShareLink; +import org.alfresco.rest.api.model.UnlockInfo; import org.alfresco.rest.api.model.UserInfo; import org.alfresco.rest.api.nodes.NodeAssocService; import org.alfresco.rest.framework.core.exceptions.ApiException; @@ -160,37 +161,37 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.extensions.surf.util.Content; -import org.springframework.extensions.webscripts.servlet.FormData; - -/** - * Centralises access to file/folder/node services and maps between representations. - * +import org.springframework.extensions.webscripts.servlet.FormData; + +/** + * Centralises access to file/folder/node services and maps between representations. + * * Note: * This class was originally used for returning some basic node info when listing Favourites. * * It has now been re-purposed and extended to implement the new Nodes (RESTful) API for * managing files & folders, as well as custom node types. - * - * @author steveglover + * + * @author steveglover * @author janv * @author Jamal Kaabi-Mofrad * - * @since publicapi1.0 - */ -public class NodesImpl implements Nodes -{ + * @since publicapi1.0 + */ +public class NodesImpl implements Nodes +{ private static final Log logger = LogFactory.getLog(NodesImpl.class); private enum Type - { + { // Note: ordered - DOCUMENT, FOLDER - } - - private NodeService nodeService; - private DictionaryService dictionaryService; - private FileFolderService fileFolderService; + DOCUMENT, FOLDER + } + + private NodeService nodeService; + private DictionaryService dictionaryService; + private FileFolderService fileFolderService; private NamespaceService namespaceService; private PermissionService permissionService; private MimetypeService mimetypeService; @@ -202,13 +203,13 @@ public class NodesImpl implements Nodes private AuthorityService authorityService; private ThumbnailService thumbnailService; private SiteService siteService; - private ActivityPoster poster; - private RetryingTransactionHelper retryingTransactionHelper; - private NodeAssocService nodeAssocService; + private ActivityPoster poster; + private RetryingTransactionHelper retryingTransactionHelper; + private NodeAssocService nodeAssocService; private LockService lockService; - - private enum Activity_Type - { + + private enum Activity_Type + { ADDED, UPDATED, DELETED, DOWNLOADED } @@ -220,7 +221,7 @@ public class NodesImpl implements Nodes private Repository repositoryHelper; private ServiceRegistry sr; private Set defaultIgnoreTypesAndAspects; - + // ignore types/aspects private Set ignoreQNames; @@ -253,13 +254,13 @@ public class NodesImpl implements Nodes this.personService = sr.getPersonService(); this.ownableService = sr.getOwnableService(); this.authorityService = sr.getAuthorityService(); - this.thumbnailService = sr.getThumbnailService(); - this.siteService = sr.getSiteService(); - this.retryingTransactionHelper = sr.getRetryingTransactionHelper(); + this.thumbnailService = sr.getThumbnailService(); + this.siteService = sr.getSiteService(); + this.retryingTransactionHelper = sr.getRetryingTransactionHelper(); this.lockService = sr.getLockService(); - - if (defaultIgnoreTypesAndAspects != null) - { + + if (defaultIgnoreTypesAndAspects != null) + { ignoreQNames = new HashSet<>(defaultIgnoreTypesAndAspects.size()); for (String type : defaultIgnoreTypesAndAspects) { @@ -272,7 +273,7 @@ public class NodesImpl implements Nodes { this.sr = sr; } - + public void setBehaviourFilter(BehaviourFilter behaviourFilter) { this.behaviourFilter = behaviourFilter; @@ -362,20 +363,20 @@ public class NodesImpl implements Nodes @Override public NodeRef validateNode(String nodeId) { - //belts-and-braces - if (nodeId == null) - { - throw new InvalidArgumentException("Missing nodeId"); - } - + //belts-and-braces + if (nodeId == null) + { + throw new InvalidArgumentException("Missing nodeId"); + } + return validateNode(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, nodeId); } - + @Override public NodeRef validateNode(StoreRef storeRef, String nodeId) { String versionLabel = null; - + int idx = nodeId.indexOf(";"); if (idx != -1) { @@ -387,11 +388,11 @@ public class NodesImpl implements Nodes throw new EntityNotFoundException(nodeId); } } - + NodeRef nodeRef = new NodeRef(storeRef, nodeId); return validateNode(nodeRef); } - + @Override public NodeRef validateNode(NodeRef nodeRef) { @@ -399,10 +400,10 @@ public class NodesImpl implements Nodes { throw new EntityNotFoundException(nodeRef.getId()); } - + return nodeRef; } - + /* * Check that nodes exists and matches given expected/excluded type(s). */ @@ -428,10 +429,10 @@ public class NodesImpl implements Nodes { throw new EntityNotFoundException(nodeRef.getId()); } - + return typeMatches(getNodeType(nodeRef), expectedTypes, excludedTypes); } - + private QName getNodeType(NodeRef nodeRef) { return nodeService.getType(nodeRef); @@ -459,7 +460,7 @@ public class NodesImpl implements Nodes allExpectedTypes.addAll(dictionaryService.getSubTypes(expectedType, true)); } } - + Set allExcludedTypes = new HashSet<>(); if (excludedTypes != null) { @@ -468,7 +469,7 @@ public class NodesImpl implements Nodes allExcludedTypes.addAll(dictionaryService.getSubTypes(excludedType, true)); } } - + boolean inExpected = allExpectedTypes.contains(type); boolean excluded = allExcludedTypes.contains(type); return (inExpected && !excluded); @@ -478,23 +479,23 @@ public class NodesImpl implements Nodes * @deprecated review usage (backward compat') */ @Override - public Node getNode(String nodeId) - { + public Node getNode(String nodeId) + { NodeRef nodeRef = validateNode(nodeId); - + return new Node(nodeRef, null, nodeService.getProperties(nodeRef), null, sr); - } + } /** * @deprecated review usage (backward compat') */ - public Node getNode(NodeRef nodeRef) - { + public Node getNode(NodeRef nodeRef) + { return new Node(nodeRef, null, nodeService.getProperties(nodeRef), null, sr); - } + } - private Type getType(NodeRef nodeRef) - { + private Type getType(NodeRef nodeRef) + { return getType(getNodeType(nodeRef), nodeRef); } @@ -553,14 +554,14 @@ public class NodesImpl implements Nodes } return null; // unknown - } - - /** + } + + /** * @deprecated note: currently required for backwards compat' (Favourites API) - */ + */ @Override - public Document getDocument(NodeRef nodeRef) - { + public Document getDocument(NodeRef nodeRef) + { Type type = getType(nodeRef); if ((type != null) && type.equals(Type.DOCUMENT)) { @@ -583,7 +584,7 @@ public class NodesImpl implements Nodes { throw new InvalidArgumentException("Node is not a file: "+nodeRef.getId()); } - } + } private void setCommonProps(Node node, NodeRef nodeRef, Map properties) { @@ -594,12 +595,12 @@ public class NodesImpl implements Nodes node.setCreatedBy((String)properties.get(ContentModel.PROP_CREATOR)); } - /** + /** * @deprecated note: currently required for backwards compat' (Favourites API) - */ + */ @Override - public Folder getFolder(NodeRef nodeRef) - { + public Folder getFolder(NodeRef nodeRef) + { Type type = getType(nodeRef); if ((type != null) && type.equals(Type.FOLDER)) { @@ -613,7 +614,7 @@ public class NodesImpl implements Nodes { throw new InvalidArgumentException("Node is not a folder: "+nodeRef.getId()); } - } + } private NodeRef getParentNodeRef(NodeRef nodeRef) { @@ -915,9 +916,9 @@ public class NodesImpl implements Nodes String perm = kv.getKey(); String op = kv.getValue(); - if (perm.equals(PermissionService.ADD_CHILDREN) && Type.DOCUMENT.equals(type)) + if (perm.equals(PermissionService.ADD_CHILDREN) && Type.DOCUMENT.equals(type)) { - // special case: do not return "create" (as an allowable op) for file/content types - note: 'type' can be null + // special case: do not return "create" (as an allowable op) for file/content types - note: 'type' can be null continue; } else if (perm.equals(PermissionService.DELETE) && (isSpecialNode(nodeRef, nodeTypeQName))) @@ -1601,10 +1602,10 @@ public class NodesImpl implements Nodes props = mapToNodeProperties(nodeInfo.getProperties()); } - // Optionally, lookup by relative path - String relativePath = nodeInfo.getRelativePath(); - parentNodeRef = getOrCreatePath(parentNodeRef, relativePath); - + // Optionally, lookup by relative path + String relativePath = nodeInfo.getRelativePath(); + parentNodeRef = getOrCreatePath(parentNodeRef, relativePath); + // Existing file/folder name handling boolean autoRename = Boolean.valueOf(parameters.getParameter(PARAM_AUTO_RENAME)); if (autoRename && (isContent || isSubClass(nodeTypeQName, ContentModel.TYPE_FOLDER))) @@ -1622,29 +1623,29 @@ public class NodesImpl implements Nodes { assocTypeQName = getAssocType(nodeInfo.getAssociation().getAssocType()); } - - Boolean versionMajor = null; - String str = parameters.getParameter(PARAM_VERSION_MAJOR); - if (str != null) - { - versionMajor = new Boolean(str); - } - String versionComment = parameters.getParameter(PARAM_VERSION_COMMENT); + + Boolean versionMajor = null; + String str = parameters.getParameter(PARAM_VERSION_MAJOR); + if (str != null) + { + versionMajor = new Boolean(str); + } + String versionComment = parameters.getParameter(PARAM_VERSION_COMMENT); // Create the node - NodeRef nodeRef; - - if (isContent) - { - // create empty file node - note: currently will be set to default encoding only (UTF-8) - nodeRef = createNewFile(parentNodeRef, nodeName, nodeTypeQName, null, props, assocTypeQName, parameters, versionMajor, versionComment); - } - else - { - // create non-content node - nodeRef = createNodeImpl(parentNodeRef, nodeName, nodeTypeQName, props, assocTypeQName); - } + NodeRef nodeRef; + if (isContent) + { + // create empty file node - note: currently will be set to default encoding only (UTF-8) + nodeRef = createNewFile(parentNodeRef, nodeName, nodeTypeQName, null, props, assocTypeQName, parameters, versionMajor, versionComment); + } + else + { + // create non-content node + nodeRef = createNodeImpl(parentNodeRef, nodeName, nodeTypeQName, props, assocTypeQName); + } + List aspectNames = nodeInfo.getAspectNames(); if (aspectNames != null) { @@ -1660,7 +1661,7 @@ public class NodesImpl implements Nodes nodeService.addAspect(nodeRef, aspectQName, null); } } - + // eg. to create mandatory assoc(s) if (nodeInfo.getTargets() != null) @@ -1707,17 +1708,17 @@ public class NodesImpl implements Nodes for (AssocChild assoc : entities) { - String childId = assoc.getChildId(); - if (childId == null) - { - throw new InvalidArgumentException("Missing childId"); - } - + String childId = assoc.getChildId(); + if (childId == null) + { + throw new InvalidArgumentException("Missing childId"); + } + QName assocTypeQName = getAssocType(assoc.getAssocType()); try { - NodeRef childNodeRef = validateNode(childId); + NodeRef childNodeRef = validateNode(childId); String nodeName = (String)nodeService.getProperty(childNodeRef, ContentModel.PROP_NAME); QName assocChildQName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, QName.createValidLocalName(nodeName)); @@ -1747,12 +1748,12 @@ public class NodesImpl implements Nodes for (AssocTarget assoc : entities) { - String targetNodeId = assoc.getTargetId(); - if (targetNodeId == null) - { - throw new InvalidArgumentException("Missing targetId"); - } - + String targetNodeId = assoc.getTargetId(); + if (targetNodeId == null) + { + throw new InvalidArgumentException("Missing targetId"); + } + String assocTypeStr = assoc.getAssocType(); QName assocTypeQName = getAssocType(assocTypeStr); try @@ -1999,31 +2000,31 @@ public class NodesImpl implements Nodes @Override public Node updateNode(String nodeId, Node nodeInfo, Parameters parameters) { - retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback() - { - @Override - public Void execute() throws Throwable - { - NodeRef nodeRef = updateNodeImpl(nodeId, nodeInfo, parameters); - ActivityInfo activityInfo = getActivityInfo(getParentNodeRef(nodeRef), nodeRef); - postActivity(Activity_Type.UPDATED, activityInfo, false); - - return null; - } - }, false, true); - - return retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback() - { - @Override - public Node execute() throws Throwable - { - return getFolderOrDocument(nodeId, parameters); - } - }, false, false); - } - - protected NodeRef updateNodeImpl(String nodeId, Node nodeInfo, Parameters parameters) - { + retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback() + { + @Override + public Void execute() throws Throwable + { + NodeRef nodeRef = updateNodeImpl(nodeId, nodeInfo, parameters); + ActivityInfo activityInfo = getActivityInfo(getParentNodeRef(nodeRef), nodeRef); + postActivity(Activity_Type.UPDATED, activityInfo, false); + + return null; + } + }, false, true); + + return retryingTransactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback() + { + @Override + public Node execute() throws Throwable + { + return getFolderOrDocument(nodeId, parameters); + } + }, false, false); + } + + protected NodeRef updateNodeImpl(String nodeId, Node nodeInfo, Parameters parameters) + { final NodeRef nodeRef = validateNode(nodeId); QName nodeTypeQName = getNodeType(nodeRef); @@ -2164,8 +2165,8 @@ public class NodesImpl implements Nodes throw new ConstraintViolatedException(dcne.getMessage()); } } - - return nodeRef; + + return nodeRef; } @Override @@ -2318,17 +2319,17 @@ public class NodesImpl implements Nodes } String versionComment = parameters.getParameter(PARAM_VERSION_COMMENT); - String fileName = parameters.getParameter(PARAM_NAME); - if (fileName != null) - { - // optionally rename, before updating the content - nodeService.setProperty(nodeRef, ContentModel.PROP_NAME, fileName); - } - else - { - fileName = (String)nodeService.getProperty(nodeRef, ContentModel.PROP_NAME); - } - + String fileName = parameters.getParameter(PARAM_NAME); + if (fileName != null) + { + // optionally rename, before updating the content + nodeService.setProperty(nodeRef, ContentModel.PROP_NAME, fileName); + } + else + { + fileName = (String)nodeService.getProperty(nodeRef, ContentModel.PROP_NAME); + } + return updateExistingFile(null, nodeRef, fileName, contentInfo, stream, parameters, versionMajor, versionComment); } @@ -2339,28 +2340,28 @@ public class NodesImpl implements Nodes behaviourFilter.disableBehaviour(nodeRef, ContentModel.ASPECT_VERSIONABLE); try { - writeContent(nodeRef, fileName, stream, true); + writeContent(nodeRef, fileName, stream, true); if ((isVersioned) || (versionMajor != null) || (versionComment != null) ) { - VersionType versionType = null; - if (versionMajor != null) + VersionType versionType = null; + if (versionMajor != null) { - versionType = (versionMajor ? VersionType.MAJOR : VersionType.MINOR); + versionType = (versionMajor ? VersionType.MAJOR : VersionType.MINOR); } - else - { - // note: it is possible to have versionable aspect but no versions (=> no version label) - if ((! isVersioned) || (nodeService.getProperty(nodeRef, ContentModel.PROP_VERSION_LABEL) == null)) - { - versionType = VersionType.MAJOR; - } - else - { - versionType = VersionType.MINOR; - } - } - + else + { + // note: it is possible to have versionable aspect but no versions (=> no version label) + if ((! isVersioned) || (nodeService.getProperty(nodeRef, ContentModel.PROP_VERSION_LABEL) == null)) + { + versionType = VersionType.MAJOR; + } + else + { + versionType = VersionType.MINOR; + } + } + createVersion(nodeRef, isVersioned, versionType, versionComment); } @@ -2377,100 +2378,100 @@ public class NodesImpl implements Nodes return getFolderOrDocumentFullInfo(nodeRef, null, null, parameters); } - private void writeContent(NodeRef nodeRef, String fileName, InputStream stream, boolean guessEncoding) + private void writeContent(NodeRef nodeRef, String fileName, InputStream stream, boolean guessEncoding) { ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true); - - String mimeType = mimetypeService.guessMimetype(fileName); - if ((mimeType != null) && (! mimeType.equals(MimetypeMap.MIMETYPE_BINARY))) - { - // quick/weak guess based on file extension - writer.setMimetype(mimeType); - } - else - { - // stronger guess based on file stream - writer.guessMimetype(fileName); - } - - InputStream is = null; - - if (guessEncoding) - { - is = new BufferedInputStream(stream); - is.mark(1024); - writer.setEncoding(guessEncoding(is, mimeType, false)); - try - { - is.reset(); - } - catch (IOException ioe) - { - if (logger.isWarnEnabled()) - { - logger.warn("Failed to reset stream after trying to guess encoding: " + ioe.getMessage()); - } - } - } - else - { - is = stream; - } - - writer.putContent(is); - } - - private String guessEncoding(InputStream in, String mimeType, boolean close) - { - String encoding = "UTF-8"; - try - { - if (in != null) - { - Charset charset = mimetypeService.getContentCharsetFinder().getCharset(in, mimeType); - encoding = charset.name(); - } - } - finally - { - try - { - if (close && (in != null)) - { - in.close(); - } - } - catch (IOException ioe) - { - if (logger.isWarnEnabled()) - { - logger.warn("Failed to close stream after trying to guess encoding: " + ioe.getMessage()); - } - } - } - return encoding; + + String mimeType = mimetypeService.guessMimetype(fileName); + if ((mimeType != null) && (! mimeType.equals(MimetypeMap.MIMETYPE_BINARY))) + { + // quick/weak guess based on file extension + writer.setMimetype(mimeType); + } + else + { + // stronger guess based on file stream + writer.guessMimetype(fileName); + } + + InputStream is = null; + + if (guessEncoding) + { + is = new BufferedInputStream(stream); + is.mark(1024); + writer.setEncoding(guessEncoding(is, mimeType, false)); + try + { + is.reset(); + } + catch (IOException ioe) + { + if (logger.isWarnEnabled()) + { + logger.warn("Failed to reset stream after trying to guess encoding: " + ioe.getMessage()); + } + } + } + else + { + is = stream; + } + + writer.putContent(is); } + private String guessEncoding(InputStream in, String mimeType, boolean close) + { + String encoding = "UTF-8"; + try + { + if (in != null) + { + Charset charset = mimetypeService.getContentCharsetFinder().getCharset(in, mimeType); + encoding = charset.name(); + } + } + finally + { + try + { + if (close && (in != null)) + { + in.close(); + } + } + catch (IOException ioe) + { + if (logger.isWarnEnabled()) + { + logger.warn("Failed to close stream after trying to guess encoding: " + ioe.getMessage()); + } + } + } + return encoding; + } + protected void createVersion(NodeRef nodeRef, boolean isVersioned, VersionType versionType, String reason) { if (! isVersioned) { - // Ensure versioning is enabled for the file (autoVersion = true, autoVersionProps = false) - Map props = new HashMap<>(2); - props.put(ContentModel.PROP_AUTO_VERSION, true); - props.put(ContentModel.PROP_AUTO_VERSION_PROPS, false); - - nodeService.addAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE, props); + // Ensure versioning is enabled for the file (autoVersion = true, autoVersionProps = false) + Map props = new HashMap<>(2); + props.put(ContentModel.PROP_AUTO_VERSION, true); + props.put(ContentModel.PROP_AUTO_VERSION_PROPS, false); + + nodeService.addAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE, props); } - - Map versionProperties = new HashMap<>(2); - versionProperties.put(VersionModel.PROP_VERSION_TYPE, versionType); - if (reason != null) + + Map versionProperties = new HashMap<>(2); + versionProperties.put(VersionModel.PROP_VERSION_TYPE, versionType); + if (reason != null) { - versionProperties.put(VersionModel.PROP_DESCRIPTION, reason); - } + versionProperties.put(VersionModel.PROP_DESCRIPTION, reason); + } - versionService.createVersion(nodeRef, versionProperties); + versionService.createVersion(nodeRef, versionProperties); } @Override @@ -2490,9 +2491,9 @@ public class NodesImpl implements Nodes String fileName = null; Content content = null; boolean autoRename = false; - QName nodeTypeQName = ContentModel.TYPE_CONTENT; + QName nodeTypeQName = ContentModel.TYPE_CONTENT; boolean overwrite = false; // If a fileName clashes for a versionable file - Boolean versionMajor = null; + Boolean versionMajor = null; String versionComment = null; String relativePath = null; String renditionNames = null; @@ -2537,7 +2538,7 @@ public class NodesImpl implements Nodes break; case "majorversion": - versionMajor = Boolean.valueOf(field.getValue()); + versionMajor = Boolean.valueOf(field.getValue()); break; case "comment": @@ -2612,7 +2613,7 @@ public class NodesImpl implements Nodes { // overwrite existing (versionable) file BasicContentInfo contentInfo = new ContentInfoImpl(content.getMimetype(), content.getEncoding(), -1, null); - return updateExistingFile(parentNodeRef, existingFile, fileName, contentInfo, content.getInputStream(), parameters, versionMajor, versionComment); + return updateExistingFile(parentNodeRef, existingFile, fileName, contentInfo, content.getInputStream(), parameters, versionMajor, versionComment); } else { @@ -2620,18 +2621,18 @@ public class NodesImpl implements Nodes throw new ConstraintViolatedException(fileName + " already exists."); } } - - // Note: pending REPO-159, we currently auto-enable versioning on new upload (but not when creating empty file) - if (versionMajor == null) - { - versionMajor = true; - } + + // Note: pending REPO-159, we currently auto-enable versioning on new upload (but not when creating empty file) + if (versionMajor == null) + { + versionMajor = true; + } // Create a new file. - NodeRef nodeRef = createNewFile(parentNodeRef, fileName, nodeTypeQName, content, properties, assocTypeQName, parameters, versionMajor, versionComment); - - // Create the response - final Node fileNode = getFolderOrDocumentFullInfo(nodeRef, parentNodeRef, nodeTypeQName, parameters); + NodeRef nodeRef = createNewFile(parentNodeRef, fileName, nodeTypeQName, content, properties, assocTypeQName, parameters, versionMajor, versionComment); + + // Create the response + final Node fileNode = getFolderOrDocumentFullInfo(nodeRef, parentNodeRef, nodeTypeQName, parameters); // RA-1052 try @@ -2683,44 +2684,44 @@ public class NodesImpl implements Nodes } } - private NodeRef createNewFile(NodeRef parentNodeRef, String fileName, QName nodeType, Content content, Map props, QName assocTypeQName, Parameters params, - Boolean versionMajor, String versionComment) + private NodeRef createNewFile(NodeRef parentNodeRef, String fileName, QName nodeType, Content content, Map props, QName assocTypeQName, Parameters params, + Boolean versionMajor, String versionComment) { - NodeRef nodeRef = createNodeImpl(parentNodeRef, fileName, nodeType, props, assocTypeQName); - - if (content == null) + NodeRef nodeRef = createNodeImpl(parentNodeRef, fileName, nodeType, props, assocTypeQName); + + if (content == null) { - // Write "empty" content - writeContent(nodeRef, fileName, new ByteArrayInputStream("".getBytes()), false); + // Write "empty" content + writeContent(nodeRef, fileName, new ByteArrayInputStream("".getBytes()), false); } - else - { - // Write content - writeContent(nodeRef, fileName, content.getInputStream(), true); - } - - if ((versionMajor != null) || (versionComment != null)) - { - behaviourFilter.disableBehaviour(nodeRef, ContentModel.ASPECT_VERSIONABLE); - try - { - // by default, first version is major, unless specified otherwise - VersionType versionType = VersionType.MAJOR; - if ((versionMajor != null) && (!versionMajor)) - { - versionType = VersionType.MINOR; - } + else + { + // Write content + writeContent(nodeRef, fileName, content.getInputStream(), true); + } + + if ((versionMajor != null) || (versionComment != null)) + { + behaviourFilter.disableBehaviour(nodeRef, ContentModel.ASPECT_VERSIONABLE); + try + { + // by default, first version is major, unless specified otherwise + VersionType versionType = VersionType.MAJOR; + if ((versionMajor != null) && (!versionMajor)) + { + versionType = VersionType.MINOR; + } - createVersion(nodeRef, false, versionType, versionComment); - - extractMetadata(nodeRef); - } finally - { - behaviourFilter.enableBehaviour(nodeRef, ContentModel.ASPECT_VERSIONABLE); - } - } - - return nodeRef; + createVersion(nodeRef, false, versionType, versionComment); + + extractMetadata(nodeRef); + } finally + { + behaviourFilter.enableBehaviour(nodeRef, ContentModel.ASPECT_VERSIONABLE); + } + } + + return nodeRef; } private String getStringOrNull(String value) @@ -2928,10 +2929,10 @@ public class NodesImpl implements Nodes { result.add(name); } - } - return result; - } - + } + return result; + } + @Override public Node lock(String nodeId, LockInfo lockInfo, Parameters parameters) { @@ -2970,25 +2971,59 @@ public class NodesImpl implements Nodes return lockInfo; } - /** - * @author Jamal Kaabi-Mofrad + @Override + public Node unlock(String nodeId, UnlockInfo unlockInfo, Parameters parameters) + { + NodeRef nodeRef = validateOrLookupNode(nodeId, null); + + if (isSpecialNode(nodeRef, getNodeType(nodeRef))) + { + throw new PermissionDeniedException("Current user doesn't have permission to unlock node " + nodeId); + } + + if (unlockInfo.getIncludeChildren() == null) + { + unlockInfo.setIncludeChildren(false); + } + if (unlockInfo.getAllowCheckedOut() == null) + { + unlockInfo.setAllowCheckedOut(false); + } + + // If there is no lock placed on the node skip the operation. + if (lockService.getLockStatus(nodeRef) != LockStatus.NO_LOCK) + { + if (permissionService.hasPermission(nodeRef, PermissionService.UNLOCK).equals(AccessStatus.ALLOWED)) + { + lockService.unlock(nodeRef, unlockInfo.getIncludeChildren(), unlockInfo.getAllowCheckedOut()); + } + else + { + throw new PermissionDeniedException("Current user doesn't have permission to unlock node " + nodeId); + } + } + return getFolderOrDocument(nodeId, parameters); + } + + /** + * @author Jamal Kaabi-Mofrad */ - /* - private static class ContentInfoWrapper implements BasicContentInfo + /* + private static class ContentInfoWrapper implements BasicContentInfo { private String mimeType; private String encoding; - public String getEncoding() - { - return encoding; - } - - public String getMimeType() - { - return mimeType; - } - + public String getEncoding() + { + return encoding; + } + + public String getMimeType() + { + return mimeType; + } + ContentInfoWrapper(BasicContentInfo basicContentInfo) { if (basicContentInfo != null) @@ -3029,6 +3064,6 @@ public class NodesImpl implements Nodes } } } - */ -} + */ +} diff --git a/source/java/org/alfresco/rest/api/model/UnlockInfo.java b/source/java/org/alfresco/rest/api/model/UnlockInfo.java new file mode 100644 index 0000000000..74b7b36a7f --- /dev/null +++ b/source/java/org/alfresco/rest/api/model/UnlockInfo.java @@ -0,0 +1,60 @@ +/* + * #%L + * Alfresco Remote API + * %% + * Copyright (C) 2005 - 2016 Alfresco Software Limited + * %% + * This file is part of the Alfresco software. + * If the software was purchased under a paid Alfresco license, the terms of + * the paid license agreement will prevail. Otherwise, the software is + * provided under the following open source license terms: + * + * 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 . + * #L% + */ +package org.alfresco.rest.api.model; + +/** + * Representation of a unlock info + * + * @author Ancuta Morarasu + */ + +public class UnlockInfo +{ + private Boolean includeChildren; + private Boolean allowCheckedOut; + + public UnlockInfo() {} + + public Boolean getIncludeChildren() + { + return includeChildren; + } + + public void setIncludeChildren(Boolean includeChildren) + { + this.includeChildren = includeChildren; + } + + public Boolean getAllowCheckedOut() + { + return allowCheckedOut; + } + + public void setAllowCheckedOut(Boolean allowCheckedOut) + { + this.allowCheckedOut = allowCheckedOut; + } +} diff --git a/source/java/org/alfresco/rest/api/nodes/NodesEntityResource.java b/source/java/org/alfresco/rest/api/nodes/NodesEntityResource.java index 64a932cf73..5a894da7b8 100644 --- a/source/java/org/alfresco/rest/api/nodes/NodesEntityResource.java +++ b/source/java/org/alfresco/rest/api/nodes/NodesEntityResource.java @@ -33,6 +33,7 @@ import org.alfresco.rest.api.Nodes; import org.alfresco.rest.api.model.LockInfo; import org.alfresco.rest.api.model.Node; import org.alfresco.rest.api.model.NodeTarget; +import org.alfresco.rest.api.model.UnlockInfo; import org.alfresco.rest.framework.BinaryProperties; import org.alfresco.rest.framework.Operation; import org.alfresco.rest.framework.WebApiDescription; @@ -178,6 +179,15 @@ public class NodesEntityResource implements public Node lock(String nodeId, LockInfo lockInfo, Parameters parameters, WithResponse withResponse) { return nodes.lock(nodeId, lockInfo, parameters); + } + + @Operation("unlock") + @WebApiDescription(title = "Unlock Node", + description="Removes a lock on a node.", + successStatus = HttpServletResponse.SC_OK) + public Node unlock(String nodeId, UnlockInfo unlockInfo, Parameters parameters, WithResponse withResponse) + { + return nodes.unlock(nodeId, unlockInfo, parameters); } } diff --git a/source/test-java/org/alfresco/rest/api/tests/AbstractBaseApiTest.java b/source/test-java/org/alfresco/rest/api/tests/AbstractBaseApiTest.java index bb1cb2e4d1..dac8ae4096 100644 --- a/source/test-java/org/alfresco/rest/api/tests/AbstractBaseApiTest.java +++ b/source/test-java/org/alfresco/rest/api/tests/AbstractBaseApiTest.java @@ -787,6 +787,18 @@ public abstract class AbstractBaseApiTest extends EnterpriseTestApi } return ResourceUtils.getFile(url); } + + protected Document lock(String nodeId, String body) throws Exception + { + HttpResponse response = post("nodes/" + nodeId + "/lock", body, null, 200); + return RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class); + } + + protected Document unlock(String nodeId, String body) throws Exception + { + HttpResponse response = post("nodes/" + nodeId + "/unlock", body, null, 200); + return RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class); + } protected static final long PAUSE_TIME = 5000; //millisecond protected static final int MAX_RETRY = 20; diff --git a/source/test-java/org/alfresco/rest/api/tests/NodeApiTest.java b/source/test-java/org/alfresco/rest/api/tests/NodeApiTest.java index 35eac7e231..536d654abb 100644 --- a/source/test-java/org/alfresco/rest/api/tests/NodeApiTest.java +++ b/source/test-java/org/alfresco/rest/api/tests/NodeApiTest.java @@ -78,6 +78,7 @@ import org.alfresco.rest.api.tests.util.MultiPartBuilder; import org.alfresco.rest.api.tests.util.MultiPartBuilder.FileData; import org.alfresco.rest.api.tests.util.MultiPartBuilder.MultiPartRequest; import org.alfresco.rest.api.tests.util.RestApiUtil; +import org.alfresco.service.cmr.lock.LockType; import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.StoreRef; import org.alfresco.service.cmr.security.PermissionService; @@ -111,6 +112,7 @@ public class NodeApiTest extends AbstractSingleNetworkSiteTest private static final String PROP_OWNER = "cm:owner"; private static final String URL_DELETED_NODES = "deleted-nodes"; + private static final String EMPTY_BODY = "{}"; protected PermissionService permissionService; @@ -3585,7 +3587,7 @@ public class NodeApiTest extends AbstractSingleNetworkSiteTest setRequestContext(user1); // create folder - Folder folderResp = createFolder(Nodes.PATH_MY, "folderT"); + Folder folderResp = createFolder(Nodes.PATH_MY, "folder" + RUNID); String folderId = folderResp.getId(); // create doc d1 @@ -3617,29 +3619,25 @@ public class NodeApiTest extends AbstractSingleNetworkSiteTest assertEquals(d1Name, documentResp.getName()); assertEquals(d1Id, documentResp.getId()); - assertEquals("READ_ONLY_LOCK", documentResp.getProperties().get("cm:lockType")); + assertEquals(LockType.READ_ONLY_LOCK.toString(), documentResp.getProperties().get("cm:lockType")); assertNotNull(documentResp.getProperties().get("cm:lockOwner")); assertNull(documentResp.getIsLocked()); // Empty lock body, the default values are used - post("nodes/"+folderId+"/lock", "{}", null, 200); + post("nodes/"+folderId+"/lock", EMPTY_BODY, null, 200); // Test delete on a folder which contains a locked node - NodeLockedException deleteNode(folderId, true, HttpStatus.SC_CONFLICT); // Test lock children // create folder - Folder folderA = createFolder(Nodes.PATH_MY, "folderA"); + String folderAName = "folder" + RUNID + "_A"; + Folder folderA = createFolder(Nodes.PATH_MY, folderAName); String folderAId = folderA.getId(); - // create 2 children files - String dA1Name = "content" + RUNID + "_A1"; - Document dA1 = createTextFile(folderAId, dA1Name, "A1 content"); - String dA1Id = dA1.getId(); - - String dA2Name = "content" + RUNID + "_A2"; - Document dA2 = createTextFile(folderId, dA2Name, "A2 content"); - String dA2Id = dA2.getId(); + // create 2 files in the folderA + createTextFile(folderAId, "content" + RUNID + "_A1", "A1 content"); + createTextFile(folderAId, "content" + RUNID + "_A2", "A2 content"); params = Collections.singletonMap("include", "isLocked"); response = getSingle(URL_NODES, folderAId, params, null, 200); @@ -3668,7 +3666,7 @@ public class NodeApiTest extends AbstractSingleNetworkSiteTest response = post(URL_NODES, folderAId, "lock", toJsonAsStringNonNull(body).getBytes(), null, null, 200); documentResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class); - assertEquals("folderA", documentResp.getName()); + assertEquals(folderAName, documentResp.getName()); assertEquals(folderAId, documentResp.getId()); assertNotNull(documentResp.getProperties().get("cm:lockType")); assertNotNull(documentResp.getProperties().get("cm:lockOwner")); @@ -3685,7 +3683,7 @@ public class NodeApiTest extends AbstractSingleNetworkSiteTest assertTrue(child.getIsLocked()); } - Folder folderB = createFolder(Nodes.PATH_MY, "folderB"); + Folder folderB = createFolder(Nodes.PATH_MY, "folder" + RUNID + "_B"); String folderBId = folderB.getId(); body = new HashMap<>(); @@ -3708,36 +3706,161 @@ public class NodeApiTest extends AbstractSingleNetworkSiteTest String ddNodeId = nodeResp.getId(); setRequestContext(networkAdmin); - post("nodes/"+ddNodeId+"/lock", toJsonAsStringNonNull(body), null, 403); + post("nodes/" + ddNodeId + "/lock", toJsonAsStringNonNull(body), null, 403); // Lock node already locked by another user - UnableToAquireLockException - post("nodes/"+folderId+"/lock", "{}", null, 422); + post("nodes/" + folderId + "/lock", EMPTY_BODY, null, 422); // Invalid lock body values setRequestContext(user1); - Folder folderC = createFolder(Nodes.PATH_MY, "folderC"); - String folderCId = folderB.getId(); + Folder folderC = createFolder(Nodes.PATH_MY, "folder" + RUNID + "_C"); + String folderCId = folderC.getId(); body = new HashMap<>(); body.put("includeChildren", "true123"); - post("nodes/"+folderBId+"/lock", toJsonAsStringNonNull(body), null, 400); + post("nodes/" + folderCId + "/lock", toJsonAsStringNonNull(body), null, 400); body = new HashMap<>(); body.put("type", "FULL123"); - post("nodes/"+folderBId+"/lock", toJsonAsStringNonNull(body), null, 400); + post("nodes/" + folderCId + "/lock", toJsonAsStringNonNull(body), null, 400); body = new HashMap<>(); - body.put("lifetime", "PERSISTENT123"); - post("nodes/"+folderBId+"/lock", toJsonAsStringNonNull(body), null, 400); + body.put("lifetime", "PERSISTENT123"); + post("nodes/" + folderCId + "/lock", toJsonAsStringNonNull(body), null, 400); body = new HashMap<>(); body.put("timeToExpire", "NaN"); - post("nodes/"+folderBId+"/lock", toJsonAsStringNonNull(body), null, 400); + post("nodes/" + folderCId + "/lock", toJsonAsStringNonNull(body), null, 400); body = new HashMap<>(); body.put("invalid_property", "true"); - post("nodes/"+folderBId+"/lock", toJsonAsStringNonNull(body), null, 400); + post("nodes/" + folderCId + "/lock", toJsonAsStringNonNull(body), null, 400); + + //cleanup + setRequestContext(user1); // all locks were made by user1 + unlock(folderId, toJsonAsStringNonNull(Collections.singletonMap("includeChildren", "true"))); + deleteNode(folderId); + unlock(folderAId, toJsonAsStringNonNull(Collections.singletonMap("includeChildren", "true"))); + deleteNode(folderAId); + unlock(folderBId, EMPTY_BODY); + deleteNode(folderBId); + deleteNode(folderCId); } + + + /** + * Tests unlock of a node + *

POST:

+ * {@literal :/alfresco/api/-default-/public/alfresco/versions/1/nodes//unlock} + */ + @Test + public void testUnlock() throws Exception + { + setRequestContext(user1); + + // create folder + Folder folderResp = createFolder(Nodes.PATH_MY, "folder" + RUNID); + String folderId = folderResp.getId(); + + // create doc d1 + String d1Name = "content" + RUNID + "_1l"; + Document d1 = createTextFile(folderId, d1Name, "The quick brown fox jumps over the lazy dog 1."); + String d1Id = d1.getId(); + + lock(d1Id, EMPTY_BODY); + + Map body = new HashMap<>(); + body.put("includeChildren", "true"); + body.put("allowCheckedOut", "true"); + + HttpResponse response = post(URL_NODES, d1Id, "unlock", toJsonAsStringNonNull(body).getBytes(), null, null, 200); + Document documentResp = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class); + + assertEquals(d1Name, documentResp.getName()); + assertEquals(d1Id, documentResp.getId()); + assertNull(documentResp.getProperties().get("cm:lockType")); + assertNull(documentResp.getProperties().get("cm:lockOwner")); + + lock(d1Id, EMPTY_BODY); + // Users with admin rights can unlock nodes locked by other users. + setRequestContext(networkAdmin); + post("nodes/" + d1Id + "/unlock", EMPTY_BODY, null, 200); + + setRequestContext(user1); + //Unlock on a not locked node should do nothing + post("nodes/" + d1Id + "/unlock", EMPTY_BODY, null, 200); + + post("nodes/" + folderId + "/unlock", EMPTY_BODY, null, 200); + + // Test unlock children + // create folder + Folder folderA = createFolder(Nodes.PATH_MY, "folder" + RUNID + "_A"); + String folderAId = folderA.getId(); + + // create 2 files in the folderA + String dA1Name = "content" + RUNID + "_A1"; + Document dA1 = createTextFile(folderAId, dA1Name, "A1 content"); + String dA1Id = dA1.getId(); + + String dA2Name = "content" + RUNID + "_A2"; + Document dA2 = createTextFile(folderAId, dA2Name, "A2 content"); + String dA2Id = dA2.getId(); + + // lock the folder and children + body = new HashMap<>(); + body.put("includeChildren", "true"); + lock(folderAId, toJsonAsStringNonNull(body)); + + body.put("includeChildren", "true"); + body.put("allowCheckedOut", "true"); + post(URL_NODES, folderAId, "unlock", toJsonAsStringNonNull(body).getBytes(), null, null, 200); + + Map params = Collections.singletonMap("include", "aspectNames,properties,isLocked"); + response = getAll(getNodeChildrenUrl(folderAId), null, params, 200); + List nodes = RestApiUtil.parseRestApiEntries(response.getJsonResponse(), Node.class); + // Test if children nodes are unlocked as well. + for (Node child : nodes) + { + assertNull(child.getProperties().get("cm:lockType")); + assertNull(child.getProperties().get("cm:lockOwner")); + assertFalse(child.getIsLocked()); + } + + // -ve + // Missing target node + post("nodes/" + "fakeId" + "/unlock", EMPTY_BODY, null, 404); + + // Unlock by a user without permission + lock(d1Id, EMPTY_BODY); + setRequestContext(user2); + post("nodes/" + d1Id + "/unlock", EMPTY_BODY, null, 403); + + // Invalid lock body values + setRequestContext(user1); + Folder folderC = createFolder(Nodes.PATH_MY, "folder" + RUNID + "_C"); + String folderCId = folderC.getId(); + lock(folderCId, EMPTY_BODY); + body = new HashMap<>(); + body.put("includeChildren", "true123"); + post("nodes/" + folderCId + "/unlock", toJsonAsStringNonNull(body), null, 400); + + body = new HashMap<>(); + body.put("allowCheckedOut", "false123"); + post("nodes/" + folderCId + "/unlock", toJsonAsStringNonNull(body), null, 400); + + body = new HashMap<>(); + body.put("invalid_property", "true"); + post("nodes/" + folderCId + "/unlock", toJsonAsStringNonNull(body), null, 400); + + // clean up + setRequestContext(user1); // all locks were made by user1 + unlock(folderId, toJsonAsStringNonNull(Collections.singletonMap("includeChildren", "true"))); + deleteNode(folderId); + unlock(folderAId, toJsonAsStringNonNull(Collections.singletonMap("includeChildren", "true"))); + deleteNode(folderAId); + unlock(folderCId, EMPTY_BODY); + deleteNode(folderCId); + } @Override public String getScope()