From 75b6831d2a2c8890ac076a93c19347e189d2aac7 Mon Sep 17 00:00:00 2001 From: Mark Rogers Date: Tue, 22 Jul 2014 12:58:48 +0000 Subject: [PATCH] Merged HEAD-BUG-FIX (5.0/Cloud) to HEAD (5.0/Cloud) 75551: Reverse Merge HEAD-BUG-FIX (5.0/Cloud) 74584: Reverse merged HEAD-BUG-FIX (5.0/Cloud) << Requires more work on the EOL branch >> 74416: Merged EOL to HEAD-BUG-FIX (5.0/Cloud) 74309: ACE-2010 EOL Legacy CMIS Inputs (2) in 5.0 - Start replacing references to the original CMIS code with Alfresco and chemistry Open CMIS classes 74342: ACE-2010 EOL Legacy CMIS Inputs (2) in 5.0 - Switch ServiceRegistry over to using Open CMIS classes 74406: ACE-2010 EOL Legacy CMIS Inputs (2) in 5.0 << Compiles and starts Share without error >> - Removed Original CMIS classes from the repository, remote-api and thor - Moved the CMIS.DictionaryBootstrap bean into opencmis-context.xml before removing cmis-api-context.xml - Some code was left under: root\projects\remote-api\source\java\org\alfresco\repo\cmis ...........................................................\client ...........................................................\ws ...........................................................\rest ................................test-java\org\alfresco\repo\cmis ................................................................\ws ................................................................\rest Will have to see if it should be be removed too, or if it is common with OpenCMIS 74407: ACE-2010 EOL Legally CMIS Inputs (2) in 5.0 - Removed left over code under: root\projects\remote-api\source\java\org\alfresco\repo\cmis ................................test-java\org\alfresco\repo\cmis - Removed an authentication URL test in QuickShareRestApiTest which was failing in the same way as the tests above. - Removed CXFAuthenticationSystemTest which appears to be using the original CMIS 74465: Merged EOL (5.0/Cloud) to HEAD-BUG-FIX (5.0/Cloud) 74464: ACE-2010 EOL Legacey CMIS Inputs (2) in 5.0 - New failure in QuickShareRestApiTest - CXFAuthenticationSystemTest (deleted) was still referenced in MiscSystemTestSuite git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@77489 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261 --- config/alfresco/cmis-ws-context.xml | 356 ----- .../web-scripts-application-context.xml | 122 -- .../repo/cmis/reference/AVMPathReference.java | 77 - .../reference/AbstractObjectReference.java | 56 - .../AbstractRepositoryReference.java | 50 - .../AssociationIdRelationshipReference.java | 87 -- .../reference/DefaultRepositoryReference.java | 51 - .../repo/cmis/reference/NodeIdReference.java | 81 - .../cmis/reference/NodePathReference.java | 81 - .../cmis/reference/ObjectIdReference.java | 88 -- .../cmis/reference/ObjectPathReference.java | 83 -- .../repo/cmis/reference/ReferenceFactory.java | 163 --- .../reference/StoreRepositoryReference.java | 80 - .../repo/cmis/rest/CMISAclMethod.java | 97 -- .../repo/cmis/rest/CMISAspectsMethod.java | 88 -- .../repo/cmis/rest/CMISAssocsMethod.java | 124 -- .../repo/cmis/rest/CMISChildrenMethod.java | 119 -- .../cmis/rest/CMISPropertyValueMethod.java | 139 -- .../repo/cmis/rest/CMISQueryWebScript.java | 50 - .../repo/cmis/rest/CMISRenditionsMethod.java | 116 -- .../repo/cmis/rest/CMISResultSetMethod.java | 96 -- .../alfresco/repo/cmis/rest/CMISScript.java | 1303 ----------------- .../repo/cmis/rest/CMISTemplateResultSet.java | 312 ---- .../cmis/rest/CMISTypeDefinitionMethod.java | 106 -- .../repo/cmis/ws/DMAbstractServicePort.java | 539 ------- .../repo/cmis/ws/DMAclServicePort.java | 72 - .../repo/cmis/ws/DMDiscoveryServicePort.java | 290 ---- .../cmis/ws/DMMultiFilingServicePort.java | 112 -- .../repo/cmis/ws/DMNavigationServicePort.java | 410 ------ .../repo/cmis/ws/DMObjectServicePort.java | 872 ----------- .../repo/cmis/ws/DMPolicyServicePort.java | 93 -- .../cmis/ws/DMRelationshipServicePort.java | 98 -- .../repo/cmis/ws/DMRepositoryServicePort.java | 672 --------- .../cmis/ws/DMServicePortThrowsAdvice.java | 75 - .../repo/cmis/ws/DMVersioningServicePort.java | 223 --- .../repo/cmis/ws/utils/ExceptionUtil.java | 96 -- .../repo/cmis/ws/utils/PropertyUtil.java | 745 ---------- .../web/scripts/content/ContentDelete.java | 133 -- .../repo/web/scripts/content/ContentGet.java | 322 ---- .../repo/web/scripts/content/ContentInfo.java | 113 -- .../repo/web/scripts/content/ContentSet.java | 187 --- .../quickshare/QuickShareContentGet.java | 11 +- .../org/alfresco/RemoteApi01TestSuite.java | 24 +- .../org/alfresco/RemoteApi08TestSuite.java | 37 - .../org/alfresco/RemoteApi09TestSuite.java | 37 - .../changelog/CMISChangeLogServiceTest.java | 482 ------ .../repo/cmis/rest/test/AspectTest.java | 142 -- .../repo/cmis/rest/test/BaseCMISTest.java | 159 -- .../test/BulkCreateAndQuerySystemTest.java | 132 -- .../cmis/rest/test/BulkCreateSystemTest.java | 151 -- .../cmis/rest/test/CMISAtomTemplatesTest.java | 218 --- .../rest/test/CmisRelationshipSystemTest.java | 120 -- .../repo/cmis/rest/test/PolicyTest.java | 78 - .../repo/cmis/ws/test/AspectTest.java | 139 -- .../repo/cmis/ws/test/BaseCMISTest.java | 137 -- .../repo/cmis/ws/test/PolicyTest.java | 97 -- .../repo/cmis/ws/test/QueryPagingTest.java | 182 --- .../quickshare/QuickShareRestApiTest.java | 12 +- 58 files changed, 21 insertions(+), 11114 deletions(-) delete mode 100644 source/java/org/alfresco/repo/cmis/reference/AVMPathReference.java delete mode 100644 source/java/org/alfresco/repo/cmis/reference/AbstractObjectReference.java delete mode 100644 source/java/org/alfresco/repo/cmis/reference/AbstractRepositoryReference.java delete mode 100644 source/java/org/alfresco/repo/cmis/reference/AssociationIdRelationshipReference.java delete mode 100644 source/java/org/alfresco/repo/cmis/reference/DefaultRepositoryReference.java delete mode 100644 source/java/org/alfresco/repo/cmis/reference/NodeIdReference.java delete mode 100644 source/java/org/alfresco/repo/cmis/reference/NodePathReference.java delete mode 100644 source/java/org/alfresco/repo/cmis/reference/ObjectIdReference.java delete mode 100644 source/java/org/alfresco/repo/cmis/reference/ObjectPathReference.java delete mode 100644 source/java/org/alfresco/repo/cmis/reference/ReferenceFactory.java delete mode 100644 source/java/org/alfresco/repo/cmis/reference/StoreRepositoryReference.java delete mode 100644 source/java/org/alfresco/repo/cmis/rest/CMISAclMethod.java delete mode 100644 source/java/org/alfresco/repo/cmis/rest/CMISAspectsMethod.java delete mode 100644 source/java/org/alfresco/repo/cmis/rest/CMISAssocsMethod.java delete mode 100644 source/java/org/alfresco/repo/cmis/rest/CMISChildrenMethod.java delete mode 100644 source/java/org/alfresco/repo/cmis/rest/CMISPropertyValueMethod.java delete mode 100644 source/java/org/alfresco/repo/cmis/rest/CMISQueryWebScript.java delete mode 100644 source/java/org/alfresco/repo/cmis/rest/CMISRenditionsMethod.java delete mode 100644 source/java/org/alfresco/repo/cmis/rest/CMISResultSetMethod.java delete mode 100644 source/java/org/alfresco/repo/cmis/rest/CMISScript.java delete mode 100644 source/java/org/alfresco/repo/cmis/rest/CMISTemplateResultSet.java delete mode 100644 source/java/org/alfresco/repo/cmis/rest/CMISTypeDefinitionMethod.java delete mode 100644 source/java/org/alfresco/repo/cmis/ws/DMAbstractServicePort.java delete mode 100644 source/java/org/alfresco/repo/cmis/ws/DMAclServicePort.java delete mode 100644 source/java/org/alfresco/repo/cmis/ws/DMDiscoveryServicePort.java delete mode 100644 source/java/org/alfresco/repo/cmis/ws/DMMultiFilingServicePort.java delete mode 100644 source/java/org/alfresco/repo/cmis/ws/DMNavigationServicePort.java delete mode 100644 source/java/org/alfresco/repo/cmis/ws/DMObjectServicePort.java delete mode 100644 source/java/org/alfresco/repo/cmis/ws/DMPolicyServicePort.java delete mode 100644 source/java/org/alfresco/repo/cmis/ws/DMRelationshipServicePort.java delete mode 100644 source/java/org/alfresco/repo/cmis/ws/DMRepositoryServicePort.java delete mode 100644 source/java/org/alfresco/repo/cmis/ws/DMServicePortThrowsAdvice.java delete mode 100644 source/java/org/alfresco/repo/cmis/ws/DMVersioningServicePort.java delete mode 100644 source/java/org/alfresco/repo/cmis/ws/utils/ExceptionUtil.java delete mode 100644 source/java/org/alfresco/repo/cmis/ws/utils/PropertyUtil.java delete mode 100644 source/java/org/alfresco/repo/web/scripts/content/ContentDelete.java delete mode 100644 source/java/org/alfresco/repo/web/scripts/content/ContentGet.java delete mode 100644 source/java/org/alfresco/repo/web/scripts/content/ContentInfo.java delete mode 100644 source/java/org/alfresco/repo/web/scripts/content/ContentSet.java delete mode 100644 source/test-java/org/alfresco/RemoteApi08TestSuite.java delete mode 100644 source/test-java/org/alfresco/RemoteApi09TestSuite.java delete mode 100644 source/test-java/org/alfresco/cmis/changelog/CMISChangeLogServiceTest.java delete mode 100644 source/test-java/org/alfresco/repo/cmis/rest/test/AspectTest.java delete mode 100644 source/test-java/org/alfresco/repo/cmis/rest/test/BaseCMISTest.java delete mode 100644 source/test-java/org/alfresco/repo/cmis/rest/test/BulkCreateAndQuerySystemTest.java delete mode 100644 source/test-java/org/alfresco/repo/cmis/rest/test/BulkCreateSystemTest.java delete mode 100644 source/test-java/org/alfresco/repo/cmis/rest/test/CMISAtomTemplatesTest.java delete mode 100644 source/test-java/org/alfresco/repo/cmis/rest/test/CmisRelationshipSystemTest.java delete mode 100644 source/test-java/org/alfresco/repo/cmis/rest/test/PolicyTest.java delete mode 100644 source/test-java/org/alfresco/repo/cmis/ws/test/AspectTest.java delete mode 100644 source/test-java/org/alfresco/repo/cmis/ws/test/BaseCMISTest.java delete mode 100644 source/test-java/org/alfresco/repo/cmis/ws/test/PolicyTest.java delete mode 100644 source/test-java/org/alfresco/repo/cmis/ws/test/QueryPagingTest.java diff --git a/config/alfresco/cmis-ws-context.xml b/config/alfresco/cmis-ws-context.xml index e3002c0447..71a809de43 100644 --- a/config/alfresco/cmis-ws-context.xml +++ b/config/alfresco/cmis-ws-context.xml @@ -9,362 +9,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - dmRepositoryService - dmNavigationService - dmObjectService - dmMultiFilingService - dmVersioningService - dmDiscoveryService - dmRelationshipService - dmPolicyService - dmAclService - - - - - - - - - - - - - - - - - - ${server.transaction.mode.readOnly} - ${server.transaction.mode.readOnly} - ${server.transaction.mode.default} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/gif diff --git a/config/alfresco/web-scripts-application-context.xml b/config/alfresco/web-scripts-application-context.xml index 5229341c30..65fea8e4b9 100644 --- a/config/alfresco/web-scripts-application-context.xml +++ b/config/alfresco/web-scripts-application-context.xml @@ -155,55 +155,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -325,73 +276,12 @@ - - - - - - - cmisserver - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -475,15 +365,6 @@ - - - - - - - - - @@ -1970,13 +1851,10 @@ - - - diff --git a/source/java/org/alfresco/repo/cmis/reference/AVMPathReference.java b/source/java/org/alfresco/repo/cmis/reference/AVMPathReference.java deleted file mode 100644 index 06d369546d..0000000000 --- a/source/java/org/alfresco/repo/cmis/reference/AVMPathReference.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.reference; - -import org.alfresco.cmis.CMISRepositoryReference; -import org.alfresco.cmis.CMISServices; -import org.alfresco.service.cmr.repository.NodeRef; - - -/** - * AVM Path Reference - * - * @author davidc - */ -public class AVMPathReference extends AbstractObjectReference -{ - protected String path; - protected String[] reference; - - /** - * Construct - * - * @param cmisServices - * @param repo - * @param path (note: AVM store relative path) - */ - public AVMPathReference(CMISServices cmisServices, CMISRepositoryReference repo, String path) - { - super(cmisServices, repo); - String[] splitPath = path.split("/"); - this.reference = new String[1 + splitPath.length]; - String avmStoreName = repo.getStoreRef().getIdentifier(); - reference[0] = avmStoreName; - this.path = avmStoreName + ":/" + path; - System.arraycopy(splitPath, 0, reference, 1, splitPath.length); - } - - /* - * (non-Javadoc) - * @see org.alfresco.cmis.reference.ObjectPathReference#getNodeRef() - */ - public NodeRef getNodeRef() - { - return cmisServices.getNode("avmpath", reference); - } - - /** - * @return AVM path (eg. avmstorename:/my/path/to/a/file) - */ - public String getPath() - { - return path; - } - - @Override - public String toString() - { - return "AVMPathReference[avmpath=" + path + "]"; - } - -} diff --git a/source/java/org/alfresco/repo/cmis/reference/AbstractObjectReference.java b/source/java/org/alfresco/repo/cmis/reference/AbstractObjectReference.java deleted file mode 100644 index 7db0f05072..0000000000 --- a/source/java/org/alfresco/repo/cmis/reference/AbstractObjectReference.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.reference; - -import org.alfresco.cmis.CMISObjectReference; -import org.alfresco.cmis.CMISRepositoryReference; -import org.alfresco.cmis.CMISServices; - - -/** - * Abstract Object Reference - * - * @author davidc - */ -public abstract class AbstractObjectReference implements CMISObjectReference -{ - protected CMISServices cmisServices; - protected CMISRepositoryReference repo; - - /** - * Construct - * - * @param cmisServices - * @param repo - */ - public AbstractObjectReference(CMISServices cmisServices, CMISRepositoryReference repo) - { - this.cmisServices = cmisServices; - this.repo = repo; - } - - /* - * (non-Javadoc) - * @see org.alfresco.cmis.CMISObjectReference#getRepositoryReference() - */ - public CMISRepositoryReference getRepositoryReference() - { - return repo; - } -} diff --git a/source/java/org/alfresco/repo/cmis/reference/AbstractRepositoryReference.java b/source/java/org/alfresco/repo/cmis/reference/AbstractRepositoryReference.java deleted file mode 100644 index bc85d6ec1a..0000000000 --- a/source/java/org/alfresco/repo/cmis/reference/AbstractRepositoryReference.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.reference; - -import org.alfresco.cmis.CMISRepositoryReference; -import org.alfresco.cmis.CMISServices; - - -/** - * Abstract Repository Reference - * - * @author davidc - */ -public abstract class AbstractRepositoryReference implements CMISRepositoryReference -{ - protected CMISServices cmisServices; - - /** - * Construct - * - * @param cmisServices - */ - public AbstractRepositoryReference(CMISServices cmisServices) - { - this.cmisServices = cmisServices; - } - - @Override - public String toString() - { - return getStoreRef().toString(); - } - -} diff --git a/source/java/org/alfresco/repo/cmis/reference/AssociationIdRelationshipReference.java b/source/java/org/alfresco/repo/cmis/reference/AssociationIdRelationshipReference.java deleted file mode 100644 index 7761dad4ac..0000000000 --- a/source/java/org/alfresco/repo/cmis/reference/AssociationIdRelationshipReference.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.reference; - -import org.alfresco.cmis.CMISRelationshipReference; -import org.alfresco.cmis.CMISRepositoryReference; -import org.alfresco.cmis.CMISServiceException; -import org.alfresco.cmis.CMISServices; -import org.alfresco.service.cmr.repository.AssociationRef; -import org.alfresco.service.cmr.repository.StoreRef; -import org.springframework.extensions.webscripts.WebScriptException; - -/** - * Association ID relationship reference. An association ID can be resolved to an {@link AssociationRef}. - * - * @author dward - */ -public class AssociationIdRelationshipReference implements CMISRelationshipReference -{ - private CMISServices cmisServices; - private String assocId; - - /** - * Construct - * - * @param cmisServices - * @param assocId - */ - public AssociationIdRelationshipReference(CMISServices cmisServices, String assocId) - { - this.cmisServices = cmisServices; - this.assocId = assocId; - } - - /* - * (non-Javadoc) - * @see org.alfresco.cmis.CMISRelationshipReference#getAssocRef() - */ - public AssociationRef getAssocRef() - { - try - { - return cmisServices.getReadableObject(this.assocId, AssociationRef.class); - } - catch (CMISServiceException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - } - - /* - * (non-Javadoc) - * @see org.alfresco.cmis.CMISObjectReference#getRepositoryReference() - */ - public CMISRepositoryReference getRepositoryReference() - { - return new AbstractRepositoryReference(cmisServices) - { - public StoreRef getStoreRef() - { - return getAssocRef().getSourceRef().getStoreRef(); - } - }; - } - - @Override - public String toString() - { - return "AssociationIdRelationshipReference[assocId=" + this.assocId + "]"; - } -} diff --git a/source/java/org/alfresco/repo/cmis/reference/DefaultRepositoryReference.java b/source/java/org/alfresco/repo/cmis/reference/DefaultRepositoryReference.java deleted file mode 100644 index e7b0dbfe64..0000000000 --- a/source/java/org/alfresco/repo/cmis/reference/DefaultRepositoryReference.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.reference; - -import org.alfresco.cmis.CMISServices; -import org.alfresco.service.cmr.repository.StoreRef; - - -/** - * Default Repository Reference - * - * @author davidc - */ -public class DefaultRepositoryReference extends AbstractRepositoryReference -{ - /** - * Construct - * - * @param cmisServices - */ - public DefaultRepositoryReference(CMISServices cmisServices) - { - super(cmisServices); - } - - /* - * (non-Javadoc) - * @see org.alfresco.cmis.CMISRepositoryReference#getStoreRef() - */ - public StoreRef getStoreRef() - { - return cmisServices.getDefaultRootStoreRef(); - } - -} diff --git a/source/java/org/alfresco/repo/cmis/reference/NodeIdReference.java b/source/java/org/alfresco/repo/cmis/reference/NodeIdReference.java deleted file mode 100644 index 06a93cdeb3..0000000000 --- a/source/java/org/alfresco/repo/cmis/reference/NodeIdReference.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.reference; - -import org.alfresco.cmis.CMISRepositoryReference; -import org.alfresco.cmis.CMISServices; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.StoreRef; - -/** - * GUID Object Reference. This class decodes node 'paths' generated by links.lib.atom.ftl. These are not the same as - * CMIS object IDs. - * - * @author davidc - */ -public class NodeIdReference extends AbstractObjectReference -{ - private String id; - private String[] reference; - - /** - * Construct - * - * @param cmisServices - * @param repo - * @param id - */ - public NodeIdReference(CMISServices cmisServices, CMISRepositoryReference repo, String id) - { - super(cmisServices, repo); - - this.id = id; - - StoreRef storeRef = repo.getStoreRef(); - String[] idParts = this.id.split("/"); - reference = new String[2 + idParts.length]; - reference[0] = storeRef.getProtocol(); - reference[1] = storeRef.getIdentifier(); - System.arraycopy(idParts, 0, reference, 2, idParts.length); - } - - /* - * (non-Javadoc) - * @see org.alfresco.cmis.CMISObjectReference#getNodeRef() - */ - public NodeRef getNodeRef() - { - return cmisServices.getNode("node", reference); - } - - /** - * @return id - */ - public String getId() - { - return id; - } - - @Override - public String toString() - { - return "NodeIdReference[storeRef=" + repo.getStoreRef() + ",id=" + id + "]"; - } - -} diff --git a/source/java/org/alfresco/repo/cmis/reference/NodePathReference.java b/source/java/org/alfresco/repo/cmis/reference/NodePathReference.java deleted file mode 100644 index bff04809a6..0000000000 --- a/source/java/org/alfresco/repo/cmis/reference/NodePathReference.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.reference; - -import org.alfresco.cmis.CMISRepositoryReference; -import org.alfresco.cmis.CMISServices; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.StoreRef; - - -/** - * Node Path Object Reference - * - * Note: This path is from the root of the store - * - * @author davidc - */ -public class NodePathReference extends AbstractObjectReference -{ - protected String path; - protected String[] reference; - - /** - * Construct - * - * @param cmisServices - * @param repo - * @param path - */ - public NodePathReference(CMISServices cmisServices, CMISRepositoryReference repo, String path) - { - super(cmisServices, repo); - this.path = path; - String[] splitPath = this.path.split("/"); - this.reference = new String[2 + splitPath.length]; - StoreRef storeRef = repo.getStoreRef(); - reference[0] = storeRef.getProtocol(); - reference[1] = storeRef.getIdentifier(); - System.arraycopy(splitPath, 0, reference, 2, splitPath.length); - } - - /* - * (non-Javadoc) - * @see org.alfresco.cmis.CMISObjectReference#getNodeRef() - */ - public NodeRef getNodeRef() - { - return cmisServices.getNode("path", reference); - } - - /** - * @return path - */ - public String getPath() - { - return path; - } - - @Override - public String toString() - { - return "NodePathReference[storeRef=" + repo.getStoreRef() + ",path=" + path + "]"; - } - -} diff --git a/source/java/org/alfresco/repo/cmis/reference/ObjectIdReference.java b/source/java/org/alfresco/repo/cmis/reference/ObjectIdReference.java deleted file mode 100644 index 25d4066f10..0000000000 --- a/source/java/org/alfresco/repo/cmis/reference/ObjectIdReference.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.reference; - -import org.alfresco.cmis.CMISObjectReference; -import org.alfresco.cmis.CMISRepositoryReference; -import org.alfresco.cmis.CMISServiceException; -import org.alfresco.cmis.CMISServices; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.StoreRef; -import org.springframework.extensions.webscripts.WebScriptException; - -/** - * CMIS Object ID reference. A CMIS object ID encapsulates both a store and a node and identifies a specific version. - * - * @author dward - */ -public class ObjectIdReference implements CMISObjectReference -{ - private CMISServices cmisServices; - private String objectId; - - /** - * Construct - * - * @param cmisServices - * @param storeRef - */ - public ObjectIdReference(CMISServices cmisServices, String objectId) - { - this.cmisServices = cmisServices; - this.objectId = objectId; - } - - /* - * (non-Javadoc) - * @see org.alfresco.cmis.CMISObjectReference#getNodeRef() - */ - public NodeRef getNodeRef() - { - try - { - return cmisServices.getReadableObject(this.objectId, NodeRef.class); - } - catch (CMISServiceException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - } - - /* - * (non-Javadoc) - * @see org.alfresco.cmis.CMISObjectReference#getRepositoryReference() - */ - public CMISRepositoryReference getRepositoryReference() - { - return new AbstractRepositoryReference(cmisServices) - { - public StoreRef getStoreRef() - { - return getNodeRef().getStoreRef(); - } - }; - } - - @Override - public String toString() - { - return "ObjectIdReference[objectId=" + this.objectId + "]"; - } - -} diff --git a/source/java/org/alfresco/repo/cmis/reference/ObjectPathReference.java b/source/java/org/alfresco/repo/cmis/reference/ObjectPathReference.java deleted file mode 100644 index 2d31639469..0000000000 --- a/source/java/org/alfresco/repo/cmis/reference/ObjectPathReference.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.reference; - -import org.alfresco.cmis.CMISRepositoryReference; -import org.alfresco.cmis.CMISServices; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.StoreRef; - - -/** - * Path Object Reference - * - * Note: This path is relative to the CMIS root path - * - * @author davidc - */ -public class ObjectPathReference extends AbstractObjectReference -{ - protected String path; - protected String[] reference; - - /** - * Construct - * - * @param cmisServices - * @param repo - * @param path - */ - public ObjectPathReference(CMISServices cmisServices, CMISRepositoryReference repo, String path) - { - super(cmisServices, repo); - this.path = cmisServices.getDefaultRootPath() + path; - String[] splitPath = this.path.split("/"); - String[] pathSegments = new String[splitPath.length -1]; - System.arraycopy(splitPath, 1, pathSegments, 0, splitPath.length -1); - this.reference = new String[2 + pathSegments.length]; - StoreRef storeRef = repo.getStoreRef(); - reference[0] = storeRef.getProtocol(); - reference[1] = storeRef.getIdentifier(); - System.arraycopy(pathSegments, 0, reference, 2, pathSegments.length); - } - - /* - * (non-Javadoc) - * @see org.alfresco.cmis.CMISObjectReference#getNodeRef() - */ - public NodeRef getNodeRef() - { - return cmisServices.getNode("path", reference); - } - - /** - * @return path - */ - public String getPath() - { - return path; - } - - @Override - public String toString() - { - return "ObjectPathReference[storeRef=" + repo.getStoreRef() + ",path=" + path + "]"; - } - -} diff --git a/source/java/org/alfresco/repo/cmis/reference/ReferenceFactory.java b/source/java/org/alfresco/repo/cmis/reference/ReferenceFactory.java deleted file mode 100644 index 8f9722360d..0000000000 --- a/source/java/org/alfresco/repo/cmis/reference/ReferenceFactory.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.reference; - -import java.util.Map; - -import org.alfresco.cmis.CMISObjectReference; -import org.alfresco.cmis.CMISRelationshipReference; -import org.alfresco.cmis.CMISRepositoryReference; -import org.alfresco.cmis.CMISServices; -import org.alfresco.service.cmr.repository.StoreRef; - - -/** - * Reference Factory - * - * @author davidc - */ -public class ReferenceFactory -{ - private CMISServices cmisService; - - /** - * @param cmisService - */ - public void setCMISService(CMISServices cmisService) - { - this.cmisService = cmisService; - } - - /** - * Create CMIS Repository Reference from URL segments - * - * @param args url arguments - * @param templateArgs url template arguments - * @return Repository Reference (or null, in case of bad url) - */ - public CMISRepositoryReference createRepoReferenceFromUrl(Map args, Map templateArgs) - { - String store_type = templateArgs.get("store_type"); - String store_id = templateArgs.get("store_id"); - if (store_type != null && store_id != null) - { - return new StoreRepositoryReference(cmisService, store_type + ":" + store_id); - } - - String store = templateArgs.get("store"); - if (store != null) - { - return new StoreRepositoryReference(cmisService, store); - } - - String avmPath = templateArgs.get("avmpath"); - if (avmPath != null && store_id != null) - { - return new StoreRepositoryReference(cmisService, StoreRef.PROTOCOL_AVM + ":" + store_id); - } - - // TODO: repository id -// String repoId = templateArgs.get("repo"); -// else if (repoId != null) -// { -// } - - return new DefaultRepositoryReference(cmisService); - } - - /** - * Create CMIS Object Reference from URL segments - * - * @param args url arguments - * @param templateArgs url template arguments - * @return Repository Reference (or null, in case of bad url) - */ - public CMISObjectReference createObjectReferenceFromUrl(Map args, Map templateArgs) - { - // Despite the name of this argument, it is included in the "Object by ID" URL template and actually accepts a - // value in object ID format (including version label suffix) so should be parsed as an object ID rather than a - // NodeRef - String objectId = args.get("noderef"); - if (objectId != null) - { - return new ObjectIdReference(cmisService, objectId); - } - - CMISRepositoryReference repo = createRepoReferenceFromUrl(args, templateArgs); - String id = templateArgs.get("id"); - if (id != null) - { - return new NodeIdReference(cmisService, repo, id); - } - - String path = templateArgs.get("path"); - if (path == null) - { - path = args.get("path"); - } - if (path != null) - { - return new ObjectPathReference(cmisService, repo, path); - } - - String nodepath = templateArgs.get("nodepath"); - if (nodepath == null) - { - nodepath = args.get("nodepath"); - } - if (nodepath != null) - { - return new NodePathReference(cmisService, repo, nodepath); - } - - String avmPath = templateArgs.get("avmpath"); - if (avmPath != null) - { - return new AVMPathReference(cmisService, repo, avmPath); - } - - return null; - } - - /** - * Create CMIS Relationship Reference from URL segments - * - * @param args url arguments - * @param templateArgs url template arguments - * @return Repository Reference (or null, in case of bad url) - */ - public CMISRelationshipReference createRelationshipReferenceFromUrl(Map args, Map templateArgs) - { - String assocId = templateArgs.get("assoc_id"); - if (assocId == null) - { - assocId = templateArgs.get("id"); - } - if (assocId == null) - { - assocId = args.get("noderef"); - } - if (assocId != null) - { - return new AssociationIdRelationshipReference(cmisService, assocId); - } - return null; - } - -} diff --git a/source/java/org/alfresco/repo/cmis/reference/StoreRepositoryReference.java b/source/java/org/alfresco/repo/cmis/reference/StoreRepositoryReference.java deleted file mode 100644 index c814740bb7..0000000000 --- a/source/java/org/alfresco/repo/cmis/reference/StoreRepositoryReference.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.reference; - -import org.alfresco.cmis.CMISServices; -import org.alfresco.service.cmr.repository.StoreRef; - - -/** - * Store Ref Repository Reference - * - * @author davidc - */ -public class StoreRepositoryReference extends AbstractRepositoryReference -{ - private StoreRef storeRef; - - /** - * Construct - * - * @param cmisServices - * @param storeRef - */ - public StoreRepositoryReference(CMISServices cmisServices, StoreRef storeRef) - { - super(cmisServices); - this.storeRef = storeRef; - } - - /** - * Construct - * - * @param cmisServices - * @param store accept storeType://storeId, storeType:storeId, storeId - */ - public StoreRepositoryReference(CMISServices cmisServices, String store) - { - super(cmisServices); - - if (store.indexOf(StoreRef.URI_FILLER) != -1) - { - storeRef = new StoreRef(store); - } - else if (store.indexOf(':') != -1) - { - String[] storeParts = store.split(":"); - storeRef = new StoreRef(storeParts[0], storeParts[1]); - } - else - { - storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, store); - } - } - - /* - * (non-Javadoc) - * @see org.alfresco.cmis.CMISRepositoryReference#getStoreRef() - */ - public StoreRef getStoreRef() - { - return storeRef; - } - -} diff --git a/source/java/org/alfresco/repo/cmis/rest/CMISAclMethod.java b/source/java/org/alfresco/repo/cmis/rest/CMISAclMethod.java deleted file mode 100644 index 1b081e3383..0000000000 --- a/source/java/org/alfresco/repo/cmis/rest/CMISAclMethod.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.rest; - -import java.util.List; - -import org.alfresco.cmis.CMISAccessControlService; -import org.alfresco.opencmis.CMISAccessControlFormatEnum; -import org.alfresco.repo.template.TemplateNode; -import org.alfresco.service.cmr.repository.NodeRef; - -import freemarker.ext.beans.BeanModel; -import freemarker.template.TemplateMethodModelEx; -import freemarker.template.TemplateModelException; -import freemarker.template.TemplateScalarModel; - -/** - * Custom FreeMarker Template language method. - *

- * Gets the ACL of a TemplateNode - *

- * Usage: cmisacl(TemplateNode node) - * cmisacl(TemplateNode node, String format) - * - * @author dward - */ -public class CMISAclMethod implements TemplateMethodModelEx -{ - private CMISAccessControlService accessControlService; - - /** - * Construct - */ - public CMISAclMethod(CMISAccessControlService accessControlService) - { - this.accessControlService = accessControlService; - } - - @SuppressWarnings("unchecked") - public Object exec(List args) throws TemplateModelException - { - NodeRef nodeRef = null; - CMISAccessControlFormatEnum format = CMISAccessControlFormatEnum.REPOSITORY_SPECIFIC_PERMISSIONS; - try - { - int i = 0; - // extract node ref - Object arg = args.get(i++); - if (arg instanceof BeanModel) - { - Object wrapped = ((BeanModel) arg).getWrappedObject(); - if (wrapped != null) - { - if (wrapped instanceof TemplateNode) - { - nodeRef = ((TemplateNode) wrapped).getNodeRef(); - } - } - } - // extract format if specified - arg = args.get(i++); - if (arg instanceof TemplateScalarModel) - { - format = CMISAccessControlFormatEnum.FACTORY.toEnum(((TemplateScalarModel) arg).getAsString()); - } - } - catch (IndexOutOfBoundsException e) - { - // Ignore optional arguments - } - - // query renditions - if (nodeRef != null) - { - return accessControlService.getAcl(nodeRef, format); - } - - return null; - } - -} diff --git a/source/java/org/alfresco/repo/cmis/rest/CMISAspectsMethod.java b/source/java/org/alfresco/repo/cmis/rest/CMISAspectsMethod.java deleted file mode 100644 index 918a1159c3..0000000000 --- a/source/java/org/alfresco/repo/cmis/rest/CMISAspectsMethod.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.rest; - -import java.util.Collections; -import java.util.List; - -import org.alfresco.cmis.CMISServices; -import org.alfresco.cmis.CMISTypeDefinition; -import org.alfresco.repo.template.TemplateNode; -import org.alfresco.service.cmr.repository.NodeRef; - -import freemarker.ext.beans.BeanModel; -import freemarker.template.TemplateMethodModelEx; -import freemarker.template.TemplateModelException; - -/** - * Custom FreeMarker Template language method. - *

- * Gets the type definitions of a TemplateNode's aspects - *

- * Usage: cmisaspects(TemplateNode node) - * - * @author dward - */ -public class CMISAspectsMethod implements TemplateMethodModelEx -{ - private CMISServices cmisService; - - /** - * Construct - */ - public CMISAspectsMethod(CMISServices cmisService) - { - this.cmisService = cmisService; - } - - @SuppressWarnings("unchecked") - public Object exec(List args) throws TemplateModelException - { - NodeRef nodeRef = null; - try - { - int i = 0; - // extract node ref - Object arg = args.get(i++); - if (arg instanceof BeanModel) - { - Object wrapped = ((BeanModel) arg).getWrappedObject(); - if (wrapped != null) - { - if (wrapped instanceof TemplateNode) - { - nodeRef = ((TemplateNode) wrapped).getNodeRef(); - } - } - } - } - catch (IndexOutOfBoundsException e) - { - // Ignore optional arguments - } - - // query aspects - if (nodeRef != null) - { - return cmisService.getAspects(nodeRef); - } - - return Collections. emptySet(); - } -} diff --git a/source/java/org/alfresco/repo/cmis/rest/CMISAssocsMethod.java b/source/java/org/alfresco/repo/cmis/rest/CMISAssocsMethod.java deleted file mode 100644 index d4de7a0147..0000000000 --- a/source/java/org/alfresco/repo/cmis/rest/CMISAssocsMethod.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.rest; - -import java.util.List; - -import org.alfresco.cmis.CMISRelationshipDirectionEnum; -import org.alfresco.cmis.CMISServiceException; -import org.alfresco.cmis.CMISServices; -import org.alfresco.repo.template.TemplateNode; -import org.alfresco.repo.web.scripts.RepositoryImageResolver; -import org.alfresco.service.cmr.repository.AssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.TemplateImageResolver; -import org.alfresco.service.cmr.repository.TemplateValueConverter; -import org.springframework.extensions.webscripts.WebScriptException; - -import freemarker.ext.beans.BeanModel; -import freemarker.template.TemplateMethodModelEx; -import freemarker.template.TemplateModelException; -import freemarker.template.TemplateScalarModel; - -/** - * Custom FreeMarker Template language method. - *

- * Gets the associations of a TemplateNode - *

- * Usage: cmisassocs(TemplateNode node, String direction) - * - * @author dward - */ -public class CMISAssocsMethod implements TemplateMethodModelEx -{ - private CMISServices cmisService; - private TemplateImageResolver imageResolver; - private TemplateValueConverter templateValueConverter; - - /** - * Construct - */ - public CMISAssocsMethod(CMISServices cmisService, RepositoryImageResolver imageResolver, - TemplateValueConverter templateValueConverter) - { - this.cmisService = cmisService; - this.imageResolver = imageResolver.getImageResolver(); - this.templateValueConverter = templateValueConverter; - } - - @SuppressWarnings("unchecked") - public Object exec(List args) throws TemplateModelException - { - NodeRef nodeRef = null; - CMISRelationshipDirectionEnum direction = CMISRelationshipDirectionEnum.SOURCE; - try - { - int i = 0; - // extract node ref - Object arg = args.get(i++); - if (arg instanceof BeanModel) - { - Object wrapped = ((BeanModel) arg).getWrappedObject(); - if (wrapped != null) - { - if (wrapped instanceof TemplateNode) - { - nodeRef = ((TemplateNode) wrapped).getNodeRef(); - } - } - } - // extract direction, if specified - arg = args.get(i++); - if (arg instanceof TemplateScalarModel) - { - String strDirection = ((TemplateScalarModel)arg).getAsString(); - if (strDirection.equalsIgnoreCase(("both"))) - { - direction = CMISRelationshipDirectionEnum.EITHER; - } - else - { - direction = CMISRelationshipDirectionEnum.FACTORY.fromLabel(strDirection); - } - } - } - catch (IndexOutOfBoundsException e) - { - // Ignore optional arguments - } - - // query relationships - if (nodeRef != null) - { - AssociationRef[] assocs; - try - { - assocs = cmisService.getRelationships(nodeRef, null, true, direction); - } - catch (CMISServiceException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - return templateValueConverter.convertValue(assocs, imageResolver); - } - - return null; - } - -} diff --git a/source/java/org/alfresco/repo/cmis/rest/CMISChildrenMethod.java b/source/java/org/alfresco/repo/cmis/rest/CMISChildrenMethod.java deleted file mode 100644 index 2fed6a0433..0000000000 --- a/source/java/org/alfresco/repo/cmis/rest/CMISChildrenMethod.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.rest; - -import java.util.List; - -import org.alfresco.cmis.CMISInvalidArgumentException; -import org.alfresco.cmis.CMISServices; -import org.alfresco.cmis.CMISTypesFilterEnum; -import org.alfresco.repo.template.TemplateNode; -import org.alfresco.repo.web.scripts.RepositoryImageResolver; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.TemplateImageResolver; -import org.springframework.extensions.webscripts.WebScriptException; - -import freemarker.ext.beans.BeanModel; -import freemarker.template.TemplateMethodModelEx; -import freemarker.template.TemplateModelException; -import freemarker.template.TemplateScalarModel; - -/** - * Custom FreeMarker Template language method. - *

- * Lists the (CMIS) children of a TemplateNode - *

- * Usage: cmischildren(TemplateNode node) - * cmischildren(TemplateNode node, String typesFilter) - * - * @author davidc - */ -public class CMISChildrenMethod implements TemplateMethodModelEx -{ - private CMISServices cmisService; - private ServiceRegistry serviceRegistry; - private TemplateImageResolver imageResolver; - - /** - * Construct - */ - public CMISChildrenMethod(CMISServices cmisService, ServiceRegistry serviceRegistry, RepositoryImageResolver imageResolver) - { - this.cmisService = cmisService; - this.serviceRegistry = serviceRegistry; - this.imageResolver = imageResolver.getImageResolver(); - } - - @SuppressWarnings("unchecked") - public Object exec(List args) throws TemplateModelException - { - TemplateNode[] children = null; - - if (args.size() > 0) - { - Object arg0 = args.get(0); - if (arg0 instanceof BeanModel) - { - // extract node ref - Object wrapped = ((BeanModel)arg0).getWrappedObject(); - if (wrapped != null) - { - if (wrapped instanceof TemplateNode) - { - NodeRef nodeRef = ((TemplateNode)wrapped).getNodeRef(); - CMISTypesFilterEnum typesFilter = CMISTypesFilterEnum.ANY; - if (args.size() > 1) - { - // extract types filter, if specified - Object arg1 = args.get(1); - if (arg1 instanceof TemplateScalarModel) - { - String typesFilterStr = ((TemplateScalarModel)arg1).getAsString(); - if (typesFilterStr != null && typesFilterStr.length() > 0) - { - typesFilter = (CMISTypesFilterEnum)CMISTypesFilterEnum.FACTORY.toEnum(typesFilterStr); - } - } - } - - // query children - NodeRef[] childNodeRefs; - try - { - childNodeRefs = cmisService.getChildren(nodeRef, typesFilter, null); - } - catch (CMISInvalidArgumentException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - children = new TemplateNode[childNodeRefs.length]; - for (int i = 0; i < childNodeRefs.length; i++) - { - children[i] = new TemplateNode(childNodeRefs[i], serviceRegistry, imageResolver); - } - } - } - } - } - - return children; - } - -} diff --git a/source/java/org/alfresco/repo/cmis/rest/CMISPropertyValueMethod.java b/source/java/org/alfresco/repo/cmis/rest/CMISPropertyValueMethod.java deleted file mode 100644 index 6a42040343..0000000000 --- a/source/java/org/alfresco/repo/cmis/rest/CMISPropertyValueMethod.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.rest; - -import java.util.List; - -import org.alfresco.cmis.CMISServiceException; -import org.alfresco.cmis.CMISServices; -import org.alfresco.repo.template.TemplateAssociation; -import org.alfresco.repo.template.TemplateNode; -import org.alfresco.repo.web.scripts.RepositoryImageResolver; -import org.alfresco.service.cmr.repository.TemplateImageResolver; -import org.alfresco.service.cmr.repository.TemplateValueConverter; -import org.springframework.extensions.webscripts.WebScriptException; - -import freemarker.ext.beans.BeanModel; -import freemarker.ext.beans.BeansWrapper; -import freemarker.template.TemplateBooleanModel; -import freemarker.template.TemplateMethodModelEx; -import freemarker.template.TemplateModel; -import freemarker.template.TemplateModelException; -import freemarker.template.TemplateScalarModel; - -/** - * Custom FreeMarker Template language method. - *

- * Retrieve the CMIS property value for an Alfresco node and optionally dereferences it as an objectId. - *

- * Usage: cmisproperty(TemplateNode node, String propertyName) - * cmisproperty(TemplateNode node, String propertyName, Boolean asObject) - * @author davidc - * @author dward - */ -public class CMISPropertyValueMethod implements TemplateMethodModelEx -{ - /** - * NULL value marker - */ - public static class NULL - { - }; - - public static TemplateModel IS_NULL = new BeanModel(new NULL(), BeansWrapper.getDefaultInstance()); - - private CMISServices cmisService; - private TemplateImageResolver imageResolver; - private TemplateValueConverter templateValueConverter; - - /** - * Construct - */ - public CMISPropertyValueMethod(CMISServices cmisService, RepositoryImageResolver imageResolver, - TemplateValueConverter templateValueConverter) - { - this.cmisService = cmisService; - this.imageResolver = imageResolver.getImageResolver(); - this.templateValueConverter = templateValueConverter; - } - - @SuppressWarnings("unchecked") - public Object exec(List args) throws TemplateModelException - { - Object wrapped = null; - String propertyName = null; - boolean asObject = false; - try - { - int i = 0; - - // extract object - Object arg = args.get(i++); - if (arg instanceof BeanModel) - { - wrapped = ((BeanModel) arg).getWrappedObject(); - } - - // extract property name - arg = args.get(i++); - if (arg instanceof TemplateScalarModel) - { - propertyName = ((TemplateScalarModel) arg).getAsString(); - } - - // extract asObject flag - arg = args.get(i++); - if (arg instanceof TemplateBooleanModel) - { - asObject = ((TemplateBooleanModel) arg).getAsBoolean(); - } - } - catch (IndexOutOfBoundsException e) - { - // Ignore optional arguments - } - - try - { - Object result = null; - if (wrapped != null && wrapped instanceof TemplateNode) - { - // retrieve property value from node, allowing aspect properties - result = cmisService.getProperty(((TemplateNode) wrapped).getNodeRef(), null, propertyName); - } - else if (wrapped != null && wrapped instanceof TemplateAssociation) - { - // retrieve property value from association - result = cmisService.getProperty(((TemplateAssociation) wrapped).getAssociationRef(), propertyName); - } - if (asObject && result instanceof String) - { - // convert result to an object if required - result = cmisService.getReadableObject((String) result, Object.class); - } - return result == null ? IS_NULL : templateValueConverter.convertValue(result, imageResolver); - } - catch (CMISServiceException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - - } - -} diff --git a/source/java/org/alfresco/repo/cmis/rest/CMISQueryWebScript.java b/source/java/org/alfresco/repo/cmis/rest/CMISQueryWebScript.java deleted file mode 100644 index cfbff427e5..0000000000 --- a/source/java/org/alfresco/repo/cmis/rest/CMISQueryWebScript.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.rest; - -import java.util.Map; - -import org.alfresco.cmis.CMISResultSet; -import org.springframework.extensions.webscripts.Cache; -import org.springframework.extensions.webscripts.DeclarativeWebScript; -import org.springframework.extensions.webscripts.Status; -import org.springframework.extensions.webscripts.WebScriptRequest; - - -/** - * Base Web Script Implementation that ensures query result sets are closed - */ -public class CMISQueryWebScript extends DeclarativeWebScript -{ - /* (non-Javadoc) - * @see org.springframework.extensions.webscripts.DeclarativeWebScript#executeFinallyImpl(org.springframework.extensions.webscripts.WebScriptRequest, org.springframework.extensions.webscripts.Status, org.springframework.extensions.webscripts.Cache, java.util.Map) - */ - @Override - protected void executeFinallyImpl(WebScriptRequest req, Status status, Cache cache, Map model) - { - Object object = model.get("resultset"); - if (object != null && object instanceof CMISResultSet) - { - CMISResultSet resultSet = (CMISResultSet)object; - resultSet.close(); - } - } - - -} diff --git a/source/java/org/alfresco/repo/cmis/rest/CMISRenditionsMethod.java b/source/java/org/alfresco/repo/cmis/rest/CMISRenditionsMethod.java deleted file mode 100644 index 45649bec48..0000000000 --- a/source/java/org/alfresco/repo/cmis/rest/CMISRenditionsMethod.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.rest; - -import java.util.List; -import java.util.Map; - -import org.alfresco.cmis.CMISFilterNotValidException; -import org.alfresco.cmis.CMISServices; -import org.alfresco.repo.template.TemplateNode; -import org.alfresco.repo.web.scripts.RepositoryImageResolver; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.TemplateImageResolver; -import org.alfresco.service.cmr.repository.TemplateValueConverter; -import org.springframework.extensions.webscripts.WebScriptException; - -import freemarker.ext.beans.BeanModel; -import freemarker.template.TemplateMethodModelEx; -import freemarker.template.TemplateModelException; -import freemarker.template.TemplateScalarModel; - -/** - * Custom FreeMarker Template language method. - *

- * Gets the renditions of a TemplateNode - *

- * Usage: cmisrenditions(TemplateNode node) - * cmisrenditions(TemplateNode node, String renditionFilter) - * - * @author dward - */ -public class CMISRenditionsMethod implements TemplateMethodModelEx -{ - private CMISServices cmisService; - private TemplateImageResolver imageResolver; - private TemplateValueConverter templateValueConverter; - - /** - * Construct - */ - public CMISRenditionsMethod(CMISServices cmisService, RepositoryImageResolver imageResolver, - TemplateValueConverter templateValueConverter) - { - this.cmisService = cmisService; - this.imageResolver = imageResolver.getImageResolver(); - this.templateValueConverter = templateValueConverter; - } - - @SuppressWarnings("unchecked") - public Object exec(List args) throws TemplateModelException - { - NodeRef nodeRef = null; - String renditionFilter = null; - try - { - int i = 0; - // extract node ref - Object arg = args.get(i++); - if (arg instanceof BeanModel) - { - Object wrapped = ((BeanModel) arg).getWrappedObject(); - if (wrapped != null) - { - if (wrapped instanceof TemplateNode) - { - nodeRef = ((TemplateNode) wrapped).getNodeRef(); - } - } - } - // extract rendition filter, if specified - arg = args.get(i++); - if (arg instanceof TemplateScalarModel) - { - renditionFilter = ((TemplateScalarModel) arg).getAsString(); - } - } - catch (IndexOutOfBoundsException e) - { - // Ignore optional arguments - } - - // query renditions - if (nodeRef != null) - { - Map renditions; - try - { - renditions = cmisService.getRenditions(nodeRef, renditionFilter); - } - catch (CMISFilterNotValidException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - return templateValueConverter.convertValue(renditions, imageResolver); - } - - return null; - } - -} diff --git a/source/java/org/alfresco/repo/cmis/rest/CMISResultSetMethod.java b/source/java/org/alfresco/repo/cmis/rest/CMISResultSetMethod.java deleted file mode 100644 index 36c1f79cb3..0000000000 --- a/source/java/org/alfresco/repo/cmis/rest/CMISResultSetMethod.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.rest; - -import java.util.List; - -import org.alfresco.cmis.CMISResultSet; -import org.alfresco.repo.web.scripts.RepositoryImageResolver; -import org.alfresco.repo.web.util.paging.Cursor; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.TemplateImageResolver; - -import freemarker.ext.beans.BeanModel; -import freemarker.template.TemplateMethodModelEx; -import freemarker.template.TemplateModelException; - -/** - * Custom FreeMarker Template language method. - *

- * Creates a CMIS result set that builds TemplateNode on iteration - *

- * Usage: cmisresultset(CMISResultSet resultset) - * - * @author davidc - */ -public final class CMISResultSetMethod implements TemplateMethodModelEx -{ - private ServiceRegistry serviceRegistry; - private TemplateImageResolver imageResolver; - - /** - * Construct - */ - public CMISResultSetMethod(ServiceRegistry serviceRegistry, RepositoryImageResolver imageResolver) - { - this.serviceRegistry = serviceRegistry; - this.imageResolver = imageResolver.getImageResolver(); - } - - /** - * @see freemarker.template.TemplateMethodModel#exec(java.util.List) - */ - @SuppressWarnings("unchecked") - public Object exec(List args) throws TemplateModelException - { - CMISTemplateResultSet resultSet = null; - - if (args.size() > 0) - { - Object arg0 = args.get(0); - if (arg0 instanceof BeanModel) - { - // extract cmis result set - Object wrapped = ((BeanModel)arg0).getWrappedObject(); - if (wrapped != null) - { - if (wrapped instanceof CMISResultSet) - { - Cursor cursor = null; - if (args.size() == 2) - { - Object arg1 = args.get(1); - if (arg1 instanceof BeanModel) - { - Object wrapped1 = ((BeanModel)arg1).getWrappedObject(); - if (wrapped1 != null && wrapped1 instanceof Cursor) - { - cursor = (Cursor)wrapped1; - } - } - } - resultSet = new CMISTemplateResultSet((CMISResultSet)wrapped, cursor, serviceRegistry, imageResolver); - } - } - } - } - - return resultSet; - } -} diff --git a/source/java/org/alfresco/repo/cmis/rest/CMISScript.java b/source/java/org/alfresco/repo/cmis/rest/CMISScript.java deleted file mode 100644 index de92214bde..0000000000 --- a/source/java/org/alfresco/repo/cmis/rest/CMISScript.java +++ /dev/null @@ -1,1303 +0,0 @@ -/* - * Copyright (C) 2005-2011 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 . - */ -package org.alfresco.repo.cmis.rest; - -import java.io.Serializable; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.alfresco.cmis.CMISAccessControlEntry; -import org.alfresco.cmis.CMISAccessControlService; -import org.alfresco.cmis.CMISAclCapabilityEnum; -import org.alfresco.cmis.CMISAclPropagationEnum; -import org.alfresco.cmis.CMISAclSupportedPermissionEnum; -import org.alfresco.cmis.CMISBaseObjectTypeIds; -import org.alfresco.cmis.CMISCapabilityChanges; -import org.alfresco.cmis.CMISChangeEvent; -import org.alfresco.cmis.CMISChangeLog; -import org.alfresco.cmis.CMISChangeLogService; -import org.alfresco.cmis.CMISConstraintException; -import org.alfresco.cmis.CMISDictionaryModel; -import org.alfresco.cmis.CMISDictionaryService; -import org.alfresco.cmis.CMISInvalidArgumentException; -import org.alfresco.cmis.CMISJoinEnum; -import org.alfresco.cmis.CMISObjectReference; -import org.alfresco.cmis.CMISPermissionDefinition; -import org.alfresco.cmis.CMISPermissionMapping; -import org.alfresco.cmis.CMISPropertyDefinition; -import org.alfresco.cmis.CMISQueryEnum; -import org.alfresco.cmis.CMISQueryOptions; -import org.alfresco.cmis.CMISQueryService; -import org.alfresco.cmis.CMISRelationshipDirectionEnum; -import org.alfresco.cmis.CMISRelationshipReference; -import org.alfresco.cmis.CMISRepositoryReference; -import org.alfresco.cmis.CMISResultSet; -import org.alfresco.cmis.CMISServiceException; -import org.alfresco.cmis.CMISServices; -import org.alfresco.cmis.CMISTypeDefinition; -import org.alfresco.cmis.CMISTypesFilterEnum; -import org.alfresco.cmis.CMISVersioningStateEnum; -import org.alfresco.cmis.CMISQueryOptions.CMISQueryMode; -import org.alfresco.cmis.acl.CMISAccessControlEntryImpl; -import org.alfresco.query.PagingResults; -import org.alfresco.repo.cmis.reference.ObjectIdReference; -import org.alfresco.repo.cmis.reference.ReferenceFactory; -import org.alfresco.repo.jscript.Association; -import org.alfresco.repo.jscript.BaseScopableProcessorExtension; -import org.alfresco.repo.jscript.ScriptNode; -import org.alfresco.repo.jscript.ValueConverter; -import org.alfresco.repo.web.util.paging.Cursor; -import org.alfresco.repo.web.util.paging.Page; -import org.alfresco.repo.web.util.paging.PagedResults; -import org.alfresco.repo.web.util.paging.Paging; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.model.FileInfo; -import org.alfresco.service.cmr.repository.AssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.util.Pair; -import org.mozilla.javascript.Context; -import org.mozilla.javascript.Scriptable; -import org.mozilla.javascript.ScriptableObject; -import org.springframework.extensions.webscripts.Status; -import org.springframework.extensions.webscripts.WebScriptException; - - -/** - * CMIS Javascript API. - * - * @author davidc - * @author dward - */ -public class CMISScript extends BaseScopableProcessorExtension -{ - // - // Argument Names - // - - public static final String ARG_CHILD_TYPES = "childTypes"; - public static final String ARG_CONTINUE_ON_FAILURE = "continueOnFailure"; - public static final String ARG_CHECKIN = "checkin"; - public static final String ARG_CHECKIN_COMMENT = "checkinComment"; - public static final String ARG_DEPTH = "depth"; - public static final String ARG_DIRECTION = "relationshipDirection"; - public static final String ARG_FILTER = "filter"; - public static final String ARG_FOLDER_BY_PATH = "folderByPath"; - public static final String ARG_FOLDER_ID = "folderId"; - public static final String ARG_INCLUDE_ALLOWABLE_ACTIONS = "includeAllowableActions"; - public static final String ARG_INCLUDE_PROPERTY_DEFINITIONS = "includePropertyDefinitions"; - public static final String ARG_INCLUDE_RELATIONSHIPS = "includeRelationships"; - public static final String ARG_INCLUDE_SUB_RELATIONSHIP_TYPES = "includeSubRelationshipTypes"; - public static final String ARG_LENGTH = "length"; - public static final String ARG_MAJOR = "major"; - public static final String ARG_MAJOR_VERSION = "majorVersion"; - public static final String ARG_MAX_ITEMS = "maxItems"; - public static final String ARG_OFFSET = "offset"; - public static final String ARG_QUERY_STATEMENT = "q"; - public static final String ARG_REMOVE_FROM = "removeFrom"; - public static final String ARG_RELATIONSHIP_TYPE = "typeId"; - public static final String ARG_REPOSITORY_ID = "repositoryId"; - public static final String ARG_RETURN_VERSION = "returnVersion"; - public static final String ARG_SKIP_COUNT = "skipCount"; - public static final String ARG_THIS_VERSION = "thisVersion"; - public static final String ARG_TYPE_ID = "typeId"; - public static final String ARG_TYPES = "types"; - public static final String ARG_UNFILE_OBJECTS = "unfileObjects"; - public static final String ARG_VERSIONING_STATE = "versioningState"; - public static final String ARG_SOURCE_FOLDER_ID = "sourceFolderId"; - public static final String ARG_INCLUDE_ACL = "includeACL"; - public static final String ARG_RENDITION_FILTER = "renditionFilter"; - public static final String ARG_CHANGE_LOG_TOKEN = "changeLogToken"; - public static final String ARG_ORDER_BY = "orderBy"; - - // service dependencies - private ServiceRegistry services; - private CMISServices cmisService; - private CMISDictionaryService cmisDictionaryService; - private CMISQueryService cmisQueryService; - private CMISAccessControlService cmisAccessControlService; - private CMISChangeLogService cmisChangeLogService; - private Paging paging; - private ReferenceFactory referenceFactory; - private ValueConverter valueConverter = new ValueConverter(); - - - /** - * Set the service registry - * - * @param services the service registry - */ - public void setServiceRegistry(ServiceRegistry services) - { - this.services = services; - } - - /** - * Set the paging helper. - * - * @param paging - * the paging helper - */ - public void setPaging(Paging paging) - { - this.paging = paging; - } - - /** - * Set the CMIS Service. - * - * @param cmisService - * the cmis service - */ - public void setCMISService(CMISServices cmisService) - { - this.cmisService = cmisService; - } - - /** - * Set the CMIS Dictionary Service. - * - * @param cmisDictionaryService - * the cmis dictionary service - */ - public void setCMISDictionaryService(CMISDictionaryService cmisDictionaryService) - { - this.cmisDictionaryService = cmisDictionaryService; - } - - /** - * Set the CMIS Query Service. - * - * @param cmisQueryService - * the cmis query service - */ - public void setCMISQueryService(CMISQueryService cmisQueryService) - { - this.cmisQueryService = cmisQueryService; - } - - /** - * Sets the CMIS access control service. - * - * @param cmisAccessControlService - * the access control service - */ - public void setCMISAccessControlService(CMISAccessControlService cmisAccessControlService) - { - this.cmisAccessControlService = cmisAccessControlService; - } - - /** - * Sets the CMIS change log service. - * - * @param cmisChangeLogService - * the change log service - */ - public void setCMISChangeLogService(CMISChangeLogService cmisChangeLogService) { - this.cmisChangeLogService = cmisChangeLogService; - } - - /** - * Set the CMIS Reference Factory. - * - * @param referenceFactory - * the reference factory - */ - public void setCMISReferenceFactory(ReferenceFactory referenceFactory) - { - this.referenceFactory = referenceFactory; - } - - /** - * Gets the supported CMIS Version - * - * @return CMIS version - */ - public String getVersion() - { - return cmisService.getCMISVersion(); - } - - /** - * Gets the supported CMIS Specification Title - * - * @return CMIS Specification Title - */ - public String getSpecTitle() - { - return cmisService.getCMISSpecTitle(); - } - - /** - * Gets the default root folder path - * - * @return default root folder path - */ - public String getDefaultRootFolderPath() - { - return cmisService.getDefaultRootPath(); - } - - /** - * Gets the default root folder - * - * @return default root folder - */ - public ScriptNode getDefaultRootFolder() - { - return new ScriptNode(cmisService.getDefaultRootNodeRef(), services, getScope()); - } - - /** - * Gets the default Types filter - * - * @return default types filter - */ - public String getDefaultTypesFilter() - { - return CMISTypesFilterEnum.FACTORY.getDefaultLabel(); - } - - /** - * Is specified Types filter valid? - * - * @param typesFilter types filter - * @return true => valid - */ - public boolean isValidTypesFilter(String typesFilter) - { - return CMISTypesFilterEnum.FACTORY.validLabel(typesFilter); - } - - /** - * Resolve to a Types Filter - * - * NOTE: If specified types filter is not specified or invalid, the default types - * filter is returned - * - * @param typesFilter types filter - * @return resolved types filter - */ - private CMISTypesFilterEnum resolveTypesFilter(String typesFilter) - { - return (CMISTypesFilterEnum)CMISTypesFilterEnum.FACTORY.toEnum(typesFilter); - } - - /** - * Create CMIS Repository Reference from URL segments - * - * @param args url arguments - * @param templateArgs url template arguments - * @return Repository Reference (or null, in case of bad url) - */ - public CMISRepositoryReference createRepoReferenceFromUrl(Map args, Map templateArgs) - { - return referenceFactory.createRepoReferenceFromUrl(args, templateArgs); - } - - /** - * Create CMIS Object Reference from URL segments - * - * @param args url arguments - * @param templateArgs url template arguments - * @return Repository Reference (or null, in case of bad url) - */ - public CMISObjectReference createObjectReferenceFromUrl(Map args, Map templateArgs) - { - return referenceFactory.createObjectReferenceFromUrl(args, templateArgs); - } - - /** - * Create CMIS Relationship Reference from URL segments - * - * @param args url arguments - * @param templateArgs url template arguments - * @return Repository Reference (or null, in case of bad url) - */ - public CMISRelationshipReference createRelationshipReferenceFromUrl(Map args, Map templateArgs) - { - return referenceFactory.createRelationshipReferenceFromUrl(args, templateArgs); - } - - /** - * Create Object Reference - * - * @param repo repository reference - * @param object id object id (NodeRef.toString() format) - * @return object id reference - */ - public CMISObjectReference createObjectIdReference(String objectId) - { - return new ObjectIdReference(cmisService, objectId); - } - - /** - * Get Node from Object Reference - * - * @param ref object reference - * @return node - */ - public ScriptNode getNode(CMISObjectReference ref) - { - NodeRef nodeRef = ref.getNodeRef(); - if (nodeRef == null) - { - return null; - } - return new ScriptNode(nodeRef, services, getScope()); - } - - /** - * Get Association from Relationship Reference - * - * @param ref relationship reference - * @return association - */ - public Association getAssociation(CMISRelationshipReference ref) - { - AssociationRef assocRef = ref.getAssocRef(); - if (assocRef == null) - { - return null; - } - return new Association(services, assocRef); - } - - /** - * Query for node children - * - * @param parent - * node to query children for - * @param typesFilter - * types filter - * @param orderBy - * comma-separated list of query names and the ascending modifier "ASC" or the descending modifier "DESC" - * for each query name - * @param page - * page to query for - * @return paged result set of children - */ - public PagedResults queryChildren(ScriptNode parent, String typesFilter, String orderBy, Page page) - { - try - { - CMISTypesFilterEnum filter = resolveTypesFilter(typesFilter); - - int maxItems = page.getSize(); - int skipCount = (page.getNumber() - (page.isZeroBasedIdx() ? 0 : 1)) * maxItems; - - PagingResults pageOfNodeInfos = cmisService.getChildren(parent.getNodeRef(), filter, BigInteger.valueOf(maxItems), BigInteger.valueOf(skipCount), orderBy); - - int pageCnt = pageOfNodeInfos.getPage().size(); - NodeRef[] children = new NodeRef[pageCnt]; - - int idx = 0; - for (FileInfo child : pageOfNodeInfos.getPage()) - { - children[idx] = child.getNodeRef(); - idx++; - } - - // total count ? - int totalCount = pageCnt; - Pair totalCounts = pageOfNodeInfos.getTotalResultCount(); - if (totalCounts != null) - { - Integer totalCountLower = totalCounts.getFirst(); - Integer totalCountUpper = totalCounts.getSecond(); - if ((totalCountLower != null) && (totalCountLower.equals(totalCountUpper))) - { - totalCount = totalCountLower; - } - } - - Cursor cursor = paging.createCursor(totalCount, page); - - ScriptNode[] nodes = new ScriptNode[pageCnt]; - for (int i = 0; i < pageCnt; i++) - { - nodes[i] = new ScriptNode(children[i], services, getScope()); - } - - PagedResults results = paging.createPagedResults(nodes, cursor); - return results; - } - catch (CMISInvalidArgumentException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - } - - /** - * Query for node relationships - * - * @param node - * @param relDef - * @param includeSubTypes - * @param direction - * @param page - * @return - */ - public PagedResults queryRelationships(ScriptNode node, CMISTypeDefinition relDef, boolean includeSubTypes, CMISRelationshipDirectionEnum direction, Page page) - { - AssociationRef[] relationships; - try - { - relationships = cmisService.getRelationships(node.getNodeRef(), relDef, includeSubTypes, direction); - } - catch (CMISInvalidArgumentException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - - Cursor cursor = paging.createCursor(relationships.length, page); - Association[] assocs = new Association[cursor.getRowCount()]; - for (int i = cursor.getStartRow(); i <= cursor.getEndRow(); i++) - { - assocs[i - cursor.getStartRow()] = new Association(services, relationships[i], getScope()); - } - - PagedResults results = paging.createPagedResults(assocs, cursor); - return results; - } - - /** - * Query for items checked-out to user within folder (and possibly descendants) - * - * @param username user - * @param folder folder - * @param includeDescendants true = include descendants - * @param page - * @return paged result set of checked-out items - */ - public PagedResults queryCheckedOut(String username, ScriptNode folder, boolean includeDescendants, Page page) - { - NodeRef[] checkedout; - try - { - checkedout = cmisService.getCheckedOut(username, (folder == null) ? null : folder.getNodeRef(), includeDescendants, null); - } - catch (CMISInvalidArgumentException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - Cursor cursor = paging.createCursor(checkedout.length, page); - ScriptNode[] nodes = new ScriptNode[cursor.getRowCount()]; - for (int i = cursor.getStartRow(); i <= cursor.getEndRow(); i++) - { - nodes[i - cursor.getStartRow()] = new ScriptNode(checkedout[i], services, getScope()); - } - - PagedResults results = paging.createPagedResults(nodes, cursor); - return results; - } - - /** - * Query for child types (of a given type), or the base types (if no type given). - * - * @param typeDef - * the type def - * @param page - * the page - * @return the paged results - */ - public PagedResults queryTypeChildren(CMISTypeDefinition typeDef, Page page) - { - Collection children = (typeDef == null) ? cmisService.getBaseTypes() : typeDef - .getSubTypes(false); - Cursor cursor = paging.createCursor(children.size(), page); - - // skip - Iterator iterTypeDefs = children.iterator(); - for (int i = 0; i < cursor.getStartRow(); i++) - { - iterTypeDefs.next(); - } - - // get types for page - CMISTypeDefinition[] types = new CMISTypeDefinition[cursor.getRowCount()]; - for (int i = cursor.getStartRow(); i <= cursor.getEndRow(); i++) - { - types[i - cursor.getStartRow()] = iterTypeDefs.next(); - } - - PagedResults results = paging.createPagedResults(types, cursor); - return results; - } - - /** - * Query for a Type Definition given a CMIS Type Id. - * - * @param typeId - * the type id - * @return CMIS Type Definition - */ - public CMISTypeDefinition queryType(String typeId) - { - try - { - return cmisService.getTypeDefinition(typeId); - } - catch (CMISInvalidArgumentException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - } - - /** - * Query the Type Definition for the given Node. - * - * @param node - * the node - * @return CMIS Type Definition - */ - public CMISTypeDefinition queryType(ScriptNode node) - { - try - { - return cmisService.getTypeDefinition(node.getNodeRef()); - } - catch (CMISInvalidArgumentException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - } - - /** - * Query the Property Definition for the given Property. - * - * @param propertyName - * the property name - * @return the CMIS property definition - */ - public CMISPropertyDefinition queryProperty(String propertyName) - { - return cmisDictionaryService.findProperty(propertyName, null); - } - - /** - * Sets the aspects on a node (Alfresco extension). - * - * @param node - * the node - * @param aspectsToRemove - * the aspects to remove - * @param aspectsToAdd - * the aspects to add - * @throws WebScriptException - * if an argument is invalid - */ - public void setAspects(ScriptNode node, Iterable aspectsToRemove, Iterable aspectsToAdd) - { - try - { - cmisService.setAspects(node.getNodeRef(), aspectsToRemove, aspectsToAdd); - } - catch (CMISInvalidArgumentException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - } - - // - // SQL Query - // - - /** - * Can you query the private working copy of a document. - * - * @return is the PWC searchable? - */ - public boolean getPwcSearchable() - { - return cmisQueryService.getPwcSearchable(); - } - - /** - * Can you query non-latest versions of a document. - * - * The current latest version is always searchable according to the type definition. - * - * @return - */ - public boolean getAllVersionsSearchable() - { - return cmisQueryService.getAllVersionsSearchable(); - } - - /** - * Get the query support level. - * - * @return the query support level - */ - public CMISQueryEnum getQuerySupport() - { - return cmisQueryService.getQuerySupport(); - } - - /** - * Get the join support level in queries. - * - * @return the join support level - */ - public CMISJoinEnum getJoinSupport() - { - return cmisQueryService.getJoinSupport(); - } - - /** - * Issue query. - * - * @param statement - * query statement - * @param page - * the page - * @return paged result set - */ - public PagedResults query(String statement, Page page) - { - Cursor unknownRows = paging.createCursor(Integer.MAX_VALUE, page); - CMISQueryOptions options = new CMISQueryOptions(statement, cmisService.getDefaultRootStoreRef()); - options.setQueryMode(CMISQueryMode.CMS_WITH_ALFRESCO_EXTENSIONS); - options.setSkipCount(unknownRows.getStartRow()); - CMISResultSet resultSet = cmisQueryService.query(options); - Cursor cursor = paging.createCursor(unknownRows.getStartRow() + resultSet.getLength(), page); - return paging.createPagedResult(resultSet, cursor); - } - - /** - * Gets the ACL capability. - * - * @return the ACL capability - */ - public CMISAclCapabilityEnum getAclCapability() - { - return cmisAccessControlService.getAclCapability(); - } - - /** - * Gets the supported permission types. - * - * @return the supported permission types - */ - public CMISAclSupportedPermissionEnum getAclSupportedPermissions() - { - return cmisAccessControlService.getSupportedPermissions(); - } - - /** - * Gets the ACL propagation. - * - * @return the ACL propagation - */ - public CMISAclPropagationEnum getAclPropagation() - { - return cmisAccessControlService.getAclPropagation(); - } - - /** - * Get all the permissions defined by the repository. - * - * @return a list of permissions - */ - public List getRepositoryPermissions() - { - return cmisAccessControlService.getRepositoryPermissions(); - } - - - /** - * Get the list of permission mappings. - * - * @return get the permission mapping as defined by the CMIS specification. - */ - public List getPermissionMappings() - { - return cmisAccessControlService.getPermissionMappings(); - } - - /** - * Gets the name of the principal who is used for anonymous access. This principal can then be passed to the ACL - * services to specify what permissions anonymous users should have. - * - * @return name of the principal who is used for anonymous access - */ - public String getPrincipalAnonymous() - { - return cmisAccessControlService.getPrincipalAnonymous(); - } - - /** - * Gets the name of the principal who is used to indicate any authenticated user. This principal can then be passed - * to the ACL services to specify what permissions any authenticated user should have. - * - * @return name of the principal who is used to indicate any authenticated user - */ - public String getPrincipalAnyone() - { - return cmisAccessControlService.getPrincipalAnyone(); - } - - /** - * Applies an ACL to a node. - * - * @param node - * the node - * @param principalIds - * the principal IDs - * @param permissions - * the permissions for each principal ID - */ - @SuppressWarnings("unchecked") - public void applyACL(ScriptNode node, Serializable principalIds, Serializable permissions) - { - List principalList = (List) valueConverter.convertValueForRepo(principalIds); - List permissionList = (List) valueConverter.convertValueForRepo(permissions); - List acesToApply = new ArrayList(principalList.size()); - for(int i=0; i typeList = cmisChangeLogService.getChangesOnTypeCapability(); - String[] changesOnType = new String[typeList.size()]; - int i=0; - for (CMISBaseObjectTypeIds type: typeList) - { - changesOnType[i++] = type.getLabel(); - } - return changesOnType; - } - - /** - * Determines whether the repository's change log can return all changes ever made to any object in the repository - * or only changes made after a particular point in time. - * - * @return false if the change log can return all changes ever made to every object.true - * if the change log includes all changes made since a particular point in time, but not all changes ever - * made. - */ - public boolean getChangesIncomplete() - { - return cmisChangeLogService.getChangesIncomplete(); - } - - /** - * Gets the change log attributes. - * - * @param changeLogToken - * the change log token - * @param maxItems - * the maximum number of events to include to return or null - * @return the change log attributes - */ - public Scriptable getChangeLog(String changeLogToken, Integer maxItems) - { - Scriptable scope = getScope(); - Context cx = Context.enter(); - try - { - Scriptable changeLogMap = cx.newObject(scope); - CMISChangeLog changeLog = cmisChangeLogService.getChangeLogEvents(changeLogToken, maxItems); - List changeEvents = changeLog.getChangeEvents(); - - // Wrap the events - int size = changeEvents.size(); - Scriptable changeEventArr = cx.newArray(scope, size); - for (int i = 0; i < size; i++) - { - ScriptableObject.putProperty(changeEventArr, i, Context.javaToJS(changeEvents.get(i), scope)); - } - ScriptableObject.putProperty(changeLogMap, "changeEvents", changeEventArr); - - // Wrap the nodes - Scriptable changeNodes = cx.newArray(scope, size); - for (int i = 0; i < size; i++) - { - ScriptableObject.putProperty(changeNodes, i, new ScriptNode(changeEvents.get(i).getChangedNode(), services, - scope)); - } - ScriptableObject.putProperty(changeLogMap, "changeNodes", changeNodes); - - // Provide the other attributes - ScriptableObject.putProperty(changeLogMap, "hasMoreItems", Context - .javaToJS(changeLog.hasMoreItems(), scope)); - ScriptableObject - .putProperty(changeLogMap, "eventCount", Context.javaToJS(changeLog.getEventCount(), scope)); - - // Handle paging parameters - String nextChangeToken = changeLog.getNextChangeToken(); - if (nextChangeToken != null) - { - ScriptableObject.putProperty(changeLogMap, "nextChangeToken", Context.javaToJS(nextChangeToken, scope)); - } - String previousPageChangeLogToken = cmisChangeLogService.getPreviousPageChangeLogToken(changeLogToken, - maxItems); - if (previousPageChangeLogToken != null) - { - ScriptableObject.putProperty(changeLogMap, "previousPageToken", Context.javaToJS( - previousPageChangeLogToken, scope)); - } - String lastPageChangeLogToken = cmisChangeLogService.getLastPageChangeLogToken(changeLogToken, maxItems); - if (lastPageChangeLogToken != null) - { - ScriptableObject.putProperty(changeLogMap, "lastPageToken", Context.javaToJS(lastPageChangeLogToken, - scope)); - } - return changeLogMap; - } - catch (CMISInvalidArgumentException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - finally - { - Context.exit(); - } - } - - /** - * Applies a versioning state to a new node, potentially resulting in a new node. - * - * @param source - * the source - * @param versioningState - * the versioning state - * @return the node to write changes to - * @throws CMISConstraintException - */ - public ScriptNode applyVersioningState(ScriptNode source, String versioningState) - { - CMISVersioningStateEnum versioningStateEnum = CMISVersioningStateEnum.FACTORY.fromLabel(versioningState); - try - { - return new ScriptNode(cmisService.applyVersioningState(source.getNodeRef(), versioningStateEnum), services, - getScope()); - } - catch (CMISServiceException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - } - - /** - * Checks out an object by ID. - * - * @param objectId - * the object id - * @return the private working copy node - */ - public ScriptNode checkOut(String objectId) - { - try - { - return new ScriptNode(cmisService.checkOut(objectId), services, getScope()); - } - catch (CMISServiceException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - } - - /** - * Checks in a given private working copy node. - * - * @param source - * the node - * @param checkinComment - * the checkin comment - * @param isMajor - * is this a major version? - * @return the checked-in node - */ - public ScriptNode checkIn(ScriptNode source, String checkinComment, boolean isMajor) - { - try - { - return new ScriptNode(cmisService.checkIn((String) cmisService.getProperty(source.getNodeRef(), CMISDictionaryModel.PROP_OBJECT_ID), checkinComment, isMajor), services, - getScope()); - } - catch (CMISServiceException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - } - - /** - * Cancels a check out. - * - * @param source - * the private working copy - */ - public void cancelCheckOut(ScriptNode source) - { - try - { - cmisService.cancelCheckOut((String) cmisService.getProperty(source.getNodeRef(), - CMISDictionaryModel.PROP_OBJECT_ID)); - } - catch (CMISServiceException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - } - - /** - * Gets all the versions of a node. - * - * @param source - * the node - * @return a Javascript array of all the versions - */ - public Scriptable getAllVersions(ScriptNode source) - { - Scriptable scope = getScope(); - Context cx = Context.enter(); - try - { - List allVersions = cmisService.getAllVersions((String) cmisService.getProperty( - source.getNodeRef(), CMISDictionaryModel.PROP_OBJECT_ID)); - // Wrap the version - int size = allVersions.size(); - Scriptable allVersionsArr = cx.newArray(scope, size); - for (int i = 0; i < size; i++) - { - ScriptableObject.putProperty(allVersionsArr, i, new ScriptNode(allVersions.get(i), services, scope)); - } - return allVersionsArr; - } - catch (CMISServiceException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - finally - { - Context.exit(); - } - } - - /** - * Gets the required version of a node - * - * @param source - * the node - * @param returnVersion - * value indicating version required - * @return the version - */ - public ScriptNode getReturnVersion(ScriptNode source, String returnVersion) - { - if (returnVersion == null || returnVersion.equals("this")) - { - return source; - } - try - { - return new ScriptNode(cmisService.getLatestVersion((String) cmisService.getProperty(source.getNodeRef(), - CMISDictionaryModel.PROP_OBJECT_ID), returnVersion.equals("latestmajor")), services, getScope()); - } - catch (CMISServiceException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - } - - /** - * Attempts to delete a folder and all of its children, recording the status in the given status object. - * - * @param source - * the folder node - * @param status - * the status - * @param continueOnFailure - * should we continue if an error occurs with one of the children? - * @param unfile - * should we remove non-primary associations to nodes rather than delete them? - * @param deleteAllVersions - * should we delete all the versions of the nodes we delete? - */ - public void deleteTree(ScriptNode source, Status status, boolean continueOnFailure, boolean unfile, - boolean deleteAllVersions) - { - // Let's avoid all deletions getting rolled back by catching the exception and setting the status ourselves - try - { - cmisService.deleteTreeReportLastError((String) cmisService.getProperty(source.getNodeRef(), - CMISDictionaryModel.PROP_OBJECT_ID), continueOnFailure, unfile, deleteAllVersions); - // Success, but no response content - status.setCode(Status.STATUS_NO_CONTENT); - status.setRedirect(true); - } - catch (CMISServiceException e) - { - status.setCode(e.getStatusCode()); - status.setMessage(e.getMessage()); - status.setRedirect(true); - } - } - - /** - * Deletes a node's content stream. - * - * @param source - * the node - */ - public void deleteContentStream(ScriptNode source) - { - try - { - cmisService.deleteContentStream((String) cmisService.getProperty(source.getNodeRef(), - CMISDictionaryModel.PROP_OBJECT_ID)); - } - catch (CMISServiceException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - } - - /** - * Deletes a node. - * - * @param source - * the node - * @param allVersions - * should we delete all the versions of the node? - */ - public void deleteObject(ScriptNode source, boolean allVersions) - { - try - { - cmisService.deleteObject((String) cmisService.getProperty(source.getNodeRef(), - CMISDictionaryModel.PROP_OBJECT_ID), allVersions); - } - catch (CMISServiceException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - } - - /** - * Deletes an association. - * - * @param assoc - * the association - */ - public void deleteObject(Association assoc) - { - try - { - cmisService.deleteObject((String) cmisService.getProperty(assoc.getAssociationRef(), - CMISDictionaryModel.PROP_OBJECT_ID), true); - } - catch (CMISServiceException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - } - - /** - * Adds an object to a folder. - * - * @param child - * the object to add - * @param parent - * the folder - */ - public void addObjectToFolder(ScriptNode child, ScriptNode parent) - { - try - { - cmisService.addObjectToFolder((String) cmisService.getProperty(child.getNodeRef(), - CMISDictionaryModel.PROP_OBJECT_ID), (String) cmisService.getProperty(parent.getNodeRef(), - CMISDictionaryModel.PROP_OBJECT_ID)); - } - catch (CMISServiceException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - } - - /** - * Moves an object from a source folder to a target folder. - * - * @param child - * the object to move - * @param targetFolder - * the target folder - * @param sourceFolderId - * the source folder object ID - */ - public void moveObject(ScriptNode child, ScriptNode targetFolder, String sourceFolderId) - { - try - { - cmisService.moveObject((String) cmisService.getProperty(child.getNodeRef(), - CMISDictionaryModel.PROP_OBJECT_ID), (String) cmisService.getProperty(targetFolder.getNodeRef(), - CMISDictionaryModel.PROP_OBJECT_ID), sourceFolderId); - } - catch (CMISServiceException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - } - - /** - * Creates a policy object of the specified type, and optionally adds the policy to a folder. Currently no policy - * types can be created in Alfresco. - * - * @param typeId - * the policy type - * @param parent - * parent folder for this new policy - * @return the created policy object - * @throws WebScriptException on error - */ - public ScriptNode createPolicy(String typeId, ScriptNode parent) - { - try - { - cmisService.createPolicy(Collections. singletonMap( - CMISDictionaryModel.PROP_OBJECT_TYPE_ID, typeId), (String) cmisService.getProperty(parent - .getNodeRef(), CMISDictionaryModel.PROP_OBJECT_ID), Collections. emptyList()); - return null; - } - catch (CMISServiceException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - } - - /** - * Applies a policy object to a target object. - * - * @param policyId - * policy Id - * @param target - * target node - * @throws WebScriptException on error - */ - public void applyPolicy(String policyId, ScriptNode target) - { - try - { - cmisService.applyPolicy(policyId, (String) cmisService.getProperty(target.getNodeRef(), - CMISDictionaryModel.PROP_OBJECT_ID)); - } - catch (CMISServiceException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - } - - /** - * Gets the list of policy objects currently applied to a target object. - * - * @param source - * source node - * @param filter - * property filter - * @throws WebScriptException on error - */ - public PagedResults getAppliedPolicies(ScriptNode source, String filter, Page page) - { - List policies; - try - { - policies = cmisService.getAppliedPolicies((String) cmisService.getProperty(source.getNodeRef(), - CMISDictionaryModel.PROP_OBJECT_ID), filter); - } - catch (CMISServiceException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - Cursor cursor = paging.createCursor(policies.size(), page); - Object[] policyArr = new Object[cursor.getRowCount()]; - for (int i = cursor.getStartRow(); i <= cursor.getEndRow(); i++) - { - policyArr[i - cursor.getStartRow()] = Context.javaToJS(policies.get(i), getScope()); - } - - PagedResults results = paging.createPagedResults(policyArr, cursor); - return results; - } - - /** - * Removes a previously applied policy from a target object. The policy object is not deleted, and may still be - * applied to other objects. - * - * @param policyId - * policy Id - * @param objectId - * target object Id. - * @throws WebScriptException - * on error - */ - public void removePolicy(String policyId, String objectId) - { - try - { - cmisService.removePolicy(policyId, objectId); - } - catch (CMISServiceException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - } -} diff --git a/source/java/org/alfresco/repo/cmis/rest/CMISTemplateResultSet.java b/source/java/org/alfresco/repo/cmis/rest/CMISTemplateResultSet.java deleted file mode 100644 index 1dbba79754..0000000000 --- a/source/java/org/alfresco/repo/cmis/rest/CMISTemplateResultSet.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.rest; - -import java.io.Serializable; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.NoSuchElementException; - -import org.alfresco.cmis.CMISPropertyDefinition; -import org.alfresco.cmis.CMISResultSet; -import org.alfresco.cmis.CMISResultSetColumn; -import org.alfresco.cmis.CMISResultSetMetaData; -import org.alfresco.cmis.CMISResultSetRow; -import org.alfresco.repo.template.TemplateNode; -import org.alfresco.repo.web.util.paging.Cursor; -import org.alfresco.service.ServiceRegistry; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.TemplateImageResolver; - -import freemarker.core.Environment; -import freemarker.template.SimpleCollection; -import freemarker.template.TemplateCollectionModel; -import freemarker.template.TemplateModelException; - - -/** - * CMIS Result Set for use in Freemarker - * - * @author davidc - */ -public class CMISTemplateResultSet implements Serializable -{ - private static final long serialVersionUID = 2245418238171563934L; - - private CMISResultSet resultSet; - private Cursor cursor; - private ServiceRegistry serviceRegistry; - private TemplateImageResolver imageResolver; - - /** - * Construct - * - * @param resultSet - * @param serviceRegistry - * @param imageResolver - */ - public CMISTemplateResultSet(CMISResultSet resultSet, Cursor cursor, ServiceRegistry serviceRegistry, TemplateImageResolver imageResolver) - { - this.resultSet = resultSet; - this.cursor = cursor; - this.serviceRegistry = serviceRegistry; - this.imageResolver = imageResolver; - } - - /** - * @return result set meta-data - */ - public CMISResultSetMetaData getMetaData() - { - return resultSet.getMetaData(); - } - - /** - * @return result set length - */ - public int getLength() - { - return resultSet.getLength(); - } - - /** - * @return start index within full result set - */ - public int getStart() - { - return resultSet.getStart(); - } - - /** - * @return selectors - */ - public String[] getSelectors() - { - return resultSet.getMetaData().getSelectorNames(); - } - - /** - * @return result set rows - * @throws TemplateModelException - */ - public TemplateCollectionModel getRows() - throws TemplateModelException - { - return new SimpleCollection(new TemplateIterator(resultSet.iterator()), Environment.getCurrentEnvironment().getObjectWrapper()); - } - - - /** - * Result Set Iterator - * - * @author davidc - */ - public class TemplateIterator implements Iterator - { - private Iterator iter; - private int idx = 0; - - /** - * Construct - * - * @param iter - */ - public TemplateIterator(Iterator iter) - { - this.iter = iter; - } - - /* (non-Javadoc) - * @see java.util.Iterator#hasNext() - */ - public boolean hasNext() - { - return (cursor == null || idx < cursor.getRowCount()) && iter.hasNext(); - } - - /* (non-Javadoc) - * @see java.util.Iterator#next() - */ - public TemplateRow next() - { - if (!hasNext()) - { - throw new NoSuchElementException(); - } - try - { - return new TemplateRow(iter.next()); - } - finally - { - idx++; - } - } - - /* (non-Javadoc) - * @see java.util.Iterator#remove() - */ - public void remove() - { - iter.remove(); - } - - - /** - * Template Row - */ - public class TemplateRow - { - private CMISResultSetRow row; - private Map nodes = null; - - /** - * Construct - * - * @param row - */ - public TemplateRow(CMISResultSetRow row) - { - this.row = row; - } - - /** - * @return a map of serializable column values with the column name as the key - */ - public Map getValues() - { - return row.getValues(); - } - - /** - * @return nodes associated with row - */ - public Collection getNodes() - { - Map nodes = buildNodes(); - return nodes.size() == 0 ? null : nodes.values(); - } - - /** - * @return node (if there is only a single node associated with the row), otherwise null - */ - public TemplateNode getNode() - { - try - { - NodeRef nodeRef = row.getNodeRef(); - return new TemplateNode(nodeRef, serviceRegistry, imageResolver); - } - catch(UnsupportedOperationException e) {} - return null; - } - - /** - * Builds a map of Template Nodes for the nodes associated with this row - * - * @return templates nodes indexed by selector - */ - private Map buildNodes() - { - if (nodes == null) - { - Map nodeRefs = row.getNodeRefs(); - if (nodeRefs == null || nodeRefs.size() == 0) - { - nodes = Collections.emptyMap(); - } - else - { - HashMap templateNodes = new HashMap(); - for (Map.Entry entry : nodeRefs.entrySet()) - { - templateNodes.put(entry.getKey(), new TemplateNode(entry.getValue(), serviceRegistry, imageResolver)); - } - nodes = templateNodes; - } - } - return nodes; - } - - /** - * Gets column type for specified column name - * - * @param colName column name - * @return column type - */ - public String getColumnType(String colName) - { - CMISResultSetColumn col = resultSet.getMetaData().getColumn(colName); - return col == null ? null : col.getCMISDataType().getLabel(); - } - - /** - * Gets property definition for specified column name - * - * @param colName column name - * @return property definition (or null, if not applicable) - */ - public CMISPropertyDefinition getPropertyDefinition(String colName) - { - CMISResultSetColumn col = resultSet.getMetaData().getColumn(colName); - return col == null ? null : col.getCMISPropertyDefinition(); - } - - /** - * Gets node for specified selector - * - * @param selector - * @return template node - */ - public TemplateNode getSelectorNode(String selector) - { - return nodes.get(selector); - } - - /** - * @return overall score - */ - public float getScore() - { - return row.getScore(); - } - - /** - * @return a map of selector name to score - */ - public Float getSelectorScore(String selector) - { - return row.getScore(selector); - } - - /** - * NOTE: If you want the overall position in paged results you have to add the skipCount for the result set - * - * @return row index - */ - public int getIndex() - { - return row.getIndex(); - } - } - } -} diff --git a/source/java/org/alfresco/repo/cmis/rest/CMISTypeDefinitionMethod.java b/source/java/org/alfresco/repo/cmis/rest/CMISTypeDefinitionMethod.java deleted file mode 100644 index 83979673d2..0000000000 --- a/source/java/org/alfresco/repo/cmis/rest/CMISTypeDefinitionMethod.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.rest; - -import java.util.List; - -import org.alfresco.cmis.CMISDictionaryService; -import org.alfresco.cmis.CMISScope; -import org.alfresco.cmis.CMISTypeDefinition; -import org.alfresco.repo.template.TemplateAssociation; -import org.alfresco.repo.template.TemplateNode; -import org.alfresco.service.namespace.QName; - -import freemarker.ext.beans.BeanModel; -import freemarker.template.TemplateMethodModelEx; -import freemarker.template.TemplateModelException; - -/** - * Custom FreeMarker Template language method. - *

- * Retrieve the CMIS Type Definition for an Alfresco node - *

- * Usage: cmistype(TemplateNode node) - * cmistype(QName nodeType) - * - * @author davidc - */ -public class CMISTypeDefinitionMethod implements TemplateMethodModelEx -{ - private static CMISScope[] EMPTY_SCOPES = new CMISScope[] {}; - private CMISDictionaryService dictionaryService; - - - /** - * Construct - */ - public CMISTypeDefinitionMethod(CMISDictionaryService dictionaryService) - { - this.dictionaryService = dictionaryService; - } - - /** - * @see freemarker.template.TemplateMethodModel#exec(java.util.List) - */ - @SuppressWarnings("unchecked") - public Object exec(List args) throws TemplateModelException - { - CMISTypeDefinition result = null; - - if (args.size() == 1) - { - Object arg0 = args.get(0); - if (arg0 instanceof BeanModel) - { - // extract node type qname - CMISScope[] matchingScopes = EMPTY_SCOPES; - QName nodeType = null; - Object wrapped = ((BeanModel)arg0).getWrappedObject(); - if (wrapped != null) - { - if (wrapped instanceof TemplateNode) - { - nodeType = ((TemplateNode)wrapped).getType(); - } - else if (wrapped instanceof TemplateAssociation) - { - nodeType = ((TemplateAssociation)wrapped).getTypeQName(); - matchingScopes = new CMISScope[] { CMISScope.RELATIONSHIP }; - } - else if (wrapped instanceof QName) - { - nodeType = (QName)wrapped; - } - else if (wrapped instanceof CMISTypeDefinition) - { - result = ((CMISTypeDefinition)wrapped).getBaseType(); - } - } - - // convert to CMIS type - if (nodeType != null) - { - result = dictionaryService.findTypeForClass(nodeType, matchingScopes); - } - } - } - - return result; - } -} diff --git a/source/java/org/alfresco/repo/cmis/ws/DMAbstractServicePort.java b/source/java/org/alfresco/repo/cmis/ws/DMAbstractServicePort.java deleted file mode 100644 index 0be03d44c7..0000000000 --- a/source/java/org/alfresco/repo/cmis/ws/DMAbstractServicePort.java +++ /dev/null @@ -1,539 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.ws; - -import java.beans.IntrospectionException; -import java.beans.Introspector; -import java.beans.PropertyDescriptor; -import java.lang.reflect.InvocationTargetException; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import javax.xml.bind.JAXBElement; - -import org.alfresco.cmis.CMISAccessControlEntry; -import org.alfresco.cmis.CMISAccessControlReport; -import org.alfresco.cmis.CMISAccessControlService; -import org.alfresco.cmis.CMISAclPropagationEnum; -import org.alfresco.cmis.CMISActionEvaluator; -import org.alfresco.cmis.CMISAllowedActionEnum; -import org.alfresco.cmis.CMISChangeLogService; -import org.alfresco.cmis.CMISDictionaryModel; -import org.alfresco.cmis.CMISFilterNotValidException; -import org.alfresco.cmis.CMISInvalidArgumentException; -import org.alfresco.cmis.CMISQueryService; -import org.alfresco.cmis.CMISRelationshipDirectionEnum; -import org.alfresco.cmis.CMISRendition; -import org.alfresco.cmis.CMISRenditionService; -import org.alfresco.cmis.CMISServiceException; -import org.alfresco.cmis.CMISServices; -import org.alfresco.cmis.CMISTypeDefinition; -import org.alfresco.cmis.PropertyFilter; -import org.alfresco.cmis.acl.CMISAccessControlEntryImpl; -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.model.ContentModel; -import org.alfresco.opencmis.CMISAccessControlFormatEnum; -import org.alfresco.repo.cmis.ws.utils.ExceptionUtil; -import org.alfresco.repo.cmis.ws.utils.PropertyUtil; -import org.alfresco.repo.security.authentication.AuthenticationUtil; -import org.alfresco.repo.web.util.paging.Cursor; -import org.alfresco.repo.web.util.paging.Page; -import org.alfresco.repo.web.util.paging.Paging; -import org.alfresco.service.cmr.model.FileFolderService; -import org.alfresco.service.cmr.repository.AssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.cmr.search.SearchService; -import org.alfresco.service.cmr.security.AuthorityService; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.service.cmr.version.Version; -import org.alfresco.service.descriptor.DescriptorService; - -/** - * Base class for all CMIS web services - * - * @author Michael Shavnev - * @author Dmitry Lazurkin - * @author Dmitry Velichkevich - * @author Stanislav Sokolovsky - */ -public class DMAbstractServicePort -{ - private static final String CMIS_USER = "cmis:user"; - - private static final String INVALID_REPOSITORY_ID_MESSAGE = "Invalid repository id"; - - private static final Map ACL_PROPAGATION_ENUM_MAPPGIN; - protected static final Map INCLUDE_RELATIONSHIPS_ENUM_MAPPING; - private static final Map ALLOWED_ACTION_ENUM_MAPPING; - static - { - ACL_PROPAGATION_ENUM_MAPPGIN = new HashMap(5); - ACL_PROPAGATION_ENUM_MAPPGIN.put(EnumACLPropagation.OBJECTONLY, CMISAclPropagationEnum.OBJECT_ONLY); - ACL_PROPAGATION_ENUM_MAPPGIN.put(EnumACLPropagation.PROPAGATE, CMISAclPropagationEnum.PROPAGATE); - ACL_PROPAGATION_ENUM_MAPPGIN.put(EnumACLPropagation.REPOSITORYDETERMINED, CMISAclPropagationEnum.REPOSITORY_DETERMINED); - - INCLUDE_RELATIONSHIPS_ENUM_MAPPING = new HashMap(5); - INCLUDE_RELATIONSHIPS_ENUM_MAPPING.put(EnumIncludeRelationships.SOURCE, CMISRelationshipDirectionEnum.SOURCE); - INCLUDE_RELATIONSHIPS_ENUM_MAPPING.put(EnumIncludeRelationships.TARGET, CMISRelationshipDirectionEnum.TARGET); - INCLUDE_RELATIONSHIPS_ENUM_MAPPING.put(EnumIncludeRelationships.BOTH, CMISRelationshipDirectionEnum.EITHER); - - try - { - ALLOWED_ACTION_ENUM_MAPPING = new HashMap(97); - for (PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(CmisAllowableActionsType.class, Object.class).getPropertyDescriptors()) - { - String label = propertyDescriptor.getName(); - CMISAllowedActionEnum allowedActionEnum = CMISAllowedActionEnum.FACTORY.fromLabel(label); - if (allowedActionEnum != null) - { - ALLOWED_ACTION_ENUM_MAPPING.put(allowedActionEnum, propertyDescriptor); - } - } - } - catch (IntrospectionException e) - { - throw new ExceptionInInitializerError(e); - } - } - - private Paging paging = new Paging(); - - protected ObjectFactory cmisObjectFactory = new ObjectFactory(); - protected CMISQueryService cmisQueryService; - protected CMISServices cmisService; - protected CMISChangeLogService cmisChangeLogService; - protected CMISRenditionService cmisRenditionService; - protected CMISAccessControlService cmisAclService; - - protected DescriptorService descriptorService; - protected NodeService nodeService; - protected FileFolderService fileFolderService; - protected SearchService searchService; - protected PropertyUtil propertiesUtil; - protected PermissionService permissionService; - protected AuthorityService authorityService; - - public void setCmisService(CMISServices cmisService) - { - this.cmisService = cmisService; - } - - public void setCmisQueryService(CMISQueryService cmisQueryService) - { - this.cmisQueryService = cmisQueryService; - } - - public void setCmisChangeLogService(CMISChangeLogService cmisChangeLogService) - { - this.cmisChangeLogService = cmisChangeLogService; - } - - public void setCmisAclService(CMISAccessControlService cmisAclService) - { - this.cmisAclService = cmisAclService; - } - - public void setCmisRenditionService(CMISRenditionService cmisRenditionService) - { - this.cmisRenditionService = cmisRenditionService; - } - - public void setDescriptorService(DescriptorService descriptorService) - { - this.descriptorService = descriptorService; - } - - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } - - public void setFileFolderService(FileFolderService fileFolderService) - { - this.fileFolderService = fileFolderService; - } - - public void setPropertiesUtil(PropertyUtil propertiesUtil) - { - this.propertiesUtil = propertiesUtil; - } - - public void setSearchService(SearchService searchService) - { - this.searchService = searchService; - } - - public void setPermissionService(PermissionService permissionService) - { - this.permissionService = permissionService; - } - - public void setAuthorityService(AuthorityService authorityService) - { - this.authorityService = authorityService; - } - - protected PropertyFilter createPropertyFilter(String filter) throws CmisException - { - try - { - return new PropertyFilter(filter); - } - catch (CMISFilterNotValidException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - protected PropertyFilter createPropertyFilter(JAXBElement element) throws CmisException - { - String filter = null; - if (element != null) - { - filter = element.getValue(); - } - return createPropertyFilter(filter); - } - - protected Cursor createCursor(int totalRows, BigInteger skipCount, BigInteger maxItems) - { - Page window = paging.createPageOrWindow(null, null, skipCount != null ? skipCount.intValue() : null, maxItems != null ? maxItems.intValue() : null); - return paging.createCursor(totalRows, window); - } - - /** - * Returns true if folder contains object - * - * @param object object NodeRef - * @param folder folder NodeRef - * @return returns true if folder contains object - */ - protected boolean isObjectInFolder(NodeRef object, NodeRef folder) - { - NodeRef searchedObjectNodeRef = fileFolderService.searchSimple(folder, (String) nodeService.getProperty(object, ContentModel.PROP_NAME)); - return (null != searchedObjectNodeRef) && (searchedObjectNodeRef.equals(object)); - } - - /** - * This method converts Alfresco's NodeRef's to CMIS objects those will be stored in resultList-parameter. Properties for returning filtering also performs - * - * @param filter properties filter value for filtering objects returning properties - * @param includeRelationships what relationships to include - * @param sourceList the list that contains all returning Node References - * @param resultList the list of CmisObjectType values for end response result collecting - * @throws CmisException - */ - protected void createCmisObjectList(PropertyFilter filter, CMISRelationshipDirectionEnum includeRelationships, boolean includeAllowableActions, String renditionFilter, - List sourceList, List resultList) throws CmisException - { - for (NodeRef objectNodeRef : sourceList) - { - resultList.add(createCmisObject(objectNodeRef, filter, includeRelationships, includeAllowableActions, renditionFilter)); - } - } - - /** - * This method creates and configures CMIS object against appropriate Alfresco object (NodeRef or AssociationRef). - * - * @param object the Alfresco object - * @param filter accepted properties filter - * @param includeRelationships what relationships to include - * @param includeAllowableActions should we include allowable actions? - * @param renditionFilter the rendition filter - * @return the converted CMIS object - * @throws CmisException on error - */ - protected CmisObjectType createCmisObject(Object object, PropertyFilter filter, EnumIncludeRelationships includeRelationships, Boolean includeAllowableActions, - String renditionFilter) throws CmisException - { - return createCmisObject(object, filter, includeRelationships == null ? null : INCLUDE_RELATIONSHIPS_ENUM_MAPPING.get(includeRelationships), includeAllowableActions != null - && includeAllowableActions, renditionFilter); - } - - /** - * This method creates and configures CMIS object against appropriate Alfresco object (NodeRef or AssociationRef). - * - * @param object the Alfresco object - * @param filter accepted properties filter - * @param includeRelationships what relationships to include - * @param includeAllowableActions should we include allowable actions? - * @param renditionFilter the rendition filter - * @return the converted CMIS object - * @throws CmisException on error - */ - protected CmisObjectType createCmisObject(Object object, PropertyFilter filter, CMISRelationshipDirectionEnum includeRelationships, boolean includeAllowableActions, - String renditionFilter) throws CmisException - { - // Get a NodeRef if we can - if (object instanceof Version) - { - object = ((Version) object).getFrozenStateNodeRef(); - } - CmisObjectType result = new CmisObjectType(); - result.setProperties(propertiesUtil.getProperties(object, filter)); - if (object instanceof NodeRef && includeRelationships != null) - { - appendWithRelationships((NodeRef) object, filter, includeRelationships, includeAllowableActions, renditionFilter, result); - } - if (includeAllowableActions) - { - result.setAllowableActions(determineObjectAllowableActions(object)); - } - if (renditionFilter != null) - { - List renditions = getRenditions(object, renditionFilter); - if (renditions != null && !renditions.isEmpty()) - { - result.getRendition().addAll(renditions); - } - } - return result; - } - - protected void appendWithRelationships(NodeRef object, PropertyFilter filter, CMISRelationshipDirectionEnum includeRelationships, boolean includeAllowableActions, - String renditionFilter, CmisObjectType result) throws CmisException - { - List relationships = result.getRelationship(); - try - { - for (AssociationRef assoc : cmisService.getRelationships(object, null, true, includeRelationships)) - { - relationships.add(createCmisObject(assoc, filter, includeRelationships, includeAllowableActions, renditionFilter)); - } - } - catch (CMISInvalidArgumentException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - /** - * Checks specified in CMIS request parameters repository Id. - * - * @param repositoryId repository id - * @throws CmisException repository diesn't exist - */ - protected void checkRepositoryId(String repositoryId) throws CmisException - { - if (!this.descriptorService.getCurrentRepositoryDescriptor().getId().equals(repositoryId)) - { - throw ExceptionUtil.createCmisException(INVALID_REPOSITORY_ID_MESSAGE, EnumServiceException.INVALID_ARGUMENT); - } - } - - protected List getRenditions(Object object, String renditionFilter) throws CmisException - { - List result = null; - if (object instanceof Version) - { - object = ((Version) object).getFrozenStateNodeRef(); - } - if (object instanceof NodeRef) - { - NodeRef document = (NodeRef) object; - - List renditions = null; - try - { - renditions = cmisRenditionService.getRenditions(document, renditionFilter); - } - catch (CMISFilterNotValidException e) - { - throw ExceptionUtil.createCmisException(e); - } - if (renditions != null && !renditions.isEmpty()) - { - result = new ArrayList(); - for (CMISRendition rendition : renditions) - { - if (rendition != null) - { - CmisRenditionType cmisRenditionType = convertToCmisRenditionType(rendition); - result.add(cmisRenditionType); - } - } - } - } - return result; - } - - private CmisRenditionType convertToCmisRenditionType(CMISRendition rendition) - { - CmisRenditionType cmisRenditionType = new CmisRenditionType(); - cmisRenditionType.setStreamId(rendition.getStreamId()); - cmisRenditionType.setKind(rendition.getKind()); - cmisRenditionType.setMimetype(rendition.getMimeType()); - cmisRenditionType.setTitle(rendition.getTitle()); - cmisRenditionType.setWidth(rendition.getWidth() != null ? BigInteger.valueOf(rendition.getWidth()) : null); - cmisRenditionType.setHeight(rendition.getHeight() != null ? BigInteger.valueOf(rendition.getHeight()) : null); - cmisRenditionType.setLength(rendition.getLength() != null ? BigInteger.valueOf(rendition.getLength()) : null); - cmisRenditionType.setRenditionDocumentId(rendition.getRenditionDocumentId()); - return cmisRenditionType; - } - - protected void appendWithAce(NodeRef identifierInstance, CmisObjectType object) - { - CMISAccessControlReport aclReport = cmisAclService.getAcl(identifierInstance, CMISAccessControlFormatEnum.REPOSITORY_SPECIFIC_PERMISSIONS); - object.setAcl(convertAclReportToCmisAclType(aclReport).getACL()); - object.setExactACL(aclReport.isExact()); - } - - protected void applyPolicies(String objectId, List policies) throws CmisException - { - // Process any provided policy IDs (they will be rejected!) - if (policies != null) - { - for (String policyId : policies) - { - try - { - cmisService.applyPolicy(policyId, objectId); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - } - } - - protected CmisACLType applyAclCarefully(NodeRef object, CmisAccessControlListType addACEs, CmisAccessControlListType removeACEs, EnumACLPropagation aclPropagation, - List policies) throws CmisException - { - if (addACEs == null && removeACEs == null) - { - return null; - } - try - { - CMISAclPropagationEnum propagation = (null == aclPropagation) ? (CMISAclPropagationEnum.PROPAGATE) : (ACL_PROPAGATION_ENUM_MAPPGIN.get(aclPropagation)); - List acesToAdd = (null == addACEs) ? (null) : (convertToAlfrescoAceEntriesList(addACEs.getPermission())); - List acesToRemove = (null == removeACEs) ? (null) : (convertToAlfrescoAceEntriesList(removeACEs.getPermission())); - CMISAccessControlReport aclReport = null; - aclReport = cmisAclService.applyAcl(object, acesToRemove, acesToAdd, propagation, CMISAccessControlFormatEnum.REPOSITORY_SPECIFIC_PERMISSIONS); - - // Process any provided policy IDs (they will be rejected!) - if (policies != null) - { - String objectId = (String) cmisService.getProperty(object, CMISDictionaryModel.PROP_OBJECT_ID); - applyPolicies(objectId, policies); - } - CmisACLType result = convertAclReportToCmisAclType(aclReport); - return result; - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - private List convertToAlfrescoAceEntriesList(List source) throws CmisException - { - List result = new LinkedList(); - for (CmisAccessControlEntryType cmisEntry : source) - { - String principalId = cmisEntry.getPrincipal().getPrincipalId(); - if (CMIS_USER.equals(principalId)) - { - principalId = AuthenticationUtil.getFullyAuthenticatedUser(); - } - for (String permission : cmisEntry.getPermission()) - { - result.add(new CMISAccessControlEntryImpl(principalId, permission)); - } - } - return result; - } - - protected CmisACLType convertAclReportToCmisAclType(CMISAccessControlReport aclReport) - { - CmisACLType result = new CmisACLType(); - CmisAccessControlListType aceList = new CmisAccessControlListType(); - result.setACL(aceList); - for (CMISAccessControlEntry ace : aclReport.getAccessControlEntries()) - { - CmisAccessControlEntryType entry = new CmisAccessControlEntryType(); - entry.setDirect(ace.getDirect()); - entry.getPermission().add(ace.getPermission()); // FIXME: [BUG] Should be List getPermission() instead of String getPermission()!!! - CmisAccessControlPrincipalType principal = new CmisAccessControlPrincipalType(); - principal.setPrincipalId(ace.getPrincipalId()); - entry.setPrincipal(principal); - aceList.getPermission().add(entry); - } - result.setExact(aclReport.isExact()); - return result; - } - - @SuppressWarnings("unchecked") - protected CmisAllowableActionsType determineObjectAllowableActions(Object objectIdentifier) throws CmisException - { - CMISTypeDefinition typeDef; - try - { - if (objectIdentifier instanceof AssociationRef) - { - typeDef = cmisService.getTypeDefinition((AssociationRef) objectIdentifier); - } - else - { - if (objectIdentifier instanceof Version) - { - objectIdentifier = ((Version) objectIdentifier).getFrozenStateNodeRef(); - } - typeDef = cmisService.getTypeDefinition((NodeRef) objectIdentifier); - } - } - catch (CMISInvalidArgumentException e) - { - throw ExceptionUtil.createCmisException(e); - } - CmisAllowableActionsType result = new CmisAllowableActionsType(); - for (Entry> entry : typeDef.getActionEvaluators().entrySet()) - { - PropertyDescriptor propertyDescriptor = ALLOWED_ACTION_ENUM_MAPPING.get(entry.getKey()); - if (propertyDescriptor != null) - { - // Let's assume that the evaluator will accept the object - try - { - propertyDescriptor.getWriteMethod().invoke(result, new Boolean(((CMISActionEvaluator) entry.getValue()).isAllowed(objectIdentifier))); - } - catch (IllegalArgumentException e) - { - throw new AlfrescoRuntimeException("Exception setting allowable actions", e); - } - catch (IllegalAccessException e) - { - throw new AlfrescoRuntimeException("Exception setting allowable actions", e); - } - catch (InvocationTargetException e) - { - throw new AlfrescoRuntimeException("Exception setting allowable actions", e.getTargetException()); - } - } - } - return result; - } -} diff --git a/source/java/org/alfresco/repo/cmis/ws/DMAclServicePort.java b/source/java/org/alfresco/repo/cmis/ws/DMAclServicePort.java deleted file mode 100644 index 1a835bf571..0000000000 --- a/source/java/org/alfresco/repo/cmis/ws/DMAclServicePort.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.ws; - -import org.alfresco.cmis.CMISAccessControlReport; -import org.alfresco.cmis.CMISServiceException; -import org.alfresco.opencmis.CMISAccessControlFormatEnum; -import org.alfresco.repo.cmis.ws.utils.ExceptionUtil; -import org.alfresco.service.cmr.repository.NodeRef; - -/** - * @author Dmitry Velichkevich - */ -@javax.jws.WebService(name = "ACLServicePort", serviceName = "ACLService", portName = "ACLServicePort", targetNamespace = "http://docs.oasis-open.org/ns/cmis/ws/200908/", endpointInterface = "org.alfresco.repo.cmis.ws.ACLServicePort") -public class DMAclServicePort extends DMAbstractServicePort implements ACLServicePort -{ - /** - * - */ - public CmisACLType applyACL(String repositoryId, String objectId, CmisAccessControlListType addACEs, CmisAccessControlListType removeACEs, EnumACLPropagation aclPropagation, - CmisExtensionType extension) throws CmisException - { - checkRepositoryId(repositoryId); - NodeRef object; - try - { - object = cmisService.getObject(objectId, NodeRef.class, true, false, false); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - return applyAclCarefully(object, addACEs, removeACEs, aclPropagation, null); - } - - /** - * - */ - public CmisACLType getACL(String repositoryId, String objectId, Boolean onlyBasicPermissions, CmisExtensionType extension) throws CmisException - { - checkRepositoryId(repositoryId); - NodeRef nodeRef; - try - { - nodeRef = cmisService.getReadableObject(objectId, NodeRef.class); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - CMISAccessControlFormatEnum permissionsKind = ((null == onlyBasicPermissions) || onlyBasicPermissions) ? (CMISAccessControlFormatEnum.CMIS_BASIC_PERMISSIONS) - : (CMISAccessControlFormatEnum.REPOSITORY_SPECIFIC_PERMISSIONS); - CMISAccessControlReport aclReport = cmisAclService.getAcl(nodeRef, permissionsKind); - return convertAclReportToCmisAclType(aclReport); - } -} diff --git a/source/java/org/alfresco/repo/cmis/ws/DMDiscoveryServicePort.java b/source/java/org/alfresco/repo/cmis/ws/DMDiscoveryServicePort.java deleted file mode 100644 index 3421cedd71..0000000000 --- a/source/java/org/alfresco/repo/cmis/ws/DMDiscoveryServicePort.java +++ /dev/null @@ -1,290 +0,0 @@ -/* - * Copyright (C) 2005-2012 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 . - */ -package org.alfresco.repo.cmis.ws; - -import java.io.Serializable; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.xml.datatype.XMLGregorianCalendar; -import javax.xml.ws.Holder; - -import org.alfresco.cmis.CMISChangeEvent; -import org.alfresco.cmis.CMISChangeLog; -import org.alfresco.cmis.CMISChangeType; -import org.alfresco.cmis.CMISDataTypeEnum; -import org.alfresco.cmis.CMISDictionaryModel; -import org.alfresco.cmis.CMISObjectNotFoundException; -import org.alfresco.cmis.CMISQueryOptions; -import org.alfresco.cmis.CMISRelationshipDirectionEnum; -import org.alfresco.cmis.CMISResultSet; -import org.alfresco.cmis.CMISResultSetColumn; -import org.alfresco.cmis.CMISResultSetRow; -import org.alfresco.cmis.CMISServiceException; -import org.alfresco.cmis.PropertyFilter; -import org.alfresco.cmis.CMISQueryOptions.CMISQueryMode; -import org.alfresco.repo.cmis.ws.utils.ExceptionUtil; -import org.alfresco.repo.security.permissions.AccessDeniedException; -import org.alfresco.service.cmr.repository.NodeRef; - -/** - * Port for Discovery service. - * - * @author Dmitry Lazurkin - * @author Dmitry Velichkevich - */ -@javax.jws.WebService(name = "DiscoveryServicePort", serviceName = "DiscoveryService", portName = "DiscoveryServicePort", targetNamespace = "http://docs.oasis-open.org/ns/cmis/ws/200908/", endpointInterface = "org.alfresco.repo.cmis.ws.DiscoveryServicePort") -public class DMDiscoveryServicePort extends DMAbstractServicePort implements DiscoveryServicePort -{ - private static Map changesTypeMapping = new HashMap(); - static - { - changesTypeMapping.put(CMISChangeType.CREATED, EnumTypeOfChanges.CREATED); - changesTypeMapping.put(CMISChangeType.UPDATED, EnumTypeOfChanges.UPDATED); - changesTypeMapping.put(CMISChangeType.SECURITY, EnumTypeOfChanges.SECURITY); - changesTypeMapping.put(CMISChangeType.DELETED, EnumTypeOfChanges.DELETED); - } - - /** - * Queries the repository for queryable object based on properties or an optional full-text string. Relationship objects are not queryable. Content-streams are not returned as - * part of query - * - * ALF-9566 : hasMoreItems was changed to be confirmed with a section (2.2.1.1 Paging) of the specification. - * - * @param parameters query parameters - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME) - */ - public QueryResponse query(Query parameters) throws CmisException - { - checkRepositoryId(parameters.getRepositoryId()); - - // TODO: includeRelationships, includeRenditions - CMISQueryOptions options = new CMISQueryOptions(parameters.getStatement(), cmisService.getDefaultRootStoreRef()); - - int skipCount = 0; - if (parameters.getSkipCount() != null && parameters.getSkipCount().getValue() != null) - { - skipCount = parameters.getSkipCount().getValue().intValue(); - options.setSkipCount(skipCount); - } - - boolean includeAllowableActions = ((null != parameters.getIncludeAllowableActions()) && (null != parameters.getIncludeAllowableActions().getValue())) ? (parameters - .getIncludeAllowableActions().getValue()) : (false); - String renditionFilter = (null != parameters.getRenditionFilter()) ? (parameters.getRenditionFilter().getValue()) : null; - - // execute query - // TODO: If the select clause includes properties from more than a single type reference, then the repository SHOULD throw an exception if includeRelationships or - // includeAllowableActions is specified as true. - options.setQueryMode(CMISQueryMode.CMS_WITH_ALFRESCO_EXTENSIONS); - QueryResponse response = new QueryResponse(); - CMISResultSet resultSet = null; - - try - { - resultSet = cmisQueryService.query(options); - CMISResultSetColumn[] columns = resultSet.getMetaData().getColumns(); - - // build query response - - response.setObjects(new CmisObjectListType()); - EnumIncludeRelationships cmisDirection = (null != parameters.getIncludeRelationships()) ? (parameters.getIncludeRelationships().getValue()) : (null); - CMISRelationshipDirectionEnum includeRelationships = INCLUDE_RELATIONSHIPS_ENUM_MAPPING.get(cmisDirection); - - int maxItems = -1; - if (parameters.getMaxItems() != null && parameters.getMaxItems().getValue() != null) - { - maxItems = parameters.getMaxItems().getValue().intValue(); - } - - // total number of items - int numItems = resultSet.getLength(); - // for each row... - int idx = 0; - for (CMISResultSetRow row : resultSet) - { - if (maxItems != -1 && idx == maxItems) - { - break; - } - - Object identifier; - NodeRef nodeRef; - try - { - nodeRef = row.getNodeRef(); - identifier = cmisService.getReadableObject((String) nodeRef.toString(), Object.class); - } - catch (CMISObjectNotFoundException e) - { - // ALF-15001: Handle stale nodeRefs in the index - numItems--; - continue; - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - - CmisPropertiesType properties = new CmisPropertiesType(); - Map values = row.getValues(); - - // for each column... - for (CMISResultSetColumn column : columns) - { - CmisProperty property = propertiesUtil.createProperty(column.getName(), column.getCMISDataType(), values.get(column.getName())); - if (property != null) - { - property.setQueryName(column.getName()); - properties.getProperty().add(property); - } - } - - CmisObjectType object = new CmisObjectType(); - object.setProperties(properties); - if (includeAllowableActions) - { - object.setAllowableActions(determineObjectAllowableActions(identifier)); - } - if (null != includeRelationships) - { - appendWithRelationships(nodeRef, createPropertyFilter((String) null), includeRelationships, includeAllowableActions, renditionFilter, object); - } - if (renditionFilter != null) - { - List renditions = getRenditions(identifier, renditionFilter); - if (renditions != null && !renditions.isEmpty()) - { - object.getRendition().addAll(renditions); - } - } - response.getObjects().getObjects().add(object); - idx++; - } - response.getObjects().setNumItems(BigInteger.valueOf(numItems)); - boolean hasMoreItems = (maxItems != -1 ? (numItems - (skipCount + maxItems)) > 0 : false) || resultSet.hasMore(); - response.getObjects().setHasMoreItems(hasMoreItems); - } - finally - { - if (resultSet != null) {resultSet.close();} - } - return response; - } - - /** - * Gets a list of content changes. Targeted for search crawlers or other applications that need to efficiently understand what has changed in the repository. Note: The content - * stream is NOT returned for any change event. - * - * @param repositoryId {@link String} value that determines Id of the necessary Repository - * @param changeLogToken generic {@link Holder} class instance with {@link String} type parameter that determines last Change Log Token - * @param includeProperties {@link Boolean} instance value that specifies whether all allowed by filter properties should be returned for Change Type equal to 'UPDATED' or - * Object Id property only - * @param filter {@link String} value for filtering properties for Change Entry with Change Type equal to 'UPDATED' - * @param includePolicyIds {@link Boolean} instance value that determines whether Policy Ids must be returned - * @param includeACL {@link Boolean} instance value that determines whether ACLs must be returned - * @param maxItems {@link BigInteger} instance value that determines required amount of Change Log Entries - * @param extension {@link CmisException} instance of unknown assignment - * @param objects generic {@link Holder} instance with {@link CmisObjectListType} type parameter for storing results of service execution - * @throws CmisException with next allowable {@link EnumServiceException} enum attribute of exception type values: CONSTRAINT, FILTER_NOT_VALID, INVALID_ARGUMENT, - * NOT_SUPPORTED, OBJECT_NOT_FOUND, PERMISSION_DENIED, RUNTIME - */ - public void getContentChanges(String repositoryId, Holder changeLogToken, Boolean includeProperties, String filter, Boolean includePolicyIds, Boolean includeACL, - BigInteger maxItems, CmisExtensionType extension, Holder objects) throws CmisException - { - if (!authorityService.hasAdminAuthority()) - { - throw ExceptionUtil.createCmisException("Cannot retrieve content changes", new AccessDeniedException("Requires admin authority")); - } - - // TODO: includePolicyIds - checkRepositoryId(repositoryId); - String changeToken = (null != changeLogToken) ? (changeLogToken.value) : (null); - Integer maxAmount = (null != maxItems) ? (maxItems.intValue()) : (null); - boolean propertiesRequsted = (null != includeProperties) ? (includeProperties.booleanValue()) : (false); - if (propertiesRequsted) - { - if ((null != filter) && !"".equals(filter) && !PropertyFilter.MATCH_ALL_FILTER.equals(filter) && !filter.contains(CMISDictionaryModel.PROP_OBJECT_ID)) - { - filter = CMISDictionaryModel.PROP_OBJECT_ID + PropertyFilter.PROPERTY_NAME_TOKENS_DELIMITER + filter; - } - } - else - { - filter = CMISDictionaryModel.PROP_OBJECT_ID; - } - - CMISChangeLog changeLog = null; - try - { - changeLog = cmisChangeLogService.getChangeLogEvents(changeToken, maxAmount); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - if (null == objects.value) - { - objects.value = new CmisObjectListType(); - } - if ((null == changeLog) || (null == changeLog.getChangeEvents()) || changeLog.getChangeEvents().isEmpty()) - { - objects.value.setHasMoreItems(false); - objects.value.setNumItems(BigInteger.valueOf(0)); - } - else - { - formatObjectsResponse(filter, propertiesRequsted, includeACL, changeLog, objects.value.getObjects()); - objects.value.setHasMoreItems(changeLog.hasMoreItems()); - objects.value.setNumItems(BigInteger.valueOf(changeLog.getChangeEvents().size())); - changeLogToken.value = changeLog.getNextChangeToken(); - } - } - - /** - * This method formats response for Get Content Changes service - * - * @param filter {@link String} value that determines user specified properties filter - * @param propertiesRequsted {@link Boolean} value that determines whether properties another than Object Id should be returned (according to specified properties filter) - * @param changeLog {@link CMISChangeLog} instance that represents descriptor for some Change Log Token - * @param result {@link List}<{@link CmisObjectType}> collection instance for storing Change Event entries from Change Log descriptor - * @throws CmisException - */ - private void formatObjectsResponse(String filter, boolean propertiesRequsted, boolean includeAce, CMISChangeLog changeLog, List result) throws CmisException - { - for (CMISChangeEvent event : changeLog.getChangeEvents()) - { - CmisObjectType object = new CmisObjectType(); - CmisPropertiesType propertiesType = new CmisPropertiesType(); - object.setProperties(propertiesType); - propertiesType.getProperty().add(propertiesUtil.createProperty(CMISDictionaryModel.PROP_OBJECT_ID, CMISDataTypeEnum.ID, event.getObjectId())); - if (nodeService.exists(event.getChangedNode()) && includeAce) - { - appendWithAce(event.getChangedNode(), object); - } - CmisChangeEventType changeInfo = new CmisChangeEventType(); - XMLGregorianCalendar modificationDate = propertiesUtil.convert(event.getChangeTime()); - changeInfo.setChangeType(changesTypeMapping.get(event.getChangeType())); - changeInfo.setChangeTime(modificationDate); - object.setChangeEventInfo(changeInfo); - result.add(object); - } - } -} diff --git a/source/java/org/alfresco/repo/cmis/ws/DMMultiFilingServicePort.java b/source/java/org/alfresco/repo/cmis/ws/DMMultiFilingServicePort.java deleted file mode 100644 index 2b5c02c9ff..0000000000 --- a/source/java/org/alfresco/repo/cmis/ws/DMMultiFilingServicePort.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.ws; - -import javax.xml.ws.Holder; - -import org.alfresco.cmis.CMISDictionaryModel; -import org.alfresco.cmis.CMISServiceException; -import org.alfresco.cmis.CMISTypeDefinition; -import org.alfresco.repo.cmis.ws.utils.ExceptionUtil; -import org.alfresco.service.cmr.repository.NodeRef; - -/** - * Port for Multi-Filing service. - * - * @author Dmitry Lazurkin - * @author Dmitry Velichkevich - */ -@javax.jws.WebService(name = "MultiFilingServicePort", serviceName = "MultiFilingService", portName = "MultiFilingServicePort", targetNamespace = "http://docs.oasis-open.org/ns/cmis/ws/200908/", endpointInterface = "org.alfresco.repo.cmis.ws.MultiFilingServicePort") -public class DMMultiFilingServicePort extends DMAbstractServicePort implements MultiFilingServicePort -{ - /** - * Adds an existing non-folder, fileable object to a folder. - * - * @param repositoryId Repository Id - * @param objectId object Id to be added to a folder - * @param folderId folder Id to which the object is added - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, CONSTRAINT) - */ - public void addObjectToFolder(String repositoryId, String objectId, String folderId, Boolean allVersions, Holder extension) throws CmisException - { - checkRepositoryId(repositoryId); - checkConstraints(objectId, folderId, false); - try - { - cmisService.addObjectToFolder(objectId, folderId); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - /** - * Removes a non-folder child object from a folder or from all folders. This does not delete the object and does not change the ID of the object. - * - * @param repositoryId repository Id - * @param objectId The object to be removed from a folder - * @param folderId The folder to be removed from. - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME) - */ - public void removeObjectFromFolder(String repositoryId, String objectId, String folderId, Holder extension) throws CmisException - { - checkRepositoryId(repositoryId); - checkConstraints(objectId, folderId, true); - - try - { - cmisService.removeObjectFromFolder(objectId, folderId); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - - } - - private void checkConstraints(String objectId, String folderId, boolean checkIsObjectInFolder) throws CmisException - { - NodeRef objectNodeRef = null; - NodeRef folderNodeRef = null; - CMISTypeDefinition objectTypeDef = null; - - try - { - objectNodeRef = cmisService.getObject(objectId, NodeRef.class, true, false, false); - folderNodeRef = cmisService.getFolder(folderId); - objectTypeDef = cmisService.getTypeDefinition(objectNodeRef); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e.getMessage(), EnumServiceException.INVALID_ARGUMENT); - } - - if (!objectTypeDef.getTypeId().getBaseTypeId().equals(CMISDictionaryModel.DOCUMENT_TYPE_ID)) - { - throw ExceptionUtil.createCmisException("Object " + objectId + " is not a document", EnumServiceException.INVALID_ARGUMENT); - } - - if (checkIsObjectInFolder && !isObjectInFolder(objectNodeRef, folderNodeRef)) - { - throw ExceptionUtil.createCmisException("Folder doesn't contain specified object", EnumServiceException.OBJECT_NOT_FOUND); - } - } - -} diff --git a/source/java/org/alfresco/repo/cmis/ws/DMNavigationServicePort.java b/source/java/org/alfresco/repo/cmis/ws/DMNavigationServicePort.java deleted file mode 100644 index 68b716d605..0000000000 --- a/source/java/org/alfresco/repo/cmis/ws/DMNavigationServicePort.java +++ /dev/null @@ -1,410 +0,0 @@ -/* - * Copyright (C) 2005-2011 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 . - */ -package org.alfresco.repo.cmis.ws; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.Stack; - -import org.alfresco.cmis.CMISDictionaryModel; -import org.alfresco.cmis.CMISInvalidArgumentException; -import org.alfresco.cmis.CMISServiceException; -import org.alfresco.cmis.CMISTypesFilterEnum; -import org.alfresco.cmis.PropertyFilter; -import org.alfresco.query.PagingResults; -import org.alfresco.repo.cmis.ws.utils.ExceptionUtil; -import org.alfresco.repo.security.authentication.AuthenticationUtil; -import org.alfresco.repo.web.util.paging.Cursor; -import org.alfresco.service.cmr.model.FileInfo; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.util.Pair; - -/** - * Port for navigation service - * - * @author Dmitry Lazurkin - * @author Dmitry Velichkevich - */ -@javax.jws.WebService(name = "NavigationServicePort", serviceName = "NavigationService", portName = "NavigationServicePort", targetNamespace = "http://docs.oasis-open.org/ns/cmis/ws/200908/", endpointInterface = "org.alfresco.repo.cmis.ws.NavigationServicePort") -public class DMNavigationServicePort extends DMAbstractServicePort implements NavigationServicePort -{ - private static final int EQUALS_CONDITION_VALUE = 0; - private static final BigInteger FULL_DESCENDANTS_HIERARCHY_CONDITION = BigInteger.valueOf(-1l); - - private static final String FILTER_TOKENS_DELIMETER = ", "; - - /** - * Gets the private working copies of checked-out objects that the user is allowed to update. - * - * @param parameters repositoryId: repository Id; folderID: folder Id; filter: property filter; includeAllowableActions; includeRelationships; maxItems: 0 = Unlimited; - * skipCount: 0 = start at beginning - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, FILTER_NOT_VALID) - */ - public CmisObjectListType getCheckedOutDocs(String repositoryId, String folderId, String filter, String orderBy, Boolean includeAllowableActions, - EnumIncludeRelationships includeRelationships, String renditionFilter, BigInteger maxItems, BigInteger skipCount, CmisExtensionType extension) throws CmisException - { - checkRepositoryId(repositoryId); - PropertyFilter propertyFilter = createPropertyFilter(filter); - - try - { - NodeRef folderRef = null; - if ((folderId != null) && !folderId.equals("")) - { - folderRef = cmisService.getFolder(folderId); - } - - NodeRef[] nodeRefs = cmisService.getCheckedOut(AuthenticationUtil.getFullyAuthenticatedUser(), folderRef, - (folderRef == null), orderBy); - Cursor cursor = createCursor(nodeRefs.length, skipCount, maxItems); - - CmisObjectListType result = new CmisObjectListType(); - List resultListing = result.getObjects(); - - for (int index = cursor.getStartRow(); index <= cursor.getEndRow(); index++) - { - resultListing.add(createCmisObject(nodeRefs[index], propertyFilter, includeRelationships, - includeAllowableActions, renditionFilter)); - } - result.setHasMoreItems(new Boolean(cursor.getEndRow() < (nodeRefs.length - 1))); - return result; - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - /** - * Gets the list of child objects contained in the specified folder. Only the filter-selected properties associated with each object are returned. The content-streams of - * documents are not returned.For returning a tree of objects of a certain depth, use {@link #getDescendants(GetDescendants parameters)}. - * - * @param parameters repositoryId: repository Id; folderId: folder Id; type: DOCUMENTS, FOLDERS, POLICIES, ANY; filter: property filter; includeAllowableActions; - * includeRelationships; maxItems: 0 = Unlimited; skipCount: 0 = start at beginning - * @return collection of CmisObjectType and boolean hasMoreItems - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, FILTER_NOT_VALID) - */ - public CmisObjectInFolderListType getChildren(String repositoryId, String folderId, String filter, String orderBy, - Boolean includeAllowableActions, EnumIncludeRelationships includeRelationships, String renditionFilter, - Boolean includePathSegments, BigInteger maxItems, BigInteger skipCount, CmisExtensionType extension) - throws CmisException - { - checkRepositoryId(repositoryId); - PropertyFilter propertyFilter = createPropertyFilter(filter); - - try - { - NodeRef folderNodeRef = cmisService.getFolder(folderId); - - PagingResults pageOfNodeInfos = cmisService.getChildren(folderNodeRef, CMISTypesFilterEnum.ANY, maxItems, skipCount, orderBy); - - int pageCnt = pageOfNodeInfos.getPage().size(); - NodeRef[] children = new NodeRef[pageCnt]; - - int idx = 0; - for (FileInfo child : pageOfNodeInfos.getPage()) - { - children[idx] = child.getNodeRef(); - idx++; - } - - CmisObjectInFolderListType result = new CmisObjectInFolderListType(); - - // has more ? - result.setHasMoreItems(pageOfNodeInfos.hasMoreItems()); - - // total count ? - Pair totalCounts = pageOfNodeInfos.getTotalResultCount(); - if (totalCounts != null) - { - Integer totalCountLower = totalCounts.getFirst(); - Integer totalCountUpper = totalCounts.getSecond(); - if ((totalCountLower != null) && (totalCountLower.equals(totalCountUpper))) - { - result.setNumItems(BigInteger.valueOf(totalCountLower)); - } - } - - for (int index = 0; index < pageCnt; index++) - { - CmisObjectType cmisObject = createCmisObject(children[index], propertyFilter, includeRelationships, - includeAllowableActions, renditionFilter); - CmisObjectInFolderType cmisObjectInFolder = new CmisObjectInFolderType(); - cmisObjectInFolder.setObject(cmisObject); - if (includePathSegments != null && includePathSegments) - { - cmisObjectInFolder.setPathSegment(propertiesUtil.getProperty(children[index], - CMISDictionaryModel.PROP_NAME, "")); - } - result.getObjects().add(cmisObjectInFolder); - } - - // TODO: Process includeRelationships, includeACL - return result; - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - /** - * Gets the list of descendant objects contained at one or more levels in the tree rooted at the specified folder. Only the filter-selected properties associated with each - * object are returned. The content-stream is not returned. For paging through the children (depth of 1) only use {@link #getChildren(GetChildren parameters)}. - * - * @param parameters repositoryId: repository Id; folderId: folder Id; depth: 1 this folder only (Default), N folders deep, -1 for all levels; filter: property filter; - * includeAllowableActions; includeRelationships; - * @return collection of CmisObjectType - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, FILTER_NOT_VALID) - */ - public List getDescendants(String repositoryId, String folderId, BigInteger depth, String filter, Boolean includeAllowableActions, - EnumIncludeRelationships includeRelationships, String renditionFilter, Boolean includePathSegments, CmisExtensionType extension) throws CmisException - { - CmisObjectInFolderContainerType objectInFolderContainerType = getDescendantsTree(repositoryId, folderId, depth, filter, includeAllowableActions, includeRelationships, - renditionFilter, includePathSegments, CMISTypesFilterEnum.ANY); - return objectInFolderContainerType.getChildren(); - } - - /** - * Gets the list of descendant objects contained at one or more levels in the tree rooted at the specified folder. Only the filter-selected properties associated with each - * object are returned. The content-stream is not returned. For paging through the children (depth of 1) only use {@link #getChildren(GetChildren parameters)}. - * - * @param parameters repositoryId: repository Id; folderId: folder Id; depth: 1 this folder only (Default), N folders deep, -1 for all levels; filter: property filter; - * includeAllowableActions; includeRelationships; - * @return collection of CmisObjectType - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, FILTER_NOT_VALID) - */ - public List getFolderTree(String repositoryId, String folderId, BigInteger depth, String filter, Boolean includeAllowableActions, - EnumIncludeRelationships includeRelationships, String renditionFilter, Boolean includePathSegments, CmisExtensionType extension) throws CmisException - { - CmisObjectInFolderContainerType objectInFolderContainerType = getDescendantsTree(repositoryId, folderId, depth, filter, includeAllowableActions, includeRelationships, - renditionFilter, includePathSegments, CMISTypesFilterEnum.FOLDERS); - return objectInFolderContainerType.getChildren(); - } - - /** - * Returns the parent folder object, and optionally all ancestor folder objects, above a specified folder object. - * - * @param parameters repositoryId: repository Id; folderId: folder Id; filter: property filter; includeAllowableActions; includeRelationships; returnToRoot: If false, return - * only the immediate parent of the folder. If true, return an ordered list of all ancestor folders from the specified folder to the root folder - * @return collection of CmisObjectType - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, FILTER_NOT_VALID) - */ - public CmisObjectType getFolderParent(String repositoryId, String folderId, String filter, CmisExtensionType extension) throws CmisException - { - checkRepositoryId(repositoryId); - if ((filter != null) && !filter.equals("") && !filter.equals("*")) - { - if (!filter.contains(CMISDictionaryModel.PROP_PARENT_ID)) - { - filter = CMISDictionaryModel.PROP_PARENT_ID + FILTER_TOKENS_DELIMETER + filter; - } - - if (!filter.contains(CMISDictionaryModel.PROP_OBJECT_ID)) - { - filter = CMISDictionaryModel.PROP_OBJECT_ID + FILTER_TOKENS_DELIMETER + filter; - } - } - PropertyFilter propertyFilter = createPropertyFilter(filter); - NodeRef parentRef; - try - { - parentRef = cmisService.getFolderParent(folderId); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - - CmisObjectType result = createCmisObject(parentRef, propertyFilter, null, false, null); - return result; - } - - /** - * Returns the parent folders for the specified non-folder, fileable object. - * - * @param parameters repositoryId: repository Id; objectId: object Id; filter: property filter; includeAllowableActions; includeRelationships; - * @return collection of CmisObjectType - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, CONSTRAINT, - * FILTER_NOT_VALID) - */ - public List getObjectParents(String repositoryId, String objectId, String filter, - Boolean includeAllowableActions, EnumIncludeRelationships includeRelationships, String renditionFilter, - Boolean includeRelativePathSegment, CmisExtensionType extension) throws CmisException - { - checkRepositoryId(repositoryId); - PropertyFilter propertyFilter = createPropertyFilter(filter); - - try - { - NodeRef childNode = (NodeRef) cmisService.getReadableObject(objectId, NodeRef.class); - List parents = receiveObjectParents(childNode); - - List result = new ArrayList(); - String relativePathSegment = propertiesUtil.getProperty(childNode, CMISDictionaryModel.PROP_NAME, ""); - for (NodeRef objectNodeRef : parents) - { - CmisObjectType cmisObject = createCmisObject(objectNodeRef, propertyFilter, includeRelationships, - includeAllowableActions, renditionFilter); - CmisObjectParentsType cmisObjectParentsType = new CmisObjectParentsType(); - cmisObjectParentsType.setObject(cmisObject); - if (includeRelativePathSegment != null && includeRelativePathSegment) - { - cmisObjectParentsType.setRelativePathSegment(relativePathSegment); - } - result.add(cmisObjectParentsType); - } - return result; - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - private CmisObjectInFolderContainerType getDescendantsTree(String repositoryId, String folderId, BigInteger depth, String filter, Boolean includeAllowableActions, - EnumIncludeRelationships includeRelationships, String renditionFilter, Boolean includePathSegments, CMISTypesFilterEnum types) throws CmisException - { - checkRepositoryId(repositoryId); - PropertyFilter propertyFilter = createPropertyFilter(filter); - depth = (depth == null) ? (BigInteger.ONE.add(BigInteger.ONE)) : depth; - depth = depth.equals(BigInteger.valueOf(-1)) ? BigInteger.valueOf(Integer.MAX_VALUE) : depth; - long maxDepth = depth.longValue(); - checkDepthParameter(depth); - - try - { - NodeRef folderNodeRef = cmisService.getFolder(folderId); - Stack descedantsStack = new Stack(); - CmisObjectInFolderContainerType objectInFolderContainer = createObjectInFolderContainer(folderNodeRef, - propertyFilter, includeAllowableActions, includeRelationships, renditionFilter, includePathSegments); - NodeRef[] children = cmisService.getChildren(folderNodeRef, types, null); - for (NodeRef childRef : children) - { - descedantsStack.push(new RecursiveElement(objectInFolderContainer, 1, childRef)); - } - while (!descedantsStack.isEmpty()) - { - RecursiveElement element = descedantsStack.pop(); - CmisObjectInFolderContainerType currentContainer = createObjectInFolderContainer(element - .getCurrentNodeRef(), propertyFilter, includeAllowableActions, includeRelationships, - renditionFilter, includePathSegments); - element.getParentContainerType().getChildren().add(currentContainer); - if (element.getDepth() <= maxDepth) - { - children = cmisService.getChildren(element.getCurrentNodeRef(), types, null); - if (children != null) - { - for (NodeRef childRef : children) - { - descedantsStack.push(new RecursiveElement(currentContainer, element.getDepth() + 1, - childRef)); - } - } - } - } - return objectInFolderContainer; - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - private CmisObjectInFolderContainerType createObjectInFolderContainer(NodeRef nodeRef, PropertyFilter filter, Boolean includeAllowableActions, - EnumIncludeRelationships includeRelationships, String renditionFilter, Boolean includePathSegments) throws CmisException - { - CmisObjectType cmisObject = createCmisObject(nodeRef, filter, includeRelationships, includeAllowableActions, - renditionFilter); - - CmisObjectInFolderType objectInFolderType = new CmisObjectInFolderType(); - objectInFolderType.setObject(cmisObject); - if (includePathSegments != null && includePathSegments) - { - String path; - try - { - path = propertiesUtil.getProperty(nodeRef, CMISDictionaryModel.PROP_NAME, ""); - } - catch (CMISInvalidArgumentException e) - { - throw ExceptionUtil.createCmisException(e); - } - objectInFolderType.setPathSegment(path); - } - CmisObjectInFolderContainerType result = new CmisObjectInFolderContainerType(); - result.setObjectInFolder(objectInFolderType); - return result; - } - - private void checkDepthParameter(BigInteger depth) throws CmisException - { - if (depth.equals(BigInteger.ZERO) || (depth.compareTo(FULL_DESCENDANTS_HIERARCHY_CONDITION) < EQUALS_CONDITION_VALUE)) - { - throw ExceptionUtil.createCmisException("The specified descendants depth is not valid. Valid depth values are: -1 (full hierarchy), N > 0", - EnumServiceException.INVALID_ARGUMENT); - } - } - - private List receiveObjectParents(NodeRef objectId) throws CmisException - { - List parents = new LinkedList(); - for (ChildAssociationRef childParentAssociation : nodeService.getParentAssocs(objectId)) - { - NodeRef parentRef = childParentAssociation.getParentRef(); - if (!parentRef.equals(nodeService.getRootNode(parentRef.getStoreRef()))) - { - parents.add(parentRef); - } - } - return parents; - } - - private class RecursiveElement - { - private CmisObjectInFolderContainerType parentContainerType; - private int depth; - private NodeRef currentNodeRef; - - public RecursiveElement(CmisObjectInFolderContainerType parentContainerType, int depth, NodeRef currentNodeRef) - { - this.parentContainerType = parentContainerType; - this.depth = depth; - this.currentNodeRef = currentNodeRef; - } - - public CmisObjectInFolderContainerType getParentContainerType() - { - return parentContainerType; - } - - public int getDepth() - { - return depth; - } - - public NodeRef getCurrentNodeRef() - { - return currentNodeRef; - } - } -} diff --git a/source/java/org/alfresco/repo/cmis/ws/DMObjectServicePort.java b/source/java/org/alfresco/repo/cmis/ws/DMObjectServicePort.java deleted file mode 100644 index e0c53d6d3b..0000000000 --- a/source/java/org/alfresco/repo/cmis/ws/DMObjectServicePort.java +++ /dev/null @@ -1,872 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.ws; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Serializable; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.activation.DataHandler; -import javax.xml.ws.Holder; - -import org.alfresco.cmis.CMISConstraintException; -import org.alfresco.cmis.CMISContentStreamAllowedEnum; -import org.alfresco.cmis.CMISDictionaryModel; -import org.alfresco.cmis.CMISInvalidArgumentException; -import org.alfresco.cmis.CMISScope; -import org.alfresco.cmis.CMISServiceException; -import org.alfresco.cmis.CMISTypeDefinition; -import org.alfresco.cmis.CMISVersioningStateEnum; -import org.alfresco.cmis.PropertyFilter; -import org.alfresco.repo.cmis.ws.DeleteTreeResponse.FailedToDelete; -import org.alfresco.repo.cmis.ws.utils.ExceptionUtil; -import org.alfresco.repo.web.util.paging.Cursor; -import org.alfresco.service.cmr.dictionary.AssociationDefinition; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.model.FileExistsException; -import org.alfresco.service.cmr.model.FileInfo; -import org.alfresco.service.cmr.model.FileNotFoundException; -import org.alfresco.service.cmr.repository.AssociationRef; -import org.alfresco.service.cmr.repository.ContentReader; -import org.alfresco.service.cmr.repository.ContentWriter; -import org.alfresco.service.cmr.repository.FileTypeImageSize; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.QName; - -/** - * Port for object service - * - * @author Dmitry Lazurkin - * @author Dmitry Velichkevich - */ -@javax.jws.WebService(name = "ObjectServicePort", serviceName = "ObjectService", portName = "ObjectServicePort", targetNamespace = "http://docs.oasis-open.org/ns/cmis/ws/200908/", endpointInterface = "org.alfresco.repo.cmis.ws.ObjectServicePort") -public class DMObjectServicePort extends DMAbstractServicePort implements ObjectServicePort -{ - private static final Map VERSIONING_STATE_ENUM_MAPPING; - - private DictionaryService dictionaryService; - - private FileTypeIconRetriever iconRetriever; - - static - { - VERSIONING_STATE_ENUM_MAPPING = new HashMap(7); - VERSIONING_STATE_ENUM_MAPPING.put(EnumVersioningState.NONE, CMISVersioningStateEnum.NONE); - VERSIONING_STATE_ENUM_MAPPING.put(EnumVersioningState.CHECKEDOUT, CMISVersioningStateEnum.CHECKED_OUT); - VERSIONING_STATE_ENUM_MAPPING.put(EnumVersioningState.MAJOR, CMISVersioningStateEnum.MAJOR); - VERSIONING_STATE_ENUM_MAPPING.put(EnumVersioningState.MINOR, CMISVersioningStateEnum.MINOR); - } - - public void setDictionaryService(DictionaryService dictionaryService) - { - this.dictionaryService = dictionaryService; - } - - /** - * Creates a document object of the specified type, and optionally adds the document to a folder - * - * @param repositoryId repository Id - * @param properties CMIS properties - * @param folderId parent folder for this new document - * @param contentStream content stream - * @param versioningState versioning state (checkedout, minor, major) - * @return Id of the created document object - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, CONSTRAINT, STORAGE, - * STREAM_NOT_SUPPORTED) - */ - public void createDocument(String repositoryId, CmisPropertiesType properties, String folderId, CmisContentStreamType contentStream, EnumVersioningState versioningState, - List policies, CmisAccessControlListType addACEs, CmisAccessControlListType removeACEs, Holder extension, Holder objectId) - throws CmisException - { - checkRepositoryId(repositoryId); - try - { - NodeRef parentNodeRef = cmisService.getFolder(folderId); - Map propertiesMap = propertiesUtil.getPropertiesMap(properties); - String typeId = extractAndAssertTypeId(propertiesMap); - CMISTypeDefinition typeDef = cmisService.getTypeDefinition(typeId); - String documentName = checkConstraintsAndGetName(typeId, typeDef, parentNodeRef, contentStream, propertiesMap, versioningState); - NodeRef newDocumentNodeRef = fileFolderService.create(parentNodeRef, documentName, typeDef.getTypeId().getQName()).getNodeRef(); - - if (null != contentStream) - { - ContentWriter writer = fileFolderService.getWriter(newDocumentNodeRef); - String mimeType = (String) propertiesMap.get(CMISDictionaryModel.PROP_CONTENT_STREAM_MIME_TYPE); - mimeType = (null == mimeType) ? (contentStream.getMimeType()) : (mimeType); - if (null != mimeType) - { - writer.setMimetype(mimeType); - } - InputStream inputstream = null; - try - { - inputstream = contentStream.getStream().getInputStream(); - } - catch (IOException e) - { - throw ExceptionUtil.createCmisException(e.getMessage(), EnumServiceException.RUNTIME, e); - } - writer.putContent(inputstream); - } - PropertyFilter propertyFilter = createPropertyFilter(createIgnoringFilter(new String[] { CMISDictionaryModel.PROP_NAME, CMISDictionaryModel.PROP_OBJECT_TYPE_ID })); - appendDataToDocument(newDocumentNodeRef, properties, versioningState, policies, addACEs, removeACEs, objectId, propertyFilter); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - if (null == properties) - { - throw ExceptionUtil.createCmisException("Properties input parameter is Mandatory", EnumServiceException.INVALID_ARGUMENT); - } - } - - /** - * Creates a document object as a copy of the given source document in the specified location - * - * @param repositoryId repository Id - * @param properties CMIS properties - * @param folderId parent folder for this new document - * @param contentStream content stream - * @param versioningState versioning state (checkedout, minor, major) - * @return Id of the created document object - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, CONSTRAINT, STORAGE, - * STREAM_NOT_SUPPORTED) - */ - public void createDocumentFromSource(String repositoryId, String sourceId, CmisPropertiesType properties, String folderId, EnumVersioningState versioningState, - List policies, CmisAccessControlListType addACEs, CmisAccessControlListType removeACEs, Holder extension, Holder objectId) - throws CmisException - { - checkRepositoryId(repositoryId); - try - { - NodeRef folderNodeRef = cmisService.getFolder(folderId); - NodeRef sourceNodeRef = cmisService.getReadableObject(sourceId, NodeRef.class); - String name = propertiesUtil.getCmisPropertyValue(properties, CMISDictionaryModel.PROP_NAME, null); - if (name == null) - { - name = propertiesUtil.getProperty(sourceNodeRef, CMISDictionaryModel.PROP_NAME, null); - } - NodeRef newDocumentNodeRef; - try - { - newDocumentNodeRef = fileFolderService.copy(sourceNodeRef, folderNodeRef, name).getNodeRef(); - } - catch (FileExistsException e) - { - throw ExceptionUtil.createCmisException("Document already exists", EnumServiceException.NAME_CONSTRAINT_VIOLATION); - } - catch (FileNotFoundException e) - { - throw ExceptionUtil.createCmisException("Source document not found", EnumServiceException.INVALID_ARGUMENT); - } - PropertyFilter propertyFilter = createPropertyFilter(createIgnoringFilter(new String[] { CMISDictionaryModel.PROP_OBJECT_TYPE_ID })); - appendDataToDocument(newDocumentNodeRef, properties, versioningState, policies, addACEs, removeACEs, objectId, propertyFilter); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - /** - * Creates a folder object of the specified type. - * - * @param repositoryId repository Id - * @param properties CMIS properties - * @param folderId parent folder for this new folder - * @return Id of the created folder object - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, CONSTRAINT, STORAGE) - */ - - public void createFolder(String repositoryId, CmisPropertiesType properties, String folderId, List policies, CmisAccessControlListType addACEs, - CmisAccessControlListType removeACEs, Holder extension, Holder objectId) throws CmisException - { - checkRepositoryId(repositoryId); - try - { - NodeRef folderNodeRef = cmisService.getFolder(folderId); - Map propertiesMap = propertiesUtil.getPropertiesMap(properties); - String typeId = extractAndAssertTypeId(propertiesMap); - CMISTypeDefinition type = cmisService.getTypeDefinition(typeId); - if (type == null || type.getTypeId() == null || type.getTypeId().getScope() != CMISScope.FOLDER) - { - throw ExceptionUtil.createCmisException("The typeID is not an Object-Type whose baseType is 'Folder': " + typeId, EnumServiceException.CONSTRAINT); - } - - String name = propertiesUtil.getCmisPropertyValue(properties, CMISDictionaryModel.PROP_NAME, null); - if (null == name) - { - throw ExceptionUtil.createCmisException("Name property not found", EnumServiceException.INVALID_ARGUMENT); - } - - NodeRef newFolderNodeRef = fileFolderService.create(folderNodeRef, name, type.getTypeId().getQName()).getNodeRef(); - propertiesUtil.setProperties(newFolderNodeRef, properties, createPropertyFilter(createIgnoringFilter(new String[] { CMISDictionaryModel.PROP_NAME, - CMISDictionaryModel.PROP_OBJECT_TYPE_ID }))); - applyAclCarefully(newFolderNodeRef, addACEs, removeACEs, EnumACLPropagation.PROPAGATE, policies); - objectId.value = propertiesUtil.getProperty(newFolderNodeRef, CMISDictionaryModel.PROP_OBJECT_ID, null); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - /** - * Creates a policy object of the specified type, and optionally adds the policy to a folder. - * - * @param repositoryId repository Id - * @param properties CMIS properties - * @param folderId parent folder for this new policy - * @return Id of the created policy object - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, CONSTRAINT, STORAGE) - */ - public void createPolicy(String repositoryId, CmisPropertiesType properties, String folderId, List policies, CmisAccessControlListType addACEs, - CmisAccessControlListType removeACEs, Holder extension, Holder objectId) throws CmisException - { - checkRepositoryId(repositoryId); - try - { - objectId.value = cmisService.createPolicy(propertiesUtil.getPropertiesMap(properties), folderId, policies); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - /** - * Creates a relationship object of the specified type. - * - * @param repositoryId repository Id - * @param typeId relationship type - * @param properties CMIS properties - * @param sourceObjectId source object Id - * @param targetObjectId target object Id - * @return Id of the created relationship object - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, CONSTRAINT, STORAGE) - */ - public void createRelationship(String repositoryId, CmisPropertiesType properties, List policies, CmisAccessControlListType addACEs, - CmisAccessControlListType removeACEs, Holder extension, Holder objectId) throws CmisException - { - // TODO: process Policies - - Map propertiesMap = propertiesUtil.getPropertiesMap(properties); - String sourceObjectId = (String) propertiesMap.get(CMISDictionaryModel.PROP_SOURCE_ID); - String targetObjectId = (String) propertiesMap.get(CMISDictionaryModel.PROP_TARGET_ID); - - checkRepositoryId(repositoryId); - - try - { - NodeRef sourceNodeRef = cmisService.getObject(sourceObjectId, NodeRef.class, true, false, false); - NodeRef targetNodeRef = cmisService.getObject(targetObjectId, NodeRef.class, true, false, false); - - String typeId = (String) propertiesMap.get(CMISDictionaryModel.PROP_OBJECT_TYPE_ID); - - CMISTypeDefinition relationshipType = cmisService.getTypeDefinition(typeId); - if (relationshipType == null || relationshipType.getTypeId() == null || relationshipType.getTypeId().getScope() != CMISScope.RELATIONSHIP) - { - throw ExceptionUtil.createCmisException(typeId, EnumServiceException.INVALID_ARGUMENT); - } - - CMISTypeDefinition sourceType = cmisService.getTypeDefinition(sourceNodeRef); - CMISTypeDefinition targetType = cmisService.getTypeDefinition(targetNodeRef); - - QName relationshipTypeQName = relationshipType.getTypeId().getQName(); - AssociationDefinition associationDef = dictionaryService.getAssociation(relationshipTypeQName); - if (associationDef != null) - { - if (!dictionaryService.isSubClass(nodeService.getType(sourceNodeRef), associationDef.getSourceClass().getName())) - { - throw ExceptionUtil.createCmisException("Source object type isn't allowed as source type", EnumServiceException.CONSTRAINT); - } - if (!dictionaryService.isSubClass(nodeService.getType(targetNodeRef), associationDef.getTargetClass().getName())) - { - throw ExceptionUtil.createCmisException("Target object type isn't allowed as target type", EnumServiceException.CONSTRAINT); - } - - // Check ACL arguments - if (addACEs != null && !addACEs.getPermission().isEmpty() || removeACEs != null && !removeACEs.getPermission().isEmpty()) - { - throw ExceptionUtil.createCmisException("ACLs are not supported for type: " + relationshipType.getDisplayName(), EnumServiceException.CONSTRAINT); - } - - AssociationRef assocRef = nodeService.createAssociation(sourceNodeRef, targetNodeRef, relationshipTypeQName); - String createdId = (String) cmisService.getProperty(assocRef, CMISDictionaryModel.PROP_OBJECT_ID); - - // Try applying policies - applyPolicies(createdId, policies); - - objectId.value = createdId; - } - else - { - throw ExceptionUtil.createCmisException((relationshipType.getTypeId().getQName() + " Relationship type not found"), EnumServiceException.INVALID_ARGUMENT); - } - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - /** - * Deletes the content-stream of the specified document. This does not delete properties. If there are other versions this does not affect them, their properties or content. - * This does not change the ID of the document. - * - * @param repositoryId repository Id - * @param objectId document Id - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, CONSTRAINT, STORAGE, - * UPDATE_CONFLICT, VERSIONING) - */ - public void deleteContentStream(String repositoryId, Holder objectId, Holder changeToken, Holder extension) throws CmisException - { - // TODO: Process changeToken - checkRepositoryId(repositoryId); - try - { - cmisService.deleteContentStream(objectId.value); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - /** - * Deletes specified object. - * - * @param repositoryId repository Id - * @param objectId object Id - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, CONSTRAINT, - * UPDATE_CONFLICT) - */ - public void deleteObject(String repositoryId, String objectId, Boolean allVersions, Holder extension) throws CmisException - { - checkRepositoryId(repositoryId); - try - { - cmisService.deleteObject(objectId, allVersions == null || allVersions); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - /** - * Deletes the tree rooted at specified folder (including that folder) - * - * @param repositoryId repository Id - * @param folderId folder Id - * @param unfileNonfolderObjects unfile : unfile all non-folder objects from folders in this tree. They may remain filed in other folders, or may become unfiled, - * deletesinglefiled : delete non-folder objects filed only in this tree, and unfile the others so they remain filed in other folders, delete : delete all non-folder - * objects in this tree (Default) - * @param continueOnFailure flag - * @return collection of object IDs that failed to delete (if continueOnFailure is FALSE, then single object ID) - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, UPDATE_CONFLICT) - */ - public FailedToDelete deleteTree(String repositoryId, String folderId, Boolean allVersions, EnumUnfileObject unfileObject, Boolean continueOnFailure, - CmisExtensionType extension) throws CmisException - { - // TODO: Process allVersions - checkRepositoryId(repositoryId); - checkUnfilingIsNotRequested(unfileObject); - - List failedToDelete; - try - { - failedToDelete = cmisService.deleteTree(folderId, continueOnFailure == null ? false : continueOnFailure, unfileObject != EnumUnfileObject.DELETE, allVersions == null || allVersions); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - FailedToDelete response = new FailedToDelete(); - response.getObjectIds().addAll(failedToDelete); - return response; - } - - /** - * Gets the specified object - * - * @param repositoryId repository Id - * @param folderPath The path to the folder - * @param filter property filter - * @return list of properties for the Folder - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND) - */ - // FIXME: createCmisObject instead of manual set-upping - public CmisObjectType getObject(String repositoryId, String objectId, String filter, Boolean includeAllowableActions, EnumIncludeRelationships includeRelationships, - String renditionFilter, Boolean includePolicyIds, Boolean includeACL, CmisExtensionType extension) throws CmisException - { - checkRepositoryId(repositoryId); - - try - { - Object object = cmisService.getReadableObject(objectId, Object.class); - PropertyFilter propertyFilter = createPropertyFilter(filter); - CmisObjectType cmisObject = createCmisObject(object, propertyFilter, includeRelationships, - includeAllowableActions, renditionFilter); - - Object versionSeries = cmisService.getVersionSeries(objectId, Object.class, false); - boolean includeAcl = (null != includeACL) ? (includeACL.booleanValue()) : (false); - if (includeAcl && (versionSeries instanceof NodeRef)) - { - appendWithAce((NodeRef) versionSeries, cmisObject); - } - - return cmisObject; - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - /** - * Gets the specified object by path - * - * @param repositoryId repository Id - * @param folderPath The path to the folder - * @param filter property filter - * @return list of properties for the Folder - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND) - */ - public CmisObjectType getObjectByPath(String repositoryId, String path, String filter, Boolean includeAllowableActions, EnumIncludeRelationships includeRelationships, - String renditionFilter, Boolean includePolicyIds, Boolean includeACL, CmisExtensionType extension) throws CmisException - { - checkRepositoryId(repositoryId); - NodeRef objectNodeRef = resolvePathInfo(path); - if (null == objectNodeRef) - { - throw ExceptionUtil.createCmisException("Path to Folder was not specified or Folder Path is invalid", EnumServiceException.OBJECT_NOT_FOUND); - } - PropertyFilter propertyFilter = createPropertyFilter(filter); - CmisObjectType object = createCmisObject(objectNodeRef, propertyFilter, includeRelationships, - includeAllowableActions, renditionFilter); - boolean includeAcl = (null != includeACL) ? (includeACL.booleanValue()) : (false); - if (includeAcl) - { - appendWithAce(objectNodeRef, object); - } - // TODO: process relationships - - return object; - } - - /** - * Gets the list of allowable actions (CMIS service calls) for an object based on the current user's context, subject to any access constraints that are currently imposed by - * the repository. - * - * @param repositoryId repository Id - * @param objectId object Id - * @return list of allowable actions - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME) - */ - public CmisAllowableActionsType getAllowableActions(String repositoryId, String objectId, CmisExtensionType extension) throws CmisException - { - checkRepositoryId(repositoryId); - Object object; - try - { - object = cmisService.getReadableObject(objectId, Object.class); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - return determineObjectAllowableActions(object); - } - - /** - * Gets the content-stream for a document. - * - * @param repositoryId repository Id - * @param documentId document to return the content-stream - * @return content stream - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, STREAM_NOT_SUPPORTED) - */ - public CmisContentStreamType getContentStream(String repositoryId, String objectId, String streamId, BigInteger offset, BigInteger length, CmisExtensionType extension) - throws CmisException - { - checkRepositoryId(repositoryId); - try - { - NodeRef nodeRef = cmisService.getReadableObject(objectId, NodeRef.class); - CMISTypeDefinition typeDefinition = cmisService.getTypeDefinition(nodeRef); - if (CMISContentStreamAllowedEnum.NOT_ALLOWED == typeDefinition.getContentStreamAllowed()) - { - throw ExceptionUtil.createCmisException("Content stream not allowed", EnumServiceException.STREAM_NOT_SUPPORTED); - } - - String filename = propertiesUtil.getProperty(nodeRef, CMISDictionaryModel.PROP_NAME, null); - - ContentReaderDataSource dataSource = null; - if (streamId != null && streamId.length() > 0) - { - FileTypeImageSize streamIcon = null; - if (streamId.equals("alf:icon16")) - { - streamIcon = FileTypeImageSize.Small; - } - else if (streamId.equals("alf:icon32")) - { - streamIcon = FileTypeImageSize.Medium; - } - if (streamIcon != null) - { - InputStream iconInputStream = iconRetriever.getIconContent(filename, streamIcon); - String iconMimetype = iconRetriever.getIconMimetype(filename, streamIcon); - if (iconInputStream != null && iconMimetype != null) - { - dataSource = new ContentReaderDataSource(iconInputStream, iconMimetype, filename, offset, length); - } - } - else - { - NodeRef renditionNodeRef = new NodeRef(streamId); - ContentReader reader = safeGetContentReader(renditionNodeRef); - dataSource = new ContentReaderDataSource(reader, filename, offset, length, reader.getSize()); - } - } - else - { - ContentReader reader = safeGetContentReader(nodeRef); - dataSource = new ContentReaderDataSource(reader, filename, offset, length, reader.getSize()); - } - - CmisContentStreamType response = new CmisContentStreamType(); - - response.setFilename(filename); - - if (dataSource != null) - { - response.setMimeType(dataSource.getContentType()); - response.setStream(new DataHandler(dataSource)); - response.setLength(BigInteger.valueOf(dataSource.getSizeToRead())); - } - - return response; - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - /** - * Moves the specified filed object from one folder to another - * - * @param repositoryId repository Id - * @param objectId object Id - * @param targetFolderId the target folder to be moved into - * @param sourceFolderId the source folder to be moved out of - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, CONSTRAINT, STORAGE, - * UPDATE_CONFLICT, VERSIONING) - */ - public void moveObject(String repositoryId, Holder objectId, String targetFolderId, String sourceFolderId, Holder extension) throws CmisException - { - checkRepositoryId(repositoryId); - try - { - cmisService.moveObject(objectId.value, targetFolderId, sourceFolderId); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - /** - * Sets (creates or replaces) the content-stream for the specified document object. - * - * @param repositoryId repository Id - * @param objectId document Id - * @param overwriteFlag flag - * @param contentStream content stream - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, CONSTRAINT, - * CONTENT_ALREADY_EXISTS, STORAGE, STREAM_NOT_SUPPORTED, UPDATE_CONFLICT, VERSIONING) - */ - - public void setContentStream(String repositoryId, Holder objectId, Boolean overwriteFlag, Holder changeToken, CmisContentStreamType contentStream, - Holder extension) throws CmisException - { - checkRepositoryId(repositoryId); - try - { - cmisService.setContentStream(objectId.value, null, overwriteFlag == null || overwriteFlag, contentStream.getStream().getInputStream(), contentStream.getMimeType()); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - catch (Exception e) - { - throw ExceptionUtil.createCmisException(e.getMessage(), EnumServiceException.RUNTIME, e); - } - } - - /** - * Updates properties of the specified object. As per the data model, content-streams are not properties. - * - * @param repositoryId repository Id - * @param objectId object Id - * @param changeToken change token - * @param properties list of properties to update - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, CONSTRAINT, - * UPDATE_CONFLICT, VERSIONING) - */ - public void updateProperties(String repositoryId, Holder objectId, Holder changeToken, CmisPropertiesType properties, Holder extension) - throws CmisException - { - checkRepositoryId(repositoryId); - - NodeRef objectNodeRef; - try - { - objectNodeRef = cmisService.getObject(objectId.value, NodeRef.class, true, false, false); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - propertiesUtil.setProperties(objectNodeRef, properties, null); - } - - /** - * Gets the properties of an object, and optionally the operations that the user is allowed to perform on the object. - * - * @param parameters - * @return collection collection of CmisObjectType - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, FOLDER_NOT_VALID) - */ - public CmisPropertiesType getProperties(String repositoryId, String objectId, String filter, CmisExtensionType extension) throws CmisException - { - checkRepositoryId(repositoryId); - - PropertyFilter propertyFilter = createPropertyFilter(filter); - - Object identifierInstance; - try - { - identifierInstance = cmisService.getReadableObject(objectId, Object.class); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - CmisPropertiesType result = propertiesUtil.getProperties(identifierInstance, propertyFilter); - - return result; - } - - /** - * Gets the renditions of an object, and optionally the operations that the user is allowed to perform on the object. - * - * @param parameters - * @return collection collection of CmisObjectType - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, FOLDER_NOT_VALID) - */ - public List getRenditions(String repositoryId, String objectId, String renditionFilter, BigInteger maxItems, BigInteger skipCount, - CmisExtensionType extension) throws CmisException - { - checkRepositoryId(repositoryId); - NodeRef objectNodeRef; - try - { - objectNodeRef = cmisService.getReadableObject(objectId, NodeRef.class); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - List result = new ArrayList(); - List renditions = getRenditions(objectNodeRef, renditionFilter); - if (renditions != null) - { - Cursor cursor = createCursor(renditions.size(), skipCount, maxItems); - for (int index = cursor.getStartRow(); index <= cursor.getEndRow(); index++) - { - result.add(renditions.get(index)); - } - } - return renditions; - } - - private void appendDataToDocument(NodeRef targetDocumentNodeRef, CmisPropertiesType properties, EnumVersioningState versioningState, List policies, - CmisAccessControlListType addACEs, CmisAccessControlListType removeACEs, Holder objectId, PropertyFilter propertyFilter) throws CMISConstraintException, - CmisException, CMISInvalidArgumentException - { - propertiesUtil.setProperties(targetDocumentNodeRef, properties, propertyFilter); - - // Apply the ACL before potentially creating a PWC - applyAclCarefully(targetDocumentNodeRef, addACEs, removeACEs, EnumACLPropagation.PROPAGATE, policies); - - if (versioningState == null) - { - versioningState = EnumVersioningState.MAJOR; - } - - targetDocumentNodeRef = cmisService.applyVersioningState(targetDocumentNodeRef, VERSIONING_STATE_ENUM_MAPPING.get(versioningState)); - objectId.value = targetDocumentNodeRef.toString(); - } - - private String createIgnoringFilter(String[] propertyNames) - { - StringBuilder filter = new StringBuilder(""); - - for (String propertyName : propertyNames) - { - if ((null != propertyName) && !propertyName.equals("")) - { - filter.append(propertyName); - filter.append(PropertyFilter.PROPERTY_NAME_TOKENS_DELIMITER); - } - } - - if (filter.length() > 0) - { - filter.deleteCharAt(filter.length() - 1); - } - - return filter.toString(); - } - - private String extractAndAssertTypeId(Map propertiesMap) throws CmisException - { - String typeId = (String) propertiesMap.get(CMISDictionaryModel.PROP_OBJECT_TYPE_ID); - if ((null == typeId) || "".equals(typeId)) - { - throw ExceptionUtil.createCmisException("Type Id property required", EnumServiceException.INVALID_ARGUMENT); - } - return typeId; - } - - private String checkConstraintsAndGetName(String documentTypeId, CMISTypeDefinition typeDef, NodeRef parentNodeRef, CmisContentStreamType contentStream, - Map propertiesMap, EnumVersioningState versioningState) throws CmisException - { - if ((null == typeDef) || (null == typeDef.getTypeId())) - { - throw ExceptionUtil.createCmisException(("Type with " + documentTypeId + "typeId was not found"), EnumServiceException.RUNTIME); - } - - if ((CMISScope.DOCUMENT != typeDef.getTypeId().getScope()) || !typeDef.isCreatable()) - { - throw ExceptionUtil.createCmisException(("Invalid document type \"" + documentTypeId + "\". This type is not a Creatable Document type"), - EnumServiceException.CONSTRAINT); - } - - if ((null != contentStream) && CMISContentStreamAllowedEnum.NOT_ALLOWED == typeDef.getContentStreamAllowed()) - { - throw ExceptionUtil.createCmisException(("Content stream not allowed for \"" + documentTypeId + "\" document object type"), EnumServiceException.STREAM_NOT_SUPPORTED); - } - else - { - if ((CMISContentStreamAllowedEnum.REQUIRED == typeDef.getContentStreamAllowed()) && (null == contentStream)) - { - throw ExceptionUtil.createCmisException("Content stream for document object of " + documentTypeId + " type is required", EnumServiceException.CONSTRAINT); - } - } - - if (!typeDef.isVersionable() && (null != versioningState)) - { - throw ExceptionUtil.createCmisException(("Verioning for \"" + documentTypeId + "\" document type is not allowed"), EnumServiceException.CONSTRAINT); - } - - CMISTypeDefinition folderTypeDefinition; - try - { - folderTypeDefinition = cmisService.getTypeDefinition(parentNodeRef); - } - catch (CMISInvalidArgumentException e) - { - throw ExceptionUtil.createCmisException(e.getMessage(), EnumServiceException.INVALID_ARGUMENT, e); - } - if ((null != folderTypeDefinition.getAllowedTargetTypes()) && !folderTypeDefinition.getAllowedTargetTypes().isEmpty() - && !folderTypeDefinition.getAllowedTargetTypes().contains(typeDef)) - { - throw ExceptionUtil.createCmisException(("Children of \"" + documentTypeId + "\" type are not allowed for specified folder"), EnumServiceException.CONSTRAINT); - } - - String result = (String) propertiesMap.get(CMISDictionaryModel.PROP_NAME); - if (null == result) - { - throw ExceptionUtil.createCmisException("Name property not found", EnumServiceException.INVALID_ARGUMENT); - } - return result; - } - - private NodeRef resolvePathInfo(String folderPath) throws CmisException - { - NodeRef result = null; - if (null != folderPath) - { - folderPath = folderPath.substring(1); - if ("".equals(folderPath)) - { - result = cmisService.getDefaultRootNodeRef(); - } - else - { - FileInfo fileInfo = null; - try - { - List splitedPath = Arrays.asList(folderPath.split("/")); - fileInfo = fileFolderService.resolveNamePath(cmisService.getDefaultRootNodeRef(), splitedPath); - } - catch (FileNotFoundException e) - { - } - result = (null != fileInfo) ? (fileInfo.getNodeRef()) : (null); - } - } - return result; - } - - private ContentReader safeGetContentReader(NodeRef objectNodeReference) throws CmisException - { - ContentReader reader = fileFolderService.getReader(objectNodeReference); - if (reader == null) - { - throw ExceptionUtil.createCmisException("The specified Document has no Content Stream", EnumServiceException.CONSTRAINT); - } - return reader; - } - - private void checkUnfilingIsNotRequested(EnumUnfileObject unfileNonfolderObjects) throws CmisException - { - if (unfileNonfolderObjects == EnumUnfileObject.UNFILE) - { - throw ExceptionUtil.createCmisException("Unfiling is not supported", EnumServiceException.NOT_SUPPORTED); - } - } - - public void setFileTypeIconRetriever(FileTypeIconRetriever iconRetriever) - { - this.iconRetriever = iconRetriever; - } -} diff --git a/source/java/org/alfresco/repo/cmis/ws/DMPolicyServicePort.java b/source/java/org/alfresco/repo/cmis/ws/DMPolicyServicePort.java deleted file mode 100644 index c9580c7535..0000000000 --- a/source/java/org/alfresco/repo/cmis/ws/DMPolicyServicePort.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.ws; - -import java.util.Collections; -import java.util.List; - -import javax.xml.ws.Holder; - -import org.alfresco.cmis.CMISServiceException; -import org.alfresco.repo.cmis.ws.utils.ExceptionUtil; - -@javax.jws.WebService(name = "PolicyServicePort", serviceName = "PolicyService", portName = "PolicyServicePort", targetNamespace = "http://docs.oasis-open.org/ns/cmis/ws/200908/", endpointInterface = "org.alfresco.repo.cmis.ws.PolicyServicePort") -public class DMPolicyServicePort extends DMAbstractServicePort implements PolicyServicePort -{ - /** - * Applies a policy object to a target object. - * - * @param repositoryId repository Id - * @param policyId policy Id - * @param objectId target object Id - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, CONSTRAINT) - */ - public void applyPolicy(String repositoryId, String policyId, String objectId, Holder extension) throws CmisException - { - checkRepositoryId(repositoryId); - try - { - cmisService.applyPolicy(policyId, objectId); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - /** - * Gets the list of policy objects currently applied to a target object. - * - * @param parameters repositoryId: repository Id; objectId: target object Id; filter: filter specifying which properties to return - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, FILTER_NOT_VALID) - */ - public List getAppliedPolicies(String repositoryId, String objectId, String filter, CmisExtensionType extension) throws CmisException - { - checkRepositoryId(repositoryId); - try - { - cmisService.getAppliedPolicies(objectId, filter); - return Collections.emptyList(); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - /** - * Removes a previously applied policy from a target object. The policy object is not deleted, and may still be applied to other objects. - * - * @param repositoryId repository Id - * @param policyId policy Id - * @param objectId target object Id. - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, CONSTRAINT) - */ - public void removePolicy(String repositoryId, String policyId, String objectId, Holder extension) throws CmisException - { - checkRepositoryId(repositoryId); - try - { - cmisService.removePolicy(policyId, objectId); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } -} diff --git a/source/java/org/alfresco/repo/cmis/ws/DMRelationshipServicePort.java b/source/java/org/alfresco/repo/cmis/ws/DMRelationshipServicePort.java deleted file mode 100644 index 9b761e7230..0000000000 --- a/source/java/org/alfresco/repo/cmis/ws/DMRelationshipServicePort.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.ws; - -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Map; - -import org.alfresco.cmis.CMISRelationshipDirectionEnum; -import org.alfresco.cmis.CMISServiceException; -import org.alfresco.cmis.CMISTypeDefinition; -import org.alfresco.cmis.PropertyFilter; -import org.alfresco.repo.cmis.ws.utils.ExceptionUtil; -import org.alfresco.repo.web.util.paging.Cursor; -import org.alfresco.service.cmr.repository.AssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; - -/** - * Port for relationship service - * - * @author Dmitry Velichkevich - */ -@javax.jws.WebService(name = "RelationshipServicePort", serviceName = "RelationshipService", portName = "RelationshipServicePort", targetNamespace = "http://docs.oasis-open.org/ns/cmis/ws/200908/", endpointInterface = "org.alfresco.repo.cmis.ws.RelationshipServicePort") -public class DMRelationshipServicePort extends DMAbstractServicePort implements RelationshipServicePort -{ - private static final Map RELATIONSHIP_DIRECTION_MAPPING; - static - { - RELATIONSHIP_DIRECTION_MAPPING = new HashMap(5); - RELATIONSHIP_DIRECTION_MAPPING.put(EnumRelationshipDirection.SOURCE, CMISRelationshipDirectionEnum.SOURCE); - RELATIONSHIP_DIRECTION_MAPPING.put(EnumRelationshipDirection.TARGET, CMISRelationshipDirectionEnum.TARGET); - RELATIONSHIP_DIRECTION_MAPPING.put(EnumRelationshipDirection.EITHER, CMISRelationshipDirectionEnum.EITHER); - } - - /** - * Gets a list of relationships associated with the object, optionally of a specified relationship type, and optionally in a specified direction. - * - * @param parameters repositoryId: Repository Id, objectId: The object with which relationships are associated with; direction: source (Default), target, both; typeId: - * Relationship Type; includeSubRelationshipTypes: false (Default); filter: property filter; includeAllowableActions: false (default); maxItems: 0 = Unlimited; - * skipCount: 0 = start at beginning - * @return collection of CmisObjectType and boolean hasMoreItems - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, FILTER_NOT_VALID) - */ - public CmisObjectListType getObjectRelationships(String repositoryId, String objectId, Boolean includeSubRelationshipTypes, EnumRelationshipDirection relationshipDirection, - String typeId, String filter, Boolean includeAllowableActions, BigInteger maxItems, BigInteger skipCount, CmisExtensionType extension) throws CmisException - { - checkRepositoryId(repositoryId); - if ((null == objectId) || "".equals(objectId) || !NodeRef.isNodeRef(objectId)) - { - throw ExceptionUtil.createCmisException(("Object with Id='" + objectId + "' is not exist!"), EnumServiceException.OBJECT_NOT_FOUND); - } - try - { - CMISTypeDefinition relDef = (null != typeId) ? (cmisService.getTypeDefinition(typeId)):(null); - NodeRef nodeRef = cmisService.getReadableObject(objectId, NodeRef.class); - AssociationRef[] assocs = cmisService.getRelationships(nodeRef, relDef, includeSubRelationshipTypes != null && includeSubRelationshipTypes, - relationshipDirection == null ? CMISRelationshipDirectionEnum.SOURCE : RELATIONSHIP_DIRECTION_MAPPING.get(relationshipDirection)); - skipCount = (null != skipCount) ? skipCount : BigInteger.ZERO; - maxItems = (null != maxItems) ? maxItems : BigInteger.ZERO; - PropertyFilter propertyFilter = createPropertyFilter(filter); - return createResult(propertyFilter, includeAllowableActions, assocs, skipCount, maxItems); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - private CmisObjectListType createResult(PropertyFilter filter, Boolean includeAllowableActions, Object[] sourceArray, BigInteger skipCount, BigInteger maxItems) - throws CmisException - { - Cursor cursor = createCursor(sourceArray.length, skipCount, maxItems); - CmisObjectListType result = new CmisObjectListType(); - for (int i = cursor.getStartRow(); i <= cursor.getEndRow(); i++) - { - result.getObjects().add(createCmisObject(sourceArray[i], filter, null, includeAllowableActions, null)); - } - result.setHasMoreItems(cursor.getEndRow() < sourceArray.length); - result.setNumItems(BigInteger.valueOf(cursor.getPageSize())); - return result; - } -} diff --git a/source/java/org/alfresco/repo/cmis/ws/DMRepositoryServicePort.java b/source/java/org/alfresco/repo/cmis/ws/DMRepositoryServicePort.java deleted file mode 100644 index 2b94f0ca6e..0000000000 --- a/source/java/org/alfresco/repo/cmis/ws/DMRepositoryServicePort.java +++ /dev/null @@ -1,672 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.ws; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.alfresco.cmis.CMISAclCapabilityEnum; -import org.alfresco.cmis.CMISAclPropagationEnum; -import org.alfresco.cmis.CMISAclSupportedPermissionEnum; -import org.alfresco.cmis.CMISBaseObjectTypeIds; -import org.alfresco.cmis.CMISCapabilityChanges; -import org.alfresco.cmis.CMISCardinalityEnum; -import org.alfresco.cmis.CMISChoice; -import org.alfresco.cmis.CMISContentStreamAllowedEnum; -import org.alfresco.cmis.CMISDataTypeEnum; -import org.alfresco.cmis.CMISDictionaryModel; -import org.alfresco.cmis.CMISInvalidArgumentException; -import org.alfresco.cmis.CMISJoinEnum; -import org.alfresco.cmis.CMISPermissionDefinition; -import org.alfresco.cmis.CMISPermissionMapping; -import org.alfresco.cmis.CMISPropertyDefinition; -import org.alfresco.cmis.CMISQueryEnum; -import org.alfresco.cmis.CMISServiceException; -import org.alfresco.cmis.CMISTypeDefinition; -import org.alfresco.cmis.CMISUpdatabilityEnum; -import org.alfresco.repo.cmis.ws.utils.ExceptionUtil; -import org.alfresco.repo.web.util.paging.Cursor; -import org.alfresco.service.descriptor.Descriptor; - -/** - * Port for repository service. - * - * @author Dmitry Lazurkin - */ -@javax.jws.WebService(name = "RepositoryServicePort", serviceName = "RepositoryService", portName = "RepositoryServicePort", targetNamespace = "http://docs.oasis-open.org/ns/cmis/ws/200908/", endpointInterface = "org.alfresco.repo.cmis.ws.RepositoryServicePort") -public class DMRepositoryServicePort extends DMAbstractServicePort implements RepositoryServicePort -{ - private static final Map JOIN_ENUM_MAPPING; - private static final Map CONTENT_STREAM_ALLOWED_ENUM_MAPPING; - private static final Map UPDATABILITY_ENUM_MAPPING; - private static final Map CARDINALITY_ENUM_MAPPING; - private static final Map PROPERTY_TYPE_ENUM_MAPPING; - private static final Map QUERY_TYPE_ENUM_MAPPING; - private static final Map CHANGES_TYPE_ENUM_MAPPING; - private static final Map BASE_IDS_TYPE_ENUM_MAPPING; - private static final Map ACL_CAPABILITY_ENUM_MAPPING; - private static final Map ACL_SUPPORTED_PERMISSION_ENUM_MAPPING; - private static final Map ACL_PROPAGATION_ENUM_MAPPGIN; - - static - { - JOIN_ENUM_MAPPING = new HashMap(); - JOIN_ENUM_MAPPING.put(CMISJoinEnum.INNER_AND_OUTER_JOIN_SUPPORT, EnumCapabilityJoin.INNERANDOUTER); - JOIN_ENUM_MAPPING.put(CMISJoinEnum.INNER_JOIN_SUPPORT, EnumCapabilityJoin.INNERONLY); - JOIN_ENUM_MAPPING.put(CMISJoinEnum.NO_JOIN_SUPPORT, EnumCapabilityJoin.NONE); - - CONTENT_STREAM_ALLOWED_ENUM_MAPPING = new HashMap(); - CONTENT_STREAM_ALLOWED_ENUM_MAPPING.put(CMISContentStreamAllowedEnum.ALLOWED, EnumContentStreamAllowed.ALLOWED); - CONTENT_STREAM_ALLOWED_ENUM_MAPPING.put(CMISContentStreamAllowedEnum.NOT_ALLOWED, EnumContentStreamAllowed.NOTALLOWED); - CONTENT_STREAM_ALLOWED_ENUM_MAPPING.put(CMISContentStreamAllowedEnum.REQUIRED, EnumContentStreamAllowed.REQUIRED); - - UPDATABILITY_ENUM_MAPPING = new HashMap(); - UPDATABILITY_ENUM_MAPPING.put(CMISUpdatabilityEnum.READ_AND_WRITE, EnumUpdatability.READWRITE); - UPDATABILITY_ENUM_MAPPING.put(CMISUpdatabilityEnum.READ_AND_WRITE_WHEN_CHECKED_OUT, EnumUpdatability.WHENCHECKEDOUT); - UPDATABILITY_ENUM_MAPPING.put(CMISUpdatabilityEnum.READ_ONLY, EnumUpdatability.READONLY); - UPDATABILITY_ENUM_MAPPING.put(CMISUpdatabilityEnum.ON_CREATE, EnumUpdatability.ONCREATE); - - CARDINALITY_ENUM_MAPPING = new HashMap(); - CARDINALITY_ENUM_MAPPING.put(CMISCardinalityEnum.MULTI_VALUED, EnumCardinality.MULTI); - CARDINALITY_ENUM_MAPPING.put(CMISCardinalityEnum.SINGLE_VALUED, EnumCardinality.SINGLE); - - PROPERTY_TYPE_ENUM_MAPPING = new HashMap(); - PROPERTY_TYPE_ENUM_MAPPING.put(CMISDataTypeEnum.BOOLEAN, EnumPropertyType.BOOLEAN); - PROPERTY_TYPE_ENUM_MAPPING.put(CMISDataTypeEnum.DATETIME, EnumPropertyType.DATETIME); - PROPERTY_TYPE_ENUM_MAPPING.put(CMISDataTypeEnum.DECIMAL, EnumPropertyType.DECIMAL); - PROPERTY_TYPE_ENUM_MAPPING.put(CMISDataTypeEnum.HTML, EnumPropertyType.HTML); - PROPERTY_TYPE_ENUM_MAPPING.put(CMISDataTypeEnum.ID, EnumPropertyType.ID); - PROPERTY_TYPE_ENUM_MAPPING.put(CMISDataTypeEnum.INTEGER, EnumPropertyType.INTEGER); - PROPERTY_TYPE_ENUM_MAPPING.put(CMISDataTypeEnum.STRING, EnumPropertyType.STRING); - PROPERTY_TYPE_ENUM_MAPPING.put(CMISDataTypeEnum.URI, EnumPropertyType.URI); - - QUERY_TYPE_ENUM_MAPPING = new HashMap(); - QUERY_TYPE_ENUM_MAPPING.put(CMISQueryEnum.BOTH_COMBINED, EnumCapabilityQuery.BOTHCOMBINED); - QUERY_TYPE_ENUM_MAPPING.put(CMISQueryEnum.BOTH_SEPERATE, EnumCapabilityQuery.BOTHSEPARATE); - QUERY_TYPE_ENUM_MAPPING.put(CMISQueryEnum.FULLTEXT_ONLY, EnumCapabilityQuery.FULLTEXTONLY); - QUERY_TYPE_ENUM_MAPPING.put(CMISQueryEnum.METADATA_ONLY, EnumCapabilityQuery.METADATAONLY); - QUERY_TYPE_ENUM_MAPPING.put(CMISQueryEnum.NONE, EnumCapabilityQuery.NONE); - - CHANGES_TYPE_ENUM_MAPPING = new HashMap(); - CHANGES_TYPE_ENUM_MAPPING.put(CMISCapabilityChanges.NONE, EnumCapabilityChanges.NONE); - CHANGES_TYPE_ENUM_MAPPING.put(CMISCapabilityChanges.OBJECTIDSONLY, EnumCapabilityChanges.OBJECTIDSONLY); - - BASE_IDS_TYPE_ENUM_MAPPING = new HashMap(); - BASE_IDS_TYPE_ENUM_MAPPING.put(CMISBaseObjectTypeIds.DOCUMENT, EnumBaseObjectTypeIds.CMIS_DOCUMENT); - BASE_IDS_TYPE_ENUM_MAPPING.put(CMISBaseObjectTypeIds.FOLDER, EnumBaseObjectTypeIds.CMIS_FOLDER); - BASE_IDS_TYPE_ENUM_MAPPING.put(CMISBaseObjectTypeIds.RELATIONSHIP, EnumBaseObjectTypeIds.CMIS_RELATIONSHIP); - BASE_IDS_TYPE_ENUM_MAPPING.put(CMISBaseObjectTypeIds.POLICY, EnumBaseObjectTypeIds.CMIS_POLICY); - - ACL_CAPABILITY_ENUM_MAPPING = new HashMap(); - ACL_CAPABILITY_ENUM_MAPPING.put(CMISAclCapabilityEnum.DISCOVER, EnumCapabilityACL.DISCOVER); - ACL_CAPABILITY_ENUM_MAPPING.put(CMISAclCapabilityEnum.MANAGE, EnumCapabilityACL.MANAGE); - ACL_CAPABILITY_ENUM_MAPPING.put(CMISAclCapabilityEnum.NONE, EnumCapabilityACL.NONE); - - ACL_PROPAGATION_ENUM_MAPPGIN = new HashMap(); - ACL_PROPAGATION_ENUM_MAPPGIN.put(CMISAclPropagationEnum.OBJECT_ONLY, EnumACLPropagation.OBJECTONLY); - ACL_PROPAGATION_ENUM_MAPPGIN.put(CMISAclPropagationEnum.PROPAGATE, EnumACLPropagation.PROPAGATE); - ACL_PROPAGATION_ENUM_MAPPGIN.put(CMISAclPropagationEnum.REPOSITORY_DETERMINED, EnumACLPropagation.REPOSITORYDETERMINED); - - ACL_SUPPORTED_PERMISSION_ENUM_MAPPING = new HashMap(); - ACL_SUPPORTED_PERMISSION_ENUM_MAPPING.put(CMISAclSupportedPermissionEnum.BASIC, EnumSupportedPermissions.BASIC); - ACL_SUPPORTED_PERMISSION_ENUM_MAPPING.put(CMISAclSupportedPermissionEnum.REPOSITORY, EnumSupportedPermissions.REPOSITORY); - ACL_SUPPORTED_PERMISSION_ENUM_MAPPING.put(CMISAclSupportedPermissionEnum.BOTH, EnumSupportedPermissions.BOTH); - } - - private List permissionDefinitions; - private List permissionMapping; - - /** - * Add property definitions to list of definitions - * - * @param propertyDefinition repository property definition - * @param wsPropertyDefs web service property definition - */ - private void addPropertyDefs(CMISTypeDefinition typeDefinition, CMISPropertyDefinition propertyDefinition, List wsPropertyDefs) - throws CmisException - { - CmisPropertyDefinitionType wsPropertyDef = createPropertyDefinitionType(propertyDefinition.getDataType()); - wsPropertyDef.setLocalName(propertyDefinition.getPropertyId().getLocalName()); - wsPropertyDef.setLocalNamespace(propertyDefinition.getPropertyId().getLocalNamespace()); - wsPropertyDef.setId(propertyDefinition.getPropertyId().getId()); - wsPropertyDef.setQueryName(propertyDefinition.getQueryName()); - wsPropertyDef.setDisplayName(propertyDefinition.getDisplayName()); - wsPropertyDef.setDescription(propertyDefinition.getDescription()); - wsPropertyDef.setPropertyType(PROPERTY_TYPE_ENUM_MAPPING.get(propertyDefinition.getDataType())); - wsPropertyDef.setCardinality(CARDINALITY_ENUM_MAPPING.get(propertyDefinition.getCardinality())); - wsPropertyDef.setUpdatability(UPDATABILITY_ENUM_MAPPING.get(propertyDefinition.getUpdatability())); - wsPropertyDef.setInherited(!typeDefinition.getOwnedPropertyDefinitions().containsKey(propertyDefinition.getPropertyId().getId())); - wsPropertyDef.setRequired(propertyDefinition.isRequired()); - wsPropertyDef.setQueryable(propertyDefinition.isQueryable()); - wsPropertyDef.setOrderable(propertyDefinition.isOrderable()); - addChoices(propertyDefinition.getDataType(), propertyDefinition.getChoices(), getChoices(wsPropertyDef)); - wsPropertyDef.setOpenChoice(propertyDefinition.isOpenChoice()); - wsPropertyDefs.add(wsPropertyDef); - } - - /** - * Add root choices to list of choices - * - * @param propertyType type of property - * @param choices repository choice object - * @param cmisChoices web service choice object - */ - private void addChoices(CMISDataTypeEnum propertyType, Collection choices, List cmisChoices) - { - for (CMISChoice choice : choices) - { - CmisChoice cmisChoiceType = getCmisChoiceType(choice, propertyType); - cmisChoices.add(cmisChoiceType); - if (choice.getChildren().isEmpty() == false) - { - addChoiceChildrens(propertyType, choice.getChildren(), cmisChoices); - } - } - } - - @SuppressWarnings("unchecked") - private List getChoices(CmisPropertyDefinitionType propertyDef) - { - List result = null; - if (propertyDef != null) - { - try - { - result = (List) propertyDef.getClass().getMethod("getChoice").invoke(propertyDef); - } - catch (Exception e) - { - } - } - return result; - } - - /** - * Create web service choice object from repository choice object - * - * @param choice repository choice - * @param propertyType type of property - * @return web service choice - */ - private CmisChoice getCmisChoiceType(CMISChoice choice, CMISDataTypeEnum propertyType) - { - CmisChoice result = null; - - switch (propertyType) - { - case BOOLEAN: - CmisChoiceBoolean choiceBooleanType = new CmisChoiceBoolean(); - choiceBooleanType.setDisplayName(choice.getName()); - choiceBooleanType.getValue().add(Boolean.parseBoolean(choice.getValue().toString())); - result = choiceBooleanType; - break; - case DATETIME: - CmisChoiceDateTime choiceDateTimeType = new CmisChoiceDateTime(); - choiceDateTimeType.setDisplayName(choice.getName()); - choiceDateTimeType.getValue().add(propertiesUtil.convert((Date) choice.getValue())); - result = choiceDateTimeType; - break; - case DECIMAL: - CmisChoiceDecimal choiceDecimalType = new CmisChoiceDecimal(); - choiceDecimalType.setDisplayName(choice.getName()); - choiceDecimalType.getValue().add(BigDecimal.valueOf(Double.parseDouble(choice.getValue().toString()))); - result = choiceDecimalType; - break; - case HTML: - break; - case ID: - CmisChoiceId choiceIdType = new CmisChoiceId(); - choiceIdType.setDisplayName(choice.getName()); - choiceIdType.getValue().add(choice.getValue().toString()); - result = choiceIdType; - break; - case INTEGER: - CmisChoiceInteger choiceIntegerType = new CmisChoiceInteger(); - choiceIntegerType.setDisplayName(choice.getName()); - choiceIntegerType.getValue().add(BigInteger.valueOf(Integer.parseInt(choice.getValue().toString()))); - result = choiceIntegerType; - break; - case STRING: - CmisChoiceString choiceStringType = new CmisChoiceString(); - choiceStringType.setDisplayName(choice.getName()); - choiceStringType.getValue().add(choice.getValue().toString()); - result = choiceStringType; - break; - case URI: - break; - } - return result; - } - - /** - * Add choices children to list of JAXBElements - * - * @param propertyType type of property - * @param choices repository choice object - * @param cmisChoices web service choice object - */ - private void addChoiceChildrens(CMISDataTypeEnum propertyType, Collection choices, List cmisChoices) - { - for (CMISChoice choice : choices) - { - CmisChoice cmisChoiceType = getCmisChoiceType(choice, propertyType); - cmisChoices.add(cmisChoiceType); - - if (choice.getChildren().isEmpty() == false) - { - addChoiceChildrens(propertyType, choice.getChildren(), cmisChoices); - } - } - } - - private CmisPropertyDefinitionType createPropertyDefinitionType(CMISDataTypeEnum type) throws CmisException - { - switch (type) - { - case BOOLEAN: - { - return new CmisPropertyBooleanDefinitionType(); - } - case DATETIME: - { - return new CmisPropertyDateTimeDefinitionType(); - } - case DECIMAL: - { - return new CmisPropertyDecimalDefinitionType(); - } - case HTML: - { - return new CmisPropertyHtmlDefinitionType(); - } - case ID: - { - return new CmisPropertyIdDefinitionType(); - } - case INTEGER: - { - return new CmisPropertyIntegerDefinitionType(); - } - case STRING: - { - return new CmisPropertyStringDefinitionType(); - } - case URI: - { - return new CmisPropertyUriDefinitionType(); - } - default: - { - throw ExceptionUtil.createCmisException(type.getLabel(), EnumServiceException.OBJECT_NOT_FOUND); - } - } - } - - /** - * Set properties for web service type definition - * - * @param cmisTypeDefinition web service type definition - * @param typeDefinition repository type definition - * @param includeProperties true if need property definitions for type definition - */ - private void setCmisTypeDefinitionProperties(CmisTypeDefinitionType cmisTypeDefinition, CMISTypeDefinition typeDefinition, boolean includeProperties) throws CmisException - { - cmisTypeDefinition.setId(typeDefinition.getTypeId().getId()); - cmisTypeDefinition.setQueryName(typeDefinition.getQueryName()); - cmisTypeDefinition.setDisplayName(typeDefinition.getDisplayName()); - cmisTypeDefinition.setBaseId(EnumBaseObjectTypeIds.fromValue(typeDefinition.getBaseType().getTypeId().getId())); - cmisTypeDefinition.setLocalNamespace(typeDefinition.getTypeId().getLocalNamespace()); - cmisTypeDefinition.setLocalName(typeDefinition.getTypeId().getLocalName()); - - if ((null != typeDefinition.getParentType()) && (null != typeDefinition.getParentType().getTypeId())) - { - cmisTypeDefinition.setParentId(typeDefinition.getParentType().getTypeId().getId()); - } - - cmisTypeDefinition.setDescription(typeDefinition.getDescription()); - cmisTypeDefinition.setCreatable(typeDefinition.isCreatable()); - cmisTypeDefinition.setFileable(typeDefinition.isFileable()); - cmisTypeDefinition.setQueryable(typeDefinition.isQueryable()); - cmisTypeDefinition.setControllableACL(typeDefinition.isControllableACL()); - cmisTypeDefinition.setControllablePolicy(typeDefinition.isControllablePolicy()); - cmisTypeDefinition.setIncludedInSupertypeQuery(typeDefinition.isIncludedInSuperTypeQuery()); - - if (includeProperties) - { - List propertyDefs = cmisTypeDefinition.getPropertyDefinition(); - for (CMISPropertyDefinition cmisPropDef : typeDefinition.getPropertyDefinitions().values()) - { - addPropertyDefs(typeDefinition, cmisPropDef, propertyDefs); - } - } - } - - /** - * Create web service type definition for typeId - * - * @param typeId type id - * @param includeProperties true if need property definitions for type definition - * @return web service type definition - * @throws CmisException if type id not found - */ - private CmisTypeDefinitionType getCmisTypeDefinition(CMISTypeDefinition typeDef, boolean includeProperties) throws CmisException - { - if (typeDef == null) - { - throw ExceptionUtil.createCmisException("Type not found", EnumServiceException.OBJECT_NOT_FOUND); - } - - CmisTypeDefinitionType result = null; - - switch (typeDef.getTypeId().getScope()) - { - case DOCUMENT: - CmisTypeDocumentDefinitionType documentDefinitionType = new CmisTypeDocumentDefinitionType(); - documentDefinitionType.setVersionable(typeDef.isVersionable()); - documentDefinitionType.setContentStreamAllowed(CONTENT_STREAM_ALLOWED_ENUM_MAPPING.get(typeDef.getContentStreamAllowed())); - result = documentDefinitionType; - break; - case FOLDER: - result = new CmisTypeFolderDefinitionType(); - break; - case POLICY: - result = new CmisTypePolicyDefinitionType(); - break; - case RELATIONSHIP: - CmisTypeRelationshipDefinitionType relationshipDefinitionType = new CmisTypeRelationshipDefinitionType(); - if (typeDef.getAllowedSourceTypes() != null) - { - for (CMISTypeDefinition definition : typeDef.getAllowedSourceTypes()) - { - relationshipDefinitionType.getAllowedSourceTypes().add(definition.getTypeId().getId()); - } - } - if (typeDef.getAllowedTargetTypes() != null) - { - for (CMISTypeDefinition definition : typeDef.getAllowedTargetTypes()) - { - relationshipDefinitionType.getAllowedTargetTypes().add(definition.getTypeId().getId()); - } - } - result = relationshipDefinitionType; - break; - case UNKNOWN: - throw ExceptionUtil.createCmisException("Unknown CMIS Type", EnumServiceException.INVALID_ARGUMENT); - } - if ((null != typeDef.getParentType()) && (null != typeDef.getParentType().getTypeId())) - { - result.setParentId(typeDef.getParentType().getTypeId().getId()); - } - setCmisTypeDefinitionProperties(result, typeDef, includeProperties); - - return result; - } - - /** - * Gets a list of available repositories for this CMIS service endpoint. - * - * @return collection of CmisRepositoryEntryType (repositoryId - repository Id, repositoryName: repository name, repositoryURI: Repository URI) - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME) - */ - public List getRepositories(CmisExtensionType extension) throws CmisException - { - CmisRepositoryEntryType repositoryEntryType = new CmisRepositoryEntryType(); - Descriptor serverDescriptor = descriptorService.getCurrentRepositoryDescriptor(); - repositoryEntryType.setRepositoryId(serverDescriptor.getId()); - repositoryEntryType.setRepositoryName(serverDescriptor.getName()); - - List result = new LinkedList(); - result.add(repositoryEntryType); - return result; - } - - /** - * Gets information about the CMIS repository and the capabilities it supports. - * - * @param parameters repositoryId: repository Id - * @return CMIS repository Info - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME) - */ - public CmisRepositoryInfoType getRepositoryInfo(String repositoryId, CmisExtensionType extension) throws CmisException - { - checkRepositoryId(repositoryId); - - Descriptor currentDescriptor = descriptorService.getCurrentRepositoryDescriptor(); - Descriptor serverDescriptor = descriptorService.getServerDescriptor(); - CmisRepositoryInfoType repositoryInfoType = new CmisRepositoryInfoType(); - repositoryInfoType.setRepositoryId(currentDescriptor.getId()); - repositoryInfoType.setRepositoryName(currentDescriptor.getName()); - repositoryInfoType.setRepositoryDescription(""); - repositoryInfoType.setVendorName("Alfresco"); - repositoryInfoType.setProductName("Alfresco Repository (" + serverDescriptor.getEdition() + ")"); - repositoryInfoType.setProductVersion(currentDescriptor.getVersion()); - try - { - repositoryInfoType.setRootFolderId(propertiesUtil.getProperty(cmisService.getDefaultRootNodeRef(), CMISDictionaryModel.PROP_OBJECT_ID, (String) null)); - } - catch (CMISInvalidArgumentException e) - { - throw ExceptionUtil.createCmisException(e); - } - repositoryInfoType.setLatestChangeLogToken(cmisChangeLogService.getLastChangeLogToken()); - // TODO: cmisVersionSupported is different in stubs and specification - repositoryInfoType.setCmisVersionSupported("1.0"); - repositoryInfoType.setChangesIncomplete(cmisChangeLogService.getChangesIncomplete()); - // TODO: getFolderTree capability - List changesOnTypeCapability = cmisChangeLogService.getChangesOnTypeCapability(); - for (CMISBaseObjectTypeIds baseId : changesOnTypeCapability) - { - repositoryInfoType.getChangesOnType().add(BASE_IDS_TYPE_ENUM_MAPPING.get(baseId)); - } - repositoryInfoType.setPrincipalAnonymous(cmisAclService.getPrincipalAnonymous()); - repositoryInfoType.setPrincipalAnyone(cmisAclService.getPrincipalAnyone()); - - CmisACLCapabilityType aclCapability = new CmisACLCapabilityType(); - aclCapability.setSupportedPermissions(ACL_SUPPORTED_PERMISSION_ENUM_MAPPING.get(cmisAclService.getSupportedPermissions())); - aclCapability.setPropagation(ACL_PROPAGATION_ENUM_MAPPGIN.get(cmisAclService.getAclPropagation())); - aclCapability.getMapping().addAll(getPermissionMapping()); - aclCapability.getPermissions().addAll(getPermissionDefinitions()); - repositoryInfoType.setAclCapability(aclCapability); - - CmisRepositoryCapabilitiesType capabilities = new CmisRepositoryCapabilitiesType(); - capabilities.setCapabilityGetDescendants(true); - capabilities.setCapabilityGetFolderTree(true); - - capabilities.setCapabilityContentStreamUpdatability(EnumCapabilityContentStreamUpdates.ANYTIME); - capabilities.setCapabilityChanges(CHANGES_TYPE_ENUM_MAPPING.get(cmisChangeLogService.getCapability())); - capabilities.setCapabilityRenditions(EnumCapabilityRendition.READ); - - capabilities.setCapabilityMultifiling(true); - capabilities.setCapabilityUnfiling(false); - capabilities.setCapabilityVersionSpecificFiling(false); - - capabilities.setCapabilityPWCUpdatable(true); - capabilities.setCapabilityPWCSearchable(cmisQueryService.getPwcSearchable()); - capabilities.setCapabilityAllVersionsSearchable(cmisQueryService.getAllVersionsSearchable()); - - capabilities.setCapabilityQuery(QUERY_TYPE_ENUM_MAPPING.get(cmisQueryService.getQuerySupport())); - capabilities.setCapabilityJoin(JOIN_ENUM_MAPPING.get(cmisQueryService.getJoinSupport())); - - capabilities.setCapabilityACL(ACL_CAPABILITY_ENUM_MAPPING.get(cmisAclService.getAclCapability())); - - repositoryInfoType.setCapabilities(capabilities); - return repositoryInfoType; - } - - private List getPermissionDefinitions() - { - if (null == permissionDefinitions) - { - permissionDefinitions = new LinkedList(); - for (CMISPermissionDefinition definition : cmisAclService.getRepositoryPermissions()) - { - CmisPermissionDefinition cmisDefinition = new CmisPermissionDefinition(); - cmisDefinition.setDescription(definition.getDescription()); - cmisDefinition.setPermission(definition.getPermission()); - permissionDefinitions.add(cmisDefinition); - } - } - return permissionDefinitions; - } - - private List getPermissionMapping() - { - if (null == permissionMapping) - { - permissionMapping = new LinkedList(); - for (CMISPermissionMapping mapping : cmisAclService.getPermissionMappings()) - { - CmisPermissionMapping cmisMapping = new CmisPermissionMapping(); - cmisMapping.getPermission().addAll(mapping.getPermissions()); - cmisMapping.setKey(EnumAllowableActionsKey.fromValue(mapping.getKey())); - permissionMapping.add(cmisMapping); - } - } - return permissionMapping; - } - - /** - * Returns the list of Object-Types defined for the Repository under the specified Type. - * - * @param parameters repositoryId: repository Id; typeId: type Id; returnPropertyDefinitions: false (default); maxItems: 0 = Repository-default number of items(Default); - * skipCount: 0 = start; - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME) - */ - public CmisTypeDefinitionListType getTypeChildren(String repositoryId, String typeId, Boolean includePropertyDefinitions, BigInteger maxItems, BigInteger skipCount, - CmisExtensionType extension) throws CmisException - { - checkRepositoryId(repositoryId); - Collection typeDefs; - try - { - typeDefs = typeId == null ? cmisService.getBaseTypes() : cmisService.getTypeDefinition(typeId).getSubTypes(false); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - // skip - Cursor cursor = createCursor(typeDefs.size(), skipCount, maxItems); - Iterator iterTypeDefs = typeDefs.iterator(); - for (int i = 0; i < cursor.getStartRow(); i++) - { - iterTypeDefs.next(); - } - - boolean includePropertyDefinitionsVal = includePropertyDefinitions == null ? false : includePropertyDefinitions.booleanValue(); - - CmisTypeDefinitionListType result = new CmisTypeDefinitionListType(); - for (int i = cursor.getStartRow(); i <= cursor.getEndRow(); i++) - { - CmisTypeDefinitionType element = getCmisTypeDefinition(iterTypeDefs.next(), includePropertyDefinitionsVal); - if (null != element) - { - result.getTypes().add(element); - } - else - { - throw ExceptionUtil.createCmisException(("Subtypes collection is corrupted. Type id: " + typeId), EnumServiceException.STORAGE); - } - } - result.setHasMoreItems(((maxItems == null) || (0 == maxItems.intValue())) ? (false) : ((cursor.getEndRow() < (typeDefs.size() - 1)))); - result.setNumItems(BigInteger.valueOf(result.getTypes().size())); - return result; - } - - /** - * Gets the definition for specified object type - * - * @param parameters repositoryId: repository Id; typeId: type Id; - * @return CMIS type definition - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME) - */ - public CmisTypeDefinitionType getTypeDefinition(String repositoryId, String typeId, CmisExtensionType extension) throws CmisException - { - checkRepositoryId(repositoryId); - CMISTypeDefinition typeDef; - try - { - typeDef = cmisService.getTypeDefinition(typeId); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - return getCmisTypeDefinition(typeDef, true); - } - - /** - * Returns the set of descendant Object-Types defined for the Repository under the specified Type. - * - * @param parameters srepositoryId: repository Id; typeId: type Id; includePropertyDefinitions: false (default); depth: The number of levels of depth in the type hierarchy from - * which to return results; - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME) - */ - public List getTypeDescendants(String repositoryId, String typeId, BigInteger depth, Boolean includePropertyDefinitions, CmisExtensionType extension) - throws CmisException - { - checkRepositoryId(repositoryId); - long depthLong = (null == depth || null == typeId) ? (-1) : (depth.longValue()); - if (0 == depthLong) - { - throw ExceptionUtil.createCmisException("Invalid depth '0'", EnumServiceException.INVALID_ARGUMENT); - } - CMISTypeDefinition typeDef; - try - { - typeDef = typeId == null ? null : cmisService.getTypeDefinition(typeId); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - List result = new LinkedList(); - getTypeDescendants(typeDef, result, includePropertyDefinitions != null && includePropertyDefinitions, 1, depthLong); - return result; - } - - private void getTypeDescendants(CMISTypeDefinition parent, List result, boolean includePropertyDefs, long depth, long maxDepth) throws CmisException - { - Collection subtypes = parent == null ? cmisService.getBaseTypes() : parent.getSubTypes(false); - for (CMISTypeDefinition subtype : subtypes) - { - CmisTypeContainer type = createTypeContainer(subtype, includePropertyDefs); - result.add(type); - if (maxDepth == -1 || depth < maxDepth) - { - List children = type.getChildren(); - getTypeDescendants(subtype, children, includePropertyDefs, depth + 1, maxDepth); - } - } - } - - private CmisTypeContainer createTypeContainer(CMISTypeDefinition parentType, boolean includeProperties) throws CmisException - { - CmisTypeContainer result = new CmisTypeContainer(); - result.setType(getCmisTypeDefinition(parentType, includeProperties)); - return result; - } -} diff --git a/source/java/org/alfresco/repo/cmis/ws/DMServicePortThrowsAdvice.java b/source/java/org/alfresco/repo/cmis/ws/DMServicePortThrowsAdvice.java deleted file mode 100644 index 68ac99dde7..0000000000 --- a/source/java/org/alfresco/repo/cmis/ws/DMServicePortThrowsAdvice.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.ws; - -import org.alfresco.repo.cmis.ws.utils.ExceptionUtil; -import org.alfresco.repo.security.permissions.AccessDeniedException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.aop.ThrowsAdvice; - -/** - * Map Alfresco Exceptions to CMIS Exceptions - * - * @author Dmitry Lazurkin - * @author Dmitry Velichkevich - */ -public class DMServicePortThrowsAdvice implements ThrowsAdvice -{ - private static final Log LOGGER = LogFactory.getLog("org.alfresco.repo.cmis.ws"); - - public void afterThrowing(AccessDeniedException e) throws CmisException - { - if (LOGGER.isInfoEnabled()) - { - LOGGER.error(e.toString(), e); - } - throw ExceptionUtil.createCmisException(("Access denied. Message: " + e.toString()), e); - } - - public void afterThrowing(java.lang.RuntimeException e) throws CmisException - { - Throwable result = e; - if (null != e.getCause()) - { - result = e.getCause(); - } - if (LOGGER.isErrorEnabled()) - { - LOGGER.error(result.toString(), result); - } - throw (result instanceof CmisException) ? ((CmisException) result) : (ExceptionUtil.createCmisException(("Runtime error. Message: " + result.toString()), result)); - } - - public void afterThrowing(java.lang.Exception e) throws CmisException - { - if (LOGGER.isInfoEnabled()) - { - LOGGER.error(e.toString(), e); - } - if (!(e instanceof CmisException)) - { - throw ExceptionUtil.createCmisException(("Some error occured during last service invokation. Message: " + e.toString()), e); - } - else - { - throw (CmisException) e; - } - } -} diff --git a/source/java/org/alfresco/repo/cmis/ws/DMVersioningServicePort.java b/source/java/org/alfresco/repo/cmis/ws/DMVersioningServicePort.java deleted file mode 100644 index 4c7c979890..0000000000 --- a/source/java/org/alfresco/repo/cmis/ws/DMVersioningServicePort.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.ws; - -import java.util.LinkedList; -import java.util.List; - -import javax.xml.ws.Holder; - -import org.alfresco.cmis.CMISContentStreamAllowedEnum; -import org.alfresco.cmis.CMISDictionaryModel; -import org.alfresco.cmis.CMISServiceException; -import org.alfresco.cmis.CMISTypeDefinition; -import org.alfresco.cmis.PropertyFilter; -import org.alfresco.repo.cmis.ws.utils.ExceptionUtil; -import org.alfresco.service.cmr.repository.ContentWriter; -import org.alfresco.service.cmr.repository.NodeRef; - -/** - * Port for versioning service. - * - * @author Dmitry Lazurkin - * @author Dmitry Velichkevich - */ -@javax.jws.WebService(name = "VersioningServicePort", serviceName = "VersioningService", portName = "VersioningServicePort", targetNamespace = "http://docs.oasis-open.org/ns/cmis/ws/200908/", endpointInterface = "org.alfresco.repo.cmis.ws.VersioningServicePort") -public class DMVersioningServicePort extends DMAbstractServicePort implements VersioningServicePort -{ - /** - * Reverses the effect of a check-out. Removes the private working copy of the checked-out document object, allowing other documents in the version series to be checked out - * again. - * - * @param repositoryId repository Id - * @param objectId document Id - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, CONSTRAINT, - * UPDATE_CONFLICT, VERSIONING) - */ - // FIXME [~BUG]: may it is better returning id of the unchecked out document - public void cancelCheckOut(String repositoryId, String objectId, Holder extension) throws CmisException - { - checkRepositoryId(repositoryId); - try - { - cmisService.cancelCheckOut(objectId); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - /** - * Makes the private working copy the current version of the document. - * - * @param repositoryId repository Id - * @param objectId document Id - * @param major is major True (Default) - * @param properties CMIS properties - * @param contentStream content stream - * @param checkinComment check in comment - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, CONSTRAINT, STORAGE, - * STREAM_NOT_SUPPORTED, UPDATE_CONFLICT, VERSIONING) - */ - // FIXME [~BUG]: it is better changing 'void' to 'PWC Id' result type - public void checkIn(String repositoryId, Holder objectId, Boolean major, CmisPropertiesType properties, CmisContentStreamType contentStream, String checkinComment, - List policies, CmisAccessControlListType addACEs, CmisAccessControlListType removeACEs, Holder extension) throws CmisException - { - checkRepositoryId(repositoryId); - try - { - NodeRef workingCopyNodeRef = cmisService.getObject(objectId.value, NodeRef.class, true, true, true); - CMISTypeDefinition seriesObjectTypeDefinition = cmisService.getTypeDefinition(workingCopyNodeRef); - - if ((null != contentStream) && (CMISContentStreamAllowedEnum.NOT_ALLOWED == seriesObjectTypeDefinition.getContentStreamAllowed())) - { - throw ExceptionUtil.createCmisException("Content stream is not allowed", EnumServiceException.STREAM_NOT_SUPPORTED); - } - - if (contentStream != null) - { - try - { - ContentWriter writer = fileFolderService.getWriter(workingCopyNodeRef); - writer.setMimetype(contentStream.getMimeType()); - writer.putContent(contentStream.getStream().getInputStream()); - } - catch (Exception e) - { - throw ExceptionUtil.createCmisException("Exception while updating content stream", EnumServiceException.RUNTIME, e); - } - } - - propertiesUtil.setProperties(workingCopyNodeRef, properties, null); - NodeRef nodeRef = cmisService.checkIn(objectId.value, checkinComment, major == null || major); - - applyAclCarefully(nodeRef, addACEs, removeACEs, EnumACLPropagation.PROPAGATE, policies); - objectId.value = propertiesUtil.getProperty(nodeRef, CMISDictionaryModel.PROP_OBJECT_ID, objectId.value); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - /** - * Create a private working copy of the object, copies the metadata and optionally content. - * - * @param repositoryId repository Id - * @param objectId ObjectID of document version to checkout - * @param contentCopied - * @return ObjectID of private working copy as documentId; True if succeed, False otherwise as contentCopied - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, CONSTRAINT, STORAGE, - * UPDATE_CONFLICT, VERSIONING) - */ - public void checkOut(String repositoryId, Holder objectId, Holder extension, Holder contentCopied) throws CmisException - { - checkRepositoryId(repositoryId); - try - { - NodeRef pwcNodeRef = cmisService.checkOut(objectId.value); - objectId.value = propertiesUtil.getProperty(pwcNodeRef, CMISDictionaryModel.PROP_OBJECT_ID, objectId.value); - contentCopied.value = null != fileFolderService.getReader(pwcNodeRef); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - /** - * Gets the list of all document versions for the specified version series. - * - * @param parameters repositoryId: repository Id; versionSeriesId: version series Id; filter: property filter; includeAllowableActions; includeRelationships; - * @return list of CmisObjectType - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, FILTER_NOT_VALID) - */ - public List getAllVersions(String repositoryId, String objectId, String filter, Boolean includeAllowableActions, CmisExtensionType extension) - throws CmisException - { - checkRepositoryId(repositoryId); - PropertyFilter propertyFilter = createPropertyFilter(filter); - List objects = new LinkedList(); - try - { - for (NodeRef nodeRef : cmisService.getAllVersions(objectId)) - { - objects.add(createCmisObject(nodeRef, propertyFilter, null, includeAllowableActions, null)); - } - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - return objects; - } - - /** - * Gets the properties of the latest version, or the latest major version, of the specified version series. - * - * @param parameters repositoryId: repository Id; versionSeriesId: version series Id; majorVersion: whether or not to return the latest major version. Default=FALSE; filter: - * property filter - * @return CmisObjectType with properties - * @throws CmisException (with following {@link EnumServiceException} : INVALID_ARGUMENT, OBJECT_NOT_FOUND, NOT_SUPPORTED, PERMISSION_DENIED, RUNTIME, FILTER_NOT_VALID) - */ - public CmisPropertiesType getPropertiesOfLatestVersion(String repositoryId, String objectId, Boolean major, String filter, CmisExtensionType extension) throws CmisException - { - checkRepositoryId(repositoryId); - NodeRef latestVersionNodeRef; - try - { - latestVersionNodeRef = cmisService.getLatestVersion(objectId, major != null && major); - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - PropertyFilter propertyFilter = createPropertyFilter(filter); - return propertiesUtil.getProperties(latestVersionNodeRef, propertyFilter); - } - - /** - * - */ - // TODO: it is necessary to add tests for this method - public CmisObjectType getObjectOfLatestVersion(String repositoryId, String objectId, Boolean major, String filter, Boolean includeAllowableActions, - EnumIncludeRelationships includeRelationships, String renditionFilter, Boolean includePolicyIds, Boolean includeACL, CmisExtensionType extension) throws CmisException - { - checkRepositoryId(repositoryId); - try - { - NodeRef latestVersionNodeRef = cmisService.getLatestVersion(objectId, major != null && major); - // TODO: includePolicyIds - PropertyFilter propertyFilter = createPropertyFilter(filter); - CmisObjectType result = createCmisObject(latestVersionNodeRef, propertyFilter, includeRelationships, - includeAllowableActions, renditionFilter); - if (includeACL) - { - appendWithAce(cmisService.getVersionSeries(objectId, NodeRef.class, false), result); - } - - return result; - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } -} diff --git a/source/java/org/alfresco/repo/cmis/ws/utils/ExceptionUtil.java b/source/java/org/alfresco/repo/cmis/ws/utils/ExceptionUtil.java deleted file mode 100644 index f5119c8fa5..0000000000 --- a/source/java/org/alfresco/repo/cmis/ws/utils/ExceptionUtil.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.ws.utils; - -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Map; - -import org.alfresco.cmis.CMISQueryException; -import org.alfresco.cmis.CMISServiceException; -import org.alfresco.repo.cmis.ws.CmisException; -import org.alfresco.repo.cmis.ws.CmisFaultType; -import org.alfresco.repo.cmis.ws.EnumServiceException; -import org.alfresco.repo.security.permissions.AccessDeniedException; -import org.alfresco.service.cmr.model.FileExistsException; -import org.alfresco.service.cmr.repository.ContentIOException; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; - -/** - * @author Dmitry Velichkevich - */ -public abstract class ExceptionUtil -{ - private static final Map CLASS_TO_ENUM_EXCEPTION_MAPPING; - static - { - CLASS_TO_ENUM_EXCEPTION_MAPPING = new HashMap(); - CLASS_TO_ENUM_EXCEPTION_MAPPING.put(AccessDeniedException.class.getName(), EnumServiceException.PERMISSION_DENIED); - CLASS_TO_ENUM_EXCEPTION_MAPPING.put(java.lang.RuntimeException.class.getName(), EnumServiceException.RUNTIME); - CLASS_TO_ENUM_EXCEPTION_MAPPING.put(UnsupportedOperationException.class.getName(), EnumServiceException.NOT_SUPPORTED); - CLASS_TO_ENUM_EXCEPTION_MAPPING.put(InvalidNodeRefException.class.getName(), EnumServiceException.INVALID_ARGUMENT); - CLASS_TO_ENUM_EXCEPTION_MAPPING.put(ContentIOException.class.getName(), EnumServiceException.NOT_SUPPORTED); - CLASS_TO_ENUM_EXCEPTION_MAPPING.put(CMISQueryException.class.getName(), EnumServiceException.INVALID_ARGUMENT); - CLASS_TO_ENUM_EXCEPTION_MAPPING.put(FileExistsException.class.getName(), EnumServiceException.NAME_CONSTRAINT_VIOLATION); - } - - public static CmisException createCmisException(String message, EnumServiceException exceptionType) - { - return createCmisException(message, exceptionType, null, 0); - } - - public static CmisException createCmisException(String message, Throwable cause) - { - EnumServiceException exceptionType = null; - - if (cause instanceof CMISServiceException) - { - return createCmisException((CMISServiceException)cause); - } - - if (CLASS_TO_ENUM_EXCEPTION_MAPPING.containsKey(cause.getClass().getName())) - { - exceptionType = CLASS_TO_ENUM_EXCEPTION_MAPPING.get(cause.getClass().getName()); - } - - exceptionType = (exceptionType == null) ? (EnumServiceException.RUNTIME) : (exceptionType); - - return createCmisException(message, exceptionType, cause, 0); - } - - public static CmisException createCmisException(String message, EnumServiceException exceptionType, Throwable cause) - { - return createCmisException(message, exceptionType, cause, 0); - } - - public static CmisException createCmisException(CMISServiceException exception) - { - return createCmisException(exception.getMessage(), EnumServiceException.fromValue(exception.getFaultName()), exception, exception.getStatusCode()); - } - - public static CmisException createCmisException(String message, EnumServiceException exceptionType, Throwable cause, int errorCode) - { - CmisFaultType fault = new CmisFaultType(); - fault.setMessage(message); - fault.setType(exceptionType); - fault.setCode(BigInteger.valueOf(errorCode)); - - return new CmisException(message, fault, cause); - } -} diff --git a/source/java/org/alfresco/repo/cmis/ws/utils/PropertyUtil.java b/source/java/org/alfresco/repo/cmis/ws/utils/PropertyUtil.java deleted file mode 100644 index cb72a26867..0000000000 --- a/source/java/org/alfresco/repo/cmis/ws/utils/PropertyUtil.java +++ /dev/null @@ -1,745 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.ws.utils; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.xml.datatype.DatatypeConfigurationException; -import javax.xml.datatype.DatatypeFactory; -import javax.xml.datatype.XMLGregorianCalendar; - -import org.alfresco.cmis.CMISDataTypeEnum; -import org.alfresco.cmis.CMISDictionaryService; -import org.alfresco.cmis.CMISInvalidArgumentException; -import org.alfresco.cmis.CMISPropertyDefinition; -import org.alfresco.cmis.CMISServiceException; -import org.alfresco.cmis.CMISServices; -import org.alfresco.cmis.CMISTypeDefinition; -import org.alfresco.cmis.PropertyFilter; -import org.alfresco.repo.cmis.ws.Aspects; -import org.alfresco.repo.cmis.ws.CmisException; -import org.alfresco.repo.cmis.ws.CmisPropertiesType; -import org.alfresco.repo.cmis.ws.CmisProperty; -import org.alfresco.repo.cmis.ws.CmisPropertyBoolean; -import org.alfresco.repo.cmis.ws.CmisPropertyDateTime; -import org.alfresco.repo.cmis.ws.CmisPropertyDecimal; -import org.alfresco.repo.cmis.ws.CmisPropertyHtml; -import org.alfresco.repo.cmis.ws.CmisPropertyId; -import org.alfresco.repo.cmis.ws.CmisPropertyInteger; -import org.alfresco.repo.cmis.ws.CmisPropertyString; -import org.alfresco.repo.cmis.ws.CmisPropertyUri; -import org.alfresco.repo.cmis.ws.EnumServiceException; -import org.alfresco.repo.cmis.ws.SetAspects; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.cmr.repository.AssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.version.Version; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; - -/** - * Class for managing access control to CMIS properties - * - * @author Dmitry Lazurkin - * @author Dmitry Velichkevich - */ -public class PropertyUtil -{ - private static final DatatypeFactory DATATYPE_FACTORY; - static - { - try - { - DATATYPE_FACTORY = DatatypeFactory.newInstance(); - } - catch (DatatypeConfigurationException e) - { - throw new RuntimeException(("Data type instance creation failed! Failed message: " + e.toString()), e); - } - } - - private final static String NAMESPACE_BEGIN = "" + QName.NAMESPACE_BEGIN; - - private DictionaryService dictionaryService; - private NamespaceService namespaceService; - private CMISServices cmisService; - private CMISDictionaryService cmisDictionaryService; - - public PropertyUtil() - { - } - - public void setDictionaryService(DictionaryService dictionaryService) - { - this.dictionaryService = dictionaryService; - } - - public void setNamespaceService(NamespaceService namespaceService) - { - this.namespaceService = namespaceService; - } - - public void setCmisService(CMISServices cmisService) - { - this.cmisService = cmisService; - } - - public void setCmisDictionaryService(CMISDictionaryService cmisDictionaryService) - { - this.cmisDictionaryService = cmisDictionaryService; - } - - /** - * Gets property value by its name from Node Reference object - * - * @param objectNodeRef - NodeRef instance that represents Id of the source object - * @param propertyName - String instance that represents property name - * @param defaultValue - some value of the appropriate for conversion type. Also null may be accepted by this parameter - * @return value instance of the appropriate type if specified object has such property and defaultValue if requested property value or objectNodeRef or - * propertyName are null or if some exception occurred during property receiving - * @throws CMISInvalidArgumentException - */ - public ResultType getProperty(NodeRef objectNodeRef, String propertyName, ResultType defaultValue) - throws CMISInvalidArgumentException - { - if ((null == objectNodeRef) || (null == propertyName)) - { - return defaultValue; - } - - Serializable value = cmisService.getProperty(objectNodeRef, propertyName); - try - { - return convertPropertyValue(value, defaultValue); - } - catch (Exception exception) - { - return defaultValue; - } - } - - /** - * Extracts from CmisPropertiesType instance property by its name and returns casted to appropriate type value of the extracted property - * - * @param cmisProperties - CmisPropertiesType properties instance - * @param property - String instance that represents property name - * @param defaultValue - some value of the appropriate for conversion type. Also null may be accepted by this parameter - * @return value instance of the appropriate type if specified cmisProperties contains specified properties and defaultValue if requested property value or - * cmisProperties or property are null or if some exception occurred during property searching and receiving - */ - public ResultType getCmisPropertyValue(CmisPropertiesType cmisProperties, String property, ResultType defaultValue) throws CmisException - { - if ((null == property) || (null == cmisProperties)) - { - return defaultValue; - } - - for (CmisProperty cmisProperty : cmisProperties.getProperty()) - { - if ((null != cmisProperty) && property.equals(getPropertyName(cmisProperty))) - { - return convertPropertyValue(getValue(cmisProperty), defaultValue); - } - } - - return defaultValue; - } - - @SuppressWarnings("unchecked") - private ResultType convertPropertyValue(Object propertyValue, ResultType defaultValue) - { - if (null == propertyValue) - { - return defaultValue; - } - - try - { - return (ResultType) propertyValue; - } - catch (Throwable e) - { - return defaultValue; - } - } - - private Serializable getValue(CmisProperty cmisProperty) throws CmisException - { - Serializable value = null; - String propertyName = getPropertyName(cmisProperty); - if ((null == cmisProperty) || (null == propertyName)) - { - return value; - } - - PropertyMultiValueStateEnum multivaluedState = getPropertyMultiValuedState(null, propertyName); - Collection convertedValue = null; - - if (cmisProperty instanceof CmisPropertyBoolean) - { - convertedValue = ((CmisPropertyBoolean) cmisProperty).getValue(); - } - else if (cmisProperty instanceof CmisPropertyDateTime) - { - convertedValue = ((CmisPropertyDateTime) cmisProperty).getValue(); - List dates = new ArrayList(convertedValue.size()); - for (Object date : convertedValue) - { - dates.add(((XMLGregorianCalendar)date).toGregorianCalendar()); - } - convertedValue = dates; - } - else if (cmisProperty instanceof CmisPropertyDecimal) - { - convertedValue = ((CmisPropertyDecimal) cmisProperty).getValue(); - } - else if (cmisProperty instanceof CmisPropertyHtml) - { - convertedValue = ((CmisPropertyHtml) cmisProperty).getValue(); - } - else if (cmisProperty instanceof CmisPropertyId) - { - convertedValue = ((CmisPropertyId) cmisProperty).getValue(); - } - else if (cmisProperty instanceof CmisPropertyInteger) - { - convertedValue = ((CmisPropertyInteger) cmisProperty).getValue(); - } - else if (cmisProperty instanceof CmisPropertyString) - { - convertedValue = ((CmisPropertyString) cmisProperty).getValue(); - } - else if (cmisProperty instanceof CmisPropertyUri) - { - convertedValue = ((CmisPropertyUri) cmisProperty).getValue(); - } - - if (null != convertedValue) - { - if (isMultiValued(propertyName, multivaluedState, convertedValue)) - { - value = (convertedValue.size() > 0) ? new ArrayList((convertedValue)) : (null); - } - else if (!convertedValue.isEmpty()) - { - value = (Serializable) convertedValue.iterator().next(); - } - } - - return value; - } - - private boolean isMultiValued(String propertyName, PropertyMultiValueStateEnum state, Collection values) throws CmisException - { - // TODO: WARNING!!! This is invalid behavior! Multi valued property state can't be identified in this way!!! - if (PropertyMultiValueStateEnum.PROPERTY_NOT_FOUND == state) - { - return (values.size() > 0) ? (values.size() > 1) : (true); - } - - if ((PropertyMultiValueStateEnum.PROPERTY_NOT_MULTIVALUED == state) && (values.size() > 1)) - { - throw ExceptionUtil.createCmisException("\"" + propertyName + "\" property is not Multi Valued", EnumServiceException.INVALID_ARGUMENT); - } - - return PropertyMultiValueStateEnum.PROPERTY_MULTIVALUED == state; - } - - private PropertyMultiValueStateEnum getPropertyMultiValuedState(String typeId, String cmisPropertyName) - { - if ((null == cmisPropertyName) || cmisPropertyName.equals("")) - { - return PropertyMultiValueStateEnum.PROPERTY_NOT_FOUND; - } - - CMISTypeDefinition typeDefinition = ((null != typeId) && !typeId.equals("")) ? (cmisDictionaryService.findType(typeId)) : (null); - CMISPropertyDefinition propertyDefinition = null; - if ((null != typeDefinition) && (null != typeDefinition.getOwnedPropertyDefinitions())) - { - propertyDefinition = typeDefinition.getOwnedPropertyDefinitions().get(cmisPropertyName); - } - else - { - propertyDefinition = cmisDictionaryService.findProperty(cmisPropertyName, null); - } - - if ((null == propertyDefinition) || (null == propertyDefinition.getPropertyAccessor())) - { - return PropertyMultiValueStateEnum.PROPERTY_NOT_FOUND; - } - - PropertyDefinition nativePropertyDefinition = null; - if (null != propertyDefinition.getPropertyAccessor().getMappedProperty()) - { - nativePropertyDefinition = dictionaryService.getProperty(propertyDefinition.getPropertyAccessor().getMappedProperty()); - } - else - { - nativePropertyDefinition = dictionaryService.getProperty(createQName(cmisPropertyName)); - } - - if (null == nativePropertyDefinition) - { - return PropertyMultiValueStateEnum.PROPERTY_NOT_FOUND; - } - - return (nativePropertyDefinition.isMultiValued()) ? (PropertyMultiValueStateEnum.PROPERTY_MULTIVALUED) : (PropertyMultiValueStateEnum.PROPERTY_NOT_MULTIVALUED); - } - - private enum PropertyMultiValueStateEnum - { - PROPERTY_MULTIVALUED, PROPERTY_NOT_MULTIVALUED, PROPERTY_NOT_FOUND; - } - - /** - * Converts CmisPropertiesType properties representation to rapidly accessible form - * - * @param cmisProperties - CmisPropertiesType properties representation - * @return Map<String, Serializable> properties representation - * @throws CmisException - */ - public Map getPropertiesMap(CmisPropertiesType cmisProperties) throws CmisException - { - Map properties = new HashMap(); - - if (null == cmisProperties) - { - return properties; - } - - for (CmisProperty cmisProperty : cmisProperties.getProperty()) - { - if (null != cmisProperty) - { - String pdid = getPropertyName(cmisProperty); - Serializable value = getValue(cmisProperty); - if (value != null) - { - properties.put(pdid, value); - } - } - } - - return properties; - } - - /** - * Sets and checks all properties' fields for specified node - * - * @param nodeRef - * - NodeRef for node for those properties must be setted - * @param properties - * - CmisPropertiesType instance that contains all the necessary properties' fields - * @param ignoringPropertiesFilter - * - PropertyFilter instance. This filter determines which properties should be ignored and not - * setted without exception. If this parameter is null all properties will be processed in common - * flow - */ - public void setProperties(NodeRef nodeRef, CmisPropertiesType properties, PropertyFilter ignoringPropertiesFilter) - throws CmisException - { - if (nodeRef == null || properties == null) - { - return; - } - - try - { - - for (CmisProperty property : properties.getProperty()) - { - String propertyName = getPropertyName(property); - if ((null == propertyName) - || ((null != ignoringPropertiesFilter) && ignoringPropertiesFilter.allow(propertyName))) - { - continue; - } - Object value = getValue(property); - cmisService.setProperty(nodeRef, propertyName, (Serializable) value); - } - - // Process Alfresco aspect-setting extension - for (Object extensionObj : properties.getAny()) - { - if (!(extensionObj instanceof SetAspects)) - { - continue; - } - SetAspects setAspects = (SetAspects) extensionObj; - cmisService.setAspects(nodeRef, setAspects.getAspectsToRemove(), setAspects.getAspectsToAdd()); - CmisPropertiesType extensionProperties = setAspects.getProperties(); - if (extensionProperties == null) - { - continue; - } - - for (CmisProperty property : extensionProperties.getProperty()) - { - String propertyName = getPropertyName(property); - if ((null == propertyName) - || ((null != ignoringPropertiesFilter) && ignoringPropertiesFilter.allow(propertyName))) - { - continue; - } - Object value = getValue(property); - - // This time, call setProperty without constraining the owning type - cmisService.setProperty(nodeRef, null, propertyName, (Serializable) value); - } - } - } - catch (CMISServiceException e) - { - throw ExceptionUtil.createCmisException(e); - } - } - - public String getPropertyName(CmisProperty property) - { - String propertyName = (null != property) ? (property.getPropertyDefinitionId()) : (null); - if (null == propertyName) - { - propertyName = property.getLocalName(); - if (null == propertyName) - { - propertyName = property.getDisplayName(); - } - } - return propertyName; - } - - private QName createQName(String s) - { - QName qname; - if (s.indexOf(NAMESPACE_BEGIN) != -1) - { - qname = QName.createQName(s); - } - else - { - qname = QName.createQName(s, namespaceService); - } - return qname; - } - - /** - * Get CMIS properties for object - * - * @param nodeRef node reference - * @param filter property filter - * @return properties - */ - public CmisPropertiesType getProperties(Object object, PropertyFilter filter) throws CmisException - { - if (object instanceof Version) - { - object = ((Version) object).getFrozenStateNodeRef(); - } - try - { - CmisPropertiesType result = new CmisPropertiesType(); - Map properties; - if (object instanceof NodeRef) - { - properties = cmisService.getProperties((NodeRef) object); - - // Handle fetching of aspects and their properties with Alfresco extension - Aspects extension = new Aspects(); - result.getAny().add(extension); - List aspects = extension.getAppliedAspects(); - Map aspectProperties = new HashMap(97); - for (CMISTypeDefinition typeDef : cmisService.getAspects((NodeRef)object)) - { - aspects.add(typeDef.getTypeId().getId()); - aspectProperties.putAll(cmisService.getProperties((NodeRef)object, typeDef)); - } - CmisPropertiesType aspectResult = new CmisPropertiesType(); - convertToCmisProperties(aspectProperties, filter, aspectResult); - extension.setProperties(aspectResult); - } - else - { - properties = cmisService.getProperties((AssociationRef) object); - } - convertToCmisProperties( properties, filter, result); - return result; - } - catch (CMISInvalidArgumentException e) - { - throw ExceptionUtil.createCmisException(e.getMessage(), EnumServiceException.INVALID_ARGUMENT, e); - } - } - - private void convertToCmisProperties(Map properties, PropertyFilter filter, CmisPropertiesType cmisProperties) throws CmisException - { - for (String propertyName : properties.keySet()) - { - CMISPropertyDefinition propertyTypeDef = cmisDictionaryService.findProperty(propertyName, null); - if ((null != propertyTypeDef) && filter.allow(propertyName)) - { - CmisProperty property = createProperty(propertyName, propertyTypeDef.getDataType(), properties.get(propertyName)); - - if (null != property) - { - cmisProperties.getProperty().add(property); - } - } - } - } - - /** - * Creates and initializes appropriate CmisProperty instance by name and data type - * - * @param pdid - String value that represents CMIS property name - * @param dataType - CMISDataTypeEnum value that specifies real type of the property - * @param value - some instance of appropriate type or some Collection that contains several values of the type - * @return appropriate CmisProperty instance - */ - @SuppressWarnings("unchecked") - public CmisProperty createProperty(String pdid, CMISDataTypeEnum dataType, Serializable value) - { - if (value == null) - { - return null; - } - - switch (dataType) - { - case BOOLEAN: - { - CmisPropertyBoolean property = new CmisPropertyBoolean(); - property.setPropertyDefinitionId(pdid); - - if (value instanceof Collection) - { - for (Boolean propertyValue : (Collection) value) - { - property.getValue().add(propertyValue); - } - } - else - { - property.getValue().add((Boolean) value); - } - - return property; - } - case STRING: - { - CmisPropertyString property = new CmisPropertyString(); - property.setPropertyDefinitionId(pdid); - - if (value instanceof Collection) - { - for (String propertyValue : (Collection) value) - { - property.getValue().add(propertyValue); - } - } - else - { - property.getValue().add((String) value); - } - - return property; - } - case INTEGER: - { - CmisPropertyInteger property = new CmisPropertyInteger(); - property.setPropertyDefinitionId(pdid); - - if (value instanceof Collection) - { - for (Object propertyValue : (Collection) value) - { - if(propertyValue instanceof Long) - { - property.getValue().add(BigInteger.valueOf((Long) propertyValue)); - } - else - { - property.getValue().add(BigInteger.valueOf((Integer) propertyValue)); - } - } - } - else - { - if(value instanceof Long) - { - property.getValue().add(BigInteger.valueOf((Long) value)); - } - else - { - property.getValue().add(BigInteger.valueOf((Integer) value)); - } - } - - return property; - } - case DATETIME: - { - CmisPropertyDateTime property = new CmisPropertyDateTime(); - property.setPropertyDefinitionId(pdid); - - if (value instanceof Collection) - { - for (Date propertyValue : (Collection) value) - { - XMLGregorianCalendar convertedValue = convert(propertyValue); - if (null != convertedValue) - { - property.getValue().add(convertedValue); - } - } - } - else - { - XMLGregorianCalendar convertedValue = convert((Date) value); - if (null != convertedValue) - { - property.getValue().add(convert((Date) value)); - } - } - - return property; - } - case ID: - { - CmisPropertyId property = new CmisPropertyId(); - property.setPropertyDefinitionId(pdid); - - if (value instanceof Collection) - { - for (Serializable propertyValue : (Collection) value) - { - // NOTE: CMIS multi-valued values cannot contain null - if (propertyValue != null) - { - property.getValue().add(propertyValue.toString()); - } - } - } - else - { - property.getValue().add(value != null ? value.toString() : null); - } - - return property; - } - case URI: - { - CmisPropertyUri property = new CmisPropertyUri(); - property.setPropertyDefinitionId(pdid); - - if (value instanceof Collection) - { - for (String propertyValue : (Collection) value) - { - property.getValue().add(propertyValue); - } - } - else - { - property.getValue().add((String) value); - } - - return property; - } - case DECIMAL: - { - CmisPropertyDecimal property = new CmisPropertyDecimal(); - property.setPropertyDefinitionId(pdid); - - if (value instanceof Collection) - { - for (Serializable propertyValue : (Collection) value) - { - property.getValue().add(decimalValue(propertyValue)); - } - } - else - { - property.getValue().add(decimalValue(value)); - } - - return property; - } - case HTML: - { - CmisPropertyHtml property = new CmisPropertyHtml(); - property.setPropertyDefinitionId(pdid); - - if (value instanceof Collection) - { - for (String propertyValue : (Collection) value) - { - property.getValue().add(propertyValue); - } - } - else - { - property.getValue().add((String) value); - } - - return property; - } - default: - { - return null; - } - } - } - - private BigDecimal decimalValue(Serializable value) - { - if ((value instanceof Float) || (value instanceof Double)) - { - return BigDecimal.valueOf(((Number) value).doubleValue()); - } - return null; - } - - /** - * Converts Date object to XMLGregorianCalendar object - * - * @param date Date object - * @return XMLGregorianCalendar object - */ - public XMLGregorianCalendar convert(Date date) - { - if (null != date) - { - GregorianCalendar calendar = new GregorianCalendar(); - calendar.setTime(date); - return DATATYPE_FACTORY.newXMLGregorianCalendar(calendar); - } - - return null; - } -} diff --git a/source/java/org/alfresco/repo/web/scripts/content/ContentDelete.java b/source/java/org/alfresco/repo/web/scripts/content/ContentDelete.java deleted file mode 100644 index e272f054df..0000000000 --- a/source/java/org/alfresco/repo/web/scripts/content/ContentDelete.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.web.scripts.content; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.cmis.CMISObjectReference; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.cmis.reference.ReferenceFactory; -import org.alfresco.service.cmr.repository.ContentData; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.springframework.extensions.webscripts.AbstractWebScript; -import org.springframework.extensions.webscripts.Status; -import org.springframework.extensions.webscripts.WebScriptException; -import org.springframework.extensions.webscripts.WebScriptRequest; -import org.springframework.extensions.webscripts.WebScriptResponse; - - -/** - * Content Delete Service - * - * Delete content stream from the Repository. - * - * @author davidc - */ -public class ContentDelete extends AbstractWebScript -{ - // Component dependencies - private ReferenceFactory referenceFactory; - private NamespaceService namespaceService; - private NodeService nodeService; - - /** - * @param reference factory - */ - public void setReferenceFactory(ReferenceFactory referenceFactory) - { - this.referenceFactory = referenceFactory; - } - - /** - * @param namespaceService - */ - public void setNamespaceService(NamespaceService namespaceService) - { - this.namespaceService = namespaceService; - } - - /** - * @param nodeService - */ - public void setNodeService(NodeService nodeService) - { - this.nodeService = nodeService; - } - - - /** - * @see org.alfresco.web.scripts.WebScript#execute(org.alfresco.web.scripts.WebScriptRequest, org.alfresco.web.scripts.WebScriptResponse) - */ - public void execute(WebScriptRequest req, WebScriptResponse res) - throws IOException - { - // create map of args - String[] names = req.getParameterNames(); - Map args = new HashMap(names.length, 1.0f); - for (String name : names) - { - args.put(name, req.getParameter(name)); - } - - // create map of template vars - Map templateVars = req.getServiceMatch().getTemplateVars(); - - // create object reference from url - CMISObjectReference reference = referenceFactory.createObjectReferenceFromUrl(args, templateVars); - NodeRef nodeRef = reference.getNodeRef(); - if (nodeRef == null) - { - throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Unable to find " + reference.toString()); - } - - // determine content property - QName propertyQName = ContentModel.PROP_CONTENT; - String contentPart = templateVars.get("property"); - if (contentPart.length() > 0 && contentPart.charAt(0) == ';') - { - if (contentPart.length() < 2) - { - throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Content property malformed"); - } - String propertyName = contentPart.substring(1); - if (propertyName.length() > 0) - { - propertyQName = QName.createQName(propertyName, namespaceService); - } - } - - // retrieve content property - ContentData contentData = (ContentData)nodeService.getProperty(nodeRef, propertyQName); - if (contentData != null) - { - contentData = new ContentData(null, null, 0, null); - nodeService.setProperty(nodeRef, propertyQName, contentData); - } - - // no content returned - res.setStatus(Status.STATUS_NO_CONTENT); - } -} \ No newline at end of file diff --git a/source/java/org/alfresco/repo/web/scripts/content/ContentGet.java b/source/java/org/alfresco/repo/web/scripts/content/ContentGet.java deleted file mode 100644 index 7788026939..0000000000 --- a/source/java/org/alfresco/repo/web/scripts/content/ContentGet.java +++ /dev/null @@ -1,322 +0,0 @@ -/* - * Copyright (C) 2005-2012 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 . - */ -package org.alfresco.repo.web.scripts.content; - -import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.cmis.CMISFilterNotValidException; -import org.alfresco.cmis.CMISObjectReference; -import org.alfresco.cmis.CMISRendition; -import org.alfresco.cmis.CMISRenditionService; -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.cmis.reference.ReferenceFactory; -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.repo.security.permissions.AccessDeniedException; -import org.alfresco.repo.web.scripts.FileTypeImageUtils; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.repository.ContentService; -import org.alfresco.service.cmr.repository.FileTypeImageSize; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.extensions.webscripts.Status; -import org.springframework.extensions.webscripts.WebScriptException; -import org.springframework.extensions.webscripts.WebScriptRequest; -import org.springframework.extensions.webscripts.WebScriptResponse; -import org.springframework.util.FileCopyUtils; -import org.springframework.web.context.ServletContextAware; -import org.springframework.web.context.support.ServletContextResource; - - -/** - * Content Retrieval Service - * - * Stream content from the Repository. - * - * @author davidc - */ -public class ContentGet extends StreamContent implements ServletContextAware -{ - // Logger - @SuppressWarnings("unused") - private static final Log logger = LogFactory.getLog(ContentGet.class); - - // Component dependencies - private ServletContext servletContext; - private ReferenceFactory referenceFactory; - private DictionaryService dictionaryService; - private NamespaceService namespaceService; - private CMISRenditionService renditionService; - private ContentService contentService; - - /** - * @param - */ - public void setServletContext(ServletContext servletContext) - { - this.servletContext = servletContext; - } - - /** - * @param reference factory - */ - public void setReferenceFactory(ReferenceFactory referenceFactory) - { - this.referenceFactory = referenceFactory; - } - - /** - * @param dictionaryService - */ - public void setDictionaryService(DictionaryService dictionaryService) - { - this.dictionaryService = dictionaryService; - } - - /** - * @param namespaceService - */ - public void setNamespaceService(NamespaceService namespaceService) - { - this.namespaceService = namespaceService; - } - - /** - * @param renditionService - */ - public void setCMISRenditionService(CMISRenditionService renditionService) - { - this.renditionService = renditionService; - } - - /** - * @param contentService - */ - public void setContentService(ContentService contentService) - { - this.contentService = contentService; - } - - /** - * @see org.alfresco.web.scripts.WebScript#execute(org.alfresco.web.scripts.WebScriptRequest, org.alfresco.web.scripts.WebScriptResponse) - */ - public void execute(WebScriptRequest req, WebScriptResponse res) - throws IOException - { - // create map of args - String[] names = req.getParameterNames(); - Map args = new HashMap(names.length, 1.0f); - for (String name : names) - { - args.put(name, req.getParameter(name)); - } - - // create map of template vars - Map templateVars = req.getServiceMatch().getTemplateVars(); - - // create object reference from url - CMISObjectReference reference = referenceFactory.createObjectReferenceFromUrl(args, templateVars); - NodeRef nodeRef = reference.getNodeRef(); - if (nodeRef == null) - { - throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Unable to find " + reference.toString()); - } - - // determine attachment - boolean attach = Boolean.valueOf(req.getParameter("a")); - - // stream content on node, or rendition of node - String streamId = req.getParameter("streamId"); - if (streamId != null && streamId.length() > 0) - { - // render content rendition - streamRendition(req, res, reference, streamId, attach); - } - else - { - // render content - QName propertyQName = ContentModel.PROP_CONTENT; - String contentPart = templateVars.get("property"); - if (contentPart.length() > 0 && contentPart.charAt(0) == ';') - { - if (contentPart.length() < 2) - { - throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Content property malformed"); - } - String propertyName = contentPart.substring(1); - if (propertyName.length() > 0) - { - propertyQName = QName.createQName(propertyName, namespaceService); - } - } - - // Stream the content - streamContentLocal(req, res, nodeRef, attach, propertyQName); - } - } - - private void streamContentLocal(WebScriptRequest req, WebScriptResponse res, NodeRef nodeRef, boolean attach, QName propertyQName) throws IOException - { - String userAgent = req.getHeader("User-Agent"); - - boolean rfc5987Supported = (null != userAgent) && (userAgent.contains("MSIE") || userAgent.contains(" Chrome/") || userAgent.contains(" FireFox/")); - - try - { - if (attach && rfc5987Supported) - { - String name = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME); - - //IE use file extension to get mimetype - //So we set correct extension. see MNT-11246 - if(userAgent.contains("MSIE")) - { - String mimeType = contentService.getReader(nodeRef, propertyQName).getMimetype(); - if (!mimetypeService.getMimetypes(FilenameUtils.getExtension(name)).contains(mimeType)) - { - name = FilenameUtils.removeExtension(name) + FilenameUtils.EXTENSION_SEPARATOR_STR + mimetypeService.getExtension(mimeType); - } - } - - streamContent(req, res, nodeRef, propertyQName, attach, name, null); - } - else - { - streamContent(req, res, nodeRef, propertyQName, attach, null, null); - } - } - catch (AccessDeniedException e) - { - throw new WebScriptException(Status.STATUS_FORBIDDEN, e.getMessage()); - } - } - - /** - * Stream content rendition - * - * @param req - * @param res - * @param reference - * @param streamId - * @param attach - * @throws IOException - */ - private void streamRendition(WebScriptRequest req, WebScriptResponse res, CMISObjectReference reference, String streamId, boolean attach) - throws IOException - { - try - { - // find rendition - CMISRendition rendition = null; - List renditions = renditionService.getRenditions(reference.getNodeRef(), "*"); - for (CMISRendition candidateRendition : renditions) - { - if (candidateRendition.getStreamId().equals(streamId)) - { - rendition = candidateRendition; - break; - } - } - if (rendition == null) - { - throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Unable to find rendition " + streamId + " for " + reference.toString()); - } - - // determine if special case for icons - if (streamId.startsWith("alf:icon")) - { - streamIcon(res, reference, streamId, attach); - } - else - { - streamContentLocal(req, res, rendition.getNodeRef(), attach, ContentModel.PROP_CONTENT); - } - } - catch(CMISFilterNotValidException e) - { - throw new WebScriptException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid Rendition Filter"); - } - } - - /** - * Stream Icon - * - * @param res - * @param reference - * @param streamId - * @param attach - * @throws IOException - */ - private void streamIcon(WebScriptResponse res, CMISObjectReference reference, String streamId, boolean attach) - throws IOException - { - // convert stream id to icon size - FileTypeImageSize imageSize = streamId.equals("alf:icon16") ? FileTypeImageSize.Small : FileTypeImageSize.Medium; - String iconSize = streamId.equals("alf:icon16") ? "-16" : ""; - - // calculate icon file name and path - String iconPath = null; - if (dictionaryService.isSubClass(nodeService.getType(reference.getNodeRef()), ContentModel.TYPE_CONTENT)) - { - String name = (String)nodeService.getProperty(reference.getNodeRef(), ContentModel.PROP_NAME); - iconPath = FileTypeImageUtils.getFileTypeImage(servletContext, name, imageSize); - } - else - { - String icon = (String)nodeService.getProperty(reference.getNodeRef(), ApplicationModel.PROP_ICON); - if (icon != null) - { - iconPath = "/images/icons/" + icon + iconSize + ".gif"; - } - else - { - iconPath = "/images/icons/space-icon-default" + iconSize + ".gif"; - } - } - - // set mimetype - String mimetype = MimetypeMap.MIMETYPE_BINARY; - int extIndex = iconPath.lastIndexOf('.'); - if (extIndex != -1) - { - String ext = iconPath.substring(extIndex + 1); - mimetype = mimetypeService.getMimetype(ext); - } - res.setContentType(mimetype); - - // stream icon - ServletContextResource resource = new ServletContextResource(servletContext, iconPath); - if (!resource.exists()) - { - throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Unable to find rendition " + streamId + " for " + reference.toString()); - } - FileCopyUtils.copy(resource.getInputStream(), res.getOutputStream()); - } - -} \ No newline at end of file diff --git a/source/java/org/alfresco/repo/web/scripts/content/ContentInfo.java b/source/java/org/alfresco/repo/web/scripts/content/ContentInfo.java deleted file mode 100644 index 88cddf63aa..0000000000 --- a/source/java/org/alfresco/repo/web/scripts/content/ContentInfo.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (C) 2005-2013 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 . - */ -package org.alfresco.repo.web.scripts.content; - -import java.io.IOException; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.cmis.CMISObjectReference; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.cmis.reference.ReferenceFactory; -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.service.cmr.repository.ContentReader; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.QName; -import org.springframework.extensions.webscripts.Cache; -import org.springframework.extensions.webscripts.WebScriptException; -import org.springframework.extensions.webscripts.WebScriptRequest; -import org.springframework.extensions.webscripts.WebScriptResponse; - -/** - * Content Info Service Get info about content from the Repository. - * - * @author alex.malinovsky - */ -public class ContentInfo extends StreamContent -{ - - private ReferenceFactory referenceFactory; - - public void setReferenceFactory(ReferenceFactory referenceFactory) - { - this.referenceFactory = referenceFactory; - } - - @Override - public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException - { - // create empty map of args - Map args = new HashMap(0, 1.0f); - // create map of template vars - Map templateVars = req.getServiceMatch().getTemplateVars(); - // create object reference from url - CMISObjectReference reference = referenceFactory.createObjectReferenceFromUrl(args, templateVars); - NodeRef nodeRef = reference.getNodeRef(); - if (nodeRef == null) - { - throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Unable to find " + reference.toString()); - } - - // render content - QName propertyQName = ContentModel.PROP_CONTENT; - - // Stream the content - streamContent(req, res, nodeRef, propertyQName, false, null, null); - } - - protected void streamContentImpl(WebScriptRequest req, WebScriptResponse res, - ContentReader reader, NodeRef nodeRef, QName propertyQName, - boolean attach, Date modified, String eTag, String attachFileName) - throws IOException - { - delegate.setAttachment(req, res, attach, attachFileName); - - // establish mimetype - String mimetype = reader.getMimetype(); - String extensionPath = req.getExtensionPath(); - if (mimetype == null || mimetype.length() == 0) - { - mimetype = MimetypeMap.MIMETYPE_BINARY; - int extIndex = extensionPath.lastIndexOf('.'); - if (extIndex != -1) - { - String ext = extensionPath.substring(extIndex + 1); - mimetype = mimetypeService.getMimetype(ext); - } - } - - // set mimetype for the content and the character encoding + length for the stream - res.setContentType(mimetype); - res.setContentEncoding(reader.getEncoding()); - res.setHeader("Content-Length", Long.toString(reader.getSize())); - - // set caching - Cache cache = new Cache(); - cache.setNeverCache(false); - cache.setMustRevalidate(true); - cache.setMaxAge(0L); - cache.setLastModified(modified); - cache.setETag(eTag); - res.setCache(cache); - } - -} diff --git a/source/java/org/alfresco/repo/web/scripts/content/ContentSet.java b/source/java/org/alfresco/repo/web/scripts/content/ContentSet.java deleted file mode 100644 index 1aba4d0161..0000000000 --- a/source/java/org/alfresco/repo/web/scripts/content/ContentSet.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.web.scripts.content; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletResponse; - -import org.alfresco.cmis.CMISDictionaryModel; -import org.alfresco.cmis.CMISObjectReference; -import org.alfresco.cmis.CMISServiceException; -import org.alfresco.cmis.CMISServices; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.cmis.reference.ObjectPathReference; -import org.alfresco.repo.cmis.reference.ReferenceFactory; -import org.alfresco.service.cmr.dictionary.DataTypeDefinition; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.cmr.repository.MimetypeService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.extensions.webscripts.AbstractWebScript; -import org.springframework.extensions.webscripts.Status; -import org.springframework.extensions.webscripts.WebScriptException; -import org.springframework.extensions.webscripts.WebScriptRequest; -import org.springframework.extensions.webscripts.WebScriptResponse; - - -/** - * Content Write Service - * - * Stream content to the Repository. - * - * @author davidc - */ -public class ContentSet extends AbstractWebScript -{ - // Logger - @SuppressWarnings("unused") - private static final Log logger = LogFactory.getLog(ContentSet.class); - - // Component dependencies - private ReferenceFactory referenceFactory; - private DictionaryService dictionaryService; - private NamespaceService namespaceService; - private CMISServices cmisService; - private MimetypeService mimetypeService; - - /** - * @param reference factory - */ - public void setReferenceFactory(ReferenceFactory referenceFactory) - { - this.referenceFactory = referenceFactory; - } - - /** - * @param dictionaryService - */ - public void setDictionaryService(DictionaryService dictionaryService) - { - this.dictionaryService = dictionaryService; - } - - /** - * @param namespaceService - */ - public void setNamespaceService(NamespaceService namespaceService) - { - this.namespaceService = namespaceService; - } - - /** - * @param cmisServices - */ - public void setCmisService(CMISServices cmisService) - { - this.cmisService = cmisService; - } - - /** - * @param mimetypeService - */ - public void setMimetypeService(MimetypeService mimetypeService) - { - this.mimetypeService = mimetypeService; - } - - /** - * @see org.alfresco.web.scripts.WebScript#execute(org.alfresco.web.scripts.WebScriptRequest, org.alfresco.web.scripts.WebScriptResponse) - */ - public void execute(WebScriptRequest req, WebScriptResponse res) - throws IOException - { - // create map of args - String[] names = req.getParameterNames(); - Map args = new HashMap(names.length, 1.0f); - for (String name : names) - { - args.put(name, req.getParameter(name)); - } - - // create map of template vars - Map templateVars = req.getServiceMatch().getTemplateVars(); - - // create object reference from url - CMISObjectReference reference = referenceFactory.createObjectReferenceFromUrl(args, templateVars); - NodeRef nodeRef = reference.getNodeRef(); - if (nodeRef == null) - { - throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Unable to find " + reference.toString()); - } - - // determine content property - QName propertyQName = ContentModel.PROP_CONTENT; - String contentPart = templateVars.get("property"); - if (contentPart.length() > 0 && contentPart.charAt(0) == ';') - { - if (contentPart.length() < 2) - { - throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Content property malformed"); - } - String propertyName = contentPart.substring(1); - if (propertyName.length() > 0) - { - propertyQName = QName.createQName(propertyName, namespaceService); - } - } - PropertyDefinition propertyDef = dictionaryService.getProperty(propertyQName); - if (propertyDef == null) - { - throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Unable to find content property " + propertyQName + " of " + reference.toString()); - } - if (!propertyDef.getDataType().getName().equals(DataTypeDefinition.CONTENT)) - { - throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Content stream not found"); - } - - // ensure content can be overwritten - String overwrite = req.getParameter("overwriteFlag"); - - // establish mimetype - String mimetype = req.getContentType(); - if (mimetype == null) - { - if (reference instanceof ObjectPathReference) - { - mimetype = mimetypeService.guessMimetype(((ObjectPathReference)reference).getPath()); - } - } - - try - { - boolean isUpdate = cmisService.setContentStream((String) cmisService.getProperty(nodeRef, - CMISDictionaryModel.PROP_OBJECT_ID), propertyQName, overwrite == null || overwrite.equals("true"), - req.getContent().getInputStream(), mimetype); - - // set status - res.setStatus(isUpdate ? Status.STATUS_OK : Status.STATUS_CREATED); - } - catch (CMISServiceException e) - { - throw new WebScriptException(e.getStatusCode(), e.getMessage(), e); - } - } -} \ No newline at end of file diff --git a/source/java/org/alfresco/repo/web/scripts/quickshare/QuickShareContentGet.java b/source/java/org/alfresco/repo/web/scripts/quickshare/QuickShareContentGet.java index 27518a072a..315eacb849 100644 --- a/source/java/org/alfresco/repo/web/scripts/quickshare/QuickShareContentGet.java +++ b/source/java/org/alfresco/repo/web/scripts/quickshare/QuickShareContentGet.java @@ -21,13 +21,14 @@ package org.alfresco.repo.web.scripts.quickshare; import java.io.IOException; import java.util.Map; +import javax.servlet.ServletContext; import javax.servlet.http.HttpServletResponse; import org.alfresco.model.ContentModel; import org.alfresco.model.QuickShareModel; import org.alfresco.repo.tenant.TenantUtil; import org.alfresco.repo.tenant.TenantUtil.TenantRunAsWork; -import org.alfresco.repo.web.scripts.content.ContentGet; +import org.alfresco.repo.web.scripts.content.StreamContent; import org.alfresco.service.cmr.quickshare.InvalidSharedIdException; import org.alfresco.service.cmr.quickshare.QuickShareService; import org.alfresco.service.cmr.repository.InvalidNodeRefException; @@ -41,6 +42,7 @@ import org.apache.commons.logging.LogFactory; import org.springframework.extensions.webscripts.WebScriptException; import org.springframework.extensions.webscripts.WebScriptRequest; import org.springframework.extensions.webscripts.WebScriptResponse; +import org.springframework.web.context.ServletContextAware; /** @@ -53,7 +55,7 @@ import org.springframework.extensions.webscripts.WebScriptResponse; * @author janv * @since Cloud/4.2 */ -public class QuickShareContentGet extends ContentGet +public class QuickShareContentGet extends StreamContent implements ServletContextAware { private static final Log logger = LogFactory.getLog(QuickShareContentGet.class); @@ -64,6 +66,10 @@ public class QuickShareContentGet extends ContentGet private boolean enabled = true; + public void setServletContext(ServletContext servletContext) + { + } + public void setNodeService(NodeService nodeService) { this.nodeService = nodeService; @@ -73,7 +79,6 @@ public class QuickShareContentGet extends ContentGet public void setNamespaceService(NamespaceService namespaceService) { this.namespaceService = namespaceService; - super.setNamespaceService(namespaceService); } public void setQuickShareService(QuickShareService quickShareService) diff --git a/source/test-java/org/alfresco/RemoteApi01TestSuite.java b/source/test-java/org/alfresco/RemoteApi01TestSuite.java index 63f45e682e..b1295f89d3 100644 --- a/source/test-java/org/alfresco/RemoteApi01TestSuite.java +++ b/source/test-java/org/alfresco/RemoteApi01TestSuite.java @@ -45,29 +45,17 @@ public class RemoteApi01TestSuite extends TestSuite } static void tests1(TestSuite suite) - { - suite.addTestSuite(org.alfresco.cmis.changelog.CMISChangeLogServiceTest.class); - suite.addTestSuite(org.alfresco.repo.cmis.rest.test.AspectTest.class); - suite.addTestSuite(org.alfresco.repo.cmis.rest.test.CMISAtomTemplatesTest.class); - } - - static void tests2(TestSuite suite) // - { - suite.addTestSuite(org.alfresco.repo.cmis.rest.test.PolicyTest.class); - } - - static void tests3(TestSuite suite) // { suite.addTestSuite(org.alfresco.repo.management.subsystems.test.SubsystemsTest.class); suite.addTestSuite(org.alfresco.repo.remoteticket.RemoteAlfrescoTicketServiceTest.class); } - static void tests4(TestSuite suite) // + static void tests2(TestSuite suite) // { suite.addTest(org.alfresco.repo.web.scripts.WebScriptTestSuite.suite()); } - static void tests5(TestSuite suite) // + static void tests3(TestSuite suite) // { suite.addTestSuite(org.alfresco.repo.webdav.GetMethodRegressionTest.class); suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.webdav.MoveMethodTest.class)); @@ -77,25 +65,25 @@ public class RemoteApi01TestSuite extends TestSuite suite.addTest(new JUnit4TestAdapter(org.alfresco.repo.webdav.WebDAVMethodTest.class)); } - static void tests6(TestSuite suite) // + static void tests4(TestSuite suite) // { // TestNodeComments.testNodeComments() fails 50% of the time we with previous tests // TestCMIS.testCMIS() fails 30% of the time with previous tests suite.addTest(new JUnit4TestAdapter(org.alfresco.rest.api.tests.ApiTest.class)); } - static void tests7(TestSuite suite) // + static void tests5(TestSuite suite) // { suite.addTest(new JUnit4TestAdapter(org.alfresco.rest.api.tests.TestCMISAPI.class)); // Fails with previous or following tests } - static void tests8(TestSuite suite) // + static void tests6(TestSuite suite) // { suite.addTest(new JUnit4TestAdapter(org.alfresco.rest.workflow.api.tests.DeploymentWorkflowApiTest.class)); suite.addTest(new JUnit4TestAdapter(org.alfresco.rest.workflow.api.tests.ProcessDefinitionWorkflowApiTest.class)); } - static void tests9(TestSuite suite) // + static void tests7(TestSuite suite) // { suite.addTest(new JUnit4TestAdapter(org.alfresco.rest.workflow.api.tests.ProcessWorkflowApiTest.class)); suite.addTest(new JUnit4TestAdapter(org.alfresco.rest.workflow.api.tests.TaskWorkflowApiTest.class)); diff --git a/source/test-java/org/alfresco/RemoteApi08TestSuite.java b/source/test-java/org/alfresco/RemoteApi08TestSuite.java deleted file mode 100644 index 3e4a345392..0000000000 --- a/source/test-java/org/alfresco/RemoteApi08TestSuite.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2005-2014 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 . - */ -package org.alfresco; - -import junit.framework.Test; -import junit.framework.TestSuite; - -/** - * See {@link RemoteApi01TestSuite} - * - * @Author Alan Davis - */ -public class RemoteApi08TestSuite extends TestSuite -{ - public static Test suite() - { - TestSuite suite = new TestSuite(); - RemoteApi01TestSuite.tests8(suite); - return suite; - } -} diff --git a/source/test-java/org/alfresco/RemoteApi09TestSuite.java b/source/test-java/org/alfresco/RemoteApi09TestSuite.java deleted file mode 100644 index ed841be858..0000000000 --- a/source/test-java/org/alfresco/RemoteApi09TestSuite.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2005-2014 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 . - */ -package org.alfresco; - -import junit.framework.Test; -import junit.framework.TestSuite; - -/** - * See {@link RemoteApi01TestSuite} - * - * @Author Alan Davis - */ -public class RemoteApi09TestSuite extends TestSuite -{ - public static Test suite() - { - TestSuite suite = new TestSuite(); - RemoteApi01TestSuite.tests9(suite); - return suite; - } -} \ No newline at end of file diff --git a/source/test-java/org/alfresco/cmis/changelog/CMISChangeLogServiceTest.java b/source/test-java/org/alfresco/cmis/changelog/CMISChangeLogServiceTest.java deleted file mode 100644 index bc6d3976ff..0000000000 --- a/source/test-java/org/alfresco/cmis/changelog/CMISChangeLogServiceTest.java +++ /dev/null @@ -1,482 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.cmis.changelog; - -import java.io.Serializable; -import java.security.SecureRandom; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import javax.transaction.Status; -import javax.transaction.UserTransaction; - -import junit.framework.TestCase; - -import org.alfresco.cmis.CMISCapabilityChanges; -import org.alfresco.cmis.CMISChangeEvent; -import org.alfresco.cmis.CMISChangeLog; -import org.alfresco.cmis.CMISChangeLogService; -import org.alfresco.cmis.CMISChangeType; -import org.alfresco.cmis.CMISInvalidArgumentException; -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.audit.AuditComponent; -import org.alfresco.repo.audit.AuditServiceImpl; -import org.alfresco.repo.audit.UserAuditFilter; -import org.alfresco.repo.audit.model.AuditModelRegistryImpl; -import org.alfresco.repo.security.authentication.AuthenticationComponent; -import org.alfresco.repo.security.authentication.AuthenticationUtil; -import org.alfresco.repo.transaction.RetryingTransactionHelper; -import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; -import org.alfresco.service.cmr.model.FileFolderService; -import org.alfresco.service.cmr.model.FileInfo; -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.AccessStatus; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.service.namespace.QName; -import org.alfresco.service.transaction.TransactionService; -import org.alfresco.test_category.OwnJVMTestsCategory; -import org.alfresco.util.ApplicationContextHelper; -import org.springframework.context.ApplicationContext; -import org.alfresco.util.Pair; -import org.junit.experimental.categories.Category; - - -/** - * Base tests for {@link CMISChangeLogServiceImpl} - * - * @author Dmitry Velichkevich - */ -@Category(OwnJVMTestsCategory.class) -public class CMISChangeLogServiceTest extends TestCase -{ - private static final String CMIS_AUTHORITY = "cmis"; - private static final String CHANGE_PREFIX = "Changed"; - private static final String INVALID_CHANGE_TOKEN = ""; - private static final String[] NAME_PARTS = new String[] { "TestDocument (", ").txt", "TestFolder (", ")" }; - - private static int TOTAL_AMOUNT = 31; - private static int CREATED_AMOUNT = 18; - private static final int THE_HALFT_OF_CREATED_AMOUNT = CREATED_AMOUNT / 2; - private static final Map EXPECTED_AMOUNTS = new HashMap(); - static - { - EXPECTED_AMOUNTS.put(CMISChangeType.CREATED, 5); - EXPECTED_AMOUNTS.put(CMISChangeType.DELETED, 3); - EXPECTED_AMOUNTS.put(CMISChangeType.SECURITY, 4); - EXPECTED_AMOUNTS.put(CMISChangeType.UPDATED, 6); - } - - private AuditModelRegistryImpl auditSubsystem; - private CMISChangeLogService changeLogService; - private NodeService nodeService; - private FileFolderService fileFolderService; - private PermissionService permissionService; - private TransactionService transactionService; - private AuthenticationComponent authenticationComponent; - private RetryingTransactionHelper retryingTransactionHelper; - private UserTransaction testTX; - - private int actualCount = 0; - private Map actualAmounts = new HashMap(); - private List created = null; - private List deleted = null; - - private void disableAudit() - { - auditSubsystem.stop(); - auditSubsystem.setProperty("audit.enabled", "true"); - auditSubsystem.setProperty("audit.cmischangelog.enabled", "false"); - } - - private void enableAudit() - { - auditSubsystem.stop(); - auditSubsystem.setProperty("audit.enabled", "true"); - auditSubsystem.setProperty("audit.cmischangelog.enabled", "true"); - } - - /** - * Tests {@link CMISChangeLogServiceImpl} with disabled Auditing feature - * - * @throws Exception - */ - public void testServiceWithDisabledAuditing() throws Exception - { - disableAudit(); - String lastChangeLogToken = changeLogService.getLastChangeLogToken(); - createTestData(EXPECTED_AMOUNTS, false); - assertEquals(CMISCapabilityChanges.NONE, changeLogService.getCapability()); - try - { - changeLogService.getChangeLogEvents(lastChangeLogToken, null); - fail("Changes Logging was not enabled but no one Change Log Service method thrown exception"); - } - catch (Exception e) - { - assertTrue("Invalid exception type from Change Log Service method call with desabled Changes Logging", e instanceof AlfrescoRuntimeException); - } - } - - /** - * Tests {@link CMISChangeLogServiceImpl} with enabled Auditing feature - * - * @throws Exception - */ - public void testEnabledAuditing() throws Exception - { - enableAudit(); - String logToken = changeLogService.getLastChangeLogToken(); - createTestData(EXPECTED_AMOUNTS, false); - assertEquals(CMISCapabilityChanges.OBJECTIDSONLY, changeLogService.getCapability()); - CMISChangeLog changeLog = changeLogService.getChangeLogEvents(logToken, null); - assertChangeLog(logToken, changeLog); - assertChangeEvents(logToken, changeLog, null, FoldersAppearing.NOT_EXPECTED); - } - - /** - * Validates Change Log descriptor that was returned for some Change Log Token - * - * @param logToken {@link String} value that represents last Change Log Token - * @param changeLog {@link CMISChangeLog} instance that represents Change Log descriptor - */ - private void assertChangeLog(String logToken, CMISChangeLog changeLog) - { - assertNotNull(("'" + logToken + "' Change Log Token has no descriptor"), changeLog); - assertNotNull(("Event Etries for '" + logToken + "' Change Log Token are undefined"), changeLog.getChangeEvents()); - assertFalse(("Descriptor for '" + logToken + "' Change Log Token has no any Event Entry"), changeLog.getChangeEvents().isEmpty()); - } - - /** - * Creates test data which will represent Change Events of all possible types - * - * @param requiredAmounts {@link Map}<{@link CMISChangeType}, {@link Integer}> container instance that determines amount of Change Event for each Change Type - * @return pair containing list of created node refs, and list of deleted node refs - * @see CMISChangeType - */ - private Pair, List> createTestData(Map requiredAmounts, boolean withFolders) - { - changeLogService.getLastChangeLogToken(); - created = new LinkedList(); - deleted = new LinkedList(); - Pair, List> result = new Pair, List>(created, deleted); - NodeRef parentNodeRef = nodeService.getRootNode(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE); - SecureRandom randomizer = new SecureRandom(); - for (CMISChangeType key : requiredAmounts.keySet()) - { - Integer amount = requiredAmounts.get(key); - for (int i = 0; i < amount; i++) - { - boolean folder = withFolders && (0 == ((Math.abs(randomizer.nextInt()) % amount) % 2)); - QName objectType = (folder) ? (ContentModel.TYPE_FOLDER) : (ContentModel.TYPE_CONTENT); - FileInfo object = fileFolderService.create(parentNodeRef, generateName(randomizer, folder), objectType); - created.add(object.getNodeRef()); - addOneToAmount(actualAmounts, CMISChangeType.CREATED); - switch (key) - { - case DELETED: - { - nodeService.deleteNode(object.getNodeRef()); - deleted.add(object.getNodeRef()); - addOneToAmount(actualAmounts, CMISChangeType.DELETED); - break; - } - case SECURITY: - { - permissionService.setPermission(object.getNodeRef(), CMIS_AUTHORITY, PermissionService.EXECUTE_CONTENT, true); - addOneToAmount(actualAmounts, CMISChangeType.SECURITY); - break; - } - case UPDATED: - { - StringBuilder nameBuilder = new StringBuilder(CHANGE_PREFIX); - nameBuilder.append(nodeService.getProperty(object.getNodeRef(), ContentModel.PROP_NAME)); - nodeService.setProperty(object.getNodeRef(), ContentModel.PROP_NAME, nameBuilder.toString()); - addOneToAmount(actualAmounts, CMISChangeType.UPDATED); - } - } - actualCount++; - } - } - return result; - } - - /** - * Deletes each element of created test data if element exist and current user has appropriate rights - * - * @param testData {@link Map}<{@link NodeRef}, {@link Map}<{@link QName}, {@link Serializable}>> container instance that contains test data - */ - private void deleteTestData() - { - if (created != null) - { - for (NodeRef object : created) - { - if (nodeService.exists(object) && (AccessStatus.ALLOWED == permissionService.hasPermission(object, PermissionService.DELETE))) - { - nodeService.deleteNode(object); - } - } - } - } - - /** - * @param folder {@link Boolean} value that determines which name should be generated (for Folder or Document Object) - * @return {@link String} value that represents generated uniquely name for Document Object - */ - private String generateName(SecureRandom randomizer, boolean folder) - { - StringBuilder nameBuilder = new StringBuilder(); - int i = (folder) ? (2) : (0); - nameBuilder.append(NAME_PARTS[i++]).append(Math.abs(randomizer.nextInt())).append(NAME_PARTS[i++]); - return nameBuilder.toString(); - } - - /** - * This method validates Change Event entries according to created earlier Objects. According to assertProperties parameter this method may and may not check properties - * of Change Event entry according to appropriate expected Object against Change Type - * - * @param expectedObjects {@link Map}<{@link NodeRef}, {@link Map}<{@link QName}, {@link Serializable}>> container instance that contains Ids and properties of - * expected Objects - * @param logToken {@link String} value that represents last Change Log Token - * @param changeLog {@link CMISChangeLog} instance that represents Change Log descriptor for last Change Log Token - * @param maxItems {@link Integer} value that determines high bound of Change Events amount - * @see CMISChangeType - */ - private void assertChangeEvents(String logToken, CMISChangeLog changeLog, Integer maxItems, FoldersAppearing foldersAppearing) - { - Map logAmounts = new HashMap(); - boolean folderWasFound = false; - int idx = 0; - for (CMISChangeEvent event : changeLog.getChangeEvents()) - { - // skip first change log entry if a log token has been specified, as the CMIS spec expects - // the change entry to be returned for the specified log token - idx++; - if (logToken != null && idx == 1) - { - continue; - } - - assertNotNull(("One of the Change Log Event Enries is undefined for '" + logToken + "' Change Log Token"), event); - assertNotNull(("Change Event Entry Id of one of the Change Entries is undefined for '" + logToken + "' Change Log Token"), event.getChangedNode()); - assertNotNull(("Change Event Change Type of one of the Change Entries is undefined for '" + logToken + "' Change Log Token"), event.getChangeType()); - assertTrue("Unexpected Object Id='" + event.getChangedNode().toString() + "' from Change Log Token Entries list for '" + logToken + "' Change Log Token", created - .contains(event.getChangedNode())); - if (!deleted.contains(event.getChangedNode())) - { - folderWasFound = folderWasFound || fileFolderService.getFileInfo(event.getChangedNode()).isFolder(); - assertTrue( - ("Object from Change Event Entries list is marked as '" + event.getChangeType().toString() + "' but does not exist for '" + logToken + "' Change Log Token"), - nodeService.exists(event.getChangedNode())); - } - else - { - assertTrue("Object has been deleted", deleted.contains(event.getChangedNode())); - assertFalse(("Object from Change Event Entries list is marked as 'DELETED' but it still exist for '" + logToken + "' Change Log Token"), nodeService.exists(event - .getChangedNode())); - } - addOneToAmount(logAmounts, event.getChangeType()); - } - if (FoldersAppearing.MUST_APPEAR == foldersAppearing) - { - assertTrue("No one Folder Object was returned", folderWasFound); - } - else - { - if (FoldersAppearing.NOT_EXPECTED == foldersAppearing) - { - assertFalse("Some Folder Object was found", folderWasFound); - } - } - if ((null == maxItems) || (maxItems >= TOTAL_AMOUNT)) - { - for (CMISChangeType key : actualAmounts.keySet()) - { - Integer actualAmount = actualAmounts.get(key); - Integer logAmount = logAmounts.get(key); - assertTrue(("Invalid Entries amount for '" + key.toString() + "' Change Type. Actual amount: " + actualAmount + ", but log amount: " + logAmount), actualAmount - .equals(logAmount)); - } - } - } - - private enum FoldersAppearing - { - NOT_EXPECTED, MAY_APPEAR, MUST_APPEAR - } - - /** - * Determines which kind of Change was handled and increments appropriate amount to 1 - * - * @param mappedAmounts {@link Map}>{@link CMISChangeType}, {@link Integer}< container instance that contains all accumulated amounts for each kind of Change - * @param changeType {@link CMISChangeType} enum value that determines kind of Change - */ - private void addOneToAmount(Map mappedAmounts, CMISChangeType changeType) - { - Integer amount = mappedAmounts.get(changeType); - amount = (null == amount) ? (Integer.valueOf(1)) : (Integer.valueOf(amount.intValue() + 1)); - mappedAmounts.put(changeType, amount); - } - - /** - * Test {@link CMISChangeLogServiceImpl} with enabled Auditing feature for Max Items parameter - * - * @throws Exception - */ - public void testEnabledAuditingForMaxItems() throws Exception - { - enableAudit(); - String logToken = changeLogService.getLastChangeLogToken(); - createTestData(EXPECTED_AMOUNTS, false); - assertEquals(CMISCapabilityChanges.OBJECTIDSONLY, changeLogService.getCapability()); - CMISChangeLog changeLog = changeLogService.getChangeLogEvents(logToken, THE_HALFT_OF_CREATED_AMOUNT); - assertChangeLog(logToken, changeLog); - assertChangeEvents(logToken, changeLog, THE_HALFT_OF_CREATED_AMOUNT, FoldersAppearing.NOT_EXPECTED); - assertEquals(THE_HALFT_OF_CREATED_AMOUNT, changeLog.getChangeEvents().size()); - assertTrue("Not all Change Log Entries were requested but result set is indicating that no one more Entry is avilable", changeLog.hasMoreItems()); - changeLog = changeLogService.getChangeLogEvents(logToken, TOTAL_AMOUNT + (logToken == null ? 0 : 1)); - assertChangeEvents(logToken, changeLog, TOTAL_AMOUNT, FoldersAppearing.NOT_EXPECTED); - assertFalse("All Change Log Entries were requested but result set is indicating that some more Entry(s) are available", changeLog.hasMoreItems()); - } - - /** - * This method tests {@link CMISChangeLogServiceImpl} on receiving Change Event Entries for Invalid Change Log Token with enable and disabled Changes Logging - * - * @throws Exception - */ - public void testReceivingChangeEventsForInvalidChangeToken() throws Exception - { - enableAudit(); - try - { - changeLogService.getChangeLogEvents(INVALID_CHANGE_TOKEN, null); - fail("Change Events were received normally for Invalid Change Log Token"); - } - catch (Exception e) - { - assertTrue("Invalid exception type from Change Log Service method call with enabled Changes Logging", e instanceof CMISInvalidArgumentException); - } - disableAudit(); - try - { - changeLogService.getChangeLogEvents(INVALID_CHANGE_TOKEN, null); - fail("Changes Logging was not enabled but not one Change Log Service method thrown exception"); - } - catch (Exception e) - { - assertTrue("Invalid exception type from Change Log Service method call with desabled Changes Logging", e instanceof AlfrescoRuntimeException); - } - } - - /** - * This method tests {@link CMISChangeLogServiceImpl} on working with Change Event entries which could contain Folder Objects - * - * @throws Exception - */ - public void testReceivingOfChangeEventsExpectingFolders() throws Exception - { - enableAudit(); - String changeToken = changeLogService.getLastChangeLogToken(); - createTestData(EXPECTED_AMOUNTS, true); - CMISChangeLog changeLogEvents = changeLogService.getChangeLogEvents(changeToken, null); - assertChangeLog(changeToken, changeLogEvents); - assertChangeEvents(changeToken, changeLogEvents, null, FoldersAppearing.MUST_APPEAR); - } - - /** - * This method tests {@link CMISChangeLogServiceImpl} on working with Change Event entries which could contain Folder Objects. Also this method tests behavior of Max Items - * parameter for Folder Objects - * - * @throws Exception - */ - public void testReceivingOfChangeEventsExpectingFoldersAndBoundedByMaxItems() throws Exception - { - enableAudit(); - String changeToken = changeLogService.getLastChangeLogToken(); - createTestData(EXPECTED_AMOUNTS, true); - CMISChangeLog changeLogEvents = changeLogService.getChangeLogEvents(changeToken, 15); - assertTrue("Not all Change Event Entries were requested but result set indicates that no more Entry(s) available", changeLogEvents.hasMoreItems()); - assertChangeLog(changeToken, changeLogEvents); - assertChangeEvents(changeToken, changeLogEvents, 15, FoldersAppearing.MAY_APPEAR); - changeLogEvents = changeLogService.getChangeLogEvents(changeToken, TOTAL_AMOUNT + (changeToken == null ? 0 : 1)); - assertChangeLog(changeToken, changeLogEvents); - assertChangeEvents(changeToken, changeLogEvents, TOTAL_AMOUNT, FoldersAppearing.MUST_APPEAR); - assertFalse("All Change Event Entries were requested but results indicating that some more Entry(s) available", changeLogEvents.hasMoreItems()); - } - - @Override - public void setUp() throws Exception - { - ApplicationContext applicationContext = ApplicationContextHelper.getApplicationContext(); - changeLogService = (CMISChangeLogService) applicationContext.getBean("CMISChangeLogService"); - nodeService = (NodeService) applicationContext.getBean("NodeService"); - permissionService = (PermissionService) applicationContext.getBean("PermissionService"); - fileFolderService = (FileFolderService) applicationContext.getBean("FileFolderService"); - transactionService = (TransactionService) applicationContext.getBean("transactionComponent"); - authenticationComponent = (AuthenticationComponent) applicationContext.getBean("authenticationComponent"); - retryingTransactionHelper = (RetryingTransactionHelper) applicationContext.getBean("retryingTransactionHelper"); - //MNT-10807 : Auditing does not take into account audit.filter.alfresco-access.transaction.user - UserAuditFilter userAuditFilter = new UserAuditFilter(); - userAuditFilter.setUserFilterPattern("System;.*"); - userAuditFilter.afterPropertiesSet(); - AuditComponent auditComponent = (AuditComponent) applicationContext.getBean("auditComponent"); - auditComponent.setUserAuditFilter(userAuditFilter); - AuditServiceImpl auditServiceImpl = (AuditServiceImpl) applicationContext.getBean("auditService"); - auditServiceImpl.setAuditComponent(auditComponent); - auditSubsystem = (AuditModelRegistryImpl) applicationContext.getBean("Audit"); - - // initialise audit subsystem - RetryingTransactionCallback initAudit = new RetryingTransactionCallback() - { - public Void execute() throws Exception - { - auditSubsystem.stop(); - auditSubsystem.setProperty("audit.enabled", "true"); - auditSubsystem.setProperty("audit.cmischangelog.enabled", "true"); - auditSubsystem.start(); - return null; - } - }; - retryingTransactionHelper.doInTransaction(initAudit, false, true); - - // start test transaction - testTX = transactionService.getUserTransaction(); - testTX.begin(); - this.authenticationComponent.setSystemUserAsCurrentUser(); - } - - @Override - protected void tearDown() throws Exception - { - deleteTestData(); - - if (testTX.getStatus() == Status.STATUS_ACTIVE) - { - testTX.rollback(); - } - AuthenticationUtil.clearCurrentSecurityContext(); - - auditSubsystem.destroy(); - } -} diff --git a/source/test-java/org/alfresco/repo/cmis/rest/test/AspectTest.java b/source/test-java/org/alfresco/repo/cmis/rest/test/AspectTest.java deleted file mode 100644 index 80eb09dc6d..0000000000 --- a/source/test-java/org/alfresco/repo/cmis/rest/test/AspectTest.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.rest.test; - -import java.io.StringReader; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import javax.xml.namespace.QName; - -import org.apache.abdera.i18n.iri.IRI; -import org.apache.abdera.model.Element; -import org.apache.abdera.model.Entry; -import org.apache.abdera.model.Link; -import org.apache.chemistry.abdera.ext.CMISConstants; -import org.apache.chemistry.abdera.ext.CMISObject; -import org.apache.chemistry.abdera.ext.CMISProperty; -import org.junit.Assert; -import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest; -import org.springframework.extensions.webscripts.TestWebScriptServer.PostRequest; -import org.springframework.extensions.webscripts.TestWebScriptServer.PutRequest; -import org.springframework.extensions.webscripts.TestWebScriptServer.Request; -import org.springframework.extensions.webscripts.TestWebScriptServer.Response; - -/** - * Tests Alfresco CMIS REST API extensions for Aspects. - * - * @author dward - */ -public class AspectTest extends BaseCMISTest -{ - public void testAspectSet() throws Exception - { - // create document for checkout - Link children = cmisClient.getChildrenLink(testCaseFolder); - Entry document = createObject(children.getHref(), getName(), "cmis:document"); - Request documentReq = new GetRequest(document.getSelfLink().getHref().toString()); - Response documentRes = sendRequest(documentReq, 200); - Assert.assertNotNull(documentRes); - String xml = documentRes.getContentAsString(); - Assert.assertNotNull(xml); - - // checkout - IRI checkedoutHREF = cmisClient.getCheckedOutCollection(cmisClient.getWorkspace(cmisService)); - Request checkoutReq = new PostRequest(checkedoutHREF.toString(), xml, CMISConstants.MIMETYPE_ENTRY); - Response pwcRes = sendRequest(checkoutReq, 201); - Assert.assertNotNull(pwcRes); - Entry pwc = parse(new StringReader(pwcRes.getContentAsString())); - Assert.assertNotNull(pwc); - - // Apply some aspects to the working copy - String updateFile = localTemplates.load("AspectTest.addAspects.cmisatomentry.xml"); - - Request updateReq = new PutRequest(pwc.getEditLink().getHref().toString(), updateFile, - CMISConstants.MIMETYPE_ENTRY); - Response pwcUpdatedres = sendRequest(updateReq, 200); - Assert.assertNotNull(pwcUpdatedres); - Entry updated = parse(new StringReader(pwcUpdatedres.getContentAsString())); - - { - Set appliedAspects = new HashSet(5); - Map aspectProperties = new HashMap(11); - extractAspectsAndProperties(updated, appliedAspects, aspectProperties); - assertContains(appliedAspects, "P:cm:syndication", "P:cm:summarizable", "P:cm:author"); - assertEquals("Aspect Test (summary)", aspectProperties.get("cm:summary")); - assertEquals("David Ward", aspectProperties.get("cm:author")); - } - - // check in with updated aspects - String checkinFile = localTemplates.load("AspectTest.removeAndAddAspects.cmisatomentry.xml"); - String checkinUrl = pwc.getSelfLink().getHref().toString(); - Request checkinReq = new PutRequest(checkinUrl, checkinFile, CMISConstants.MIMETYPE_ENTRY).setArgs(Collections - .singletonMap("checkin", "true")); - Response checkinRes = sendRequest(checkinReq, 200); - Assert.assertNotNull(checkinRes); - Entry checkedIn = parse(new StringReader(checkinRes.getContentAsString())); - { - Set appliedAspects = new HashSet(5); - Map aspectProperties = new HashMap(11); - extractAspectsAndProperties(checkedIn, appliedAspects, aspectProperties); - assertContains(appliedAspects, "P:cm:syndication", "P:cm:summarizable", "P:cm:countable"); - assertDoesNotContain(appliedAspects, "P:cm:author"); - assertEquals("Aspect Test (new summary)", aspectProperties.get("cm:summary")); - assertNull(aspectProperties.get("cm:author")); - } - } - - /** - * @param document - * @param appliedAspects - * @param aspectProperties - */ - private void extractAspectsAndProperties(Entry document, Set appliedAspects, - Map aspectProperties) - { - CMISObject documentObject = document.getExtension(CMISConstants.OBJECT); - Assert.assertNotNull(documentObject); - Element aspectEl = documentObject.getProperties().getExtension(new QName("http://www.alfresco.org", "aspects")); - Assert.assertNotNull(aspectEl); - for (Element child : aspectEl) - { - if (child.getQName().equals(ELEMENT_APPLIED_ASPECTS)) - { - appliedAspects.add(child.getText()); - } - else if (child.getQName().equals(ELEMENT_PROPERTIES)) - { - for (Element propertyEl : child) - { - if (propertyEl instanceof CMISProperty) - { - CMISProperty prop = (CMISProperty) propertyEl; - aspectProperties.put(prop.getId(), prop.getStringValue()); - } - } - } - else - { - fail("Unexpected element: " + child.getQName()); - } - } - } -} diff --git a/source/test-java/org/alfresco/repo/cmis/rest/test/BaseCMISTest.java b/source/test-java/org/alfresco/repo/cmis/rest/test/BaseCMISTest.java deleted file mode 100644 index 6a770b1fc4..0000000000 --- a/source/test-java/org/alfresco/repo/cmis/rest/test/BaseCMISTest.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.rest.test; - -import java.io.Reader; -import java.io.StringReader; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import javax.xml.namespace.QName; - -import org.alfresco.repo.cmis.rest.AlfrescoCMISExtensionFactory; -import org.alfresco.repo.web.scripts.BaseWebScriptTest; -import org.apache.abdera.Abdera; -import org.apache.abdera.factory.Factory; -import org.apache.abdera.i18n.iri.IRI; -import org.apache.abdera.model.Document; -import org.apache.abdera.model.Element; -import org.apache.abdera.model.Entry; -import org.apache.abdera.model.Service; -import org.apache.abdera.parser.ParseException; -import org.apache.abdera.parser.Parser; -import org.apache.chemistry.abdera.ext.CMISConstants; -import org.apache.chemistry.tck.atompub.client.CMISClient; -import org.apache.chemistry.tck.atompub.utils.ResourceLoader; -import org.junit.Assert; -import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest; -import org.springframework.extensions.webscripts.TestWebScriptServer.PostRequest; -import org.springframework.extensions.webscripts.TestWebScriptServer.Request; -import org.springframework.extensions.webscripts.TestWebScriptServer.Response; - -/** - * Base class for Alfresco specific CMIS REST API tests. - * - * @author dward - */ -public abstract class BaseCMISTest extends BaseWebScriptTest -{ - protected static final QName ELEMENT_PROPERTIES = new QName("http://www.alfresco.org", "properties"); - protected static final QName ELEMENT_APPLIED_ASPECTS = new QName("http://www.alfresco.org", "appliedAspects"); - - protected static final String URL_CMIS = "/cmis"; - - protected Abdera abdera; - protected Parser parser; - protected Factory factory; - - public BaseCMISTest() - { - // construct Abdera Service - abdera = new Abdera(); - factory = abdera.getFactory(); - factory.registerExtension(new AlfrescoCMISExtensionFactory()); - parser = factory.newParser(); - - // construct test templates - localTemplates = new ResourceLoader('/' + getClass().getPackage().getName().replace('.', '/') + '/'); - - // Create a dummy client. We won't / can't use it to make requests. - cmisClient = new CMISClient(null, null, null, null); - cmisClient.setValidate(false); - } - - protected CMISClient cmisClient; - protected ResourceLoader localTemplates; - protected Service cmisService; - protected Entry testCaseFolder; - - @Override - public void setUp() throws Exception - { - super.setUp(); - - setDefaultRunAs("admin"); - - Request req = new GetRequest(URL_CMIS); - Response res = sendRequest(req, 200); - String xml = res.getContentAsString(); - Assert.assertNotNull(xml); - Assert.assertTrue(xml.length() > 0); - cmisService = parse(new StringReader(xml)); - Assert.assertNotNull(cmisService); - IRI rootFolderHREF = cmisClient.getRootCollection(cmisClient.getWorkspace(cmisService)); - Assert.assertNotNull(rootFolderHREF); - String folderName = getClass().getSimpleName() + System.currentTimeMillis() + " - " + getName(); - testCaseFolder = createObject(rootFolderHREF, folderName, "cmis:folder"); - } - - protected T parse(Reader doc) - { - Document entryDoc = parser.parse(doc); - return entryDoc.getRoot(); - } - - protected T fetch(IRI href, Map args) throws Exception - { - Request get = new GetRequest(href.toString()).setArgs(args); - Response res = sendRequest(get, 200); - Assert.assertNotNull(res); - String xml = res.getContentAsString(); - T result = this. parse(new StringReader(xml)); - Assert.assertNotNull(result); - return result; - } - - protected Entry createObject(IRI parent, String name, String type) throws Exception - { - return createObject(parent, name, type, 201); - } - - protected T createObject(IRI parent, String name, String type, int expectedStatus) throws Exception - { - String createObject = localTemplates.load("BaseCMISTest.createObject.atomentry.xml"); - createObject = createObject.replace("${NAME}", name); - createObject = createObject.replace("${TYPE}", type); - Request req = new PostRequest(parent.toString(), createObject, CMISConstants.MIMETYPE_ENTRY); - Response res = sendRequest(req, expectedStatus); - Assert.assertNotNull(res); - try - { - String xml = res.getContentAsString(); - return this. parse(new StringReader(xml)); - } - catch (ParseException e) - { - } - return null; - } - - protected void assertContains(Set actual, String... expected) - { - Assert.assertTrue(actual.containsAll(Arrays.asList(expected))); - } - - protected void assertDoesNotContain(Set actual, String... unexpected) - { - Set copy = new HashSet(actual); - copy.retainAll(Arrays.asList(unexpected)); - Assert.assertTrue(copy.isEmpty()); - } -} diff --git a/source/test-java/org/alfresco/repo/cmis/rest/test/BulkCreateAndQuerySystemTest.java b/source/test-java/org/alfresco/repo/cmis/rest/test/BulkCreateAndQuerySystemTest.java deleted file mode 100644 index 02c9ada96c..0000000000 --- a/source/test-java/org/alfresco/repo/cmis/rest/test/BulkCreateAndQuerySystemTest.java +++ /dev/null @@ -1,132 +0,0 @@ -package org.alfresco.repo.cmis.rest.test; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; -import java.util.List; - -import javax.xml.namespace.QName; - -import org.apache.abdera.Abdera; -import org.apache.abdera.model.Document; -import org.apache.abdera.model.Element; -import org.apache.abdera.model.Entry; -import org.apache.abdera.model.Feed; -import org.apache.abdera.protocol.Response; -import org.apache.abdera.protocol.client.AbderaClient; -import org.apache.abdera.protocol.client.ClientResponse; -import org.apache.chemistry.abdera.ext.CMISConstants; -import org.apache.chemistry.abdera.ext.CMISExtensionFactory; -import org.apache.chemistry.abdera.ext.CMISObject; -import org.apache.chemistry.abdera.ext.CMISProperties; -import org.apache.chemistry.abdera.ext.CMISProperty; -import org.apache.commons.httpclient.UsernamePasswordCredentials; -import org.apache.commons.httpclient.methods.StringRequestEntity; - - -public class BulkCreateAndQuerySystemTest -{ - private static Abdera abdera; - private static final String URL = "http://localhost:8080"; - private static final String rootFolder = "testfolder"; - - public static void main(String[] args) throws Exception { - abdera = new Abdera(); - abdera.getFactory().registerExtension(new CMISExtensionFactory()); - - AbderaClient client = new AbderaClient(abdera); - - client.setMaxConnectionsPerHost(100); - client.addCredentials(URL, null, "basic", new UsernamePasswordCredentials("admin", "admin")); - - String rootId = createFolder(client, URL + "/alfresco/service/cmis/p/children", rootFolder); - - for (int i = 0; i < 10000; i++) { - createFolder(client, URL + "/alfresco/service/cmis/p/" + rootFolder + "/children", "folder_" + i); - findFolder(client, rootId, "folder_" + i); - } - } - - private static void findFolder(AbderaClient client, String inFolderId, String name) { - System.out.println("querying for " + name + " in " + inFolderId); - String query = "\n" + - "SELECT cmis:Name, cmis:ObjectId FROM cmis:folder WHERE cmis:Name='" + name + "' AND IN_FOLDER('" + inFolderId + "')\n" + - "100\n" + - "0\n" + - ""; - - StringRequestEntity requestEntity; - try { - requestEntity = new StringRequestEntity(query, "application/cmisquery+xml", "ISO-8859-1"); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - - ClientResponse response = client.post(URL + "/alfresco/service/cmis/queries", requestEntity); - try { - if (response.getType() == Response.ResponseType.SUCCESS) { - - Document feed = response.getDocument(); - List entries = feed.getRoot().getEntries(); - for (Entry entry : entries) { - System.out.println("received query result with name " + entry.getTitle()); - } - } else { - throw new RuntimeException(response.getStatusText()); - } - } finally { - response.release(); - } - } - - private static String createFolder(AbderaClient client, String parent, String name) throws Exception { - Entry entry = abdera.newEntry(); - entry.setTitle(name); - entry.setSummary("Summary..."); - - CMISObject cmisObject = entry.addExtension(CMISConstants.OBJECT); - CMISProperties properties = cmisObject.addExtension(CMISConstants.PROPERTIES); - CMISProperty property = properties.addExtension(CMISConstants.ID_PROPERTY); - property.setAttributeValue(CMISConstants.PROPERTY_ID, CMISConstants.PROP_OBJECT_TYPE_ID); - Element value = property.addExtension(CMISConstants.PROPERTY_VALUE); - value.setText("cmis:folder"); - - ClientResponse resp = client.post(parent, entry); - - try { - if (resp.getType() != Response.ResponseType.SUCCESS) { - printError(resp); - - throw new RuntimeException(resp.getStatusText()); - } else { - System.out.println("Created folder " + name); - - Document entryDoc = resp.getDocument(); - Entry root = entryDoc.getRoot(); - - CMISObject object = root.getExtension(CMISConstants.OBJECT); - CMISProperties p = object.getProperties(); - - return p.find(CMISConstants.PROP_OBJECT_ID).getStringValue(); - } - } finally { - resp.release(); - } - } - - private static void printError(ClientResponse resp) { - try { - InputStream inputStream = resp.getInputStream(); - BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); - String line = reader.readLine(); - while (line != null) { - System.out.println(line); - line = reader.readLine(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } -} diff --git a/source/test-java/org/alfresco/repo/cmis/rest/test/BulkCreateSystemTest.java b/source/test-java/org/alfresco/repo/cmis/rest/test/BulkCreateSystemTest.java deleted file mode 100644 index fdce80c7b0..0000000000 --- a/source/test-java/org/alfresco/repo/cmis/rest/test/BulkCreateSystemTest.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.rest.test; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; - -import org.apache.abdera.Abdera; -import org.apache.abdera.model.Document; -import org.apache.abdera.model.Element; -import org.apache.abdera.model.Entry; -import org.apache.abdera.protocol.Response; -import org.apache.abdera.protocol.client.AbderaClient; -import org.apache.abdera.protocol.client.ClientResponse; -import org.apache.chemistry.abdera.ext.CMISConstants; -import org.apache.chemistry.abdera.ext.CMISExtensionFactory; -import org.apache.chemistry.abdera.ext.CMISObject; -import org.apache.chemistry.abdera.ext.CMISProperties; -import org.apache.chemistry.abdera.ext.CMISProperty; -import org.apache.commons.httpclient.UsernamePasswordCredentials; - - -/** - * Test ALFCOM-2947 CMIS: createFolder & immediately add document can fail - */ -public class BulkCreateSystemTest -{ - private static Abdera abdera; - - public static void main(String[] args) throws Exception - { - abdera = new Abdera(); - abdera.getFactory().registerExtension(new CMISExtensionFactory()); - - AbderaClient client = new AbderaClient(abdera); - client.usePreemptiveAuthentication(true); - client.addCredentials("http://localhost:8080", null, "basic", new UsernamePasswordCredentials("admin", "admin")); - - String root = createFolder(client, - "http://localhost:8080/alfresco/service/api/path/workspace/SpacesStore/Company%20Home/children", - "testfolder14"); - - for (int i = 0; i < 100; i++) - { - String folder = createFolder(client, root, "folder_" + i); - createDocument(client, folder, "doc"); - } - } - - private static String createFolder(AbderaClient client, String parent, String name) throws Exception - { - Entry entry = abdera.newEntry(); - entry.setTitle(name); - entry.setSummary("Summarize summarize..."); - - CMISObject cmisObject = entry.addExtension(CMISConstants.OBJECT); - CMISProperties properties = cmisObject.addExtension(CMISConstants.PROPERTIES); - CMISProperty property = properties.addExtension(CMISConstants.ID_PROPERTY); - property.setAttributeValue(CMISConstants.PROPERTY_ID, CMISConstants.PROP_OBJECT_TYPE_ID); - Element value = property.addExtension(CMISConstants.PROPERTY_VALUE); - value.setText("cmis:Folder"); - - ClientResponse resp = client.post(parent, entry); - - try - { - if (resp.getType() != Response.ResponseType.SUCCESS) - { - printError(resp); - - throw new RuntimeException(resp.getStatusText()); - } else - { - System.out.println("Created folder " + name); - - Document entryDoc = resp.getDocument(); - Entry root = entryDoc.getRoot(); - - return root.getLink("children").getHref().toString(); - } - } finally - { - resp.release(); - } - } - - private static void createDocument(AbderaClient client, String parent, String name) - { - Entry entry = abdera.newEntry(); - entry.setTitle(name); - entry.setSummary("Summarize summarize..."); - - CMISObject cmisObject = entry.addExtension(CMISConstants.OBJECT); - CMISProperties properties = cmisObject.addExtension(CMISConstants.PROPERTIES); - CMISProperty property = properties.addExtension(CMISConstants.ID_PROPERTY); - property.setAttributeValue(CMISConstants.PROPERTY_ID, CMISConstants.PROP_OBJECT_TYPE_ID); - Element value = property.addExtension(CMISConstants.PROPERTY_VALUE); - value.setText("document"); - - ClientResponse resp = client.post(parent, entry); - - try - { - if (resp.getType() != Response.ResponseType.SUCCESS) - { - printError(resp); - - throw new RuntimeException(resp.getStatusText()); - } - } finally - { - resp.release(); - } - } - - private static void printError(ClientResponse resp) - { - try - { - InputStream inputStream = resp.getInputStream(); - BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); - String line = reader.readLine(); - while (line != null) - { - System.out.println(line); - line = reader.readLine(); - } - } catch (IOException e) - { - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/source/test-java/org/alfresco/repo/cmis/rest/test/CMISAtomTemplatesTest.java b/source/test-java/org/alfresco/repo/cmis/rest/test/CMISAtomTemplatesTest.java deleted file mode 100644 index 85ddcaf328..0000000000 --- a/source/test-java/org/alfresco/repo/cmis/rest/test/CMISAtomTemplatesTest.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright (C) 2005-2013 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 . - */ -package org.alfresco.repo.cmis.rest.test; - -import java.io.Serializable; -import java.io.StringReader; -import java.util.HashMap; -import java.util.Map; - -import javax.xml.XMLConstants; -import javax.xml.transform.Source; -import javax.xml.transform.sax.SAXSource; -import javax.xml.transform.stream.StreamSource; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; -import javax.xml.validation.Validator; - -import org.alfresco.model.ApplicationModel; -import org.alfresco.model.ContentModel; -import org.alfresco.repo.security.authentication.AuthenticationUtil; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.NodeService; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; -import org.apache.abdera.model.Entry; -import org.apache.abdera.model.Link; - -import org.junit.Assert; -import org.junit.Test; -import org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest; -import org.springframework.extensions.webscripts.TestWebScriptServer.Request; -import org.springframework.extensions.webscripts.TestWebScriptServer.Response; -import org.xml.sax.InputSource; - -public class CMISAtomTemplatesTest extends BaseCMISTest -{ - private NodeService nodeService; - - static String docName; - - static String xmlResponse; - - @Override - public void setUp() throws Exception - { - super.setUp(); - - // create document - docName = "Test 1 _" + System.currentTimeMillis(); - Link children = cmisClient.getChildrenLink(testCaseFolder); - Entry document = createObject(children.getHref(), docName, "cmis:document"); - Request documentReq = new GetRequest(document.getSelfLink().getHref().toString()); - Response documentRes = sendRequest(documentReq, 200); - Assert.assertNotNull(documentRes); - xmlResponse = documentRes.getContentAsString(); - Assert.assertNotNull(xmlResponse); - - this.nodeService = (NodeService)getServer().getApplicationContext().getBean("NodeService"); - } - - @Test - public void testChildrenGetAtomFeed() throws Exception - { - // retrieve the list of nodes - String id = testCaseFolder.getId().toString().replace("urn:uuid:", "workspace:SpacesStore/i/"); - Request get = new GetRequest("/cmis/s/" + id + "/children"); - Response res = sendRequest(get, 200); - String xml = res.getContentAsString(); - - // check document name with repeatable spaces in xml response. - assertEquals("Probably, children.get.atomfeed.ftl template has compress dirrective", true, xml.contains(docName)); - } - - @Test - public void testItemGetAtomentryTemplate() throws Exception - { - // check document name with repeatable spaces in xml response. - assertEquals("Probably, item.get.atomentry.ftl template has compress dirrective", true, xmlResponse.contains(docName)); - } - - /* - * Get children, if parent has object of non-cmis type - * cm:folderlink is non-cmis type. - */ - @Test - public void testChildrenWithLink() throws Exception - { - String testFolderRefStr = testCaseFolder.getId().toString().replace("urn:uuid:", "workspace://SpacesStore/"); - NodeRef testFolderRef = new NodeRef(testFolderRefStr); - - Map props = new HashMap(2, 1.0f); - String linkName = "link " + testCaseFolder.getTitle() + ".url"; - props.put(ContentModel.PROP_NAME, linkName); - props.put(ContentModel.PROP_LINK_DESTINATION, testFolderRef); - - AuthenticationUtil.pushAuthentication();; - AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser(); - - NodeRef linkRef = null; - - try - { - ChildAssociationRef childRef = nodeService.createNode( - testFolderRef, - ContentModel.ASSOC_CONTAINS, - QName.createQName(testCaseFolder.getTitle()), - ApplicationModel.TYPE_FOLDERLINK, - props); - linkRef = childRef.getChildRef(); - - String id = testCaseFolder.getId().toString().replace("urn:uuid:", "workspace:SpacesStore/i/"); - Request get = new GetRequest("/cmis/s/" + id + "/children"); - sendRequest(get, 200); - } - finally - { - if (linkRef != null) - { - nodeService.deleteNode(linkRef); - } - AuthenticationUtil.popAuthentication(); - } - - - - } - - @Test - public void testCheckXmlResponse() throws Exception - { - String testFolderRefStr = testCaseFolder.getId().toString().replace("urn:uuid:", "workspace://SpacesStore/"); - NodeRef testFolderRef = new NodeRef(testFolderRefStr); - - Map properties = new HashMap(); - properties.put(ContentModel.PROP_NAME, "testcontent"); - properties.put(ContentModel.PROP_DESCRIPTION, "content - test doc for test"); - - AuthenticationUtil.pushAuthentication(); - AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser(); - - NodeRef testDocNodeRef = null; - try - { - ChildAssociationRef testDoc = nodeService.createNode(testFolderRef, ContentModel.ASSOC_CONTAINS, - QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "testcontent"), ContentModel.TYPE_CONTENT, properties); - testDocNodeRef = testDoc.getChildRef(); - properties.clear(); - properties.put(ApplicationModel.PROP_EDITINLINE, true); - nodeService.addAspect(testDocNodeRef, ApplicationModel.ASPECT_INLINEEDITABLE, properties); - - String id = testDocNodeRef.toString().replace("workspace://SpacesStore/", "workspace:SpacesStore/i/"); - Request get = new GetRequest("/cmis/s/" + id); - Response res = sendRequest(get, 200); - String xml = res.getContentAsString(); - - try - { - validateXmlResponse(xml); - } - catch (Exception e) - { - fail(e.getMessage()); - } - - } - finally - { - if (testDocNodeRef != null) - { - nodeService.deleteNode(testDocNodeRef); - } - AuthenticationUtil.popAuthentication(); - } - } - - private void validateXmlResponse(String xml) throws Exception - { - Source[] shemas = new Source[] { - new StreamSource(new StringReader(localTemplates.load("xml.xsd"))), - new StreamSource(new StringReader(localTemplates.load("atom.xsd"))), - new StreamSource(new StringReader(localTemplates.load("app.xsd"))), - new StreamSource(new StringReader(localTemplates.load("CMIS-Core.xsd"))), - new StreamSource(new StringReader(localTemplates.load("envelope.xsd"))), - new StreamSource(new StringReader(localTemplates.load("Alfresco-Core.xsd"))) - }; - - Schema schema = null; - String language = XMLConstants.W3C_XML_SCHEMA_NS_URI; - SchemaFactory factory = SchemaFactory.newInstance(language); - schema = factory.newSchema(shemas); - - // creating a Validator instance - Validator validator = schema.newValidator(); - - // preparing the XML file as a SAX source - SAXSource source = new SAXSource(new InputSource(new StringReader(xml))); - - // validating the SAX source against the schema - validator.validate(source); - } -} \ No newline at end of file diff --git a/source/test-java/org/alfresco/repo/cmis/rest/test/CmisRelationshipSystemTest.java b/source/test-java/org/alfresco/repo/cmis/rest/test/CmisRelationshipSystemTest.java deleted file mode 100644 index fb41ba353d..0000000000 --- a/source/test-java/org/alfresco/repo/cmis/rest/test/CmisRelationshipSystemTest.java +++ /dev/null @@ -1,120 +0,0 @@ -package org.alfresco.repo.cmis.rest.test; - -import static org.junit.Assert.assertEquals; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import org.alfresco.cmis.client.impl.AlfrescoObjectFactoryImpl; -import org.apache.chemistry.opencmis.client.api.Document; -import org.apache.chemistry.opencmis.client.api.Folder; -import org.apache.chemistry.opencmis.client.api.ItemIterable; -import org.apache.chemistry.opencmis.client.api.ObjectType; -import org.apache.chemistry.opencmis.client.api.OperationContext; -import org.apache.chemistry.opencmis.client.api.Relationship; -import org.apache.chemistry.opencmis.client.api.Session; -import org.apache.chemistry.opencmis.client.api.SessionFactory; -import org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl; -import org.apache.chemistry.opencmis.commons.PropertyIds; -import org.apache.chemistry.opencmis.commons.SessionParameter; -import org.apache.chemistry.opencmis.commons.enums.BindingType; -import org.apache.chemistry.opencmis.commons.enums.RelationshipDirection; -import org.junit.BeforeClass; -import org.junit.Test; -import org.safehaus.uuid.UUIDGenerator; - -/** - * CMIS Relationship integration tests. - * - * @author Alex Strachan (tidy up by Alan Davis) - */ -public class CmisRelationshipSystemTest -{ - static Session session; - - static Document doc1; - - @BeforeClass - public static void classSetup() throws Exception - { - SessionFactory factory = SessionFactoryImpl.newInstance(); - Map sessionParameters = new HashMap(); - sessionParameters - .put(SessionParameter.ATOMPUB_URL, "http://localhost:8080/alfresco/s/cmis"); - sessionParameters.put(SessionParameter.USER, "admin"); - sessionParameters.put(SessionParameter.PASSWORD, "admin"); - sessionParameters.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value()); - sessionParameters.put(SessionParameter.OBJECT_FACTORY_CLASS, - AlfrescoObjectFactoryImpl.class.getName()); - session = factory.getRepositories(sessionParameters).get(0).createSession(); - - /* - * Association example from: - * http://forums.alfresco.com/en/viewtopic.php?f=45&t=27219 - */ - HashMap prop1 = new HashMap(); - prop1.put(PropertyIds.NAME, GUID()); - prop1.put(PropertyIds.OBJECT_TYPE_ID, "D:ws:article"); - - HashMap prop2 = new HashMap(); - prop2.put(PropertyIds.NAME, GUID()); - prop2.put(PropertyIds.OBJECT_TYPE_ID, "D:ws:article"); - - Folder folder = (Folder) session.getObjectByPath("/"); - - doc1 = folder.createDocument(prop1, null, null, null, null, null, - session.getDefaultContext()); - Document doc2 = folder.createDocument(prop2, null, null, null, null, null, - session.getDefaultContext()); - - Map relProps = new HashMap(); - relProps.put("cmis:sourceId", doc1.getId()); - relProps.put("cmis:targetId", doc2.getId()); - relProps.put("cmis:objectTypeId", "R:ws:relatedArticles"); - session.createRelationship(relProps, null, null, null); - } - - private static String GUID() - { - return UUIDGenerator.getInstance().generateRandomBasedUUID().toString(); - } - - @Test - public void testObjectRelationships() throws Exception - { - // Can't use object relationships retrieval due an isValidCmisRelationship issue. - // TODO Change expected value to 1 rather than 0 once bug is fixed. - assertEquals(0, doc1.getRelationships().size()); - } - - private void testGetRelationshipsViaSession(RelationshipDirection direction) throws Exception - { - // Try and get relationships using the session - ObjectType typeDefinition = session.getTypeDefinition("R:ws:relatedArticles"); - OperationContext operationContext = session.createOperationContext(); - - ItemIterable relationships = session.getRelationships(doc1, true, direction, - typeDefinition, operationContext); - int relationshipCount = 0; - Iterator iterator = relationships.iterator(); - while (iterator.hasNext()) - { - relationshipCount++; - iterator.next(); - } - assertEquals(1, relationshipCount); - } - - @Test - public void testRelationshipDirectionEither() throws Exception - { - testGetRelationshipsViaSession(RelationshipDirection.EITHER); - } - - @Test - public void testRelationshipDirectionSource() throws Exception - { - testGetRelationshipsViaSession(RelationshipDirection.SOURCE); - } -} \ No newline at end of file diff --git a/source/test-java/org/alfresco/repo/cmis/rest/test/PolicyTest.java b/source/test-java/org/alfresco/repo/cmis/rest/test/PolicyTest.java deleted file mode 100644 index 6bbf6a8802..0000000000 --- a/source/test-java/org/alfresco/repo/cmis/rest/test/PolicyTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.rest.test; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.abdera.i18n.iri.IRI; -import org.apache.abdera.model.Entry; -import org.apache.abdera.model.Feed; -import org.apache.abdera.model.Link; -import org.apache.chemistry.abdera.ext.CMISConstants; -import org.apache.chemistry.abdera.ext.CMISTypeDefinition; -import org.junit.Assert; -import org.springframework.extensions.webscripts.TestWebScriptServer.PostRequest; -import org.springframework.extensions.webscripts.TestWebScriptServer.Request; - -/** - * Tests Alfresco CMIS Policy implementation. - * - * @author dward - */ -public class PolicyTest extends BaseCMISTest -{ - public void testPolicies() throws Exception - { - // Try creating an object with the cmis:policy base type (expect a constraint exception) - Link children = cmisClient.getChildrenLink(testCaseFolder); - createObject(children.getHref(), getName(), "cmis:policy", 409); - - // Try creating an object of any of the cmis:policy subtypes - IRI typesHREF = cmisClient.getTypesChildrenCollection(cmisClient.getWorkspace(cmisService)); - Map args = new HashMap(); - args.put("typeId", "cmis:policy"); - args.put("includePropertyDefinitions", "true"); - Feed types = fetch(typesHREF, args); - List entries = types.getEntries(); - assertNotSame(0, entries.size()); - for (Entry type : entries) { - CMISTypeDefinition entryType = type.getExtension(CMISConstants.TYPE_DEFINITION); - Assert.assertNotNull(entryType); - createObject(children.getHref(), getName(), entryType.getId(), 409); - } - - // Create a document to attempt to apply policies to - Entry document = createObject(children.getHref(), getName(), "cmis:document"); - - // retrieve policies feed on document (this should be empty) - Link polsLink = document.getLink(CMISConstants.REL_POLICIES); - assertNotNull(polsLink); - Feed polsBefore = fetch(polsLink.getHref(), null); - assertNotNull(polsBefore); - assertEquals(0, polsBefore.getEntries().size()); - - // Try applying a policy (expect a constraint exception) - String policyFile = localTemplates.load("PolicyTest.applyPolicy.atomentry.xml"); - policyFile = policyFile.replace("${OBJECTID}", "doesnotexist"); - Request req = new PostRequest(polsLink.getHref().toString(), policyFile, CMISConstants.MIMETYPE_ENTRY); - sendRequest(req, 409); - } -} diff --git a/source/test-java/org/alfresco/repo/cmis/ws/test/AspectTest.java b/source/test-java/org/alfresco/repo/cmis/ws/test/AspectTest.java deleted file mode 100644 index dad9686133..0000000000 --- a/source/test-java/org/alfresco/repo/cmis/ws/test/AspectTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.ws.test; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import javax.xml.ws.Holder; - -import org.alfresco.repo.cmis.ws.Aspects; -import org.alfresco.repo.cmis.ws.CmisExtensionType; -import org.alfresco.repo.cmis.ws.CmisPropertiesType; -import org.alfresco.repo.cmis.ws.CmisProperty; -import org.alfresco.repo.cmis.ws.CmisPropertyString; -import org.alfresco.repo.cmis.ws.SetAspects; -import org.junit.Assert; - -/** - * Tests Alfresco CMIS WebService API extensions for Aspects. - * - * @author dward - */ -public class AspectTest extends BaseCMISTest -{ - public void testAspectSet() throws Exception - { - // create document for checkout - Holder objectId = new Holder(); - objectServicePort.createDocument(repositoryId, createObjectProperties(getName(), "cmis:document"), - testFolderId, null, null, null, null, null, new Holder(), objectId); - Assert.assertNotNull(objectId.value); - - // checkout - versioningServicePort.checkOut(repositoryId, objectId, new Holder(), new Holder()); - Assert.assertNotNull(objectId.value); - - // Apply some aspects to the working copy - { - CmisPropertiesType properties = new CmisPropertiesType(); - SetAspects extension = new SetAspects(); - properties.getAny().add(extension); - extension.getAspectsToAdd().addAll(Arrays.asList(new String[] - { - "P:cm:syndication", "P:cm:summarizable" - })); - CmisPropertiesType extensionProperties = new CmisPropertiesType(); - extension.setProperties(extensionProperties); - setStringProperty(extensionProperties, "cm:summary", "Aspect Test (summary)"); - // Add a property without explicitly adding its aspect. Should be automatically added. - setStringProperty(extensionProperties, "cm:author", "David Ward"); - objectServicePort.updateProperties(repositoryId, objectId, null, properties, null); - CmisPropertiesType updated = objectServicePort.getProperties(repositoryId, objectId.value, null, null); - Set appliedAspects = new HashSet(5); - Map aspectProperties = new HashMap(11); - extractAspectsAndProperties(updated, appliedAspects, aspectProperties); - assertContains(appliedAspects, "P:cm:syndication", "P:cm:summarizable", "P:cm:author"); - assertEquals("Aspect Test (summary)", aspectProperties.get("cm:summary")); - assertEquals("David Ward", aspectProperties.get("cm:author")); - } - - // check in with updated aspects - { - CmisPropertiesType properties = new CmisPropertiesType(); - SetAspects extension = new SetAspects(); - properties.getAny().add(extension); - extension.getAspectsToAdd().add("P:cm:countable"); - extension.getAspectsToRemove().add("P:cm:author"); - CmisPropertiesType extensionProperties = new CmisPropertiesType(); - extension.setProperties(extensionProperties); - setStringProperty(extensionProperties, "cm:summary", "Aspect Test (new summary)"); - versioningServicePort.checkIn(repositoryId, objectId, null, properties, null, null, null, null, null, - new Holder()); - CmisPropertiesType checkedIn = objectServicePort.getProperties(repositoryId, objectId.value, null, null); - Set appliedAspects = new HashSet(5); - Map aspectProperties = new HashMap(11); - extractAspectsAndProperties(checkedIn, appliedAspects, aspectProperties); - assertContains(appliedAspects, "P:cm:syndication", "P:cm:summarizable", "P:cm:countable"); - assertDoesNotContain(appliedAspects, "P:cm:author"); - assertEquals("Aspect Test (new summary)", aspectProperties.get("cm:summary")); - assertNull(aspectProperties.get("cm:author")); - } - } - - /** - * @param properties - * @param appliedAspects - * @param aspectProperties - */ - private void extractAspectsAndProperties(CmisPropertiesType properties, Set appliedAspects, - Map aspectProperties) - { - Aspects extension = null; - for (Object object : properties.getAny()) - { - if (object instanceof Aspects) - { - extension = (Aspects) object; - break; - } - } - if (extension == null) - { - fail("alf:aspects element not included"); - } - appliedAspects.addAll(extension.getAppliedAspects()); - CmisPropertiesType extensionProperties = extension.getProperties(); - if (extensionProperties == null) - { - return; - } - for (CmisProperty property : extensionProperties.getProperty()) - { - if (property instanceof CmisPropertyString) - { - aspectProperties.put(property.getPropertyDefinitionId(), ((CmisPropertyString) property).getValue() - .get(0)); - } - } - } -} diff --git a/source/test-java/org/alfresco/repo/cmis/ws/test/BaseCMISTest.java b/source/test-java/org/alfresco/repo/cmis/ws/test/BaseCMISTest.java deleted file mode 100644 index 256b264578..0000000000 --- a/source/test-java/org/alfresco/repo/cmis/ws/test/BaseCMISTest.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.ws.test; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -import javax.xml.ws.Holder; - -import junit.framework.TestCase; - -import org.alfresco.cmis.CMISDictionaryModel; -import org.alfresco.repo.cmis.ws.CmisException; -import org.alfresco.repo.cmis.ws.CmisExtensionType; -import org.alfresco.repo.cmis.ws.CmisPropertiesType; -import org.alfresco.repo.cmis.ws.CmisPropertyId; -import org.alfresco.repo.cmis.ws.CmisPropertyString; -import org.alfresco.repo.cmis.ws.ObjectServicePort; -import org.alfresco.repo.cmis.ws.PolicyServicePort; -import org.alfresco.repo.cmis.ws.RepositoryServicePort; -import org.alfresco.repo.cmis.ws.VersioningServicePort; -import org.alfresco.repo.security.authentication.AuthenticationUtil; -import org.alfresco.util.ApplicationContextHelper; -import org.junit.Assert; -import org.springframework.context.ApplicationContext; - -/** - * Base class for tests to Alfresco CMIS WebService API extensions. - * - * @author dward - */ -public abstract class BaseCMISTest extends TestCase -{ - protected RepositoryServicePort repositoryServicePort; - protected ObjectServicePort objectServicePort; - protected VersioningServicePort versioningServicePort; - protected PolicyServicePort policyServicePort; - protected String defaultRunAs = "admin"; - protected String repositoryId; - protected String testFolderId; - - protected ApplicationContext ctx; - - public BaseCMISTest() - { - ctx = ApplicationContextHelper.getApplicationContext(new String[] - { - ApplicationContextHelper.CONFIG_LOCATIONS[0], "classpath:alfresco/web-services-application-context.xml" - }); - repositoryServicePort = (RepositoryServicePort) ctx.getBean("dmRepositoryService"); - objectServicePort = (ObjectServicePort) ctx.getBean("dmObjectService"); - versioningServicePort = (VersioningServicePort) ctx.getBean("dmVersioningService"); - policyServicePort = (PolicyServicePort) ctx.getBean("dmPolicyService"); - try - { - repositoryId = repositoryServicePort.getRepositories(null).get(0).getRepositoryId(); - } - catch (CmisException e) - { - throw new RuntimeException(e); - } - } - - public void setDefaultRunAs(String defaultRunAs) - { - this.defaultRunAs = defaultRunAs; - } - - @Override - protected void setUp() throws Exception - { - AuthenticationUtil.setFullyAuthenticatedUser(defaultRunAs); - String rootFolderId = repositoryServicePort.getRepositoryInfo(repositoryId, null).getRootFolderId(); - Holder objectId = new Holder(); - String folderName = getClass().getSimpleName() + System.currentTimeMillis() + " - " + getName(); - objectServicePort.createFolder(repositoryId, createObjectProperties(folderName, "cmis:folder"), rootFolderId, - null, null, null, new Holder(), objectId); - testFolderId = objectId.value; - } - - @Override - protected void tearDown() throws Exception - { - AuthenticationUtil.clearCurrentSecurityContext(); - } - - protected CmisPropertiesType createObjectProperties(String name, String type) - { - CmisPropertiesType properties = new CmisPropertiesType(); - CmisPropertyString stringProperty = new CmisPropertyString(); - stringProperty.setPropertyDefinitionId(CMISDictionaryModel.PROP_NAME); - stringProperty.getValue().add(name); - properties.getProperty().add(stringProperty); - CmisPropertyId idProperty = new CmisPropertyId(); - idProperty.setPropertyDefinitionId(CMISDictionaryModel.PROP_OBJECT_TYPE_ID); - idProperty.getValue().add(type); - properties.getProperty().add(idProperty); - return properties; - } - - protected void setStringProperty(CmisPropertiesType properties, String id, String value) - { - CmisPropertyString stringProperty = new CmisPropertyString(); - properties.getProperty().add(stringProperty); - stringProperty.setPropertyDefinitionId(id); - stringProperty.getValue().add(value); - } - - protected void assertContains(Set actual, String... expected) - { - Assert.assertTrue(actual.containsAll(Arrays.asList(expected))); - } - - protected void assertDoesNotContain(Set actual, String... unexpected) - { - Set copy = new HashSet(actual); - copy.retainAll(Arrays.asList(unexpected)); - Assert.assertTrue(copy.isEmpty()); - } -} diff --git a/source/test-java/org/alfresco/repo/cmis/ws/test/PolicyTest.java b/source/test-java/org/alfresco/repo/cmis/ws/test/PolicyTest.java deleted file mode 100644 index 8f10e1d96c..0000000000 --- a/source/test-java/org/alfresco/repo/cmis/ws/test/PolicyTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2005-2010 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 . - */ -package org.alfresco.repo.cmis.ws.test; - -import java.util.List; - -import javax.xml.ws.Holder; - -import org.alfresco.repo.cmis.ws.CmisException; -import org.alfresco.repo.cmis.ws.CmisExtensionType; -import org.alfresco.repo.cmis.ws.CmisObjectType; -import org.alfresco.repo.cmis.ws.CmisTypeDefinitionListType; -import org.alfresco.repo.cmis.ws.CmisTypeDefinitionType; -import org.alfresco.repo.cmis.ws.EnumServiceException; -import org.junit.Assert; - -/** - * Tests Alfresco CMIS Policy Web Service implementation. - * - * @author dward - */ -public class PolicyTest extends BaseCMISTest -{ - public void testPolicies() throws Exception - { - // Try creating an object with the cmis:policy base type (expect a constraint exception) - Holder objectId = new Holder(); - try - { - objectServicePort.createPolicy(repositoryId, createObjectProperties(getName(), "cmis:policy"), - testFolderId, null, null, null, new Holder(), objectId); - fail("Expected CmisException"); - } - catch (CmisException e) - { - Assert.assertEquals(EnumServiceException.CONSTRAINT, e.getFaultInfo().getType()); - } - - // Try creating an object of any of the cmis:policy subtypes - CmisTypeDefinitionListType typeDefs = repositoryServicePort.getTypeChildren(repositoryId, "cmis:policy", true, - null, null, null); - List entries = typeDefs.getTypes(); - assertNotSame(0, entries.size()); - for (CmisTypeDefinitionType type : entries) - { - try - { - objectServicePort.createPolicy(repositoryId, createObjectProperties(getName(), type.getId()), - testFolderId, null, null, null, new Holder(), objectId); - fail("Expected CmisException"); - } - catch (CmisException e) - { - Assert.assertEquals(EnumServiceException.CONSTRAINT, e.getFaultInfo().getType()); - } - } - - // Create a document to attempt to apply policies to - objectServicePort.createDocument(repositoryId, createObjectProperties(getName(), "cmis:document"), - testFolderId, null, null, null, null, null, new Holder(), objectId); - Assert.assertNotNull(objectId.value); - - // retrieve list of policies applied to document (this should be empty) - List policies = policyServicePort.getAppliedPolicies(repositoryId, objectId.value, null, null); - assertNotNull(policies); - assertEquals(0, policies.size()); - - // Try applying a policy (expect a constraint exception) - try - { - policyServicePort - .applyPolicy(repositoryId, "doesnotexist", objectId.value, new Holder()); - fail("Expected CmisException"); - } - catch (CmisException e) - { - Assert.assertEquals(EnumServiceException.CONSTRAINT, e.getFaultInfo().getType()); - } - - } -} diff --git a/source/test-java/org/alfresco/repo/cmis/ws/test/QueryPagingTest.java b/source/test-java/org/alfresco/repo/cmis/ws/test/QueryPagingTest.java deleted file mode 100644 index 93b7f0bfb7..0000000000 --- a/source/test-java/org/alfresco/repo/cmis/ws/test/QueryPagingTest.java +++ /dev/null @@ -1,182 +0,0 @@ -package org.alfresco.repo.cmis.ws.test; - -import java.math.BigInteger; -import java.util.List; - -import javax.activation.DataHandler; -import javax.xml.ws.Holder; - -import org.alfresco.cmis.CMISDictionaryModel; -import org.alfresco.repo.cmis.ws.CmisContentStreamType; -import org.alfresco.repo.cmis.ws.CmisException; -import org.alfresco.repo.cmis.ws.CmisExtensionType; -import org.alfresco.repo.cmis.ws.CmisObjectInFolderListType; -import org.alfresco.repo.cmis.ws.CmisObjectInFolderType; -import org.alfresco.repo.cmis.ws.CmisObjectType; -import org.alfresco.repo.cmis.ws.CmisPropertiesType; -import org.alfresco.repo.cmis.ws.CmisProperty; -import org.alfresco.repo.cmis.ws.CmisPropertyId; -import org.alfresco.repo.cmis.ws.CmisPropertyString; -import org.alfresco.repo.cmis.ws.DiscoveryServicePort; -import org.alfresco.repo.cmis.ws.EnumVersioningState; -import org.alfresco.repo.cmis.ws.NavigationServicePort; -import org.alfresco.repo.cmis.ws.ObjectFactory; -import org.alfresco.repo.cmis.ws.Query; -import org.alfresco.repo.cmis.ws.QueryResponse; -import org.alfresco.repo.content.MimetypeMap; - -/** - * The test of paging support of results of DMDiscoveryServicePort.query() - * - * @author Arseny Kovalchuk - */ -public class QueryPagingTest extends BaseCMISTest -{ - private static final int NUMBER_OF_DOCUMENTS = 50; - private static final String QUERY_DOCUMENTS_TEMPLATE = "select * from cmis:document d where in_folder('%1$s')"; - - private static final ObjectFactory OBJECT_FACTORY = new ObjectFactory(); - - private String queryDocuments; - - protected DiscoveryServicePort discoveryServicePort; - protected NavigationServicePort navigationServicePort; - - public QueryPagingTest() - { - super(); - discoveryServicePort = (DiscoveryServicePort) ctx.getBean("dmDiscoveryService"); - navigationServicePort = (NavigationServicePort) ctx.getBean("dmNavigationService"); - } - - protected void setUp() throws Exception { - super.setUp(); - queryDocuments = String.format(QUERY_DOCUMENTS_TEMPLATE, testFolderId); - //System.out.println(queryDocuments); - } - - /** - * The main reason for this test is ALF-9566 - * - * @throws Exception - */ - public void testPagingSupport() throws Exception - { - clearDocumentsInFolder(testFolderId); - - createDocumentsInFolder(testFolderId, NUMBER_OF_DOCUMENTS); - - // Select 10 of NUMBER_OF_DOCUMENTS, 0 documents to skip, so NUMBER_OF_DOCUMENTS - 10 still available - int skipCount = 0; - int maxItems = 10; - QueryResponse response = discoveryServicePort.query(createQuery(maxItems, skipCount)); - assertEquals(NUMBER_OF_DOCUMENTS - skipCount, response.getObjects().getNumItems().intValue()); - assertEquals(maxItems, response.getObjects().getObjects().size()); - assertTrue(response.getObjects().isHasMoreItems()); - - // Select 10 of NUMBER_OF_DOCUMENTS, 10 documents to skip, so NUMBER_OF_DOCUMENTS - 10 - 10 still available - skipCount = 10; - maxItems = 10; - response = discoveryServicePort.query(createQuery(maxItems, skipCount)); - assertEquals(NUMBER_OF_DOCUMENTS - skipCount, response.getObjects().getNumItems().intValue()); - assertEquals(maxItems, response.getObjects().getObjects().size()); - assertTrue(response.getObjects().isHasMoreItems()); - - // Select 10 of NUMBER_OF_DOCUMENTS, NUMBER_OF_DOCUMENTS - 10 to skip, so there are no docs available - skipCount = NUMBER_OF_DOCUMENTS - 10; - maxItems = 10; - response = discoveryServicePort.query(createQuery(maxItems, skipCount)); - assertEquals(NUMBER_OF_DOCUMENTS - skipCount, response.getObjects().getNumItems().intValue()); - assertEquals(maxItems, response.getObjects().getObjects().size()); - assertFalse(response.getObjects().isHasMoreItems()); - - // Select NUMBER_OF_DOCUMENTS to select, 0 to skip, so, there are no docs available - skipCount = 0; - maxItems = NUMBER_OF_DOCUMENTS; - response = discoveryServicePort.query(createQuery(maxItems, skipCount)); - assertEquals(NUMBER_OF_DOCUMENTS - skipCount, response.getObjects().getNumItems().intValue()); - assertEquals(maxItems, response.getObjects().getObjects().size()); - assertFalse(response.getObjects().isHasMoreItems()); - - clearDocumentsInFolder(testFolderId); - } - - protected void createDocumentsInFolder(String folderId, int docsCount) throws Exception - { - for (int i = 0; i < NUMBER_OF_DOCUMENTS; i++) - { - String docName = "Test Document " + i + ".txt"; - //System.out.println("Creating " + docName); - createDocument(docName, folderId); - } - } - - protected void clearDocumentsInFolder(String folderId) throws CmisException - { - CmisObjectInFolderListType result = navigationServicePort.getChildren(repositoryId, testFolderId, "*", null, false, null, null, false, BigInteger.valueOf(-1), - BigInteger.ZERO, null); - if (!result.getObjects().isEmpty()) - { - for(CmisObjectInFolderType obj : result.getObjects()) - { - String documentId = getObjectId(obj.getObject()); - //System.out.println("Deleting document with ID:" + documentId); - objectServicePort.deleteObject(repositoryId, documentId, true, new Holder()); - } - } - } - - protected String getObjectId(CmisObjectType object) - { - CmisPropertiesType propertiesType = object.getProperties(); - for(CmisProperty property : propertiesType.getProperty()) - { - if ((property instanceof CmisPropertyId) && CMISDictionaryModel.PROP_OBJECT_ID.equals(property.getPropertyDefinitionId())) - { - return ((CmisPropertyId) property).getValue().iterator().next(); - } - } - return null; - } - - protected String createDocument(String name, String parentFolderId) throws Exception - { - String content = "This is a test content"; - CmisPropertiesType properties = new CmisPropertiesType(); - List propertiesList = properties.getProperty(); - CmisPropertyString cmisProperty = new CmisPropertyString(); - cmisProperty.setPropertyDefinitionId(CMISDictionaryModel.PROP_NAME); - cmisProperty.getValue().add(name); - CmisPropertyId idProperty = new CmisPropertyId(); - idProperty.setPropertyDefinitionId(CMISDictionaryModel.PROP_OBJECT_TYPE_ID); - idProperty.getValue().add(CMISDictionaryModel.DOCUMENT_TYPE_ID.getId()); - - propertiesList.add(cmisProperty); - propertiesList.add(idProperty); - - CmisContentStreamType cmisStream = new CmisContentStreamType(); - cmisStream.setFilename(name); - cmisStream.setMimeType(MimetypeMap.MIMETYPE_TEXT_PLAIN); - - DataHandler dataHandler = new DataHandler(content, MimetypeMap.MIMETYPE_TEXT_PLAIN); - cmisStream.setStream(dataHandler); - - Holder extensions = new Holder(); - Holder idHolder = new Holder(); - objectServicePort.createDocument(repositoryId, properties, parentFolderId, cmisStream, EnumVersioningState.MAJOR, null, null, null, extensions, idHolder); - return idHolder.value; - } - - private Query createQuery(int maxItems, int skipCount) - { - Query parameters = new Query(); - parameters.setRepositoryId(repositoryId); - parameters.setStatement(queryDocuments); - parameters.setSkipCount(OBJECT_FACTORY.createQuerySkipCount(BigInteger.valueOf(skipCount))); - parameters.setMaxItems(OBJECT_FACTORY.createQueryMaxItems(BigInteger.valueOf(maxItems))); - parameters.setIncludeAllowableActions(OBJECT_FACTORY.createQueryIncludeAllowableActions(Boolean.FALSE)); - parameters.setSearchAllVersions(OBJECT_FACTORY.createQuerySearchAllVersions(Boolean.FALSE)); - return parameters; - } - -} diff --git a/source/test-java/org/alfresco/repo/web/scripts/quickshare/QuickShareRestApiTest.java b/source/test-java/org/alfresco/repo/web/scripts/quickshare/QuickShareRestApiTest.java index 83b382a458..d647bef2f2 100644 --- a/source/test-java/org/alfresco/repo/web/scripts/quickshare/QuickShareRestApiTest.java +++ b/source/test-java/org/alfresco/repo/web/scripts/quickshare/QuickShareRestApiTest.java @@ -225,9 +225,10 @@ public class QuickShareRestApiTest extends BaseWebScriptTest assertEquals(TEST_MIMETYPE_JPEG, mimetype); // get content for node (authenticated) - rsp = sendRequest(new GetRequest(AUTH_CONTENT_URL.replace("{node_ref_3}", testNodeRef_3)), expectedStatusOK, USER_ONE); - byte[] content = rsp.getContentAsByteArray(); - checkBytes(TEST_CONTENT, content); +// Commented out when removing original CMIS impl +// rsp = sendRequest(new GetRequest(AUTH_CONTENT_URL.replace("{node_ref_3}", testNodeRef_3)), expectedStatusOK, USER_ONE); +// byte[] content = rsp.getContentAsByteArray(); +// checkBytes(TEST_CONTENT, content); // get content thumbnail for node (authenticated) rsp = sendRequest(new GetRequest(AUTH_CONTENT_THUMBNAIL_URL.replace("{node_ref_3}", testNodeRef_3).replace("{thumbnailname}", "doclib")), expectedStatusOK, USER_ONE); @@ -237,7 +238,8 @@ public class QuickShareRestApiTest extends BaseWebScriptTest // As user two ... rsp = sendRequest(new GetRequest(AUTH_METADATA_URL.replace("{node_ref_3}", testNodeRef_3)), expectedStatusServerError, USER_TWO); - rsp = sendRequest(new GetRequest(AUTH_CONTENT_URL.replace("{node_ref_3}", testNodeRef_3)), expectedStatusForbidden, USER_TWO); +// Commented out when removing original CMIS impl +// rsp = sendRequest(new GetRequest(AUTH_CONTENT_URL.replace("{node_ref_3}", testNodeRef_3)), expectedStatusForbidden, USER_TWO); rsp = sendRequest(new GetRequest(AUTH_CONTENT_THUMBNAIL_URL.replace("{node_ref_3}", testNodeRef_3).replace("{thumbnailname}", "doclib")), expectedStatusServerError, USER_TWO); // As user one ... @@ -261,7 +263,7 @@ public class QuickShareRestApiTest extends BaseWebScriptTest // get content for share (note: can be unauthenticated) rsp = sendRequest(new GetRequest(SHARE_CONTENT_URL.replace("{shared_id}", sharedId)), expectedStatusOK, USER_TWO); - content = rsp.getContentAsByteArray(); + byte[] content = rsp.getContentAsByteArray(); checkBytes(TEST_CONTENT, content); // get content thumbnail for share (note: can be unauthenticated)