diff --git a/.classpath b/.classpath index 9dc0d94b11..e0ca138f62 100644 --- a/.classpath +++ b/.classpath @@ -9,5 +9,6 @@ + diff --git a/.externalToolBuilders/JibX.launch b/.externalToolBuilders/JibX.launch index 7849a631a2..186d90d901 100644 --- a/.externalToolBuilders/JibX.launch +++ b/.externalToolBuilders/JibX.launch @@ -1,34 +1,34 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.project b/.project index 8e3892e2f1..ec6d5cbc97 100644 --- a/.project +++ b/.project @@ -1,28 +1,27 @@ - - - Repository - JavaCC Nature - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.ui.externaltools.ExternalToolBuilder - auto,full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/JibX.launch - - - - - - org.eclipse.jdt.core.javanature - rk.eclipse.javacc.javaccnature - - + + + Repository + JavaCC Nature + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.ui.externaltools.ExternalToolBuilder + + + LaunchConfigHandle + <project>/.externalToolBuilders/JibX.launch + + + + + + org.eclipse.jdt.core.javanature + rk.eclipse.javacc.javaccnature + + diff --git a/config/alfresco/messages/dictionary-messages.properties b/config/alfresco/messages/dictionary-messages.properties deleted file mode 100644 index 7d397c4c5c..0000000000 --- a/config/alfresco/messages/dictionary-messages.properties +++ /dev/null @@ -1,51 +0,0 @@ -# Dictionary-related messages - -d_dictionary.model.err.no_model=Model ''{0}'' does not exist -d_dictionary.model.err.type_not_found=Failed to create anonymous type as specified type {0} not found -d_dictionary.model.err.aspect_not_found=Failed to create anonymous type as specified aspect {0} not found - -d_dictionary.constraint.err.cyclic_ref=Constraint ''{0}'' is part of a cyclic reference of constraints -d_dictionary.constraint.err.type_and_ref=Constraint ''{0}'' cannot have a 'type' and be a 'reference' attribute -d_dictionary.constraint.err.type_or_ref=Constraint ''{0}'' cannot have a 'type' and be a 'reference' attribute -d_dictionary.constraint.err.ref_not_found=Constraint reference ''{0}'' not found on constraint ''{1}'' -d_dictionary.constraint.err.anon_needs_property=Anonymous constraints can only be declared within the context of a property -d_dictionary.constraint.err.invalid_type=Constraint type ''{0}'' on constraint ''{1}'' is not a well-known type or a valid Constraint implementation -d_dictionary.constraint.err.property_simple_and_list="Constraint ''{0}'' has both a simple and list value for property ''{1}'' -d_dictionary.constraint.err.construct_failure=Failed to construct an instance of type ''{0}'' for constraint ''{1}'' -d_dictionary.constraint.err.property_mismatch=Property mismatch setting property ''{0}'' on constraint ''{1}'' -d_dictionary.constraint.err.reserved_property=Property ''{0}'' is reserved and can't be set on constraint ''{1}''. -d_dictionary.constraint.err.property_not_set=Property ''{0}'' has not been set on constraint ''{1}'' -d_dictionary.constraint.err.evaluate_exception=Exception during evaluation of constraint ''{0}'': {1} - -d_dictionary.property.err.property_type_not_specified=Property type of property ''{0}'' must be specified -d_dictionary.property.err.property_type_not_found=Property type ''{0}'' of property ''{1}'' is not found -d_dictionary.property.err.single_valued_content=Content properties must be single-valued -d_dictionary.property.err.duplicate_constraint_on_property=Found duplicate constraint definition ''{0}'' within property ''{1}'' -d_dictionary.property.err.cannot_relax_mandatory=Cannot relax mandatory attribute of property ''{0} -d_dictionary.property.err.cannot_relax_mandatory_enforcement=Cannot relax mandatory attribute enforcement of property ''{0} - -d_dictionary.constraint.registered.not_registered=There is no constraint registered by name ''{0}''. - -d_dictionary.constraint.regex.no_match=Value ''{0}'' does not match regular expression: {1} -d_dictionary.constraint.regex.match=Value ''{0}'' matches regular expression: {1} -d_dictionary.constraint.regex.error.cm\:filename=Value ''{0}'' is not valid as a file name. This property must be a valid file name. - -d_dictionary.constraint.numeric_range.invalid_min_value=Invalid 'minValue' property: {0} -d_dictionary.constraint.numeric_range.invalid_max_value=Invalid 'maxValue' property: {0} -d_dictionary.constraint.numeric_range.non_numeric=Property value could not be converted to a double: {0} -d_dictionary.constraint.numeric_range.out_of_range=Numeric value ''{0}'' is not in range [{1}; {2}] - -d_dictionary.constraint.string_length.invalid_min_length=Invalid 'minLength' property: {0} -d_dictionary.constraint.string_length.invalid_max_length=Invalid 'maxLength' property: {0} -d_dictionary.constraint.string_length.non_string=Property value could not be converted to a String: {0} -d_dictionary.constraint.string_length.invalid_length=String length of ''{0}'' is not in range [{1}; {2}] - -d_dictionary.constraint.list_of_values.no_values=The list of allowed values is empty -d_dictionary.constraint.list_of_values.non_string=Property value could not be converted to a String: {0} -d_dictionary.constraint.list_of_values.invalid_value=The value is not an allowed value: {0} - -d_dictionary.constraint.user_name.invalid_user_name=The value ''{0}'' is not an allowed user name: it is an authority of type: {1} -d_dictionary.constraint.user_name.non_string=Property value could not be converted to a String: {0} - -d_dictionary.constraint.authority_name.invalid_authority_name=The value ''{0}'' is not an allowed authority name: it is an authority of type: {1} -d_dictionary.constraint.authority_name.non_string=Property value could not be converted to a String: {0} \ No newline at end of file diff --git a/config/alfresco/messages/dictionary-model.properties b/config/alfresco/messages/dictionary-model.properties deleted file mode 100644 index 79ffd2954e..0000000000 --- a/config/alfresco/messages/dictionary-model.properties +++ /dev/null @@ -1,34 +0,0 @@ -# Display labels for Dictionary Model - -d_dictionary.description=Alfresco Dictionary Model - -d_dictionary.datatype.d_any.title=Any -d_dictionary.datatype.d_any.description=Any -d_dictionary.datatype.d_text.title=Text -d_dictionary.datatype.d_text.description=Text -d_dictionary.datatype.d_content.title=Content -d_dictionary.datatype.d_content.description=Content -d_dictionary.datatype.d_int.title=Integer -d_dictionary.datatype.d_int.description=Integer -d_dictionary.datatype.d_long.title=Long -d_dictionary.datatype.d_long.description=Long -d_dictionary.datatype.d_float.title=Float -d_dictionary.datatype.d_float.description=Float -d_dictionary.datatype.d_double.title=Double -d_dictionary.datatype.d_double.description=Double -d_dictionary.datatype.d_date.title=Date -d_dictionary.datatype.d_date.description=Date -d_dictionary.datatype.d_datetime.title=Date and Time -d_dictionary.datatype.d_datetime.description=Date and Time -d_dictionary.datatype.d_boolean.title=Boolean -d_dictionary.datatype.d_boolean.description=Boolean -d_dictionary.datatype.d_qname.title=Qualified Name -d_dictionary.datatype.d_qname.description=Qualified Name -d_dictionary.datatype.d_guid.title=Unique Identifier -d_dictionary.datatype.d_guid.description=Unique Identifier -d_dictionary.datatype.d_category.title=Category -d_dictionary.datatype.d_category.description=Category -d_dictionary.datatype.d_noderef.title=Reference -d_dictionary.datatype.d_noderef.description=Reference -d_dictionary.datatype.d_path.title=Path -d_dictionary.datatype.d_path.description=Path diff --git a/config/alfresco/model/dictionaryModel.xml b/config/alfresco/model/dictionaryModel.xml deleted file mode 100644 index e870393d6c..0000000000 --- a/config/alfresco/model/dictionaryModel.xml +++ /dev/null @@ -1,126 +0,0 @@ - - - Alfresco Dictionary Model - Alfresco - 2005-09-29 - 1.0 - - - - - - - - - - - - - - - - org.alfresco.repo.search.impl.lucene.analysis.AlfrescoStandardAnalyser - java.lang.Object - - - - org.alfresco.repo.search.impl.lucene.analysis.AlfrescoStandardAnalyser - java.lang.String - - - - org.alfresco.repo.search.impl.lucene.analysis.AlfrescoStandardAnalyser - org.alfresco.service.cmr.repository.MLText - - - - org.alfresco.repo.search.impl.lucene.analysis.AlfrescoStandardAnalyser - org.alfresco.service.cmr.repository.ContentData - - - - org.alfresco.repo.search.impl.lucene.analysis.IntegerAnalyser - java.lang.Integer - - - - org.alfresco.repo.search.impl.lucene.analysis.LongAnalyser - java.lang.Long - - - - org.alfresco.repo.search.impl.lucene.analysis.FloatAnalyser - java.lang.Float - - - - org.alfresco.repo.search.impl.lucene.analysis.DoubleAnalyser - java.lang.Double - - - - org.alfresco.repo.search.impl.lucene.analysis.DateAnalyser - java.util.Date - - - - org.alfresco.repo.search.impl.lucene.analysis.DateTimeAnalyser - java.util.Date - - - - org.alfresco.repo.search.impl.lucene.analysis.AlfrescoStandardAnalyser - java.lang.Boolean - - - - org.alfresco.repo.search.impl.lucene.analysis.AlfrescoStandardAnalyser - org.alfresco.service.namespace.QName - - - - org.alfresco.repo.search.impl.lucene.analysis.AlfrescoStandardAnalyser - org.alfresco.service.cmr.repository.NodeRef - - - - org.alfresco.repo.search.impl.lucene.analysis.AlfrescoStandardAnalyser - org.alfresco.service.cmr.repository.ChildAssociationRef - - - - org.alfresco.repo.search.impl.lucene.analysis.AlfrescoStandardAnalyser - org.alfresco.service.cmr.repository.AssociationRef - - - - org.alfresco.repo.search.impl.lucene.analysis.AlfrescoStandardAnalyser - org.alfresco.service.cmr.repository.Path - - - - org.alfresco.repo.search.impl.lucene.analysis.AlfrescoStandardAnalyser - org.alfresco.service.cmr.repository.NodeRef - - - - org.alfresco.repo.search.impl.lucene.analysis.VerbatimAnalyser - java.util.Locale - - - - org.alfresco.repo.search.impl.lucene.analysis.VerbatimAnalyser - org.alfresco.util.VersionNumber - - - - org.alfresco.repo.search.impl.lucene.analysis.VerbatimAnalyser - org.alfresco.service.cmr.repository.Period - - - - - - - - diff --git a/source/java/org/alfresco/model/ContentModel.java b/source/java/org/alfresco/model/ContentModel.java deleted file mode 100644 index 1bb945ba7a..0000000000 --- a/source/java/org/alfresco/model/ContentModel.java +++ /dev/null @@ -1,322 +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.model; - -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; - - -/** - * Content Model Constants - */ -public interface ContentModel -{ - // - // System Model Definitions - // - - // base type constants - static final QName TYPE_BASE = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "base"); - static final QName ASPECT_REFERENCEABLE = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "referenceable"); - static final QName PROP_STORE_PROTOCOL = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "store-protocol"); - static final QName PROP_STORE_IDENTIFIER = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "store-identifier"); - static final QName PROP_NODE_UUID = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "node-uuid"); - static final QName PROP_NODE_DBID = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "node-dbid"); - - // tag for incomplete nodes - static final QName ASPECT_INCOMPLETE = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "incomplete"); - - // tag for temporary nodes - static final QName ASPECT_TEMPORARY = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "temporary"); - - // tag for nodes being formed (CIFS) - static final QName ASPECT_NO_CONTENT = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "noContent"); - - // tag for localized nodes - static final QName ASPECT_LOCALIZED = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "localized"); - static final QName PROP_LOCALE = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "locale"); - - // archived nodes aspect constants - static final QName ASPECT_ARCHIVED = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "archived"); - static final QName PROP_ARCHIVED_ORIGINAL_PARENT_ASSOC = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "archivedOriginalParentAssoc"); - static final QName PROP_ARCHIVED_BY = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "archivedBy"); - static final QName PROP_ARCHIVED_DATE = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "archivedDate"); - static final QName PROP_ARCHIVED_ORIGINAL_OWNER = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "archivedOriginalOwner"); - static final QName ASPECT_ARCHIVED_ASSOCS = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "archived-assocs"); - static final QName PROP_ARCHIVED_PARENT_ASSOCS = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "archivedParentAssocs"); - static final QName PROP_ARCHIVED_CHILD_ASSOCS = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "archivedChildAssocs"); - static final QName PROP_ARCHIVED_SOURCE_ASSOCS = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "archivedSourceAssocs"); - static final QName PROP_ARCHIVED_TARGET_ASSOCS = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "archivedTargetAssocs"); - - // referenceable aspect constants - static final QName TYPE_REFERENCE = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "reference"); - static final QName PROP_REFERENCE = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "reference"); - - // container type constants - static final QName TYPE_CONTAINER = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "container"); - /** child association type supported by {@link #TYPE_CONTAINER} */ - static final QName ASSOC_CHILDREN =QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "children"); - - // roots - static final QName ASPECT_ROOT = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "aspect_root"); - static final QName TYPE_STOREROOT = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "store_root"); - - // descriptor properties - static final QName PROP_SYS_NAME = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "name"); - static final QName PROP_SYS_VERSION_MAJOR = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "versionMajor"); - static final QName PROP_SYS_VERSION_MINOR = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "versionMinor"); - static final QName PROP_SYS_VERSION_REVISION = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "versionRevision"); - static final QName PROP_SYS_VERSION_LABEL = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "versionLabel"); - static final QName PROP_SYS_VERSION_BUILD = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "versionBuild"); - static final QName PROP_SYS_VERSION_SCHEMA = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "versionSchema"); - static final QName PROP_SYS_VERSION_EDITION = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "versionEdition"); - static final QName PROP_SYS_VERSION_PROPERTIES = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "versionProperties"); - - // - // Content Model Definitions - // - - // content management type constants - static final QName TYPE_CMOBJECT = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "cmobject"); - static final QName PROP_NAME = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "name"); - - // copy aspect constants - static final QName ASPECT_COPIEDFROM = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "copiedfrom"); - static final QName PROP_COPY_REFERENCE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "source"); - - // working copy aspect contants - static final QName ASPECT_WORKING_COPY = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "workingcopy"); - static final QName PROP_WORKING_COPY_OWNER = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "workingCopyOwner"); - static final QName PROP_WORKING_COPY_MODE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "workingCopyMode"); - - // content type and aspect constants - static final QName TYPE_CONTENT = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "content"); - static final QName PROP_CONTENT = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "content"); - - // title aspect - static final QName ASPECT_TITLED = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "titled"); - static final QName PROP_TITLE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "title"); - static final QName PROP_DESCRIPTION = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "description"); - - // auditable aspect - static final QName ASPECT_AUDITABLE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "auditable"); - static final QName PROP_CREATED = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "created"); - static final QName PROP_CREATOR = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "creator"); - static final QName PROP_MODIFIED = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "modified"); - static final QName PROP_MODIFIER = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "modifier"); - static final QName PROP_ACCESSED = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "accessed"); - - // author aspect - static final QName ASPECT_AUTHOR = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "author"); - static final QName PROP_AUTHOR = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "author"); - - // categories - static final QName TYPE_CATEGORYROOT = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "category_root"); - static final QName ASPECT_CLASSIFIABLE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "classifiable"); - //static final QName ASPECT_CATEGORISATION = QName.createQName(NamespaceService.ALFRESCO_URI, "aspect_categorisation"); - static final QName ASPECT_GEN_CLASSIFIABLE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "generalclassifiable"); - static final QName TYPE_CATEGORY = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "category"); - static final QName PROP_CATEGORIES = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "categories"); - static final QName ASSOC_CATEGORIES = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "categories"); - static final QName ASSOC_SUBCATEGORIES = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "subcategories"); - - // tags - a subsection of categories - static final QName ASPECT_TAGGABLE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "taggable"); - static final QName PROP_TAGS = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "taggable"); - - // tagscope aspect - static final QName ASPECT_TAGSCOPE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "tagscope"); - static final QName PROP_TAGSCOPE_CACHE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "tagScopeCache"); - - // lock aspect - public final static QName ASPECT_LOCKABLE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "lockable"); - public final static QName PROP_LOCK_OWNER = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "lockOwner"); - public final static QName PROP_LOCK_TYPE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "lockType"); - public final static QName PROP_EXPIRY_DATE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "expiryDate"); - - // version aspect - static final QName ASPECT_VERSIONABLE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "versionable"); - static final QName PROP_VERSION_LABEL = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "versionLabel"); - static final QName PROP_INITIAL_VERSION = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "initialVersion"); - static final QName PROP_AUTO_VERSION = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "autoVersion"); - static final QName PROP_AUTO_VERSION_PROPS = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "autoVersionOnUpdateProps"); - - // folders - static final QName TYPE_SYSTEM_FOLDER = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "systemfolder"); - static final QName TYPE_FOLDER = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "folder"); - /** child association type supported by {@link #TYPE_FOLDER} */ - static final QName ASSOC_CONTAINS = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "contains"); - - // person - static final QName TYPE_PERSON = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "person"); - static final QName PROP_USERNAME = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "userName"); - static final QName PROP_HOMEFOLDER = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "homeFolder"); - static final QName PROP_FIRSTNAME = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "firstName"); - static final QName PROP_LASTNAME = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "lastName"); - static final QName PROP_EMAIL = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "email"); - static final QName PROP_ORGID = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "organizationId"); - static final QName PROP_HOME_FOLDER_PROVIDER = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "homeFolderProvider"); - static final QName PROP_DEFAULT_HOME_FOLDER_PATH = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "defaultHomeFolderPath"); - static final QName PROP_PRESENCEPROVIDER = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "presenceProvider"); - static final QName PROP_PRESENCEUSERNAME = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "presenceUsername"); - static final QName PROP_ORGANIZATION = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "organization"); - static final QName PROP_JOBTITLE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "jobtitle"); - static final QName PROP_LOCATION = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "location"); - static final QName PROP_PERSONDESC = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "persondescription"); - static final QName PROP_TELEPHONE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "telephone"); - static final QName PROP_MOBILE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "mobile"); - static final QName PROP_COMPANYADDRESS1 = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "companyaddress1"); - static final QName PROP_COMPANYADDRESS2 = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "companyaddress2"); - static final QName PROP_COMPANYADDRESS3 = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "companyaddress3"); - static final QName PROP_COMPANYPOSTCODE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "companypostcode"); - static final QName PROP_COMPANYTELEPHONE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "companytelephone"); - static final QName PROP_COMPANYFAX = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "companyfax"); - static final QName PROP_COMPANYEMAIL = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "companyemail"); - static final QName PROP_SKYPE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "skype"); - static final QName PROP_GOOGLEUSERNAME = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "googleusername"); - static final QName PROP_INSTANTMSG = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "instantmsg"); - - static final QName PROP_SIZE_CURRENT = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "sizeCurrent"); - static final QName PROP_SIZE_QUOTA = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "sizeQuota"); - - static final QName ASSOC_AVATAR = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "avatar"); - - // Authority - static final QName TYPE_AUTHORITY = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "authority"); - - static final QName TYPE_AUTHORITY_CONTAINER = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "authorityContainer"); - static final QName PROP_AUTHORITY_NAME = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "authorityName"); - static final QName PROP_AUTHORITY_DISPLAY_NAME = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "authorityDisplayName"); - - static final QName ASSOC_MEMBER = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "member"); - - // Zone - static final QName TYPE_ZONE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "zone"); - static final QName ASSOC_IN_ZONE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "inZone"); - - // Ownable aspect - static final QName ASPECT_OWNABLE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "ownable"); - static final QName PROP_OWNER = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "owner"); - - // Templatable aspect - static final QName ASPECT_TEMPLATABLE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "templatable"); - static final QName PROP_TEMPLATE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "template"); - - // Webscriptable aspect - static final QName ASPECT_WEBSCRIPTABLE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "webscriptable"); - static final QName PROP_WEBSCRIPT = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "webscript"); - - // Dictionary model - static final QName TYPE_DICTIONARY_MODEL = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "dictionaryModel"); - static final QName PROP_MODEL_NAME = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "modelName"); - static final QName PROP_MODEL_DESCRIPTION = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "modelDescription"); - static final QName PROP_MODEL_AUTHOR = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "modelAuthor"); - static final QName PROP_MODEL_PUBLISHED_DATE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "modelPublishedDate"); - static final QName PROP_MODEL_VERSION = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "modelVersion"); - static final QName PROP_MODEL_ACTIVE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "modelActive"); - - // referencing aspect - static final QName ASPECT_REFERENCING = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "referencing"); - static final QName ASSOC_REFERENCES = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "references"); - - // link object - static final QName TYPE_LINK = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "link"); - static final QName PROP_LINK_DESTINATION = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "destination"); - - // attachable aspect - static final QName ASPECT_ATTACHABLE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "attachable"); - static final QName ASSOC_ATTACHMENTS = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "attachments"); - - // email aspect - static final QName ASPECT_MAILED = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "emailed"); - static final QName PROP_SENTDATE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "sentdate"); - static final QName PROP_ORIGINATOR = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "originator"); - static final QName PROP_ADDRESSEE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "addressee"); - static final QName PROP_ADDRESSEES = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "addressees"); - static final QName PROP_SUBJECT = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "subjectline"); - - // countable aspect - static final QName ASPECT_COUNTABLE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "countable"); - static final QName PROP_HITS = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "hits"); - static final QName PROP_COUNTER = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "counter"); - - // References Node Aspect. - static final QName ASPECT_REFERENCES_NODE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "referencesnode"); - static final QName PROP_NODE_REF = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "noderef"); - - // Multilingual Type - static final QName TYPE_MULTILINGUAL_CONTAINER = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "mlContainer"); - static final QName ASSOC_MULTILINGUAL_CHILD = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "mlChild"); - static final QName ASPECT_MULTILINGUAL_DOCUMENT = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "mlDocument"); - static final QName ASPECT_MULTILINGUAL_EMPTY_TRANSLATION = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "mlEmptyTranslation"); - - // Thumbnail Type - static final QName TYPE_THUMBNAIL = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "thumbnail"); - static final QName PROP_THUMBNAIL_NAME = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "thumbnailName"); - static final QName PROP_CONTENT_PROPERTY_NAME = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "contentPropertyName"); - static final QName PROP_AUTOMATIC_UPDATE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "automaticUpdate"); - - // Thumbnailed Aspect - /** - * This aspect type has been deprecated. - * From Alfresco 3.3 the {@link RenditionModel#ASPECT_RENDITIONED rn:renditioned} - * (which is a child of cm:thumbnailed) should be used instead. - */ - @Deprecated - static final QName ASPECT_THUMBNAILED = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "thumbnailed"); - /** - * This association type has been deprecated. - * From Alfresco 3.3 this association no longer exists and has been replaced with - * {@link RenditionModel#ASSOC_RENDITION rn:rendition} association. From Alfresco - * 3.3 onwards {@link QNamePatch a patch} is executed at startup which renames - * the cm:thumbnails QName to rn:rendition in the database. - *

- * This field has been updated to point to that association and references to this - * field should be updated to use the new field. - */ - @Deprecated - static final QName ASSOC_THUMBNAILS = RenditionModel.ASSOC_RENDITION; - - // StoreSelector Aspect - static final QName ASPECT_STORE_SELECTOR = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "storeSelector"); - static final QName PROP_STORE_NAME = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "storeName"); - - // Preference Aspect - static final QName ASPECT_PREFERENCES = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "preferences"); - static final QName PROP_PREFERENCE_VALUES = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "preferenceValues"); - static final QName ASSOC_PREFERENCE_IMAGE = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "preferenceImage"); - - // - // User Model Definitions - // - - static final String USER_MODEL_URI = "http://www.alfresco.org/model/user/1.0"; - static final String USER_MODEL_PREFIX = "usr"; - - static final QName TYPE_USER = QName.createQName(USER_MODEL_URI, "user"); - static final QName PROP_USER_USERNAME = QName.createQName(USER_MODEL_URI, "username"); - static final QName PROP_PASSWORD = QName.createQName(USER_MODEL_URI, "password"); - static final QName PROP_ENABLED = QName.createQName(USER_MODEL_URI, "enabled"); - static final QName PROP_ACCOUNT_EXPIRES = QName.createQName(USER_MODEL_URI, "accountExpires"); - static final QName PROP_ACCOUNT_EXPIRY_DATE = QName.createQName(USER_MODEL_URI, "accountExpiryDate"); - static final QName PROP_CREDENTIALS_EXPIRE = QName.createQName(USER_MODEL_URI, "credentialsExpire"); - static final QName PROP_CREDENTIALS_EXPIRY_DATE = QName.createQName(USER_MODEL_URI, "credentialsExpiryDate"); - static final QName PROP_ACCOUNT_LOCKED = QName.createQName(USER_MODEL_URI, "accountLocked"); - static final QName PROP_SALT = QName.createQName(USER_MODEL_URI, "salt"); -} diff --git a/source/java/org/alfresco/model/RenditionModel.java b/source/java/org/alfresco/model/RenditionModel.java deleted file mode 100644 index 02f18041ea..0000000000 --- a/source/java/org/alfresco/model/RenditionModel.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2005-2010 Alfresco Software Limited. - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - - * This program 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 General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - * As a special exception to the terms and conditions of version 2.0 of - * the GPL, you may redistribute this Program in connection with Free/Libre - * and Open Source Software ("FLOSS") applications as described in Alfresco's - * FLOSS exception. You should have received a copy of the text describing - * the FLOSS exception, and it is also available here: - * http://www.alfresco.com/legal/licensing" - */ -package org.alfresco.model; - -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; - -/** - * Rendition Model Constants - */ -public interface RenditionModel -{ - static final QName ASPECT_RENDITION = QName.createQName(NamespaceService.RENDITION_MODEL_1_0_URI, "rendition"); - static final QName ASPECT_HIDDEN_RENDITION = QName.createQName(NamespaceService.RENDITION_MODEL_1_0_URI, "hiddenRendition"); - static final QName ASPECT_VISIBLE_RENDITION = QName.createQName(NamespaceService.RENDITION_MODEL_1_0_URI, "visibleRendition"); - - static final QName ASPECT_RENDITIONED = QName.createQName(NamespaceService.RENDITION_MODEL_1_0_URI, "renditioned"); - static final QName ASSOC_RENDITION = QName.createQName(NamespaceService.RENDITION_MODEL_1_0_URI, "rendition"); -} diff --git a/source/java/org/alfresco/repo/cache/MemoryCache.java b/source/java/org/alfresco/repo/cache/MemoryCache.java deleted file mode 100644 index f074ba46e8..0000000000 --- a/source/java/org/alfresco/repo/cache/MemoryCache.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.cache; - -import java.io.Serializable; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -/** - * A cache backed by a simple HashMap. - *

- * Note: This cache is not transaction- or thread-safe. Use it for single-threaded tests only. - * - * @author Derek Hulley - * @since 3.2 - */ -public class MemoryCache implements SimpleCache -{ - private Map map; - - public MemoryCache() - { - map = new HashMap(15); - } - - public boolean contains(K key) - { - return map.containsKey(key); - } - - public Collection getKeys() - { - return map.keySet(); - } - - public V get(K key) - { - return map.get(key); - } - - public void put(K key, V value) - { - map.put(key, value); - } - - public void remove(K key) - { - map.remove(key); - } - - public void clear() - { - map.clear(); - } -} diff --git a/source/java/org/alfresco/repo/cache/SimpleCache.java b/source/java/org/alfresco/repo/cache/SimpleCache.java deleted file mode 100644 index 409836df15..0000000000 --- a/source/java/org/alfresco/repo/cache/SimpleCache.java +++ /dev/null @@ -1,76 +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.cache; - -import java.io.Serializable; -import java.util.Collection; - -/** - * Basic caching interface. - *

- * All implementations must be thread-safe. Additionally, the use of the - * Serializable for both keys and values ensures that the underlying - * cache implementations can support both clustered caches as well as persistent - * caches. - *

- * All implementations must support null values. It therefore follows - * that - *

- *    (simpleCache.contains(key) == true) does not imply (simpleCache.get(key) != null)
- * 
- * but - *
- *    (simpleCache.contains(key) == false) implies (simpleCache.get(key) == null)
- * 
- * 
- * @author Derek Hulley
- */
-public interface SimpleCache
-{
-    /**
-     * @param key       the cache key to check up on
-     * @return          Returns true if there is a cache entry,
-     *                  regardless of whether the value itself is null
-     */
-    public boolean contains(K key);
-    
-    public Collection getKeys();
-    
-    /**
-     * @param key
-     * @return          Returns the value associated with the key.  It will be null
-     *                  if the value is null or if the cache doesn't have an entry.
-     */
-    public V get(K key);
-    
-    /**
-     * @param key       the key against which to store the value
-     * @param value     the value to store.  null is allowed.
-     */
-    public void put(K key, V value);
-    
-    /**
-     * Removes the cache entry whether or not the value stored against it is null.
-     * 
-     * @param key       the key value to remove
-     */
-    public void remove(K key);
-    
-    public void clear();
-}
diff --git a/source/java/org/alfresco/repo/content/AbstractContentAccessor.java b/source/java/org/alfresco/repo/content/AbstractContentAccessor.java
index 79087c0708..251488c733 100644
--- a/source/java/org/alfresco/repo/content/AbstractContentAccessor.java
+++ b/source/java/org/alfresco/repo/content/AbstractContentAccessor.java
@@ -61,9 +61,6 @@ public abstract class AbstractContentAccessor implements ContentAccessor
     
     private StackTraceElement[] traceLoggerChannelAssignTrace;
     
-    /** when set, ensures that listeners are executed within a transaction */
-    private RetryingTransactionHelper transactionHelper;
-    
     private String contentUrl;
     private String mimetype;
     private String encoding;
@@ -126,11 +123,6 @@ public abstract class AbstractContentAccessor implements ContentAccessor
         return property;
     }
 
-    public void setRetryingTransactionHelper(RetryingTransactionHelper helper)
-    {
-        this.transactionHelper = helper;
-    }
-    
     /**
      * Derived classes can call this method to ensure that necessary trace logging is performed
      * when the IO Channel is opened.
@@ -263,33 +255,12 @@ public abstract class AbstractContentAccessor implements ContentAccessor
                 // nothing to do
                 return;
             }
-            RetryingTransactionCallback cb = new RetryingTransactionCallback()
+
+            for (ContentStreamListener listener : listeners)
             {
-                public Object execute()
-                {
-                    for (ContentStreamListener listener : listeners)
-                    {
-                        listener.contentStreamClosed();
-                    }
-                    return null;
-                }
-            };
-            if (transactionHelper != null)
-            {
-                // Execute in transaction.
-                transactionHelper.doInTransaction(cb, false);
-            }
-            else
-            {
-                try
-                {
-                    cb.execute();       
-                }
-                catch (Throwable e)
-                {
-                    throw new ContentIOException("Failed to executed channel close callbacks", e);
-                }
+                listener.contentStreamClosed();
             }
+                    
             // done
             if (logger.isDebugEnabled())
             {
@@ -356,37 +327,12 @@ public abstract class AbstractContentAccessor implements ContentAccessor
                 // nothing to do
                 return;
             }
-            // We're now doing this in a retrying transaction, which means
-            // that the body of execute() must be idempotent.
-            RetryingTransactionCallback cb = new RetryingTransactionCallback()
+          
+            for (ContentStreamListener listener : listeners)
             {
-                public Object execute()
-                {
-                    for (ContentStreamListener listener : listeners)
-                    {
-                        listener.contentStreamClosed();
-                    }
-                    return null;
-                }
-            };
-            // We're now doing this inside a Retrying transaction.
-            // NB 
-            if (transactionHelper != null)
-            {
-                // just create a transaction
-                transactionHelper.doInTransaction(cb, false);
-            }
-            else
-            {
-                try
-                {
-                    cb.execute();
-                }
-                catch (Throwable e)
-                {
-                    throw new ContentIOException("Failed to executed channel close callbacks", e);
-                }
+                listener.contentStreamClosed();
             }
+                   
             // done
             if (logger.isDebugEnabled())
             {
diff --git a/source/java/org/alfresco/repo/content/AbstractContentStreamListener.java b/source/java/org/alfresco/repo/content/AbstractContentStreamListener.java
new file mode 100644
index 0000000000..8333a8d2a5
--- /dev/null
+++ b/source/java/org/alfresco/repo/content/AbstractContentStreamListener.java
@@ -0,0 +1,84 @@
+/*
+ * 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.content;
+
+import org.alfresco.repo.transaction.RetryingTransactionHelper;
+import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
+import org.alfresco.service.cmr.repository.ContentIOException;
+import org.alfresco.service.cmr.repository.ContentStreamListener;
+
+/**
+ * @author Andy
+ *
+ */
+public abstract class AbstractContentStreamListener implements ContentStreamListener
+{
+    
+    /** when set, ensures that listeners are executed within a transaction */
+    private RetryingTransactionHelper transactionHelper;
+    
+    public void setRetryingTransactionHelper(RetryingTransactionHelper helper)
+    {
+        this.transactionHelper = helper;
+    }
+    
+    /* (non-Javadoc)
+     * @see org.alfresco.service.cmr.repository.ContentStreamListener#contentStreamClosed()
+     */
+    public final void contentStreamClosed() throws ContentIOException
+    {
+        RetryingTransactionCallback cb = new RetryingTransactionCallback()
+        {
+            public Object execute()
+            {
+                contentStreamClosedImpl();
+                return null;
+            }
+        };
+        if (transactionHelper != null)
+        {
+            // Execute in transaction.
+            transactionHelper.doInTransaction(cb, false);
+        }
+        else
+        {
+            try
+            {
+                cb.execute();       
+            }
+            catch (Throwable e)
+            {
+                throw new ContentIOException("Failed to executed channel close callbacks", e);
+            }
+        }
+
+    }
+    
+    /**
+     * ContentStreamListeners must implement this method.
+     * The implementation must be idempotent.
+     * 
+     * The method will be executed inside a retrying transaction helper if one is set.
+     * Listeners will not generally require this unless they write to the database.
+     * 
+     * @throws ContentIOException
+     */
+    public abstract void  contentStreamClosedImpl() throws ContentIOException;
+
+}
diff --git a/source/java/org/alfresco/repo/content/AbstractWritableContentStoreTest.java b/source/java/org/alfresco/repo/content/AbstractWritableContentStoreTest.java
index ab0d7158c1..95fe1842a6 100644
--- a/source/java/org/alfresco/repo/content/AbstractWritableContentStoreTest.java
+++ b/source/java/org/alfresco/repo/content/AbstractWritableContentStoreTest.java
@@ -490,7 +490,6 @@ public abstract class AbstractWritableContentStoreTest extends AbstractReadOnlyC
                 streamClosed[0] = true;
             }
         };
-        writer.setRetryingTransactionHelper(null);
         writer.addListener(listener);
         
         // write some content
diff --git a/source/java/org/alfresco/repo/content/ContentServiceImpl.java b/source/java/org/alfresco/repo/content/ContentServiceImpl.java
index 5885dc500b..1ac48bd755 100644
--- a/source/java/org/alfresco/repo/content/ContentServiceImpl.java
+++ b/source/java/org/alfresco/repo/content/ContentServiceImpl.java
@@ -48,7 +48,6 @@ import org.alfresco.service.cmr.repository.ContentData;
 import org.alfresco.service.cmr.repository.ContentIOException;
 import org.alfresco.service.cmr.repository.ContentReader;
 import org.alfresco.service.cmr.repository.ContentService;
-import org.alfresco.service.cmr.repository.ContentStreamListener;
 import org.alfresco.service.cmr.repository.ContentWriter;
 import org.alfresco.service.cmr.repository.NoTransformerException;
 import org.alfresco.service.cmr.repository.NodeRef;
@@ -467,8 +466,9 @@ public class ContentServiceImpl implements ContentService, ApplicationContextAwa
         {
             // need a listener to update the node when the stream closes
             WriteStreamListener listener = new WriteStreamListener(nodeService, nodeRef, propertyQName, writer);
+            listener.setRetryingTransactionHelper(transactionHelper);
             writer.addListener(listener);
-            writer.setRetryingTransactionHelper(transactionHelper);
+            
         }
         
         // give back to the client
@@ -596,12 +596,10 @@ public class ContentServiceImpl implements ContentService, ApplicationContextAwa
      * Ensures that, upon closure of the output stream, the node is updated with
      * the latest URL of the content to which it refers.
      * 

- * The listener close operation does not need a transaction as the - * ContentWriter takes care of that. * * @author Derek Hulley */ - private static class WriteStreamListener implements ContentStreamListener + private static class WriteStreamListener extends AbstractContentStreamListener { private NodeService nodeService; private NodeRef nodeRef; @@ -620,7 +618,7 @@ public class ContentServiceImpl implements ContentService, ApplicationContextAwa this.writer = writer; } - public void contentStreamClosed() throws ContentIOException + public void contentStreamClosedImpl() throws ContentIOException { try { diff --git a/source/java/org/alfresco/repo/content/MimetypeMap.java b/source/java/org/alfresco/repo/content/MimetypeMap.java deleted file mode 100644 index 947a3201df..0000000000 --- a/source/java/org/alfresco/repo/content/MimetypeMap.java +++ /dev/null @@ -1,372 +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.content; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.repo.content.encoding.ContentCharsetFinder; -import org.alfresco.service.cmr.repository.MimetypeService; -import org.alfresco.util.PropertyCheck; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.extensions.config.Config; -import org.springframework.extensions.config.ConfigElement; -import org.springframework.extensions.config.ConfigLookupContext; -import org.springframework.extensions.config.ConfigService; - -/** - * Provides a bidirectional mapping between well-known mimetypes and - * the registered file extensions. All mimetypes and extensions - * are stored and handled as lowercase. - * - * @author Derek Hulley - */ -public class MimetypeMap implements MimetypeService -{ - public static final String PREFIX_TEXT = "text/"; - public static final String EXTENSION_BINARY = "bin"; - - public static final String MIMETYPE_TEXT_PLAIN = "text/plain"; - public static final String MIMETYPE_TEXT_MEDIAWIKI = "text/mediawiki"; - public static final String MIMETYPE_TEXT_CSS = "text/css"; - public static final String MIMETYPE_TEXT_CSV = "text/csv"; - public static final String MIMETYPE_TEXT_JAVASCRIPT = "text/javascript"; - public static final String MIMETYPE_XML = "text/xml"; - public static final String MIMETYPE_HTML = "text/html"; - public static final String MIMETYPE_XHTML = "application/xhtml+xml"; - public static final String MIMETYPE_PDF = "application/pdf"; - public static final String MIMETYPE_JSON = "application/json"; - public static final String MIMETYPE_WORD = "application/msword"; - public static final String MIMETYPE_EXCEL = "application/vnd.ms-excel"; - public static final String MIMETYPE_BINARY = "application/octet-stream"; - public static final String MIMETYPE_PPT = "application/vnd.ms-powerpoint"; - public static final String MIMETYPE_APP_DWG = "application/dwg"; - public static final String MIMETYPE_IMG_DWG = "image/vnd.dwg"; - public static final String MIMETYPE_FLASH = "application/x-shockwave-flash"; - public static final String MIMETYPE_IMAGE_GIF = "image/gif"; - public static final String MIMETYPE_IMAGE_JPEG = "image/jpeg"; - public static final String MIMETYPE_IMAGE_RGB = "image/x-rgb"; - public static final String MIMETYPE_IMAGE_SVG = "image/svg"; - public static final String MIMETYPE_IMAGE_PNG = "image/png"; - public static final String MIMETYPE_JAVASCRIPT = "application/x-javascript"; - public static final String MIMETYPE_ZIP = "application/zip"; - public static final String MIMETYPE_OPENSEARCH_DESCRIPTION = "application/opensearchdescription+xml"; - public static final String MIMETYPE_ATOM = "application/atom+xml"; - public static final String MIMETYPE_RSS = "application/rss+xml"; - public static final String MIMETYPE_RFC822 = "message/rfc822"; - public static final String MIMETYPE_OUTLOOK_MSG = "application/vnd.ms-outlook"; - // Open Document - public static final String MIMETYPE_OPENDOCUMENT_TEXT = "application/vnd.oasis.opendocument.text"; - public static final String MIMETYPE_OPENDOCUMENT_TEXT_TEMPLATE = "application/vnd.oasis.opendocument.text-template"; - public static final String MIMETYPE_OPENDOCUMENT_GRAPHICS = "application/vnd.oasis.opendocument.graphics"; - public static final String MIMETYPE_OPENDOCUMENT_GRAPHICS_TEMPLATE= "application/vnd.oasis.opendocument.graphics-template"; - public static final String MIMETYPE_OPENDOCUMENT_PRESENTATION= "application/vnd.oasis.opendocument.presentation"; - public static final String MIMETYPE_OPENDOCUMENT_PRESENTATION_TEMPLATE= "application/vnd.oasis.opendocument.presentation-template"; - public static final String MIMETYPE_OPENDOCUMENT_SPREADSHEET= "application/vnd.oasis.opendocument.spreadsheet"; - public static final String MIMETYPE_OPENDOCUMENT_SPREADSHEET_TEMPLATE= "application/vnd.oasis.opendocument.spreadsheet-template"; - public static final String MIMETYPE_OPENDOCUMENT_CHART= "application/vnd.oasis.opendocument.chart"; - public static final String MIMETYPE_OPENDOCUMENT_CHART_TEMPLATE= "applicationvnd.oasis.opendocument.chart-template"; - public static final String MIMETYPE_OPENDOCUMENT_IMAGE= "application/vnd.oasis.opendocument.image"; - public static final String MIMETYPE_OPENDOCUMENT_IMAGE_TEMPLATE= "applicationvnd.oasis.opendocument.image-template"; - public static final String MIMETYPE_OPENDOCUMENT_FORMULA= "application/vnd.oasis.opendocument.formula"; - public static final String MIMETYPE_OPENDOCUMENT_FORMULA_TEMPLATE= "applicationvnd.oasis.opendocument.formula-template"; - public static final String MIMETYPE_OPENDOCUMENT_TEXT_MASTER= "application/vnd.oasis.opendocument.text-master"; - public static final String MIMETYPE_OPENDOCUMENT_TEXT_WEB= "application/vnd.oasis.opendocument.text-web"; - public static final String MIMETYPE_OPENDOCUMENT_DATABASE= "application/vnd.oasis.opendocument.database"; - // Open Office - public static final String MIMETYPE_OPENOFFICE1_WRITER = "application/vnd.sun.xml.writer"; - public static final String MIMETYPE_OPENOFFICE1_CALC = "application/vnd.sun.xml.calc"; - public static final String MIMETYPE_OPENOFFICE1_DRAW = "application/vnd.sun.xml.draw"; - public static final String MIMETYPE_OPENOFFICE1_IMPRESS = "application/vnd.sun.xml.impress"; - // Open XML - public static final String MIMETYPE_OPENXML_WORDPROCESSING = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; - public static final String MIMETYPE_OPENXML_SPREADSHEET = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; - public static final String MIMETYPE_OPENXML_PRESENTATION = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; - // Star Office - public static final String MIMETYPE_STAROFFICE5_DRAW = "application/vnd.stardivision.draw"; - public static final String MIMETYPE_STAROFFICE5_CALC = "application/vnd.stardivision.calc"; - public static final String MIMETYPE_STAROFFICE5_IMPRESS = "application/vnd.stardivision.impress"; - public static final String MIMETYPE_STAROFFICE5_IMPRESS_PACKED = "application/vnd.stardivision.impress-packed"; - public static final String MIMETYPE_STAROFFICE5_CHART = "application/vnd.stardivision.chart"; - public static final String MIMETYPE_STAROFFICE5_WRITER = "application/vnd.stardivision.writer"; - public static final String MIMETYPE_STAROFFICE5_WRITER_GLOBAL = "application/vnd.stardivision.writer-global"; - public static final String MIMETYPE_STAROFFICE5_MATH = "application/vnd.stardivision.math"; - // WordPerfect - public static final String MIMETYPE_WORDPERFECT = "application/wordperfect"; - // Audio - public static final String MIMETYPE_MP3 = "audio/x-mpeg"; - // Alfresco - public static final String MIMETYPE_ACP = "application/acp"; - - private static final String CONFIG_AREA = "mimetype-map"; - private static final String CONFIG_CONDITION = "Mimetype Map"; - private static final String ELEMENT_MIMETYPES = "mimetypes"; - private static final String ATTR_MIMETYPE = "mimetype"; - private static final String ATTR_DISPLAY = "display"; - private static final String ATTR_DEFAULT = "default"; - private static final String ATTR_TEXT = "text"; - - private static final Log logger = LogFactory.getLog(MimetypeMap.class); - - private ConfigService configService; - private ContentCharsetFinder contentCharsetFinder; - - private List mimetypes; - private Map extensionsByMimetype; - private Map mimetypesByExtension; - private Map displaysByMimetype; - private Map displaysByExtension; - private Set textMimetypes; - - /** - * Default constructor - * - * @since 2.1 - */ - public MimetypeMap() - { - } - - @Deprecated - public MimetypeMap(ConfigService configService) - { - logger.warn( - "MimetypeMap(ConfigService configService) has been deprecated. " + - "Use the default constructor and property 'configService'"); - this.configService = configService; - } - - /** - * @param configService the config service to use to read mimetypes from - */ - public void setConfigService(ConfigService configService) - { - this.configService = configService; - } - - /** - * {@inheritDoc} - */ - public ContentCharsetFinder getContentCharsetFinder() - { - return contentCharsetFinder; - } - - /** - * Set the system default content characterset decoder - */ - public void setContentCharsetFinder(ContentCharsetFinder contentCharsetFinder) - { - this.contentCharsetFinder = contentCharsetFinder; - } - - /** - * Initialises the map using the configuration service provided - */ - public void init() - { - PropertyCheck.mandatory(this, "configService", configService); - PropertyCheck.mandatory(this, "contentCharsetFinder", contentCharsetFinder); - - this.mimetypes = new ArrayList(40); - this.extensionsByMimetype = new HashMap(59); - this.mimetypesByExtension = new HashMap(59); - this.displaysByMimetype = new HashMap(59); - this.displaysByExtension = new HashMap(59); - this.textMimetypes = new HashSet(23); - - Config config = configService.getConfig(CONFIG_CONDITION, new ConfigLookupContext(CONFIG_AREA)); - ConfigElement mimetypesElement = config.getConfigElement(ELEMENT_MIMETYPES); - List mimetypes = mimetypesElement.getChildren(); - int count = 0; - for (ConfigElement mimetypeElement : mimetypes) - { - count++; - // add to list of mimetypes - String mimetype = mimetypeElement.getAttribute(ATTR_MIMETYPE); - if (mimetype == null || mimetype.length() == 0) - { - logger.warn("Ignoring empty mimetype " + count); - continue; - } - // we store it as lowercase - mimetype = mimetype.toLowerCase(); - if (this.mimetypes.contains(mimetype)) - { - throw new AlfrescoRuntimeException("Duplicate mimetype definition: " + mimetype); - } - this.mimetypes.add(mimetype); - // add to map of mimetype displays - String mimetypeDisplay = mimetypeElement.getAttribute(ATTR_DISPLAY); - if (mimetypeDisplay != null && mimetypeDisplay.length() > 0) - { - this.displaysByMimetype.put(mimetype, mimetypeDisplay); - } - - // Check if it is a text format - String isTextStr = mimetypeElement.getAttribute(ATTR_TEXT); - boolean isText = Boolean.parseBoolean(isTextStr); - if (isText || mimetype.startsWith(PREFIX_TEXT)) - { - this.textMimetypes.add(mimetype); - } - - // get all the extensions - boolean isFirst = true; - List extensions = mimetypeElement.getChildren(); - for (ConfigElement extensionElement : extensions) - { - // add to map of mimetypes by extension - String extension = extensionElement.getValue(); - if (extension == null || extension.length() == 0) - { - logger.warn("Ignoring empty extension for mimetype: " + mimetype); - continue; - } - // put to lowercase - extension = extension.toLowerCase(); - this.mimetypesByExtension.put(extension, mimetype); - // add to map of extension displays - String extensionDisplay = extensionElement.getAttribute(ATTR_DISPLAY); - if (extensionDisplay != null && extensionDisplay.length() > 0) - { - this.displaysByExtension.put(extension, extensionDisplay); - } - else if (mimetypeDisplay != null && mimetypeDisplay.length() > 0) - { - // no display defined for the extension - use the mimetype's display - this.displaysByExtension.put(extension, mimetypeDisplay); - } - // add to map of extensions by mimetype if it is the default or first extension - String isDefaultStr = extensionElement.getAttribute(ATTR_DEFAULT); - boolean isDefault = Boolean.parseBoolean(isDefaultStr); - if (isDefault || isFirst) - { - this.extensionsByMimetype.put(mimetype, extension); - } - // Loop again - isFirst = false; - } - // check that there were extensions defined - if (extensions.size() == 0) - { - logger.warn("No extensions defined for mimetype: " + mimetype); - } - } - - // make the collections read-only - this.mimetypes = Collections.unmodifiableList(this.mimetypes); - this.extensionsByMimetype = Collections.unmodifiableMap(this.extensionsByMimetype); - this.mimetypesByExtension = Collections.unmodifiableMap(this.mimetypesByExtension); - this.displaysByMimetype = Collections.unmodifiableMap(this.displaysByMimetype); - this.displaysByExtension = Collections.unmodifiableMap(this.displaysByExtension); - } - - /** - * Get the file extension associated with the mimetype. - * - * @param mimetype a valid mimetype - * @return Returns the default extension for the mimetype. Returns the {@link #MIMETYPE_BINARY binary} - * mimetype extension. - * - * @see #MIMETYPE_BINARY - * @see #EXTENSION_BINARY - */ - public String getExtension(String mimetype) - { - String extension = extensionsByMimetype.get(mimetype); - return (extension == null ? EXTENSION_BINARY : extension); - } - - /** - * Get the mimetype for the specified extension - * - * @param extension a valid file extension - * @return Returns a valid mimetype if found, or {@link #MIMETYPE_BINARY binary} as default. - */ - public String getMimetype(String extension) - { - String mimetype = MIMETYPE_BINARY; - if (extension != null) - { - extension = extension.toLowerCase(); - if (mimetypesByExtension.containsKey(extension)) - { - mimetype = mimetypesByExtension.get(extension); - } - } - return mimetype; - } - - public Map getDisplaysByExtension() - { - return displaysByExtension; - } - - public Map getDisplaysByMimetype() - { - return displaysByMimetype; - } - - public Map getExtensionsByMimetype() - { - return extensionsByMimetype; - } - - public List getMimetypes() - { - return mimetypes; - } - - public Map getMimetypesByExtension() - { - return mimetypesByExtension; - } - - public boolean isText(String mimetype) - { - return textMimetypes.contains(mimetype); - } - - /** - * @see #MIMETYPE_BINARY - */ - public String guessMimetype(String filename) - { - String mimetype = MIMETYPE_BINARY; - // extract the extension - int index = filename.lastIndexOf('.'); - if (index > -1 && (index < filename.length() - 1)) - { - String extension = filename.substring(index + 1).toLowerCase(); - if (mimetypesByExtension.containsKey(extension)) - { - mimetype = mimetypesByExtension.get(extension); - } - } - return mimetype; - } -} diff --git a/source/java/org/alfresco/repo/content/encoding/ContentCharsetFinder.java b/source/java/org/alfresco/repo/content/encoding/ContentCharsetFinder.java deleted file mode 100644 index 96266f64f2..0000000000 --- a/source/java/org/alfresco/repo/content/encoding/ContentCharsetFinder.java +++ /dev/null @@ -1,110 +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.content.encoding; - -import java.io.InputStream; -import java.nio.charset.Charset; -import java.util.List; - -import org.alfresco.encoding.CharactersetFinder; -import org.alfresco.service.cmr.repository.MimetypeService; - -/** - * Utility bean to guess the charset given a stream and a mimetype. - * - * @since 2.1 - * @author Derek Hulley - */ -public class ContentCharsetFinder -{ - private Charset defaultCharset = Charset.defaultCharset(); - private MimetypeService mimetypeService; - private List charactersetFinders; - - /** - * Override the system default charset. Where the characterset cannot be determined for - * a mimetype and input stream, this mimetype will be used. The default is 'UTF-8'. - * - * @param defaultCharset the default characterset - */ - public void setDefaultCharset(String defaultCharset) - { - this.defaultCharset = Charset.forName(defaultCharset); - } - - /** - * Set the mimetype service that will help determine if a particular mimetype can be - * treated as encoded text or not. - */ - public void setMimetypeService(MimetypeService mimetypeService) - { - this.mimetypeService = mimetypeService; - } - - /** - * Set the list of characterset finder to execute, in order, for text based content. - * @param charactersetFinders a list of finders - */ - public void setCharactersetFinders(List charactersetFinders) - { - this.charactersetFinders = charactersetFinders; - } - - /** - * Gets the characterset from the stream, if the mimetype is text and the text - * has enough information to give the encoding away. Otherwise, the default - * is returned. - * - * @param is a stream that will not be affected by the call, but must - * support marking - * @param mimetype the mimetype of the stream data - null if not known - * @return returns a characterset and never null - */ - public Charset getCharset(InputStream is, String mimetype) - { - if (mimetype == null) - { - return defaultCharset; - } - // Is it text? - if (!mimetypeService.isText(mimetype)) - { - return defaultCharset; - } - // Try the finders - Charset charset = null; - for (CharactersetFinder finder : charactersetFinders) - { - charset = finder.detectCharset(is); - if (charset != null) - { - break; - } - } - // Done - if (charset == null) - { - return defaultCharset; - } - else - { - return charset; - } - } -} diff --git a/source/java/org/alfresco/repo/content/replication/ReplicatingContentStore.java b/source/java/org/alfresco/repo/content/replication/ReplicatingContentStore.java index b99d800b1e..c4856dba93 100644 --- a/source/java/org/alfresco/repo/content/replication/ReplicatingContentStore.java +++ b/source/java/org/alfresco/repo/content/replication/ReplicatingContentStore.java @@ -27,6 +27,7 @@ import java.util.concurrent.locks.ReentrantReadWriteLock; import org.alfresco.error.AlfrescoRuntimeException; import org.alfresco.repo.content.AbstractContentStore; +import org.alfresco.repo.content.AbstractContentStreamListener; import org.alfresco.repo.content.ContentContext; import org.alfresco.repo.content.ContentExistsException; import org.alfresco.repo.content.ContentStore; @@ -315,9 +316,10 @@ public class ReplicatingContentStore extends AbstractContentStore " writer: " + writer); } // attach the listener - ContentStreamListener listener = new ReplicatingWriteListener(secondaryStores, writer, outboundThreadPoolExecutor); + ReplicatingWriteListener listener = new ReplicatingWriteListener(secondaryStores, writer, outboundThreadPoolExecutor); + listener.setRetryingTransactionHelper(transactionHelper); // mandatory when listeners are added writer.addListener(listener); - writer.setRetryingTransactionHelper(transactionHelper); // mandatory when listeners are added + } // done @@ -388,13 +390,11 @@ public class ReplicatingContentStore extends AbstractContentStore * Replicates the content upon stream closure. If the thread pool is available, * then the process will be asynchronous. *

- * No transaction boundaries have been declared as the - * {@link ContentWriter#addListener(ContentStreamListener)} method indicates that - * all listeners will be called within a transaction. + * * @author Derek Hulley */ - public static class ReplicatingWriteListener implements ContentStreamListener + public static class ReplicatingWriteListener extends AbstractContentStreamListener { private List stores; private ContentWriter writer; @@ -410,7 +410,7 @@ public class ReplicatingContentStore extends AbstractContentStore this.threadPoolExecutor = threadPoolExecutor; } - public void contentStreamClosed() throws ContentIOException + public void contentStreamClosedImpl() throws ContentIOException { Runnable runnable = new ReplicateOnCloseRunnable(); if (threadPoolExecutor == null) diff --git a/source/java/org/alfresco/repo/dictionary/CompiledModel.java b/source/java/org/alfresco/repo/dictionary/CompiledModel.java deleted file mode 100644 index 2807a7ca1a..0000000000 --- a/source/java/org/alfresco/repo/dictionary/CompiledModel.java +++ /dev/null @@ -1,427 +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.dictionary; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -import org.alfresco.service.cmr.dictionary.AspectDefinition; -import org.alfresco.service.cmr.dictionary.AssociationDefinition; -import org.alfresco.service.cmr.dictionary.ClassDefinition; -import org.alfresco.service.cmr.dictionary.ConstraintDefinition; -import org.alfresco.service.cmr.dictionary.DataTypeDefinition; -import org.alfresco.service.cmr.dictionary.DictionaryException; -import org.alfresco.service.cmr.dictionary.ModelDefinition; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.cmr.dictionary.TypeDefinition; -import org.alfresco.service.namespace.DynamicNamespacePrefixResolver; -import org.alfresco.service.namespace.NamespaceException; -import org.alfresco.service.namespace.NamespacePrefixResolver; -import org.alfresco.service.namespace.QName; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - - -/** - * Compiled representation of a model definition. - * - * In this case, compiled means that - * a) all references between model items have been resolved - * b) inheritence of class features have been flattened - * c) overridden class features have been resolved - * - * A compiled model also represents a valid model. - * - * @author David Caruana - * - */ -/*package*/ class CompiledModel implements ModelQuery -{ - - // Logger - private static final Log logger = LogFactory.getLog(DictionaryDAOImpl.class); - - private M2Model model; - private ModelDefinition modelDefinition; - private Map dataTypes = new HashMap(); - private Map classes = new HashMap(); - private Map types = new HashMap(); - private Map aspects = new HashMap(); - private Map properties = new HashMap(); - private Map associations = new HashMap(); - private Map constraints = new HashMap(); - - /** - * Construct - * - * @param model model definition - * @param dictionaryDAO dictionary DAO - * @param namespaceDAO namespace DAO - */ - /*package*/ CompiledModel(M2Model model, DictionaryDAO dictionaryDAO, NamespaceDAO namespaceDAO) - { - try - { - // Phase 1: Construct model definitions from model entries - // resolving qualified names - this.model = model; - constructDefinitions(model, namespaceDAO); - - // Phase 2: Resolve dependencies between model definitions - ModelQuery query = new DelegateModelQuery(this, dictionaryDAO); - resolveDependencies(query, namespaceDAO); - - // Phase 3: Resolve inheritance of values within class hierachy - NamespacePrefixResolver localPrefixes = createLocalPrefixResolver(model, namespaceDAO); - resolveInheritance(query, localPrefixes, constraints); - - // Phase 4: Resolve constraint dependencies - for (ConstraintDefinition def : constraints.values()) - { - ((M2ConstraintDefinition)def).resolveDependencies(query); - } - } - catch(Exception e) - { - throw new DictionaryException("Failed to compile model " + model.getName(), e); - } - } - - - /** - * @return the model definition - */ - /*package*/ M2Model getM2Model() - { - return model; - } - - - /** - * Construct compiled definitions - * - * @param model model definition - * @param namespaceDAO namespace DAO - */ - private void constructDefinitions(M2Model model, NamespaceDAO namespaceDAO) - { - NamespacePrefixResolver localPrefixes = createLocalPrefixResolver(model, namespaceDAO); - - // Construct Model Definition - modelDefinition = new M2ModelDefinition(model, localPrefixes); - - // Construct Property Types - for (M2DataType propType : model.getPropertyTypes()) - { - M2DataTypeDefinition def = new M2DataTypeDefinition(modelDefinition, propType, localPrefixes); - if (dataTypes.containsKey(def.getName())) - { - throw new DictionaryException("Found duplicate property type definition " + propType.getName()); - } - dataTypes.put(def.getName(), def); - } - - // Construct Type Definitions - for (M2Type type : model.getTypes()) - { - M2TypeDefinition def = new M2TypeDefinition(modelDefinition, type, localPrefixes, properties, associations); - if (classes.containsKey(def.getName())) - { - throw new DictionaryException("Found duplicate class definition " + type.getName() + " (a type)"); - } - classes.put(def.getName(), def); - types.put(def.getName(), def); - } - - // Construct Aspect Definitions - for (M2Aspect aspect : model.getAspects()) - { - M2AspectDefinition def = new M2AspectDefinition(modelDefinition, aspect, localPrefixes, properties, associations); - if (classes.containsKey(def.getName())) - { - throw new DictionaryException("Found duplicate class definition " + aspect.getName() + " (an aspect)"); - } - classes.put(def.getName(), def); - aspects.put(def.getName(), def); - } - - // Construct Constraint Definitions - for (M2Constraint constraint : model.getConstraints()) - { - M2ConstraintDefinition def = new M2ConstraintDefinition(modelDefinition, null, constraint, localPrefixes); - QName qname = def.getName(); - if (constraints.containsKey(qname)) - { - throw new DictionaryException("Found duplicate constraint definition " + constraint.getName() + " (an aspect)"); - } - constraints.put(qname, def); - } - } - - - /** - * Create a local namespace prefix resolver containing the namespaces defined and imported - * in the model - * - * @param model model definition - * @param namespaceDAO namespace DAO - * @return the local namespace prefix resolver - */ - private NamespacePrefixResolver createLocalPrefixResolver(M2Model model, NamespaceDAO namespaceDAO) - { - // Retrieve set of existing URIs for validation purposes - Collection uris = namespaceDAO.getURIs(); - - // Create a namespace prefix resolver based on imported and defined - // namespaces within the model - DynamicNamespacePrefixResolver prefixResolver = new DynamicNamespacePrefixResolver(null); - for (M2Namespace imported : model.getImports()) - { - String uri = imported.getUri(); - if (!uris.contains(uri)) - { - throw new NamespaceException("URI " + uri + " cannot be imported as it is not defined (with prefix " + imported.getPrefix()); - } - prefixResolver.registerNamespace(imported.getPrefix(), uri); - } - for (M2Namespace defined : model.getNamespaces()) - { - prefixResolver.registerNamespace(defined.getPrefix(), defined.getUri()); - } - return prefixResolver; - } - - - /** - * Resolve dependencies between model items - * - * @param query support for querying other items in model - */ - private void resolveDependencies(ModelQuery query, NamespaceDAO namespaceDAO) - { - NamespacePrefixResolver prefixResolver = createLocalPrefixResolver(model, namespaceDAO); - - for (DataTypeDefinition def : dataTypes.values()) - { - ((M2DataTypeDefinition)def).resolveDependencies(query); - } - for (ClassDefinition def : classes.values()) - { - ((M2ClassDefinition)def).resolveDependencies(query, prefixResolver, constraints); - } - } - - - /** - * Resolve class feature inheritence - * - * @param query support for querying other items in model - */ - private void resolveInheritance( - ModelQuery query, - NamespacePrefixResolver prefixResolver, - Map modelConstraints) - { - // Calculate order of class processing (root to leaf) - Map> order = new TreeMap>(); - for (ClassDefinition def : classes.values()) - { - // Calculate class depth in hierarchy - int depth = 0; - QName parentName = def.getParentName(); - while (parentName != null) - { - ClassDefinition parentClass = getClass(parentName); - if (parentClass == null) - { - break; - } - depth = depth +1; - parentName = parentClass.getParentName(); - } - - // Map class to depth - List classes = order.get(depth); - if (classes == null) - { - classes = new ArrayList(); - order.put(depth, classes); - } - classes.add(def); - - if (logger.isTraceEnabled()) - { - logger.trace("Resolving inheritance: class " + def.getName() + " found at depth " + depth); - } - } - - // Resolve inheritance of each class - for (int depth = 0; depth < order.size(); depth++) - { - for (ClassDefinition def : order.get(depth)) - { - ((M2ClassDefinition)def).resolveInheritance(query, prefixResolver, modelConstraints); - } - } - } - - - /** - * @return the compiled model definition - */ - public ModelDefinition getModelDefinition() - { - return modelDefinition; - } - - - /** - * @return the compiled property types - */ - public Collection getDataTypes() - { - return dataTypes.values(); - } - - - /** - * @return the compiled types - */ - public Collection getTypes() - { - return types.values(); - } - - - /** - * @return the compiled aspects - */ - public Collection getAspects() - { - return aspects.values(); - } - - /** - * - * @return the compiled properties - */ - public Collection getProperties() - { - return properties.values(); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.ModelQuery#getPropertyType(org.alfresco.repo.ref.QName) - */ - public DataTypeDefinition getDataType(QName name) - { - return dataTypes.get(name); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ModelQuery#getDataType(java.lang.Class) - */ - public DataTypeDefinition getDataType(Class javaClass) - { - for (DataTypeDefinition dataTypeDef : dataTypes.values()) - { - if (dataTypeDef.getJavaClassName().equals(javaClass.getName())) - { - return dataTypeDef; - } - } - return null; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.ModelQuery#getType(org.alfresco.repo.ref.QName) - */ - public TypeDefinition getType(QName name) - { - return types.get(name); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.ModelQuery#getAspect(org.alfresco.repo.ref.QName) - */ - public AspectDefinition getAspect(QName name) - { - return aspects.get(name); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.ModelQuery#getClass(org.alfresco.repo.ref.QName) - */ - public ClassDefinition getClass(QName name) - { - return classes.get(name); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.ModelQuery#getProperty(org.alfresco.repo.ref.QName) - */ - public PropertyDefinition getProperty(QName name) - { - return properties.get(name); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.ModelQuery#getAssociation(org.alfresco.repo.ref.QName) - */ - public AssociationDefinition getAssociation(QName name) - { - return associations.get(name); - } - - /** - * @return the compiled associations - */ - public Collection getAssociations() - { - return associations.values(); - } - - /** - * @return the compiled constraints - */ - public Collection getConstraints() - { - return constraints.values(); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.ModelQuery#getConstraint(QName) - */ - public ConstraintDefinition getConstraint(QName name) - { - return constraints.get(name); - } -} diff --git a/source/java/org/alfresco/repo/dictionary/DelegateModelQuery.java b/source/java/org/alfresco/repo/dictionary/DelegateModelQuery.java deleted file mode 100644 index a2525b2bc4..0000000000 --- a/source/java/org/alfresco/repo/dictionary/DelegateModelQuery.java +++ /dev/null @@ -1,166 +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.dictionary; - -import org.alfresco.service.cmr.dictionary.AspectDefinition; -import org.alfresco.service.cmr.dictionary.AssociationDefinition; -import org.alfresco.service.cmr.dictionary.ClassDefinition; -import org.alfresco.service.cmr.dictionary.ConstraintDefinition; -import org.alfresco.service.cmr.dictionary.DataTypeDefinition; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.cmr.dictionary.TypeDefinition; -import org.alfresco.service.namespace.QName; - -/** - * Model query that delegates its search if itself cannot find the model - * item required. - * - * @author David Caruana - * - */ -/*package*/ class DelegateModelQuery implements ModelQuery -{ - - private ModelQuery query; - private ModelQuery delegate; - - - /** - * Construct - * - * @param query - * @param delegate - */ - /*package*/ DelegateModelQuery(ModelQuery query, ModelQuery delegate) - { - this.query = query; - this.delegate = delegate; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.ModelQuery#getPropertyType(org.alfresco.repo.ref.QName) - */ - public DataTypeDefinition getDataType(QName name) - { - DataTypeDefinition def = query.getDataType(name); - if (def == null) - { - def = delegate.getDataType(name); - } - return def; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ModelQuery#getDataType(java.lang.Class) - */ - public DataTypeDefinition getDataType(Class javaClass) - { - DataTypeDefinition def = query.getDataType(javaClass); - if (def == null) - { - def = delegate.getDataType(javaClass); - } - return def; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.ModelQuery#getType(org.alfresco.repo.ref.QName) - */ - public TypeDefinition getType(QName name) - { - TypeDefinition def = query.getType(name); - if (def == null) - { - def = delegate.getType(name); - } - return def; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.ModelQuery#getAspect(org.alfresco.repo.ref.QName) - */ - public AspectDefinition getAspect(QName name) - { - AspectDefinition def = query.getAspect(name); - if (def == null) - { - def = delegate.getAspect(name); - } - return def; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.ModelQuery#getClass(org.alfresco.repo.ref.QName) - */ - public ClassDefinition getClass(QName name) - { - ClassDefinition def = query.getClass(name); - if (def == null) - { - def = delegate.getClass(name); - } - return def; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.ModelQuery#getProperty(org.alfresco.repo.ref.QName) - */ - public PropertyDefinition getProperty(QName name) - { - PropertyDefinition def = query.getProperty(name); - if (def == null) - { - def = delegate.getProperty(name); - } - return def; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.ModelQuery#getAssociation(org.alfresco.repo.ref.QName) - */ - public AssociationDefinition getAssociation(QName name) - { - AssociationDefinition def = query.getAssociation(name); - if (def == null) - { - def = delegate.getAssociation(name); - } - return def; - } - - /* (non-Javadoc) - * @see ModelQuery#getConstraint(QName) - */ - public ConstraintDefinition getConstraint(QName name) - { - ConstraintDefinition def = query.getConstraint(name); - if (def == null) - { - def = delegate.getConstraint(name); - } - return def; - } -} diff --git a/source/java/org/alfresco/repo/dictionary/DictionaryBootstrap.java b/source/java/org/alfresco/repo/dictionary/DictionaryBootstrap.java deleted file mode 100644 index c42fb4e6e2..0000000000 --- a/source/java/org/alfresco/repo/dictionary/DictionaryBootstrap.java +++ /dev/null @@ -1,198 +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.dictionary; - -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.springframework.extensions.surf.util.I18NUtil; -import org.alfresco.repo.tenant.TenantService; -import org.alfresco.service.cmr.dictionary.DictionaryException; -import org.alfresco.service.namespace.QName; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - - -/** - * Bootstrap Dictionary DAO with pre-defined models & message resources (from classpath) - * - * @author David Caruana, janv - * - */ -public class DictionaryBootstrap implements DictionaryListener -{ - // The list of models to bootstrap with - private List models = new ArrayList(); - - // The list of model resource bundles to bootstrap with - private List resourceBundles = new ArrayList(); - - // Dictionary DAO - private DictionaryDAO dictionaryDAO = null; - - // Tenant Service - private TenantService tenantService; - - // Logger - private static Log logger = LogFactory.getLog(DictionaryBootstrap.class); - - - /** - * Sets the Dictionary DAO - * - * @param dictionaryDAO - */ - public void setDictionaryDAO(DictionaryDAO dictionaryDAO) - { - this.dictionaryDAO = dictionaryDAO; - } - - /** - * Sets the Tenant Service - * - * @param tenantService - */ - public void setTenantService(TenantService tenantService) - { - this.tenantService = tenantService; - } - - /** - * Sets the initial list of models to bootstrap with - * - * @param modelResources the model names - */ - public void setModels(List modelResources) - { - this.models = modelResources; - } - - /** - * Sets the initial list of models to bootstrap with - * - * @param modelResources the model names - */ - public void setLabels(List labels) - { - this.resourceBundles = labels; - } - - /** - * Bootstrap the Dictionary - register and populate - * - */ - public void bootstrap() - { - onDictionaryInit(); - initStaticMessages(); - - register(); - } - - /** - * Register with the Dictionary - */ - public void register() - { - dictionaryDAO.register(this); - } - - /* - * (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryListener#onInit() - */ - public void onDictionaryInit() - { - long startTime = System.currentTimeMillis(); - - if (logger.isTraceEnabled()) - { - logger.trace("onDictionaryInit: ["+Thread.currentThread()+"]"); - } - - Collection modelsBefore = dictionaryDAO.getModels(); // note: on first bootstrap will init empty dictionary - int modelsBeforeCnt = (modelsBefore != null ? modelsBefore.size() : 0); - - if ((tenantService == null) || (! tenantService.isTenantUser())) - { - // register models - for (String bootstrapModel : models) - { - InputStream modelStream = getClass().getClassLoader().getResourceAsStream(bootstrapModel); - if (modelStream == null) - { - throw new DictionaryException("Could not find bootstrap model " + bootstrapModel); - } - try - { - M2Model model = M2Model.createModel(modelStream); - - if (logger.isDebugEnabled()) - { - logger.debug("Loading model: "+model.getName()+" (from "+bootstrapModel+")"); - } - - dictionaryDAO.putModel(model); - } - catch(DictionaryException e) - { - throw new DictionaryException("Could not import bootstrap model " + bootstrapModel, e); - } - } - - Collection modelsAfter = dictionaryDAO.getModels(); - int modelsAfterCnt = (modelsAfter != null ? modelsAfter.size() : 0); - - if (logger.isDebugEnabled()) - { - logger.debug("Model count: before="+modelsBeforeCnt+", load="+models.size()+", after="+modelsAfterCnt+" in "+(System.currentTimeMillis()-startTime)+" msecs ["+Thread.currentThread()+"]"); - } - } - } - - /* - * (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryListener#afterInit() - */ - public void afterDictionaryInit() - { - } - - /* - * (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryListener#onDictionaryDestroy() - */ - public void afterDictionaryDestroy() - { - } - - /** - * Register the static resource bundles - */ - private void initStaticMessages() - { - // register messages - for (String resourceBundle : resourceBundles) - { - I18NUtil.registerResourceBundle(resourceBundle); - } - } -} diff --git a/source/java/org/alfresco/repo/dictionary/DictionaryComponent.java b/source/java/org/alfresco/repo/dictionary/DictionaryComponent.java deleted file mode 100644 index 1186be2449..0000000000 --- a/source/java/org/alfresco/repo/dictionary/DictionaryComponent.java +++ /dev/null @@ -1,425 +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.dictionary; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Map; - -import org.alfresco.repo.tenant.TenantDeployer; -import org.alfresco.service.cmr.dictionary.AspectDefinition; -import org.alfresco.service.cmr.dictionary.AssociationDefinition; -import org.alfresco.service.cmr.dictionary.ClassDefinition; -import org.alfresco.service.cmr.dictionary.ConstraintDefinition; -import org.alfresco.service.cmr.dictionary.DataTypeDefinition; -import org.alfresco.service.cmr.dictionary.DictionaryService; -import org.alfresco.service.cmr.dictionary.ModelDefinition; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.cmr.dictionary.TypeDefinition; -import org.alfresco.service.namespace.QName; -import org.springframework.extensions.surf.util.ParameterCheck; - - -/** - * Data Dictionary Service Implementation - * - * @author David Caruana - */ -public class DictionaryComponent implements DictionaryService, TenantDeployer -{ - private DictionaryDAO dictionaryDAO; - - // TODO: Check passed arguments are valid - - /** - * Sets the Meta Model DAO - * - * @param metaModelDAO meta model DAO - */ - public void setDictionaryDAO(DictionaryDAO dictionaryDAO) - { - this.dictionaryDAO = dictionaryDAO; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryService#getAllModels() - */ - public Collection getAllModels() - { - return dictionaryDAO.getModels(); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryService#getModel(org.alfresco.repo.ref.QName) - */ - public ModelDefinition getModel(QName model) - { - return dictionaryDAO.getModel(model); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryService#getAllPropertyTypes() - */ - public Collection getAllDataTypes() - { - Collection propertyTypes = new ArrayList(); - for (QName model : getAllModels()) - { - propertyTypes.addAll(getDataTypes(model)); - } - return propertyTypes; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryService#getPropertyTypes(org.alfresco.repo.ref.QName) - */ - public Collection getDataTypes(QName model) - { - Collection propertyTypes = dictionaryDAO.getDataTypes(model); - Collection qnames = new ArrayList(propertyTypes.size()); - for (DataTypeDefinition def : propertyTypes) - { - qnames.add(def.getName()); - } - return qnames; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryService#getAllTypes() - */ - public Collection getAllTypes() - { - Collection types = new ArrayList(100); - for (QName model : getAllModels()) - { - types.addAll(getTypes(model)); - } - return types; - } - - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.DictionaryService#getSubTypes(org.alfresco.service.namespace.QName, boolean) - */ - public Collection getSubTypes(QName superType, boolean follow) - { - return dictionaryDAO.getSubTypes(superType, follow); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryService#getTypes(org.alfresco.repo.ref.QName) - */ - public Collection getTypes(QName model) - { - Collection types = dictionaryDAO.getTypes(model); - Collection qnames = new ArrayList(types.size()); - for (TypeDefinition def : types) - { - qnames.add(def.getName()); - } - return qnames; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryService#getAllAspects() - */ - public Collection getAllAspects() - { - Collection aspects = new ArrayList(64); - for (QName model : getAllModels()) - { - aspects.addAll(getAspects(model)); - } - return aspects; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryService#getAllAssociations() - */ - public Collection getAllAssociations() - { - Collection associations = new ArrayList(64); - for (QName model : getAllModels()) - { - associations.addAll(getAssociations(model)); - } - return associations; - } - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.DictionaryService#getSubAspects(org.alfresco.service.namespace.QName, boolean) - */ - public Collection getSubAspects(QName superAspect, boolean follow) - { - return dictionaryDAO.getSubAspects(superAspect, follow); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryService#getAspects(org.alfresco.repo.ref.QName) - */ - public Collection getAspects(QName model) - { - Collection aspects = dictionaryDAO.getAspects(model); - Collection qnames = new ArrayList(aspects.size()); - for (AspectDefinition def : aspects) - { - qnames.add(def.getName()); - } - return qnames; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryService#getAssociations(org.alfresco.repo.ref.QName) - */ - public Collection getAssociations(QName model) - { - Collection associations = dictionaryDAO.getAssociations(model); - Collection qnames = new ArrayList(associations.size()); - for (AssociationDefinition def : associations) - { - qnames.add(def.getName()); - } - return qnames; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryService#isSubClass(org.alfresco.repo.ref.QName, org.alfresco.repo.ref.QName) - */ - public boolean isSubClass(QName className, QName ofClassName) - { - // Validate arguments - ParameterCheck.mandatory("className", className); - ParameterCheck.mandatory("ofClassName", ofClassName); - ClassDefinition classDef = getClass(className); - if (classDef == null) - { - return false; - } - ClassDefinition ofClassDef = getClass(ofClassName); - if (ofClassDef == null) - { - return false; - } - - // Only check if both ends are either a type or an aspect - boolean subClassOf = false; - if (classDef.isAspect() == ofClassDef.isAspect()) - { - while (classDef != null) - { - if (classDef.equals(ofClassDef)) - { - subClassOf = true; - break; - } - - // No match yet, so go to parent class - QName parentClassName = classDef.getParentName(); - classDef = (parentClassName == null) ? null : getClass(parentClassName); - } - } - return subClassOf; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryService#getPropertyType(org.alfresco.repo.ref.QName) - */ - public DataTypeDefinition getDataType(QName name) - { - return dictionaryDAO.getDataType(name); - } - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.DictionaryService#getDataType(java.lang.Class) - */ - public DataTypeDefinition getDataType(Class javaClass) - { - return dictionaryDAO.getDataType(javaClass); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryService#getType(org.alfresco.repo.ref.QName) - */ - public TypeDefinition getType(QName name) - { - return dictionaryDAO.getType(name); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryService#getAspect(org.alfresco.repo.ref.QName) - */ - public AspectDefinition getAspect(QName name) - { - return dictionaryDAO.getAspect(name); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryService#getClass(org.alfresco.repo.ref.QName) - */ - public ClassDefinition getClass(QName name) - { - return dictionaryDAO.getClass(name); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryService#getAnonymousType(org.alfresco.repo.ref.QName, java.util.Collection) - */ - public TypeDefinition getAnonymousType(QName type, Collection aspects) - { - return dictionaryDAO.getAnonymousType(type, aspects); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryService#getProperty(org.alfresco.repo.ref.QName, org.alfresco.repo.ref.QName) - */ - public PropertyDefinition getProperty(QName className, QName propertyName) - { - PropertyDefinition propDef = null; - ClassDefinition classDef = dictionaryDAO.getClass(className); - if (classDef != null) - { - Map propDefs = classDef.getProperties(); - propDef = propDefs.get(propertyName); - } - return propDef; - } - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.DictionaryService#getPropertyDefs(org.alfresco.service.namespace.QName) - */ - public Map getPropertyDefs(QName className) - { - ClassDefinition classDef = dictionaryDAO.getClass(className); - if (classDef != null) - { - return classDef.getProperties(); - } - return null; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryService#getProperty(org.alfresco.repo.ref.QName) - */ - public PropertyDefinition getProperty(QName propertyName) - { - return dictionaryDAO.getProperty(propertyName); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryService#getAssociation(org.alfresco.repo.ref.QName) - */ - public AssociationDefinition getAssociation(QName associationName) - { - return dictionaryDAO.getAssociation(associationName); - } - - /* - * (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.DictionaryService#getAllProperties(org.alfresco.service.namespace.QName) - */ - public Collection getAllProperties(QName dataType) - { - Collection aspects = new HashSet(64); - for (QName model : getAllModels()) - { - aspects.addAll(getProperties(model, dataType)); - } - return aspects; - } - - /* - * (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.DictionaryService#getAllProperties(org.alfresco.service.namespace.QName, org.alfresco.service.namespace.QName) - */ - public Collection getProperties(QName model, QName dataType) - { - Collection propDefs = dictionaryDAO.getProperties(model, dataType); - HashSet props = new HashSet(propDefs.size()); - for(PropertyDefinition def : propDefs) - { - props.add(def.getName()); - } - return props; - - } - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.DictionaryService#getProperties(org.alfresco.service.namespace.QName) - */ - public Collection getProperties(QName model) - { - Collection propDefs = dictionaryDAO.getProperties(model); - HashSet props = new HashSet(propDefs.size()); - for(PropertyDefinition def : propDefs) - { - props.add(def.getName()); - } - return props; - } - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.DictionaryService#getConstraint(org.alfresco.service.namespace.QName) - */ - public ConstraintDefinition getConstraint(QName constraintQName) - { - return dictionaryDAO.getConstraint(constraintQName); - } - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.DictionaryService#getConstraints(org.alfresco.service.namespace.QName) - */ - public Collection getConstraints(QName model) - { - return dictionaryDAO.getConstraints(model); - } - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.DictionaryService#getConstraints(org.alfresco.service.namespace.QName, boolean) - */ - public Collection getConstraints(QName model, boolean referenceableDefsOnly) - { - return dictionaryDAO.getConstraints(model, referenceableDefsOnly); - } - - public void init() - { - dictionaryDAO.init(); - } - - public void destroy() - { - dictionaryDAO.destroy(); - } - - public void onEnableTenant() - { - dictionaryDAO.reset(); // to initialise empty dictionary and re-populate - } - - public void onDisableTenant() - { - dictionaryDAO.destroy(); - } - - -} diff --git a/source/java/org/alfresco/repo/dictionary/DictionaryDAO.java b/source/java/org/alfresco/repo/dictionary/DictionaryDAO.java deleted file mode 100644 index 16226d0d70..0000000000 --- a/source/java/org/alfresco/repo/dictionary/DictionaryDAO.java +++ /dev/null @@ -1,188 +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.dictionary; - -import java.util.Collection; -import java.util.List; - -import org.alfresco.service.cmr.dictionary.AspectDefinition; -import org.alfresco.service.cmr.dictionary.AssociationDefinition; -import org.alfresco.service.cmr.dictionary.ConstraintDefinition; -import org.alfresco.service.cmr.dictionary.DataTypeDefinition; -import org.alfresco.service.cmr.dictionary.ModelDefinition; -import org.alfresco.service.cmr.dictionary.NamespaceDefinition; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.cmr.dictionary.TypeDefinition; -import org.alfresco.service.namespace.QName; - - -/** - * Dictionary Data Access - * - * @author David Caruana - */ -public interface DictionaryDAO extends ModelQuery -{ - - /** - * @return the models known by the dictionary - */ - public Collection getModels(); - - /** - * @param name the model to retrieve - * @return the named model definition - */ - public ModelDefinition getModel(QName name); - - /** - * @param model the model to retrieve property types for - * @return the property types of the model - */ - public Collection getDataTypes(QName model); - - /** - * @param model the model to retrieve types for - * @return the types of the model - */ - public Collection getTypes(QName model); - - /** - * @param superType - * @param follow true => follow up the super-class hierarchy, false => immediate sub types only - * @return - */ - public Collection getSubTypes(QName superType, boolean follow); - - /** - * @param model the model to retrieve aspects for - * @return the aspects of the model - */ - public Collection getAspects(QName model); - - - /** - * @param model the model to retrieve associations for - * @return the associations of the model - */ - public Collection getAssociations(QName model); - - /** - * @param superAspect - * @param follow true => follow up the super-class hierarchy, false => immediate sub aspects only - * @return - */ - public Collection getSubAspects(QName superAspect, boolean follow); - - /** - * @param model the model for which to get properties for - * @return the properties of the model - */ - public Collection getProperties(QName model); - - /** - * Construct an anonymous type that combines a primary type definition and - * and one or more aspects - * - * @param type the primary type - * @param aspects the aspects to combine - * @return the anonymous type definition - */ - public TypeDefinition getAnonymousType(QName type, Collection aspects); - - /** - * Adds a model to the dictionary. The model is compiled and validated. - * - * @param model the model to add - * @return QName name of model - */ - public QName putModel(M2Model model); - - /** - * Removes a model from the dictionary. The types and aspect in the model will no longer be - * available. - * - * @param model the qname of the model to remove - */ - public void removeModel(QName model); - - /** - * Get all properties for the model and that are of the given data type. - * If dataType is null then the all properties will be returned. - * - * @param modelName - * @param dataType - * @return - */ - public Collection getProperties(QName modelName, QName dataType); - - /** - * @param model the model to retrieve namespaces for - * @return the namespaces of the model - */ - public Collection getNamespaces(QName modelName); - - /** - * @param model the model to retrieve constraint defs (including property constaint refs) - * @return the constraints of the model - */ - public Collection getConstraints(QName model); - - /** - * @param model the model to retrieve constraint defs (optionally only referenceable constraints) - * @return the constraints of the model - */ - public Collection getConstraints(QName model, boolean referenceableDefsOnly); - - /** - * Return diffs between input model and model in the Dictionary. - * - * If the input model does not exist in the Dictionary then no diffs will be returned. - * - * @param model - * @return model diffs (if any) - */ - public List diffModel(M2Model model); - - /** - * - * Register listener with the Dictionary - * - * @param dictionaryListener - */ - public void register(DictionaryListener dictionaryListener); - - /** - * Reset the Dictionary - destroy & re-initialise - */ - public void reset(); - - /** - * Initialise the Dictionary - */ - public void init(); - - /** - * Destroy the Dictionary - */ - public void destroy(); - - // MT-specific - public boolean isModelInherited(QName name); -} diff --git a/source/java/org/alfresco/repo/dictionary/DictionaryDAOImpl.java b/source/java/org/alfresco/repo/dictionary/DictionaryDAOImpl.java deleted file mode 100644 index 6a5e94ce5e..0000000000 --- a/source/java/org/alfresco/repo/dictionary/DictionaryDAOImpl.java +++ /dev/null @@ -1,1296 +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.dictionary; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.repo.cache.SimpleCache; -import org.alfresco.repo.security.authentication.AuthenticationUtil; -import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork; -import org.alfresco.repo.tenant.TenantService; -import org.alfresco.repo.transaction.AlfrescoTransactionSupport; -import org.alfresco.service.cmr.dictionary.AspectDefinition; -import org.alfresco.service.cmr.dictionary.AssociationDefinition; -import org.alfresco.service.cmr.dictionary.ClassDefinition; -import org.alfresco.service.cmr.dictionary.ConstraintDefinition; -import org.alfresco.service.cmr.dictionary.DataTypeDefinition; -import org.alfresco.service.cmr.dictionary.DictionaryException; -import org.alfresco.service.cmr.dictionary.ModelDefinition; -import org.alfresco.service.cmr.dictionary.NamespaceDefinition; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.cmr.dictionary.TypeDefinition; -import org.alfresco.service.namespace.QName; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - - -/** - * Default implementation of the Dictionary. - * - * @author David Caruana, janv - * - */ -public class DictionaryDAOImpl implements DictionaryDAO -{ - /** - * Lock objects - */ - private ReadWriteLock lock = new ReentrantReadWriteLock(); - private Lock readLock = lock.readLock(); - private Lock writeLock = lock.writeLock(); - - // Namespace Data Access - private NamespaceDAO namespaceDAO; - - // Tenant Service - private TenantService tenantService; - - // Internal cache (clusterable) - private SimpleCache dictionaryRegistryCache; - - // used to reset the cache - private ThreadLocal dictionaryRegistryThreadLocal = new ThreadLocal(); - private ThreadLocal defaultDictionaryRegistryThreadLocal = new ThreadLocal(); - - // Static list of registered dictionary listeners - private List dictionaryListeners = new ArrayList(); - - // Logger - private static Log logger = LogFactory.getLog(DictionaryDAO.class); - - - // inject dependencies - - public void setTenantService(TenantService tenantService) - { - this.tenantService = tenantService; - } - - public void setDictionaryRegistryCache(SimpleCache dictionaryRegistryCache) - { - this.dictionaryRegistryCache = dictionaryRegistryCache; - } - - /** - * Construct - * - * @param namespaceDAO namespace data access - */ - public DictionaryDAOImpl(NamespaceDAO namespaceDAO) - { - this.namespaceDAO = namespaceDAO; - this.namespaceDAO.registerDictionary(this); - - } - - /** - * Register with the Dictionary - */ - public void register(DictionaryListener dictionaryListener) - { - if (! dictionaryListeners.contains(dictionaryListener)) - { - dictionaryListeners.add(dictionaryListener); - } - } - - /** - * Initialise the Dictionary & Namespaces - */ - public void init() - { - initDictionary(tenantService.getCurrentUserDomain()); - } - - /** - * Destroy the Dictionary & Namespaces - */ - public void destroy() - { - String tenantDomain = tenantService.getCurrentUserDomain(); - - removeDictionaryRegistry(tenantDomain); - - namespaceDAO.destroy(); - - // notify registered listeners that dictionary has been destroyed - for (DictionaryListener dictionaryDeployer : dictionaryListeners) - { - dictionaryDeployer.afterDictionaryDestroy(); - } - - if (logger.isDebugEnabled()) - { - logger.debug("Dictionary destroyed"); - } - } - - /** - * Reset the Dictionary & Namespaces - */ - public void reset() - { - if (logger.isDebugEnabled()) - { - logger.debug("Resetting dictionary ..."); - } - - destroy(); - init(); - - if (logger.isDebugEnabled()) - { - logger.debug("... resetting dictionary completed"); - } - } - - // load dictionary (models and namespaces) - private DictionaryRegistry initDictionary(final String tenantDomain) - { - long startTime = System.currentTimeMillis(); - - if (logger.isDebugEnabled()) - { - logger.debug("Init Dictionary: ["+Thread.currentThread()+"] "+(tenantDomain.equals(TenantService.DEFAULT_DOMAIN) ? "" : " (Tenant: "+tenantDomain+")")); - } - - try - { - return AuthenticationUtil.runAs(new RunAsWork() - { - public DictionaryRegistry doWork() - { - try - { - DictionaryRegistry dictionaryRegistry = initDictionaryRegistry(tenantDomain); - - if (dictionaryRegistry == null) - { - // unexpected - throw new AlfrescoRuntimeException("Failed to init dictionaryRegistry " + tenantDomain); - } - - try - { - writeLock.lock(); - dictionaryRegistryCache.put(tenantDomain, dictionaryRegistry); - } - finally - { - writeLock.unlock(); - } - - return dictionaryRegistry; - } - finally - { - try - { - readLock.lock(); - if (dictionaryRegistryCache.get(tenantDomain) != null) - { - removeDataDictionaryLocal(tenantDomain); - } - } - finally - { - readLock.unlock(); - } - } - } - }, tenantService.getDomainUser(AuthenticationUtil.getSystemUserName(), tenantDomain)); - } - finally - { - if (logger.isInfoEnabled()) - { - logger.info("Init Dictionary: model count = "+(getModels() != null ? getModels().size() : 0) +" in "+(System.currentTimeMillis()-startTime)+" msecs ["+Thread.currentThread()+"] "+(tenantDomain.equals(TenantService.DEFAULT_DOMAIN) ? "" : " (Tenant: "+tenantDomain+")")); - } - } - } - - private DictionaryRegistry initDictionaryRegistry(String tenantDomain) - { - // create threadlocal, if needed - DictionaryRegistry dictionaryRegistry = createDataDictionaryLocal(tenantDomain); - - dictionaryRegistry.setCompiledModels(new HashMap()); - dictionaryRegistry.setUriToModels(new HashMap>()); - - if (logger.isTraceEnabled()) - { - logger.trace("Empty dictionary initialised: "+dictionaryRegistry+" - "+defaultDictionaryRegistryThreadLocal+" ["+Thread.currentThread()+"]"); - } - - // initialise empty namespaces - namespaceDAO.init(); - - // populate the dictionary based on registered sources - for (DictionaryListener dictionaryDeployer : dictionaryListeners) - { - dictionaryDeployer.onDictionaryInit(); - } - - // notify registered listeners that dictionary has been initialised (population is complete) - for (DictionaryListener dictionaryListener : dictionaryListeners) - { - dictionaryListener.afterDictionaryInit(); - } - - return dictionaryRegistry; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.DictionaryDAO#putModel(org.alfresco.repo.dictionary.impl.M2Model) - */ - public QName putModel(M2Model model) - { - String tenantDomain = tenantService.getCurrentUserDomain(); - - // Compile model definition - CompiledModel compiledModel = model.compile(this, namespaceDAO); - QName modelName = compiledModel.getModelDefinition().getName(); - - // Remove namespace definitions for previous model, if it exists - CompiledModel previousVersion = getCompiledModels(tenantDomain).get(modelName); - if (previousVersion != null) - { - for (M2Namespace namespace : previousVersion.getM2Model().getNamespaces()) - { - namespaceDAO.removePrefix(namespace.getPrefix()); - namespaceDAO.removeURI(namespace.getUri()); - unmapUriToModel(namespace.getUri(), previousVersion, tenantDomain); - } - for (M2Namespace importNamespace : previousVersion.getM2Model().getImports()) - { - unmapUriToModel(importNamespace.getUri(), previousVersion, tenantDomain); - } - } - - // Create namespace definitions for new model - for (M2Namespace namespace : model.getNamespaces()) - { - namespaceDAO.addURI(namespace.getUri()); - namespaceDAO.addPrefix(namespace.getPrefix(), namespace.getUri()); - mapUriToModel(namespace.getUri(), compiledModel, tenantDomain); - } - for (M2Namespace importNamespace : model.getImports()) - { - mapUriToModel(importNamespace.getUri(), compiledModel, tenantDomain); - } - - // Publish new Model Definition - getCompiledModels(tenantDomain).put(modelName, compiledModel); - - if (logger.isTraceEnabled()) - { - logger.trace("Registered model: " + modelName.toPrefixString(namespaceDAO)); - for (M2Namespace namespace : model.getNamespaces()) - { - logger.trace("Registered namespace: '" + namespace.getUri() + "' (prefix '" + namespace.getPrefix() + "')"); - } - } - - return modelName; - } - - /** - * @see org.alfresco.repo.dictionary.DictionaryDAO#removeModel(org.alfresco.service.namespace.QName) - */ - public void removeModel(QName modelName) - { - String tenantDomain = tenantService.getCurrentUserDomain(); - - CompiledModel compiledModel = getCompiledModels(tenantDomain).get(modelName); - if (compiledModel != null) - { - // Remove the namespaces from the namespace service - M2Model model = compiledModel.getM2Model(); - for (M2Namespace namespace : model.getNamespaces()) - { - namespaceDAO.removePrefix(namespace.getPrefix()); - namespaceDAO.removeURI(namespace.getUri()); - unmapUriToModel(namespace.getUri(), compiledModel, tenantDomain); - } - - // Remove the model from the list - getCompiledModels(tenantDomain).remove(modelName); - } - } - - /** - * Map Namespace URI to Model - * - * @param uri namespace uri - * @param model model - * @param tenantDomain - */ - private void mapUriToModel(String uri, CompiledModel model, String tenantDomain) - { - List models = getUriToModels(tenantDomain).get(uri); - if (models == null) - { - models = new ArrayList(); - getUriToModels(tenantDomain).put(uri, models); - } - if (!models.contains(model)) - { - models.add(model); - } - } - - /** - * Unmap Namespace URI from Model - * - * @param uri namespace uri - * @param model model - * @param tenantDomain - */ - private void unmapUriToModel(String uri, CompiledModel model, String tenantDomain) - { - List models = getUriToModels(tenantDomain).get(uri); - if (models != null) - { - models.remove(model); - } - } - - - /** - * Get Models mapped to Namespace Uri - * - * @param uri namespace uri - * @return mapped models - */ - private List getModelsForUri(String uri) - { - String tenantDomain = tenantService.getCurrentUserDomain(); - if (! tenantDomain.equals(TenantService.DEFAULT_DOMAIN)) - { - // get non-tenant models (if any) - List models = getUriToModels(TenantService.DEFAULT_DOMAIN).get(uri); - - List filteredModels = new ArrayList(); - if (models != null) - { - filteredModels.addAll(models); - } - - // get tenant models (if any) - List tenantModels = getUriToModels(tenantDomain).get(uri); - if (tenantModels != null) - { - if (models != null) - { - // check to see if tenant model overrides a non-tenant model - for (CompiledModel tenantModel : tenantModels) - { - for (CompiledModel model : models) - { - if (tenantModel.getM2Model().getName().equals(model.getM2Model().getName())) - { - filteredModels.remove(model); - } - } - } - } - filteredModels.addAll(tenantModels); - models = filteredModels; - } - - if (models == null) - { - models = Collections.emptyList(); - } - return models; - } - - List models = getUriToModels(TenantService.DEFAULT_DOMAIN).get(uri); - if (models == null) - { - models = Collections.emptyList(); - } - return models; - } - - /** - * @param modelName the model name - * @return the compiled model of the given name - */ - /* package */ CompiledModel getCompiledModel(QName modelName) - { - String tenantDomain = tenantService.getCurrentUserDomain(); - if (! tenantDomain.equals(TenantService.DEFAULT_DOMAIN)) - { - // get tenant-specific model (if any) - CompiledModel model = getCompiledModels(tenantDomain).get(modelName); - if (model != null) - { - return model; - } - // else drop down to check for shared (core/system) models ... - } - - // get non-tenant model (if any) - CompiledModel model = getCompiledModels(TenantService.DEFAULT_DOMAIN).get(modelName); - if (model == null) - { - throw new DictionaryException("d_dictionary.model.err.no_model", modelName); - } - return model; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.ModelQuery#getPropertyType(org.alfresco.repo.ref.QName) - */ - public DataTypeDefinition getDataType(QName typeName) - { - if (typeName != null) { - List models = getModelsForUri(typeName.getNamespaceURI()); - for (CompiledModel model : models) - { - DataTypeDefinition dataType = model.getDataType(typeName); - if (dataType != null) - { - return dataType; - } - } - } - return null; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ModelQuery#getDataType(java.lang.Class) - */ - @SuppressWarnings("unchecked") - public DataTypeDefinition getDataType(Class javaClass) - { - String tenantDomain = tenantService.getCurrentUserDomain(); - if (! tenantDomain.equals(TenantService.DEFAULT_DOMAIN)) - { - // get tenant models (if any) - for (CompiledModel model : getCompiledModels(tenantDomain).values()) - { - DataTypeDefinition dataTypeDef = model.getDataType(javaClass); - if (dataTypeDef != null) - { - return dataTypeDef; - } - } - - // get non-tenant models (if any) - for (CompiledModel model : getCompiledModels(TenantService.DEFAULT_DOMAIN).values()) - { - DataTypeDefinition dataTypeDef = model.getDataType(javaClass); - if (dataTypeDef != null) - { - return dataTypeDef; - } - } - - return null; - } - else - { - for (CompiledModel model : getCompiledModels(TenantService.DEFAULT_DOMAIN).values()) - { - DataTypeDefinition dataTypeDef = model.getDataType(javaClass); - if (dataTypeDef != null) - { - return dataTypeDef; - } - } - } - return null; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.DictionaryDAO#getPropertyTypes(org.alfresco.repo.ref.QName) - */ - public Collection getDataTypes(QName modelName) - { - CompiledModel model = getCompiledModel(modelName); - return model.getDataTypes(); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.ModelQuery#getType(org.alfresco.repo.ref.QName) - */ - public TypeDefinition getType(QName typeName) - { - if (typeName != null) { - List models = getModelsForUri(typeName.getNamespaceURI()); - for (CompiledModel model : models) - { - TypeDefinition type = model.getType(typeName); - if (type != null) - { - return type; - } - } - - if (logger.isWarnEnabled()) - { - logger.warn("Type not found: "+typeName); - } - } - return null; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryDAO#getSubTypes(org.alfresco.service.namespace.QName, boolean) - */ - public Collection getSubTypes(QName superType, boolean follow) - { - // note: could be optimised further, if compiled into the model - - // Get all types (with parent type) for all models - Map allTypesAndParents = new HashMap(); // name, parent - - for (CompiledModel model : getCompiledModels().values()) - { - for (TypeDefinition type : model.getTypes()) - { - allTypesAndParents.put(type.getName(), type.getParentName()); - } - } - - // Get sub types - HashSet subTypes = new HashSet(); - for (QName type : allTypesAndParents.keySet()) - { - if (follow) - { - // all sub types - QName current = type; - while ((current != null) && !current.equals(superType)) - { - current = allTypesAndParents.get(current); // get parent - } - if (current != null) - { - subTypes.add(type); - } - } - else - { - // immediate sub types only - QName typesSuperType = allTypesAndParents.get(type); - if (typesSuperType != null && typesSuperType.equals(superType)) - { - subTypes.add(type); - } - } - - } - return subTypes; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.ModelQuery#getAspect(org.alfresco.repo.ref.QName) - */ - public AspectDefinition getAspect(QName aspectName) - { - if (aspectName != null) { - List models = getModelsForUri(aspectName.getNamespaceURI()); - for (CompiledModel model : models) - { - AspectDefinition aspect = model.getAspect(aspectName); - if (aspect != null) - { - return aspect; - } - } - } - return null; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryDAO#getSubAspects(org.alfresco.service.namespace.QName, boolean) - */ - public Collection getSubAspects(QName superAspect, boolean follow) - { - // note: could be optimised further, if compiled into the model - - // Get all aspects (with parent aspect) for all models - Map allAspectsAndParents = new HashMap(); // name, parent - - for (CompiledModel model : getCompiledModels().values()) - { - for (AspectDefinition aspect : model.getAspects()) - { - allAspectsAndParents.put(aspect.getName(), aspect.getParentName()); - } - } - - // Get sub aspects - HashSet subAspects = new HashSet(); - for (QName aspect : allAspectsAndParents.keySet()) - { - if (follow) - { - // all sub aspects - QName current = aspect; - while ((current != null) && !current.equals(superAspect)) - { - current = allAspectsAndParents.get(current); // get parent - } - if (current != null) - { - subAspects.add(aspect); - } - } - else - { - // immediate sub aspects only - if (allAspectsAndParents.get(aspect).equals(superAspect)) - { - subAspects.add(aspect); - } - } - } - return subAspects; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.ModelQuery#getClass(org.alfresco.repo.ref.QName) - */ - public ClassDefinition getClass(QName className) - { - List models = getModelsForUri(className.getNamespaceURI()); - - for (CompiledModel model : models) - { - ClassDefinition classDef = model.getClass(className); - if (classDef != null) - { - return classDef; - } - } - return null; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.ModelQuery#getProperty(org.alfresco.repo.ref.QName) - */ - public PropertyDefinition getProperty(QName propertyName) - { - List models = getModelsForUri(propertyName.getNamespaceURI()); - for (CompiledModel model : models) - { - PropertyDefinition propDef = model.getProperty(propertyName); - if (propDef != null) - { - return propDef; - } - } - return null; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ModelQuery#getConstraint(org.alfresco.service.namespace.QName) - */ - public ConstraintDefinition getConstraint(QName constraintQName) - { - List models = getModelsForUri(constraintQName.getNamespaceURI()); - for (CompiledModel model : models) - { - ConstraintDefinition constraintDef = model.getConstraint(constraintQName); - if (constraintDef != null) - { - return constraintDef; - } - } - return null; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.ModelQuery#getAssociation(org.alfresco.repo.ref.QName) - */ - public AssociationDefinition getAssociation(QName assocName) - { - List models = getModelsForUri(assocName.getNamespaceURI()); - for (CompiledModel model : models) - { - AssociationDefinition assocDef = model.getAssociation(assocName); - if (assocDef != null) - { - return assocDef; - } - } - return null; - } - - public Collection getAssociations(QName modelName) - { - CompiledModel model = getCompiledModel(modelName); - return model.getAssociations(); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.DictionaryDAO#getModels() - */ - public Collection getModels() - { - // get all models - including inherited models, if applicable - return getCompiledModels().keySet(); - } - - // MT-specific - public boolean isModelInherited(QName modelName) - { - String tenantDomain = tenantService.getCurrentUserDomain(); - if (! tenantDomain.equals(TenantService.DEFAULT_DOMAIN)) - { - // get tenant-specific model (if any) - CompiledModel model = getCompiledModels(tenantDomain).get(modelName); - if (model != null) - { - return false; - } - // else drop down to check for shared (core/system) models ... - } - - // get non-tenant model (if any) - CompiledModel model = getCompiledModels(TenantService.DEFAULT_DOMAIN).get(modelName); - if (model == null) - { - throw new DictionaryException("d_dictionary.model.err.no_model", modelName); - } - - if (! tenantDomain.equals(TenantService.DEFAULT_DOMAIN)) - { - return true; - } - else - { - return false; - } - } - - private Map getCompiledModels() - { - String tenantDomain = tenantService.getCurrentUserDomain(); - if (! tenantDomain.equals(TenantService.DEFAULT_DOMAIN)) - { - // return all tenant-specific models and all inherited (non-overridden) models - Map filteredModels = new HashMap(); - - // get tenant models (if any) - Map tenantModels = getCompiledModels(tenantDomain); - - // get non-tenant models - these will include core/system models and any additional custom models (which are implicitly available to all tenants) - Map nontenantModels = getCompiledModels(TenantService.DEFAULT_DOMAIN); - - // check for overrides - filteredModels.putAll(nontenantModels); - - for (QName tenantModel : tenantModels.keySet()) - { - for (QName nontenantModel : nontenantModels.keySet()) - { - if (tenantModel.equals(nontenantModel)) - { - // override - filteredModels.remove(nontenantModel); - break; - } - } - } - - filteredModels.putAll(tenantModels); - return filteredModels; - } - else - { - // return all (non-tenant) models - return getCompiledModels(TenantService.DEFAULT_DOMAIN); - } - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.DictionaryDAO#getModel(org.alfresco.repo.ref.QName) - */ - public ModelDefinition getModel(QName name) - { - CompiledModel model = getCompiledModel(name); - return model.getModelDefinition(); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.DictionaryDAO#getTypes(org.alfresco.repo.ref.QName) - */ - public Collection getTypes(QName modelName) - { - CompiledModel model = getCompiledModel(modelName); - return model.getTypes(); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.DictionaryDAO#getAspects(org.alfresco.repo.ref.QName) - */ - public Collection getAspects(QName modelName) - { - CompiledModel model = getCompiledModel(modelName); - return model.getAspects(); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.DictionaryDAO#getAnonymousType(org.alfresco.repo.ref.QName, java.util.Collection) - */ - public TypeDefinition getAnonymousType(QName type, Collection aspects) - { - TypeDefinition typeDef = getType(type); - if (typeDef == null) - { - throw new DictionaryException("d_dictionary.model.err.type_not_found", type); - } - Collection aspectDefs = new ArrayList(); - if (aspects != null) - { - for (QName aspect : aspects) - { - AspectDefinition aspectDef = getAspect(aspect); - if (aspectDef == null) - { - throw new DictionaryException("d_dictionary.model.err.aspect_not_found", aspect); - } - aspectDefs.add(aspectDef); - } - } - return new M2AnonymousTypeDefinition(typeDef, aspectDefs); - } - - /* - * (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryDAO#getProperties(org.alfresco.service.namespace.QName) - */ - public Collection getProperties(QName modelName) - { - CompiledModel model = getCompiledModel(modelName); - return model.getProperties(); - } - - /* - * (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryDAO#getProperties(org.alfresco.service.namespace.QName, org.alfresco.service.namespace.QName) - */ - public Collection getProperties(QName modelName, QName dataType) - { - HashSet properties = new HashSet(); - - Collection props = getProperties(modelName); - for(PropertyDefinition prop : props) - { - if((dataType == null) || prop.getDataType().getName().equals(dataType)) - { - properties.add(prop); - } - } - return properties; - } - - /* - * (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryDAO#getNamespaces(org.alfresco.service.namespace.QName) - */ - public Collection getNamespaces(QName modelName) - { - CompiledModel model = getCompiledModel(modelName); - ModelDefinition modelDef = model.getModelDefinition(); - return modelDef.getNamespaces(); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.DictionaryDAO#getConstraints(org.alfresco.service.namespace.QName) - */ - public Collection getConstraints(QName modelName) - { - return getConstraints(modelName, false); - } - - public Collection getConstraints(QName modelName, boolean referenceableDefsOnly) - { - CompiledModel model = getCompiledModel(modelName); - if (referenceableDefsOnly) - { - return getReferenceableConstraintDefs(model); - } - else - { - return model.getConstraints(); - } - } - - private Collection getReferenceableConstraintDefs(CompiledModel model) - { - Collection conDefs = model.getConstraints(); - Collection propDefs = model.getProperties(); - for (PropertyDefinition propDef : propDefs) - { - for (ConstraintDefinition conDef : propDef.getConstraints()) - { - conDefs.remove(conDef); - } - } - - return conDefs; - } - - // re-entrant (eg. via reset) - private DictionaryRegistry getDictionaryRegistry(String tenantDomain) - { - DictionaryRegistry dictionaryRegistry = null; - - // check threadlocal first - return if set - dictionaryRegistry = getDictionaryRegistryLocal(tenantDomain); - if (dictionaryRegistry != null) - { - return dictionaryRegistry; // return local dictionaryRegistry - } - - try - { - // check cache second - return if set - readLock.lock(); - dictionaryRegistry = dictionaryRegistryCache.get(tenantDomain); - - if (dictionaryRegistry != null) - { - return dictionaryRegistry; // return cached config - } - } - finally - { - readLock.unlock(); - } - - if (logger.isTraceEnabled()) - { - logger.trace("getDictionaryRegistry: not in cache (or threadlocal) - re-init ["+Thread.currentThread().getId()+", "+AlfrescoTransactionSupport.getTransactionId()+"]"+(tenantDomain.equals(TenantService.DEFAULT_DOMAIN) ? "" : " (Tenant: "+tenantDomain+")")); - } - - // reset caches - may have been invalidated (e.g. in a cluster) - dictionaryRegistry = initDictionary(tenantDomain); - - if (dictionaryRegistry == null) - { - // unexpected - throw new AlfrescoRuntimeException("Failed to get dictionaryRegistry " + tenantDomain); - } - - return dictionaryRegistry; - } - - // create threadlocal - private DictionaryRegistry createDataDictionaryLocal(String tenantDomain) - { - // create threadlocal, if needed - DictionaryRegistry dictionaryRegistry = getDictionaryRegistryLocal(tenantDomain); - if (dictionaryRegistry == null) - { - dictionaryRegistry = new DictionaryRegistry(tenantDomain); - - if (tenantDomain.equals(TenantService.DEFAULT_DOMAIN)) - { - defaultDictionaryRegistryThreadLocal.set(dictionaryRegistry); - } - else - { - dictionaryRegistryThreadLocal.set(dictionaryRegistry); - } - } - - return dictionaryRegistry; - } - - // get threadlocal - private DictionaryRegistry getDictionaryRegistryLocal(String tenantDomain) - { - DictionaryRegistry dictionaryRegistry = null; - - if (tenantDomain.equals(TenantService.DEFAULT_DOMAIN)) - { - dictionaryRegistry = this.defaultDictionaryRegistryThreadLocal.get(); - } - else - { - dictionaryRegistry = this.dictionaryRegistryThreadLocal.get(); - } - - // check to see if domain switched - if ((dictionaryRegistry != null) && (tenantDomain.equals(dictionaryRegistry.getTenantDomain()))) - { - return dictionaryRegistry; // return threadlocal, if set - } - - return null; - } - - // remove threadlocal - private void removeDataDictionaryLocal(String tenantDomain) - { - if (tenantDomain.equals(TenantService.DEFAULT_DOMAIN)) - { - defaultDictionaryRegistryThreadLocal.set(null); // it's in the cache, clear the threadlocal - } - else - { - dictionaryRegistryThreadLocal.set(null); // it's in the cache, clear the threadlocal - } - } - - private void removeDictionaryRegistry(String tenantDomain) - { - try - { - writeLock.lock(); - if (dictionaryRegistryCache.get(tenantDomain) != null) - { - dictionaryRegistryCache.remove(tenantDomain); - } - - removeDataDictionaryLocal(tenantDomain); - } - finally - { - writeLock.unlock(); - } - } - - /** - * Get compiledModels from the cache (in the context of the given tenant domain) - * - * @param tenantDomain - */ - private Map getCompiledModels(String tenantDomain) - { - return getDictionaryRegistry(tenantDomain).getCompiledModels(); - } - - /** - * Get uriToModels from the cache (in the context of the given tenant domain) - * - * @param tenantDomain - */ - private Map> getUriToModels(String tenantDomain) - { - return getDictionaryRegistry(tenantDomain).getUriToModels(); - } - - /** - * Return diffs between input model and model in the Dictionary. - * - * If the input model does not exist in the Dictionary then no diffs will be returned. - * - * @param model - * @return model diffs (if any) - */ - public List diffModel(M2Model model) - { - // Compile model definition - CompiledModel compiledModel = model.compile(this, namespaceDAO); - QName modelName = compiledModel.getModelDefinition().getName(); - - CompiledModel previousVersion = null; - try { previousVersion = getCompiledModel(modelName); } catch (DictionaryException e) {} // ignore missing model - - if (previousVersion == null) - { - return new ArrayList(0); - } - else - { - return diffModel(previousVersion, compiledModel); - } - } - - /** - * Return diffs between two compiled models. - * - * note: - * - checks classes (types & aspects) for incremental updates - * - checks properties for incremental updates, but does not include the diffs - * - checks assocs & child assocs for incremental updates, but does not include the diffs - * - incremental updates include changes in title/description, property default value, etc - * - ignores changes in model definition except name (ie. title, description, author, published date, version are treated as an incremental update) - * - * TODO - * - imports - * - namespace - * - datatypes - * - constraints (including property constraints - references and inline) - * - * @param model - * @return model diffs (if any) - */ - /* package */ List diffModel(CompiledModel previousVersion, CompiledModel model) - { - List M2ModelDiffs = new ArrayList(); - - if (previousVersion != null) - { - Collection previousTypes = previousVersion.getTypes(); - Collection previousAspects = previousVersion.getAspects(); - Collection previousConDefs = getReferenceableConstraintDefs(previousVersion); - - if (model == null) - { - // delete model - for (TypeDefinition previousType : previousTypes) - { - M2ModelDiffs.add(new M2ModelDiff(previousType.getName(), M2ModelDiff.TYPE_TYPE, M2ModelDiff.DIFF_DELETED)); - } - for (AspectDefinition previousAspect : previousAspects) - { - M2ModelDiffs.add(new M2ModelDiff(previousAspect.getName(), M2ModelDiff.TYPE_ASPECT, M2ModelDiff.DIFF_DELETED)); - } - for (ConstraintDefinition previousConDef : previousConDefs) - { - M2ModelDiffs.add(new M2ModelDiff(previousConDef.getName(), M2ModelDiff.TYPE_CONSTRAINT, M2ModelDiff.DIFF_DELETED)); - } - } - else - { - // update model - Collection types = model.getTypes(); - Collection aspects = model.getAspects(); - Collection conDefs = getReferenceableConstraintDefs(model); - - if (previousTypes.size() != 0) - { - M2ModelDiffs.addAll(M2ClassDefinition.diffClassLists(new ArrayList(previousTypes), new ArrayList(types), M2ModelDiff.TYPE_TYPE)); - } - else - { - for (TypeDefinition type : types) - { - M2ModelDiffs.add(new M2ModelDiff(type.getName(), M2ModelDiff.TYPE_TYPE, M2ModelDiff.DIFF_CREATED)); - } - } - - if (previousAspects.size() != 0) - { - M2ModelDiffs.addAll(M2ClassDefinition.diffClassLists(new ArrayList(previousAspects), new ArrayList(aspects), M2ModelDiff.TYPE_ASPECT)); - } - else - { - for (AspectDefinition aspect : aspects) - { - M2ModelDiffs.add(new M2ModelDiff(aspect.getName(), M2ModelDiff.TYPE_ASPECT, M2ModelDiff.DIFF_CREATED)); - } - } - - if (previousConDefs.size() != 0) - { - M2ModelDiffs.addAll(M2ConstraintDefinition.diffConstraintLists(new ArrayList(previousConDefs), new ArrayList(conDefs))); - } - else - { - for (ConstraintDefinition conDef : conDefs) - { - M2ModelDiffs.add(new M2ModelDiff(conDef.getName(), M2ModelDiff.TYPE_CONSTRAINT, M2ModelDiff.DIFF_CREATED)); - } - } - } - } - else - { - if (model != null) - { - // new model - Collection types = model.getTypes(); - Collection aspects = model.getAspects(); - - for (TypeDefinition type : types) - { - M2ModelDiffs.add(new M2ModelDiff(type.getName(), M2ModelDiff.TYPE_TYPE, M2ModelDiff.DIFF_CREATED)); - } - - for (AspectDefinition aspect : aspects) - { - M2ModelDiffs.add(new M2ModelDiff(aspect.getName(), M2ModelDiff.TYPE_ASPECT, M2ModelDiff.DIFF_CREATED)); - } - } - else - { - // nothing to diff - } - } - - return M2ModelDiffs; - } - - /* package */ class DictionaryRegistry - { - private Map> uriToModels = new HashMap>(0); - private Map compiledModels = new HashMap(0); - - private String tenantDomain; - - public DictionaryRegistry(String tenantDomain) - { - this.tenantDomain = tenantDomain; - } - - public String getTenantDomain() - { - return tenantDomain; - } - - public Map> getUriToModels() - { - return uriToModels; - } - public void setUriToModels(Map> uriToModels) - { - this.uriToModels = uriToModels; - } - public Map getCompiledModels() - { - return compiledModels; - } - public void setCompiledModels(Map compiledModels) - { - this.compiledModels = compiledModels; - } - } -} diff --git a/source/java/org/alfresco/repo/dictionary/DictionaryListener.java b/source/java/org/alfresco/repo/dictionary/DictionaryListener.java deleted file mode 100644 index 631f3ad0aa..0000000000 --- a/source/java/org/alfresco/repo/dictionary/DictionaryListener.java +++ /dev/null @@ -1,38 +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.dictionary; - - -/** - * Dictionary Listener interface. - *

- * This interface allows Dictionary Listeners to register with the DictionaryService. - * - */ -public interface DictionaryListener -{ - // callback for (re-)initialising the Dictionary caches - public void onDictionaryInit(); - - // callback once dictionary destroy is complete - public void afterDictionaryDestroy(); - - // callback once dictionary initialisation is complete - public void afterDictionaryInit(); -} diff --git a/source/java/org/alfresco/repo/dictionary/DictionaryNamespaceComponent.java b/source/java/org/alfresco/repo/dictionary/DictionaryNamespaceComponent.java deleted file mode 100644 index 50910a2994..0000000000 --- a/source/java/org/alfresco/repo/dictionary/DictionaryNamespaceComponent.java +++ /dev/null @@ -1,104 +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.dictionary; - -import java.util.Collection; - -import org.alfresco.service.namespace.NamespaceService; - - -/** - * Data Dictionary Namespace Service Implementation - * - * @author David Caruana - */ -public class DictionaryNamespaceComponent implements NamespaceService -{ - /** - * Namespace DAO - */ - private NamespaceDAO namespaceDAO; - - - /** - * Sets the Namespace DAO - * - * @param namespaceDAO namespace DAO - */ - public void setNamespaceDAO(NamespaceDAO namespaceDAO) - { - this.namespaceDAO = namespaceDAO; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.NamespaceService#getURIs() - */ - public Collection getURIs() - { - return namespaceDAO.getURIs(); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.NamespaceService#getPrefixes() - */ - public Collection getPrefixes() - { - return namespaceDAO.getPrefixes(); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.ref.NamespacePrefixResolver#getNamespaceURI(java.lang.String) - */ - public String getNamespaceURI(String prefix) - { - return namespaceDAO.getNamespaceURI(prefix); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.ref.NamespacePrefixResolver#getPrefixes(java.lang.String) - */ - public Collection getPrefixes(String namespaceURI) - { - return namespaceDAO.getPrefixes(namespaceURI); - } - - - /* (non-Javadoc) - * @see org.alfresco.service.namespace.NamespaceService#registerNamespace(java.lang.String, java.lang.String) - */ - public void registerNamespace(String prefix, String uri) - { - // TODO: - throw new UnsupportedOperationException(); - } - - - /* (non-Javadoc) - * @see org.alfresco.service.namespace.NamespaceService#registerNamespace(java.lang.String, java.lang.String) - */ - public void unregisterNamespace(String prefix) - { - // TODO: - throw new UnsupportedOperationException(); - } -} diff --git a/source/java/org/alfresco/repo/dictionary/DiffModelTest.java b/source/java/org/alfresco/repo/dictionary/DiffModelTest.java deleted file mode 100644 index 1b95cf5b79..0000000000 --- a/source/java/org/alfresco/repo/dictionary/DiffModelTest.java +++ /dev/null @@ -1,1260 +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.dictionary; - -import java.io.ByteArrayInputStream; -import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; -import net.sf.ehcache.Cache; -import net.sf.ehcache.CacheManager; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.repo.cache.EhCacheAdapter; -import org.alfresco.repo.dictionary.DictionaryDAOImpl.DictionaryRegistry; -import org.alfresco.repo.dictionary.NamespaceDAOImpl.NamespaceRegistry; -import org.alfresco.repo.tenant.SingleTServiceImpl; -import org.alfresco.repo.tenant.TenantService; -import org.alfresco.service.namespace.QName; - -public class DiffModelTest extends TestCase -{ - public static final String MODEL1_XML = - "" + - - " Another description" + - " Alfresco" + - " 2007-08-01" + - " 1.0" + - - " " + - " " + - " " + - - " " + - " " + - " " + - - " " + - - " " + - " Base" + - " The Base Type 1" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - " Base" + - " The Base Type 2" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - " Base" + - " The Base Type 3" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - - " " + - - " " + - " Base" + - " The Base Aspect 1" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - " Base" + - " The Base Aspect 2" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - " Base" + - " The Base Aspect 3" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - - ""; - - public static final String MODEL1_UPDATE1_XML = - "" + - - " Another description" + - " Alfresco" + - " 2007-08-01" + - " 1.0" + - - " " + - " " + - " " + - - " " + - " " + - " " + - - " " + - - " " + - " Base" + - " The Base Type 1" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - " Base" + - " The Base Type 3" + - " " + - " " + - " d:text" + - " " + - " " + - " " + - - " " + - " Base" + - " The Base Type 4" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - - " " + - - " " + - " Base" + - " The Base Aspect 1" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - " Base" + - " The Base Aspect 3" + - " " + - " " + - " d:int" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - " Base" + - " The Base Aspect 4" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - - ""; - - public static final String MODEL2_XML = - "" + - - " Another description" + - " Alfresco" + - " 2007-08-01" + - " 1.0" + - - " " + - " " + - " " + - - " " + - " " + - " " + - - " " + - - " " + - " Base" + - " The Base Type 1" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - - " " + - - " " + - " Base" + - " The Base Aspect 1" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - - ""; - - public static final String MODEL2_EXTRA_PROPERTIES_XML = - "" + - - " Another description" + - " Alfresco" + - " 2007-08-01" + - " 1.0" + - - " " + - " " + - " " + - - " " + - " " + - " " + - - " " + - - " " + - " Base" + - " The Base Type 1" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " d:date" + - " " + - " " + - " " + - - " " + - - " " + - - " " + - " Base" + - " The Base Aspect 1" + - " " + - " " + - " d:boolean" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - - ""; - - public static final String MODEL3_XML = - "" + - - " Another description" + - " Alfresco" + - " 2007-08-01" + - " 1.0" + - - " " + - " " + - " " + - - " " + - " " + - " " + - - " " + - - " " + - " Base" + - " The Base Type 1" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - - " " + - - " " + - " Base" + - " The Base Aspect 1" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - - ""; - - public static final String MODEL3_EXTRA_TYPES_AND_ASPECTS_XML = - "" + - - " Another description" + - " Alfresco" + - " 2007-08-01" + - " 1.0" + - - " " + - " " + - " " + - - " " + - " " + - " " + - - " " + - - " " + - " Base" + - " The Base Type 1" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - " Base" + - " The Base Type 2" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - - " " + - - " " + - " Base" + - " The Base Aspect 1" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - " Base" + - " The Base Aspect 2" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - - ""; - - public static final String MODEL4_XML = - "" + - - " Another description" + - " Alfresco" + - " 2007-08-01" + - " 1.0" + - - " " + - " " + - " " + - - " " + - " " + - " " + - - " " + - - " " + - " Base" + - " The Base Type 1" + - " " + - " " + - " d:text" + - " " + - " " + - " " + - - " " + - - " " + - - " " + - " Base" + - " The Base Aspect 1" + - " " + - " " + - " d:text" + - " " + - " " + - " " + - - " " + - - ""; - - public static final String MODEL4_EXTRA_DEFAULT_ASPECT_XML = - "" + - - " Another description" + - " Alfresco" + - " 2007-08-01" + - " 1.0" + - - " " + - " " + - " " + - - " " + - " " + - " " + - - " " + - - " " + - " Base" + - " The Base Type 1" + - " " + - " " + - " d:text" + - " " + - " " + - " " + - " test1:aspect1" + - " " + - " " + - - " " + - - " " + - - " " + - " Base" + - " The Base Aspect 1" + - " " + - " " + - " d:text" + - " " + - " " + - " " + - - " " + - - ""; - - public static final String MODEL5_XML = - "" + - - " Another description" + - " Alfresco" + - " 2007-08-01" + - " 1.0" + - - " " + - " " + - " " + - - " " + - " " + - " " + - - " " + - - " " + - " Base" + - " The Base Type 1" + - " " + - " " + - " d:text" + - " " + - " " + - " " + - - " " + - " Base" + - " The Base Type 2" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - - " " + - - " " + - " Base" + - " The Base Aspect 1" + - " " + - " " + - " d:text" + - " " + - " " + - " " + - - " " + - " Base" + - " The Base Aspect 2" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - - ""; - - public static final String MODEL5_EXTRA_ASSOCIATIONS_XML = - "" + - - " Another description" + - " Alfresco" + - " 2007-08-01" + - " 1.0" + - - " " + - " " + - " " + - - " " + - " " + - " " + - - " " + - - " " + - " Base" + - " The Base Type 1" + - " " + - " " + - " d:text" + - " " + - " " + - " " + - " " + - " " + - " false" + - " false" + - " " + - " " + - " test1:type2" + - " false" + - " false" + - " " + - " " + - " " + - " " + - - " " + - " Base" + - " The Base Type 2" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - - " " + - - " " + - " Base" + - " The Base Aspect 1" + - " " + - " " + - " d:text" + - " " + - " " + - " " + - " " + - " " + - " test1:role1" + - " false" + - " true" + - " " + - " " + - " test1:aspect2" + - " test1:role2" + - " false" + - " true" + - " " + - " " + - " " + - " " + - - " " + - " Base" + - " The Base Aspect 2" + - " " + - " " + - " d:text" + - " " + - " " + - " d:int" + - " " + - " " + - " " + - - " " + - - ""; - - public static final String MODEL6_XML = - "" + - - " Another description" + - " Alfresco" + - " 2007-08-01" + - " 1.0" + - - " " + - " " + - " " + - - " " + - " " + - " " + - - " " + - - " " + - " Type1 Title" + - " Type1 Description" + - " " + - " " + - " Prop1 Title" + - " Prop1 Description" + - " d:text" + - " " + - " " + - " " + - - " " + - - " " + - - " " + - " Aspect1 Title" + - " Aspect1 Description" + - " " + - " " + - " Prop9 Title" + - " Prop9 Description" + - " d:text" + - " " + - " " + - " " + - - " " + - - ""; - - public static final String MODEL6_UPDATE1_XML = - "" + - - " Another description - UPDATE1" + - " Alfresco - UPDATE1" + - " 2009-08-01" + - " 2.0" + - - " " + - " " + - " " + - - " " + - " " + - " " + - - " " + - - " " + - " Type1 Title - UPDATE1" + - " Type1 Description - UPDATE1" + - " " + - " " + - " Prop1 Title - UPDATE1" + - " Prop1 Description - UPDATE1" + - " d:text" + - " " + - " " + - " " + - - " " + - - " " + - - " " + - " Aspect1 Title" + - " Aspect1 Description" + - " " + - " " + - " Prop9 Title - UPDATE1" + - " Prop9 Description - UPDATE1" + - " d:text" + - " " + - " " + - " " + - - " " + - - ""; - - private DictionaryDAOImpl dictionaryDAO; - - /** - * Setup - */ - protected void setUp() throws Exception - { - // Initialise the Dictionary - TenantService tenantService = new SingleTServiceImpl(); - - NamespaceDAOImpl namespaceDAO = new NamespaceDAOImpl(); - namespaceDAO.setTenantService(tenantService); - - initNamespaceCaches(namespaceDAO); - - dictionaryDAO = new DictionaryDAOImpl(namespaceDAO); - dictionaryDAO.setTenantService(tenantService); - - initDictionaryCaches(dictionaryDAO); - - - // include Alfresco dictionary model - List bootstrapModels = new ArrayList(); - bootstrapModels.add("alfresco/model/dictionaryModel.xml"); - - DictionaryBootstrap bootstrap = new DictionaryBootstrap(); - bootstrap.setModels(bootstrapModels); - bootstrap.setDictionaryDAO(dictionaryDAO); - bootstrap.bootstrap(); - } - - private void initDictionaryCaches(DictionaryDAOImpl dictionaryDAO) - { - CacheManager cacheManager = new CacheManager(); - - Cache dictionaryEhCache = new Cache("dictionaryCache", 50, false, true, 0L, 0L); - cacheManager.addCache(dictionaryEhCache); - EhCacheAdapter dictionaryCache = new EhCacheAdapter(); - dictionaryCache.setCache(dictionaryEhCache); - - dictionaryDAO.setDictionaryRegistryCache(dictionaryCache); - } - - private void initNamespaceCaches(NamespaceDAOImpl namespaceDAO) - { - CacheManager cacheManager = new CacheManager(); - - Cache namespaceEhCache = new Cache("namespaceCache", 50, false, true, 0L, 0L); - cacheManager.addCache(namespaceEhCache); - EhCacheAdapter namespaceCache = new EhCacheAdapter(); - namespaceCache.setCache(namespaceEhCache); - - namespaceDAO.setNamespaceRegistryCache(namespaceCache); - } - - public void testDeleteModel() - { - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(MODEL1_XML.getBytes()); - - M2Model model = M2Model.createModel(byteArrayInputStream); - QName modelName = dictionaryDAO.putModel(model); - - CompiledModel previousVersion = dictionaryDAO.getCompiledModel(modelName); - - List modelDiffs = dictionaryDAO.diffModel(previousVersion, null); - - for (M2ModelDiff modelDiff : modelDiffs) - { - System.out.println(modelDiff.toString()); - } - - assertEquals(6, modelDiffs.size()); - - assertEquals(3, countDiffs(modelDiffs, M2ModelDiff.TYPE_TYPE, M2ModelDiff.DIFF_DELETED)); - assertEquals(3, countDiffs(modelDiffs, M2ModelDiff.TYPE_ASPECT, M2ModelDiff.DIFF_DELETED)); - } - - @SuppressWarnings("unused") - public void testNoExistingModelToDelete() - { - try - { - List modelDiffs = dictionaryDAO.diffModel(null, null); - assertTrue("Should throw exeception that there is no previous version of the model to delete", true); - } - catch (AlfrescoRuntimeException e) - { - assertTrue("Wrong error message", e.getMessage().equals("Invalid arguments - no previous version of model to delete")); - } - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(MODEL1_XML.getBytes()); - - M2Model model = M2Model.createModel(byteArrayInputStream); - QName modelName = dictionaryDAO.putModel(model); - - CompiledModel compiledModel = dictionaryDAO.getCompiledModel(modelName); - - try - { - List modelDiffs = dictionaryDAO.diffModel(null, compiledModel); - assertTrue("Should throw exeception that there is no previous version of the model to delete", true); - } - catch (AlfrescoRuntimeException e) - { - assertTrue("Wrong error message", e.getMessage().equals("Invalid arguments - no previous version of model to delete")); - } - } - - public void testNewModel() - { - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(MODEL1_XML.getBytes()); - - M2Model model = M2Model.createModel(byteArrayInputStream); - QName modelName = dictionaryDAO.putModel(model); - - CompiledModel newVersion = dictionaryDAO.getCompiledModel(modelName); - - List modelDiffs = dictionaryDAO.diffModel(null, newVersion); - - for (M2ModelDiff modelDiff : modelDiffs) - { - System.out.println(modelDiff.toString()); - } - - assertEquals(6, modelDiffs.size()); - - assertEquals(3, countDiffs(modelDiffs, M2ModelDiff.TYPE_TYPE, M2ModelDiff.DIFF_CREATED)); - assertEquals(3, countDiffs(modelDiffs, M2ModelDiff.TYPE_ASPECT, M2ModelDiff.DIFF_CREATED)); - } - - public void testNonIncUpdateModel() - { - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(MODEL1_XML.getBytes()); - M2Model model = M2Model.createModel(byteArrayInputStream); - QName modelName = dictionaryDAO.putModel(model); - CompiledModel previousVersion = dictionaryDAO.getCompiledModel(modelName); - - byteArrayInputStream = new ByteArrayInputStream(MODEL1_UPDATE1_XML.getBytes()); - model = M2Model.createModel(byteArrayInputStream); - modelName = dictionaryDAO.putModel(model); - CompiledModel newVersion = dictionaryDAO.getCompiledModel(modelName); - - List modelDiffs = dictionaryDAO.diffModel(previousVersion, newVersion); - - for (M2ModelDiff M2ModelDiff : modelDiffs) - { - System.out.println(M2ModelDiff.toString()); - } - - assertEquals(16, modelDiffs.size()); - - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_TYPE, M2ModelDiff.DIFF_CREATED)); - assertEquals(2, countDiffs(modelDiffs, M2ModelDiff.TYPE_TYPE, M2ModelDiff.DIFF_UNCHANGED)); - assertEquals(0, countDiffs(modelDiffs, M2ModelDiff.TYPE_TYPE, M2ModelDiff.DIFF_UPDATED)); - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_TYPE, M2ModelDiff.DIFF_DELETED)); - - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_ASPECT, M2ModelDiff.DIFF_CREATED)); - assertEquals(2, countDiffs(modelDiffs, M2ModelDiff.TYPE_ASPECT, M2ModelDiff.DIFF_UNCHANGED)); - assertEquals(0, countDiffs(modelDiffs, M2ModelDiff.TYPE_ASPECT, M2ModelDiff.DIFF_UPDATED)); - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_ASPECT, M2ModelDiff.DIFF_DELETED)); - - assertEquals(0, countDiffs(modelDiffs, M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_CREATED)); - assertEquals(6, countDiffs(modelDiffs, M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_UNCHANGED)); - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_UPDATED)); - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_DELETED)); - } - - public void testIncUpdatePropertiesAdded() - { - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(MODEL2_XML.getBytes()); - M2Model model = M2Model.createModel(byteArrayInputStream); - QName modelName = dictionaryDAO.putModel(model); - CompiledModel previousVersion = dictionaryDAO.getCompiledModel(modelName); - - byteArrayInputStream = new ByteArrayInputStream(MODEL2_EXTRA_PROPERTIES_XML.getBytes()); - model = M2Model.createModel(byteArrayInputStream); - modelName = dictionaryDAO.putModel(model); - CompiledModel newVersion = dictionaryDAO.getCompiledModel(modelName); - - List modelDiffs = dictionaryDAO.diffModel(previousVersion, newVersion); - - for (M2ModelDiff modelDiff : modelDiffs) - { - System.out.println(modelDiff.toString()); - } - - assertEquals(8, modelDiffs.size()); - - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_TYPE, M2ModelDiff.DIFF_UNCHANGED)); - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_ASPECT, M2ModelDiff.DIFF_UNCHANGED)); - assertEquals(4, countDiffs(modelDiffs, M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_UNCHANGED)); - assertEquals(2, countDiffs(modelDiffs, M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_CREATED)); - } - - public void testIncUpdateTypesAndAspectsAdded() - { - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(MODEL3_XML.getBytes()); - M2Model model = M2Model.createModel(byteArrayInputStream); - QName modelName = dictionaryDAO.putModel(model); - CompiledModel previousVersion = dictionaryDAO.getCompiledModel(modelName); - - byteArrayInputStream = new ByteArrayInputStream(MODEL3_EXTRA_TYPES_AND_ASPECTS_XML.getBytes()); - model = M2Model.createModel(byteArrayInputStream); - modelName = dictionaryDAO.putModel(model); - CompiledModel newVersion = dictionaryDAO.getCompiledModel(modelName); - - List modelDiffs = dictionaryDAO.diffModel(previousVersion, newVersion); - - for (M2ModelDiff modelDiff : modelDiffs) - { - System.out.println(modelDiff.toString()); - } - - assertEquals(8, modelDiffs.size()); - - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_TYPE, M2ModelDiff.DIFF_UNCHANGED)); - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_ASPECT, M2ModelDiff.DIFF_UNCHANGED)); - - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_TYPE, M2ModelDiff.DIFF_CREATED)); - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_ASPECT, M2ModelDiff.DIFF_CREATED)); - - assertEquals(4, countDiffs(modelDiffs, M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_UNCHANGED)); - } - - public void testIncUpdateAssociationsAdded() - { - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(MODEL5_XML.getBytes()); - M2Model model = M2Model.createModel(byteArrayInputStream); - QName modelName = dictionaryDAO.putModel(model); - CompiledModel previousVersion = dictionaryDAO.getCompiledModel(modelName); - - byteArrayInputStream = new ByteArrayInputStream(MODEL5_EXTRA_ASSOCIATIONS_XML.getBytes()); - model = M2Model.createModel(byteArrayInputStream); - modelName = dictionaryDAO.putModel(model); - CompiledModel newVersion = dictionaryDAO.getCompiledModel(modelName); - - List modelDiffs = dictionaryDAO.diffModel(previousVersion, newVersion); - - for (M2ModelDiff modelDiff : modelDiffs) - { - System.out.println(modelDiff.toString()); - } - - assertEquals(12, modelDiffs.size()); - - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_TYPE, M2ModelDiff.DIFF_UPDATED_INC)); - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_TYPE, M2ModelDiff.DIFF_UNCHANGED)); - - assertEquals(2, countDiffs(modelDiffs, M2ModelDiff.TYPE_ASPECT, M2ModelDiff.DIFF_UNCHANGED)); - - assertEquals(6, countDiffs(modelDiffs, M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_UNCHANGED)); - - assertEquals(2, countDiffs(modelDiffs, M2ModelDiff.TYPE_ASSOCIATION, M2ModelDiff.DIFF_CREATED)); - } - - public void testIncUpdateTitleDescription() - { - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(MODEL6_XML.getBytes()); - M2Model model = M2Model.createModel(byteArrayInputStream); - QName modelName = dictionaryDAO.putModel(model); - CompiledModel previousVersion = dictionaryDAO.getCompiledModel(modelName); - - byteArrayInputStream = new ByteArrayInputStream(MODEL6_UPDATE1_XML.getBytes()); - model = M2Model.createModel(byteArrayInputStream); - modelName = dictionaryDAO.putModel(model); - CompiledModel newVersion = dictionaryDAO.getCompiledModel(modelName); - - List modelDiffs = dictionaryDAO.diffModel(previousVersion, newVersion); - - for (M2ModelDiff modelDiff : modelDiffs) - { - System.out.println(modelDiff.toString()); - } - - assertEquals(4, modelDiffs.size()); - - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_TYPE, M2ModelDiff.DIFF_UPDATED_INC)); - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_ASPECT, M2ModelDiff.DIFF_UNCHANGED)); - assertEquals(2, countDiffs(modelDiffs, M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_UPDATED_INC)); - } - - public void testNonIncUpdatePropertiesRemoved() - { - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(MODEL2_EXTRA_PROPERTIES_XML.getBytes()); - M2Model model = M2Model.createModel(byteArrayInputStream); - QName modelName = dictionaryDAO.putModel(model); - CompiledModel previousVersion = dictionaryDAO.getCompiledModel(modelName); - - byteArrayInputStream = new ByteArrayInputStream(MODEL2_XML.getBytes()); - model = M2Model.createModel(byteArrayInputStream); - modelName = dictionaryDAO.putModel(model); - CompiledModel newVersion = dictionaryDAO.getCompiledModel(modelName); - - List modelDiffs = dictionaryDAO.diffModel(previousVersion, newVersion); - - for (M2ModelDiff modelDiff : modelDiffs) - { - System.out.println(modelDiff.toString()); - } - - assertEquals(8, modelDiffs.size()); - - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_TYPE, M2ModelDiff.DIFF_UNCHANGED)); - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_ASPECT, M2ModelDiff.DIFF_UNCHANGED)); - assertEquals(4, countDiffs(modelDiffs, M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_UNCHANGED)); - assertEquals(2, countDiffs(modelDiffs, M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_DELETED)); - } - - public void testNonIncUpdateTypesAndAspectsRemoved() - { - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(MODEL3_EXTRA_TYPES_AND_ASPECTS_XML.getBytes()); - M2Model model = M2Model.createModel(byteArrayInputStream); - QName modelName = dictionaryDAO.putModel(model); - CompiledModel previousVersion = dictionaryDAO.getCompiledModel(modelName); - - byteArrayInputStream = new ByteArrayInputStream(MODEL3_XML.getBytes()); - model = M2Model.createModel(byteArrayInputStream); - modelName = dictionaryDAO.putModel(model); - CompiledModel newVersion = dictionaryDAO.getCompiledModel(modelName); - - List modelDiffs = dictionaryDAO.diffModel(previousVersion, newVersion); - - for (M2ModelDiff modelDiff : modelDiffs) - { - System.out.println(modelDiff.toString()); - } - - assertEquals(8, modelDiffs.size()); - - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_TYPE, M2ModelDiff.DIFF_UNCHANGED)); - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_ASPECT, M2ModelDiff.DIFF_UNCHANGED)); - - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_TYPE, M2ModelDiff.DIFF_DELETED)); - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_ASPECT, M2ModelDiff.DIFF_DELETED)); - - assertEquals(4, countDiffs(modelDiffs, M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_UNCHANGED)); - } - - public void testNonIncUpdateDefaultAspectAdded() - { - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(MODEL4_XML.getBytes()); - M2Model model = M2Model.createModel(byteArrayInputStream); - QName modelName = dictionaryDAO.putModel(model); - CompiledModel previousVersion = dictionaryDAO.getCompiledModel(modelName); - - byteArrayInputStream = new ByteArrayInputStream(MODEL4_EXTRA_DEFAULT_ASPECT_XML.getBytes()); - model = M2Model.createModel(byteArrayInputStream); - modelName = dictionaryDAO.putModel(model); - CompiledModel newVersion = dictionaryDAO.getCompiledModel(modelName); - - List modelDiffs = dictionaryDAO.diffModel(previousVersion, newVersion); - - for (M2ModelDiff modelDiff : modelDiffs) - { - System.out.println(modelDiff.toString()); - } - - assertEquals(4, modelDiffs.size()); - - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_TYPE, M2ModelDiff.DIFF_UPDATED)); - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_ASPECT, M2ModelDiff.DIFF_UNCHANGED)); - assertEquals(2, countDiffs(modelDiffs, M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_UNCHANGED)); - } - - public void testNonIncUpdateAssociationsRemoved() - { - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(MODEL5_EXTRA_ASSOCIATIONS_XML.getBytes()); - M2Model model = M2Model.createModel(byteArrayInputStream); - QName modelName = dictionaryDAO.putModel(model); - CompiledModel previousVersion = dictionaryDAO.getCompiledModel(modelName); - - byteArrayInputStream = new ByteArrayInputStream(MODEL5_XML.getBytes()); - model = M2Model.createModel(byteArrayInputStream); - modelName = dictionaryDAO.putModel(model); - CompiledModel newVersion = dictionaryDAO.getCompiledModel(modelName); - - List modelDiffs = dictionaryDAO.diffModel(previousVersion, newVersion); - - for (M2ModelDiff modelDiff : modelDiffs) - { - System.out.println(modelDiff.toString()); - } - - assertEquals(12, modelDiffs.size()); - - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_TYPE, M2ModelDiff.DIFF_UPDATED)); - assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_TYPE, M2ModelDiff.DIFF_UNCHANGED)); - - assertEquals(2, countDiffs(modelDiffs, M2ModelDiff.TYPE_ASPECT, M2ModelDiff.DIFF_UNCHANGED)); - - assertEquals(6, countDiffs(modelDiffs, M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_UNCHANGED)); - - assertEquals(2, countDiffs(modelDiffs, M2ModelDiff.TYPE_ASSOCIATION, M2ModelDiff.DIFF_DELETED)); - } - - private int countDiffs(List M2ModelDiffs, String elementType, String diffType) - { - int count = 0; - for (M2ModelDiff modelDiff : M2ModelDiffs) - { - if (modelDiff.getDiffType().equals(diffType) && modelDiff.getElementType().equals(elementType)) - { - count++; - } - } - return count; - } - -} - diff --git a/source/java/org/alfresco/repo/dictionary/IndexTokenisationMode.java b/source/java/org/alfresco/repo/dictionary/IndexTokenisationMode.java deleted file mode 100644 index 3f2c4fcfbc..0000000000 --- a/source/java/org/alfresco/repo/dictionary/IndexTokenisationMode.java +++ /dev/null @@ -1,63 +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.dictionary; - -/** - * How tokenisation is supported in the index. - * - * - * @author andyh - * - */ -public enum IndexTokenisationMode { - /** - * Tokenise the property. If the analyser supported ordering then the field - * supports ordering FTS is supported via analysis. - */ - TRUE, - /** - * Do not tokenise the property. The field supports ordering and pattern - * matching. - */ - FALSE, - /** - * There may be two indexes - one to support ordering and one to support - * search. - */ - BOTH; - - public static String serializer(IndexTokenisationMode indexTokenisationMode) { - return indexTokenisationMode.toString(); - } - - public static IndexTokenisationMode deserializer(String value) { - if (value == null) { - return null; - } else if (value.equalsIgnoreCase(TRUE.toString())) { - return TRUE; - } else if (value.equalsIgnoreCase(FALSE.toString())) { - return FALSE; - } else if (value.equalsIgnoreCase(BOTH.toString())) { - return BOTH; - } else { - throw new IllegalArgumentException( - "Invalid IndexTokenisationMode: " + value); - } - } -} diff --git a/source/java/org/alfresco/repo/dictionary/M2AnonymousTypeDefinition.java b/source/java/org/alfresco/repo/dictionary/M2AnonymousTypeDefinition.java deleted file mode 100644 index 31d4c53fd8..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2AnonymousTypeDefinition.java +++ /dev/null @@ -1,216 +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.dictionary; - -import java.io.Serializable; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.alfresco.service.cmr.dictionary.AspectDefinition; -import org.alfresco.service.cmr.dictionary.AssociationDefinition; -import org.alfresco.service.cmr.dictionary.ChildAssociationDefinition; -import org.alfresco.service.cmr.dictionary.ModelDefinition; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.cmr.dictionary.TypeDefinition; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; - - -/** - * Compiled anonymous type definition. - * - * @author David Caruana - * - */ -/*package*/ class M2AnonymousTypeDefinition implements TypeDefinition -{ - private TypeDefinition type; - private Map properties = new HashMap(); - private Map associations = new HashMap(); - private Map childassociations = new HashMap(); - - - /** - * Construct - * - * @param type the primary type - * @param aspects the aspects to combine with the type - */ - /*package*/ M2AnonymousTypeDefinition(TypeDefinition type, Collection aspects) - { - this.type = type; - - // Combine features of type and aspects - properties.putAll(type.getProperties()); - associations.putAll(type.getAssociations()); - childassociations.putAll(type.getChildAssociations()); - for (AspectDefinition aspect : aspects) - { - properties.putAll(aspect.getProperties()); - associations.putAll(aspect.getAssociations()); - childassociations.putAll(aspect.getChildAssociations()); - } - } - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.ClassDefinition#getModel() - */ - public ModelDefinition getModel() - { - return type.getModel(); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.TypeDefinition#getDefaultAspects() - */ - public List getDefaultAspects() - { - return type.getDefaultAspects(); - } - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.ClassDefinition#getDefaultAspects(boolean) - */ - public List getDefaultAspects(boolean inherited) - { - return type.getDefaultAspects(inherited); - } - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.ClassDefinition#getDefaultAspectNames() - */ - public Set getDefaultAspectNames() - { - return type.getDefaultAspectNames(); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ClassDefinition#getName() - */ - public QName getName() - { - return QName.createQName(NamespaceService.DICTIONARY_MODEL_1_0_URI, "anonymous#" + type.getName().getLocalName()); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ClassDefinition#getTitle() - */ - public String getTitle() - { - return type.getTitle(); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ClassDefinition#getDescription() - */ - public String getDescription() - { - return type.getDescription(); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ClassDefinition#getParentName() - */ - public QName getParentName() - { - return type.getParentName(); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ClassDefinition#isAspect() - */ - public boolean isAspect() - { - return type.isAspect(); - } - - public Boolean getArchive() - { - return type.getArchive(); - } - - public Boolean getIncludedInSuperTypeQuery() - { - return type.getIncludedInSuperTypeQuery(); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ClassDefinition#getProperties() - */ - public Map getProperties() - { - return Collections.unmodifiableMap(properties); - } - - /** - * @see org.alfresco.service.cmr.dictionary.ClassDefinition#getDefaultValues() - */ - public Map getDefaultValues() - { - Map result = new HashMap(5); - - for(Map.Entry entry : properties.entrySet()) - { - PropertyDefinition propertyDefinition = entry.getValue(); - String defaultValue = propertyDefinition.getDefaultValue(); - if (defaultValue != null) - { - result.put(entry.getKey(), defaultValue); - } - } - - return Collections.unmodifiableMap(result); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ClassDefinition#getAssociations() - */ - public Map getAssociations() - { - return Collections.unmodifiableMap(associations); - } - - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.ClassDefinition#isContainer() - */ - public boolean isContainer() - { - return !childassociations.isEmpty(); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ClassDefinition#getChildAssociations() - */ - public Map getChildAssociations() - { - return Collections.unmodifiableMap(childassociations); - } - -} diff --git a/source/java/org/alfresco/repo/dictionary/M2Aspect.java b/source/java/org/alfresco/repo/dictionary/M2Aspect.java deleted file mode 100644 index cff91f9f43..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2Aspect.java +++ /dev/null @@ -1,34 +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.dictionary; - -/** - * Aspect definition. - * - * @author David Caruana - */ -public class M2Aspect extends M2Class -{ - - /*package*/ M2Aspect() - { - super(); - } - -} diff --git a/source/java/org/alfresco/repo/dictionary/M2AspectDefinition.java b/source/java/org/alfresco/repo/dictionary/M2AspectDefinition.java deleted file mode 100644 index 2a7f4444a5..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2AspectDefinition.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.dictionary; - -import java.util.Map; - -import org.alfresco.service.cmr.dictionary.AspectDefinition; -import org.alfresco.service.cmr.dictionary.AssociationDefinition; -import org.alfresco.service.cmr.dictionary.ModelDefinition; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.namespace.NamespacePrefixResolver; -import org.alfresco.service.namespace.QName; - - -/** - * Compiled Aspect Definition. - * - * @author David Caruana - */ -/*package*/ class M2AspectDefinition extends M2ClassDefinition - implements AspectDefinition -{ - - /*package*/ M2AspectDefinition(ModelDefinition model, M2Aspect m2Aspect, NamespacePrefixResolver resolver, Map modelProperties, Map modelAssociations) - { - super(model, m2Aspect, resolver, modelProperties, modelAssociations); - } - - @Override - public String getDescription() - { - String value = M2Label.getLabel(model, "aspect", name, "description"); - - // if we don't have a description call the super class - if (value == null) - { - value = super.getDescription(); - } - - return value; - } - - @Override - public String getTitle() - { - String value = M2Label.getLabel(model, "aspect", name, "title"); - - // if we don't have a title call the super class - if (value == null) - { - value = super.getTitle(); - } - - return value; - } -} diff --git a/source/java/org/alfresco/repo/dictionary/M2Association.java b/source/java/org/alfresco/repo/dictionary/M2Association.java deleted file mode 100644 index eebfca3755..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2Association.java +++ /dev/null @@ -1,39 +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.dictionary; - - -/** - * Association definition. - * - * @author David Caruana - */ -public class M2Association extends M2ClassAssociation -{ - - /*package*/ M2Association() - { - } - - /*package*/ M2Association(String name) - { - super(name); - } - -} diff --git a/source/java/org/alfresco/repo/dictionary/M2AssociationDefinition.java b/source/java/org/alfresco/repo/dictionary/M2AssociationDefinition.java deleted file mode 100644 index f8390a84fa..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2AssociationDefinition.java +++ /dev/null @@ -1,364 +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.dictionary; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.alfresco.service.cmr.dictionary.AssociationDefinition; -import org.alfresco.service.cmr.dictionary.ClassDefinition; -import org.alfresco.service.cmr.dictionary.DictionaryException; -import org.alfresco.service.cmr.dictionary.ModelDefinition; -import org.alfresco.service.namespace.NamespacePrefixResolver; -import org.alfresco.service.namespace.QName; -import org.alfresco.util.EqualsHelper; - - -/** - * Compiled Association Definition. - * - * @author David Caruana - */ -/*package*/ class M2AssociationDefinition implements AssociationDefinition -{ - - private ClassDefinition classDef; - private M2ClassAssociation assoc; - private QName name; - private QName targetClassName; - private ClassDefinition targetClass; - private QName sourceRoleName; - private QName targetRoleName; - - - /** - * Construct - * - * @param m2Association association definition - * @return the definition - */ - /*package*/ M2AssociationDefinition(ClassDefinition classDef, M2ClassAssociation assoc, NamespacePrefixResolver resolver) - { - this.classDef = classDef; - this.assoc = assoc; - - // Resolve names - this.name = QName.createQName(assoc.getName(), resolver); - this.targetClassName = QName.createQName(assoc.getTargetClassName(), resolver); - this.sourceRoleName = QName.createQName(assoc.getSourceRoleName(), resolver); - this.targetRoleName = QName.createQName(assoc.getTargetRoleName(), resolver); - } - - @Override - public String toString() - { - StringBuilder sb = new StringBuilder(56); - sb.append("Association") - .append("[ class=").append(classDef) - .append(", name=").append(name) - .append(", target class=").append(targetClassName) - .append(", source role=").append(sourceRoleName) - .append(", target role=").append(targetRoleName) - .append("]"); - return sb.toString(); - } - - - /*package*/ M2ClassAssociation getM2Association() - { - return assoc; - } - - - /*package*/ void resolveDependencies(ModelQuery query) - { - if (targetClassName == null) - { - throw new DictionaryException("Target class of association " + name.toPrefixString() + " must be specified"); - } - targetClass = query.getClass(targetClassName); - if (targetClass == null) - { - throw new DictionaryException("Target class " + targetClassName.toPrefixString() + " of association " + name.toPrefixString() + " is not found"); - } - } - - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.AssociationDefinition#getModel() - */ - public ModelDefinition getModel() - { - return classDef.getModel(); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.AssociationDefinition#getName() - */ - public QName getName() - { - return name; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.AssociationDefinition#isChild() - */ - public boolean isChild() - { - return (assoc instanceof M2ChildAssociation); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.AssociationDefinition#getTitle() - */ - public String getTitle() - { - String value = M2Label.getLabel(classDef.getModel(), "association", name, "title"); - if (value == null) - { - value = assoc.getTitle(); - } - return value; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.AssociationDefinition#getDescription() - */ - public String getDescription() - { - String value = M2Label.getLabel(classDef.getModel(), "association", name, "description"); - if (value == null) - { - value = assoc.getDescription(); - } - return value; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.AssociationDefinition#isProtected() - */ - public boolean isProtected() - { - return assoc.isProtected(); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.AssociationDefinition#getSourceClass() - */ - public ClassDefinition getSourceClass() - { - return classDef; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.AssociationDefinition#getSourceRoleName() - */ - public QName getSourceRoleName() - { - return sourceRoleName; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.AssociationDefinition#isSourceMandatory() - */ - public boolean isSourceMandatory() - { - return assoc.isSourceMandatory(); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.AssociationDefinition#isSourceMany() - */ - public boolean isSourceMany() - { - return assoc.isSourceMany(); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.AssociationDefinition#getTargetClass() - */ - public ClassDefinition getTargetClass() - { - return targetClass; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.AssociationDefinition#getTargetRoleName() - */ - public QName getTargetRoleName() - { - return targetRoleName; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.AssociationDefinition#isTargetMandatory() - */ - public boolean isTargetMandatory() - { - return assoc.isTargetMandatory(); - } - - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.AssociationDefinition#isTargetMandatoryEnforced() - */ - public boolean isTargetMandatoryEnforced() - { - return assoc.isTargetMandatoryEnforced(); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.AssociationDefinition#isTargetMany() - */ - public boolean isTargetMany() - { - return assoc.isTargetMany(); - } - - /* package */ M2ModelDiff diffAssoc(AssociationDefinition assocDef) - { - M2ModelDiff modelDiff = null; - boolean isUpdated = false; - boolean isUpdatedIncrementally = false; - - if (this == assocDef) - { - modelDiff = new M2ModelDiff(name, M2ModelDiff.TYPE_ASSOCIATION, M2ModelDiff.DIFF_UNCHANGED); - return modelDiff; - } - - // check name - cannot be null - if (! name.equals(assocDef.getName())) - { - isUpdated = true; - } - - // check title - if (! EqualsHelper.nullSafeEquals(getTitle(), assocDef.getTitle(), false)) - { - isUpdatedIncrementally = true; - } - - // check description - if (! EqualsHelper.nullSafeEquals(getDescription(), assocDef.getDescription(), false)) - { - isUpdatedIncrementally = true; - } - - // check source class qname - if (! EqualsHelper.nullSafeEquals(getSourceClass().getName(), assocDef.getSourceClass().getName())) - { - isUpdated = true; - } - - // check source role qname - if (! EqualsHelper.nullSafeEquals(getSourceRoleName(), assocDef.getSourceRoleName())) - { - isUpdated = true; - } - - // check target class qname - if (! EqualsHelper.nullSafeEquals(getTargetClass().getName(), assocDef.getTargetClass().getName())) - { - isUpdated = true; - } - - // check target role qname - if (! EqualsHelper.nullSafeEquals(getTargetRoleName(), assocDef.getTargetRoleName())) - { - isUpdated = true; - } - - // TODO - additional checks - is... (x7) - - if (isUpdated) - { - modelDiff = new M2ModelDiff(name, M2ModelDiff.TYPE_ASSOCIATION, M2ModelDiff.DIFF_UPDATED); - } - else if (isUpdatedIncrementally) - { - modelDiff = new M2ModelDiff(name, M2ModelDiff.TYPE_ASSOCIATION, M2ModelDiff.DIFF_UPDATED_INC); - } - else - { - modelDiff = new M2ModelDiff(name, M2ModelDiff.TYPE_ASSOCIATION, M2ModelDiff.DIFF_UNCHANGED); - } - - return modelDiff; - } - - /*package*/ static Collection diffAssocLists(Collection previousAssocs, Collection newAssocs) - { - List modelDiffs = new ArrayList(); - - for (AssociationDefinition previousAssoc : previousAssocs) - { - boolean found = false; - for (AssociationDefinition newAssoc : newAssocs) - { - if (newAssoc.getName().equals(previousAssoc.getName())) - { - modelDiffs.add(((M2AssociationDefinition)previousAssoc).diffAssoc(newAssoc)); - found = true; - break; - } - } - - if (! found) - { - modelDiffs.add(new M2ModelDiff(previousAssoc.getName(), M2ModelDiff.TYPE_ASSOCIATION, M2ModelDiff.DIFF_DELETED)); - } - } - - for (AssociationDefinition newAssoc : newAssocs) - { - boolean found = false; - for (AssociationDefinition previousAssoc : previousAssocs) - { - if (newAssoc.getName().equals(previousAssoc.getName())) - { - found = true; - break; - } - } - - if (! found) - { - modelDiffs.add(new M2ModelDiff(newAssoc.getName(), M2ModelDiff.TYPE_ASSOCIATION, M2ModelDiff.DIFF_CREATED)); - } - } - - return modelDiffs; - } - -} diff --git a/source/java/org/alfresco/repo/dictionary/M2ChildAssociation.java b/source/java/org/alfresco/repo/dictionary/M2ChildAssociation.java deleted file mode 100644 index f582bedb0f..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2ChildAssociation.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.dictionary; - - -/** - * Child Association definition. - * - * @author David Caruana - * - */ -public class M2ChildAssociation extends M2ClassAssociation -{ - private String requiredChildName = null; - private Boolean allowDuplicateChildName = null; - private Boolean propagateTimestamps = null; - - - /*package*/ M2ChildAssociation() - { - } - - - /*package*/ M2ChildAssociation(String name) - { - super(name); - } - - - public String getRequiredChildName() - { - return requiredChildName; - } - - - public void setRequiredChildName(String requiredChildName) - { - this.requiredChildName = requiredChildName; - } - - - public boolean allowDuplicateChildName() - { - return allowDuplicateChildName == null ? true : allowDuplicateChildName; - } - - - public void setAllowDuplicateChildName(boolean allowDuplicateChildName) - { - this.allowDuplicateChildName = allowDuplicateChildName; - } - - public boolean isPropagateTimestamps() - { - return propagateTimestamps == null ? false : propagateTimestamps; - } - - public void setPropagateTimestamps(boolean propagateTimestamps) - { - this.propagateTimestamps = propagateTimestamps; - } -} diff --git a/source/java/org/alfresco/repo/dictionary/M2ChildAssociationDefinition.java b/source/java/org/alfresco/repo/dictionary/M2ChildAssociationDefinition.java deleted file mode 100644 index 7270e6ae06..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2ChildAssociationDefinition.java +++ /dev/null @@ -1,63 +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.dictionary; - -import org.alfresco.service.cmr.dictionary.ChildAssociationDefinition; -import org.alfresco.service.cmr.dictionary.ClassDefinition; -import org.alfresco.service.namespace.NamespacePrefixResolver; - - -/** - * Compiled Association Definition. - * - * @author David Caruana - */ -/*package*/ class M2ChildAssociationDefinition extends M2AssociationDefinition - implements ChildAssociationDefinition -{ - - /** - * Construct - * @param classDef class definition - * @param assoc child assocation - * @param resolver namespace resolver - */ - /*package*/ M2ChildAssociationDefinition(ClassDefinition classDef, M2ChildAssociation assoc, NamespacePrefixResolver resolver) - { - super(classDef, assoc, resolver); - } - - - public String getRequiredChildName() - { - return ((M2ChildAssociation)getM2Association()).getRequiredChildName(); - } - - - public boolean getDuplicateChildNamesAllowed() - { - return ((M2ChildAssociation)getM2Association()).allowDuplicateChildName(); - } - - - public boolean getPropagateTimestamps() - { - return ((M2ChildAssociation)getM2Association()).isPropagateTimestamps(); - } -} diff --git a/source/java/org/alfresco/repo/dictionary/M2Class.java b/source/java/org/alfresco/repo/dictionary/M2Class.java deleted file mode 100644 index 6e499c55e3..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2Class.java +++ /dev/null @@ -1,257 +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.dictionary; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * Abstract Class Definition. - * - * @author David Caruana - * - */ -public abstract class M2Class -{ - private String name = null; - private String title = null; - private String description = null; - private String parentName = null; - private Boolean archive = null; - private Boolean includedInSuperTypeQuery = null; - - private List properties = new ArrayList(); - private List propertyOverrides = new ArrayList(); - private List associations = new ArrayList(); - private List mandatoryAspects = new ArrayList(); - - /*package*/ M2Class() - { - } - - - public String getName() - { - return name; - } - - - public void setName(String name) - { - this.name = name; - } - - - public String getTitle() - { - return title; - } - - - public void setTitle(String title) - { - this.title = title; - } - - - public String getDescription() - { - return description; - } - - - public void setDescription(String description) - { - this.description = description; - } - - - public String getParentName() - { - return parentName; - } - - - public void setParentName(String parentName) - { - this.parentName = parentName; - } - - - public Boolean getArchive() - { - return archive; - } - - public void setArchive(boolean archive) - { - this.archive = Boolean.valueOf(archive); - } - - public Boolean getIncludedInSuperTypeQuery() - { - return includedInSuperTypeQuery; - } - - public void setIncludedInSuperTypeQuery(boolean includedInSuperTypeQuery) - { - this.includedInSuperTypeQuery = Boolean.valueOf(includedInSuperTypeQuery); - } - - public M2Property createProperty(String name) - { - M2Property property = new M2Property(); - property.setName(name); - properties.add(property); - return property; - } - - - public void removeProperty(String name) - { - M2Property property = getProperty(name); - if (property != null) - { - properties.remove(property); - } - } - - - public List getProperties() - { - return Collections.unmodifiableList(properties); - } - - - public M2Property getProperty(String name) - { - for (M2Property candidate : properties) - { - if (candidate.getName().equals(name)) - { - return candidate; - } - } - return null; - } - - - public M2Association createAssociation(String name) - { - M2Association association = new M2Association(); - association.setName(name); - associations.add(association); - return association; - } - - - public M2ChildAssociation createChildAssociation(String name) - { - M2ChildAssociation association = new M2ChildAssociation(); - association.setName(name); - associations.add(association); - return association; - } - - - public void removeAssociation(String name) - { - M2ClassAssociation association = getAssociation(name); - if (association != null) - { - associations.remove(association); - } - } - - - public List getAssociations() - { - return Collections.unmodifiableList(associations); - } - - - public M2ClassAssociation getAssociation(String name) - { - for (M2ClassAssociation candidate : associations) - { - if (candidate.getName().equals(name)) - { - return candidate; - } - } - return null; - } - - - public M2PropertyOverride createPropertyOverride(String name) - { - M2PropertyOverride property = new M2PropertyOverride(); - property.setName(name); - propertyOverrides.add(property); - return property; - } - - - public void removePropertyOverride(String name) - { - M2PropertyOverride property = getPropertyOverride(name); - if (property != null) - { - propertyOverrides.remove(property); - } - } - - - public List getPropertyOverrides() - { - return Collections.unmodifiableList(propertyOverrides); - } - - - public M2PropertyOverride getPropertyOverride(String name) - { - for (M2PropertyOverride candidate : propertyOverrides) - { - if (candidate.getName().equals(name)) - { - return candidate; - } - } - return null; - } - - public void addMandatoryAspect(String name) - { - mandatoryAspects.add(name); - } - - - public void removeMandatoryAspect(String name) - { - mandatoryAspects.remove(name); - } - - - public List getMandatoryAspects() - { - return Collections.unmodifiableList(mandatoryAspects); - } - -} diff --git a/source/java/org/alfresco/repo/dictionary/M2ClassAssociation.java b/source/java/org/alfresco/repo/dictionary/M2ClassAssociation.java deleted file mode 100644 index 9b4b4ade30..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2ClassAssociation.java +++ /dev/null @@ -1,212 +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.dictionary; - - -/** - * Abstract Association Definition. - * - * @author David Caruana - * - */ -public abstract class M2ClassAssociation -{ - private String name = null; - private Boolean isProtected = null; - private String title = null; - private String description = null; - private String sourceRoleName = null; - private Boolean isSourceMandatory = null; - private Boolean isSourceMany = null; - private String targetClassName = null; - private String targetRoleName = null; - private Boolean isTargetMandatory = null; - private Boolean isTargetMandatoryEnforced = null; - private Boolean isTargetMany = null; - - - /*package*/ M2ClassAssociation() - { - } - - - /*package*/ M2ClassAssociation(String name) - { - this.name = name; - } - - - public boolean isChild() - { - return this instanceof M2ChildAssociation; - } - - - public String getName() - { - return name; - } - - - public void setName(String name) - { - this.name = name; - } - - - public boolean isProtected() - { - return isProtected == null ? false : isProtected; - } - - - public void setProtected(boolean isProtected) - { - this.isProtected = isProtected; - } - - - public String getTitle() - { - return title; - } - - - public void setTitle(String title) - { - this.title = title; - } - - - public String getDescription() - { - return description; - } - - - public void setDescription(String description) - { - this.description = description; - } - - - public String getSourceRoleName() - { - return sourceRoleName; - } - - - public void setSourceRoleName(String name) - { - this.sourceRoleName = name; - } - - - public boolean isSourceMandatory() - { - return isSourceMandatory == null ? true : isSourceMandatory; - } - - - public void setSourceMandatory(boolean isSourceMandatory) - { - this.isSourceMandatory = isSourceMandatory; - } - - - public boolean isSourceMany() - { - return isSourceMany == null ? false : isSourceMany; - } - - - public void setSourceMany(boolean isSourceMany) - { - this.isSourceMany = isSourceMany; - } - - - public String getTargetClassName() - { - return targetClassName; - } - - - public void setTargetClassName(String targetClassName) - { - this.targetClassName = targetClassName; - } - - - public String getTargetRoleName() - { - return targetRoleName; - } - - - public void setTargetRoleName(String name) - { - this.targetRoleName = name; - } - - public Boolean getTargetMandatory() - { - return isTargetMandatory(); - } - - public boolean isTargetMandatory() - { - return isTargetMandatory == null ? false : isTargetMandatory; - } - - - public void setTargetMandatory(boolean isTargetMandatory) - { - this.isTargetMandatory = isTargetMandatory; - } - - public Boolean getTargetMandatoryEnforced() - { - return isTargetMandatoryEnforced(); - } - - public boolean isTargetMandatoryEnforced() - { - return isTargetMandatoryEnforced == null ? false : isTargetMandatoryEnforced; - } - - - public void setTargetMandatoryEnforced(boolean isTargetMandatoryEnforced) - { - this.isTargetMandatoryEnforced = isTargetMandatoryEnforced; - } - - - public boolean isTargetMany() - { - return isTargetMany == null ? true : isTargetMany; - } - - - public void setTargetMany(boolean isTargetMany) - { - this.isTargetMany = isTargetMany; - } - -} diff --git a/source/java/org/alfresco/repo/dictionary/M2ClassDefinition.java b/source/java/org/alfresco/repo/dictionary/M2ClassDefinition.java deleted file mode 100644 index 89971ecce6..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2ClassDefinition.java +++ /dev/null @@ -1,718 +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.dictionary; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.alfresco.service.cmr.dictionary.AspectDefinition; -import org.alfresco.service.cmr.dictionary.AssociationDefinition; -import org.alfresco.service.cmr.dictionary.ChildAssociationDefinition; -import org.alfresco.service.cmr.dictionary.ClassDefinition; -import org.alfresco.service.cmr.dictionary.ConstraintDefinition; -import org.alfresco.service.cmr.dictionary.DictionaryException; -import org.alfresco.service.cmr.dictionary.ModelDefinition; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.namespace.NamespacePrefixResolver; -import org.alfresco.service.namespace.QName; -import org.alfresco.util.EqualsHelper; - - -/** - * Compiled Class Definition - * - * @author David Caruana - */ -/*package*/ class M2ClassDefinition implements ClassDefinition -{ - protected ModelDefinition model; - protected M2Class m2Class; - protected QName name; - protected QName parentName = null; - - private Map propertyOverrides = new HashMap(); - private Map properties = new HashMap(); - private Map inheritedProperties = new HashMap(); - private Map associations = new HashMap(); - private Map inheritedAssociations = new HashMap(); - private Map inheritedChildAssociations = new HashMap(); - private List defaultAspects = new ArrayList(); - private List defaultAspectNames = new ArrayList(); - private List inheritedDefaultAspects = new ArrayList(); - private Set inheritedDefaultAspectNames = new HashSet(); - private Boolean archive = null; - private Boolean inheritedArchive = null; - private Boolean includedInSuperTypeQuery = null; - private Boolean inheritedIncludedInSuperTypeQuery = null; - - /** - * Construct - * - * @param m2Class class definition - * @param resolver namepsace resolver - * @param modelProperties global list of model properties - * @param modelAssociations global list of model associations - */ - /*package*/ M2ClassDefinition(ModelDefinition model, M2Class m2Class, NamespacePrefixResolver resolver, Map modelProperties, Map modelAssociations) - { - this.model = model; - this.m2Class = m2Class; - - // Resolve Names - this.name = QName.createQName(m2Class.getName(), resolver); - if (!model.isNamespaceDefined(name.getNamespaceURI())) - { - throw new DictionaryException("Cannot define class " + name.toPrefixString() + " as namespace " + name.getNamespaceURI() + " is not defined by model " + model.getName().toPrefixString()); - } - this.archive = m2Class.getArchive(); - this.includedInSuperTypeQuery = m2Class.getIncludedInSuperTypeQuery(); - if (m2Class.getParentName() != null && m2Class.getParentName().length() > 0) - { - this.parentName = QName.createQName(m2Class.getParentName(), resolver); - } - - // Construct Properties - for (M2Property property : m2Class.getProperties()) - { - PropertyDefinition def = new M2PropertyDefinition(this, property, resolver); - if (!model.isNamespaceDefined(def.getName().getNamespaceURI())) - { - throw new DictionaryException("Cannot define property " + def.getName().toPrefixString() + " as namespace " + def.getName().getNamespaceURI() + " is not defined by model " + model.getName().toPrefixString()); - } - if (properties.containsKey(def.getName())) - { - throw new DictionaryException("Found duplicate property definition " + def.getName().toPrefixString() + " within class " + name.toPrefixString()); - } - - // Check for existence of property elsewhere within the model - PropertyDefinition existingDef = modelProperties.get(def.getName()); - if (existingDef != null) - { - // TODO: Consider sharing property, if property definitions are equal - throw new DictionaryException("Found duplicate property definition " + def.getName().toPrefixString() + " within class " - + name.toPrefixString() + " and class " + existingDef.getContainerClass().getName().toPrefixString()); - } - - properties.put(def.getName(), def); - modelProperties.put(def.getName(), def); - } - - // Construct Associations - for (M2ClassAssociation assoc : m2Class.getAssociations()) - { - AssociationDefinition def; - if (assoc instanceof M2ChildAssociation) - { - def = new M2ChildAssociationDefinition(this, (M2ChildAssociation)assoc, resolver); - } - else - { - def = new M2AssociationDefinition(this, assoc, resolver); - } - if (!model.isNamespaceDefined(def.getName().getNamespaceURI())) - { - throw new DictionaryException("Cannot define association " + def.getName().toPrefixString() + " as namespace " + def.getName().getNamespaceURI() + " is not defined by model " + model.getName().toPrefixString()); - } - if (associations.containsKey(def.getName())) - { - throw new DictionaryException("Found duplicate association definition " + def.getName().toPrefixString() + " within class " + name.toPrefixString()); - } - - // Check for existence of association elsewhere within the model - AssociationDefinition existingDef = modelAssociations.get(def.getName()); - if (existingDef != null) - { - // TODO: Consider sharing association, if association definitions are equal - throw new DictionaryException("Found duplicate association definition " + def.getName().toPrefixString() + " within class " - + name.toPrefixString() + " and class " + existingDef.getSourceClass().getName().toPrefixString()); - } - - associations.put(def.getName(), def); - modelAssociations.put(def.getName(), def); - } - - // Construct Property overrides - for (M2PropertyOverride override : m2Class.getPropertyOverrides()) - { - QName overrideName = QName.createQName(override.getName(), resolver); - if (properties.containsKey(overrideName)) - { - throw new DictionaryException("Found duplicate property and property override definition " + overrideName.toPrefixString() + " within class " + name.toPrefixString()); - } - if (propertyOverrides.containsKey(overrideName)) - { - throw new DictionaryException("Found duplicate property override definition " + overrideName.toPrefixString() + " within class " + name.toPrefixString()); - } - propertyOverrides.put(overrideName, override); - } - - // Resolve qualified names - for (String aspectName : m2Class.getMandatoryAspects()) - { - QName name = QName.createQName(aspectName, resolver); - if (!defaultAspectNames.contains(name)) - { - defaultAspectNames.add(name); - } - } - } - - @Override - public String toString() - { - StringBuilder sb = new StringBuilder(120); - sb.append("ClassDef") - .append("[name=").append(name) - .append("]"); - return sb.toString(); - } - - - /*package*/ void resolveDependencies( - ModelQuery query, - NamespacePrefixResolver prefixResolver, - Map modelConstraints) - { - if (parentName != null) - { - ClassDefinition parent = query.getClass(parentName); - if (parent == null) - { - throw new DictionaryException("Parent class " + parentName.toPrefixString() + " of class " + name.toPrefixString() + " is not found"); - } - } - - for (PropertyDefinition def : properties.values()) - { - ((M2PropertyDefinition)def).resolveDependencies(query, prefixResolver, modelConstraints); - } - for (AssociationDefinition def : associations.values()) - { - ((M2AssociationDefinition)def).resolveDependencies(query); - } - - for (Map.Entry override : propertyOverrides.entrySet()) - { - PropertyDefinition propDef = query.getProperty(override.getKey()); - if (propDef == null) - { - throw new DictionaryException("Class " + name.toPrefixString() + " attempting to override property " + override.getKey().toPrefixString() + " which does not exist"); - } - } - - for (QName aspectName : defaultAspectNames) - { - AspectDefinition aspect = query.getAspect(aspectName); - if (aspect == null) - { - throw new DictionaryException("Mandatory aspect " + aspectName.toPrefixString() + " of class " + name.toPrefixString() + " is not found"); - } - defaultAspects.add(aspect); - } - } - - - /*package*/ void resolveInheritance( - ModelQuery query, - NamespacePrefixResolver prefixResolver, - Map modelConstraints) - { - // Retrieve parent class - ClassDefinition parentClass = (parentName == null) ? null : query.getClass(parentName); - - // Build list of inherited properties (and process overridden values) - if (parentClass != null) - { - for (PropertyDefinition def : parentClass.getProperties().values()) - { - M2PropertyOverride override = propertyOverrides.get(def.getName()); - if (override == null) - { - inheritedProperties.put(def.getName(), def); - } - else - { - inheritedProperties.put( - def.getName(), - new M2PropertyDefinition(this, def, override, prefixResolver, modelConstraints)); - } - } - } - - // Append list of defined properties - for (PropertyDefinition def : properties.values()) - { - if (inheritedProperties.containsKey(def.getName())) - { - throw new DictionaryException("Duplicate property definition " + def.getName().toPrefixString() + " found in class hierarchy of " + name.toPrefixString()); - } - inheritedProperties.put(def.getName(), def); - } - - // Build list of inherited associations - if (parentClass != null) - { - inheritedAssociations.putAll(parentClass.getAssociations()); - } - - // Append list of defined associations - for (AssociationDefinition def : associations.values()) - { - if (inheritedAssociations.containsKey(def.getName())) - { - throw new DictionaryException("Duplicate association definition " + def.getName().toPrefixString() + " found in class hierarchy of " + name.toPrefixString()); - } - inheritedAssociations.put(def.getName(), def); - } - - // Derive Child Associations - for (AssociationDefinition def : inheritedAssociations.values()) - { - if (def instanceof ChildAssociationDefinition) - { - inheritedChildAssociations.put(def.getName(), (ChildAssociationDefinition)def); - } - } - - // Build list of inherited default aspects - if (parentClass != null) - { - inheritedDefaultAspects.addAll(parentClass.getDefaultAspects()); - } - - // Append list of defined default aspects - for (AspectDefinition def : defaultAspects) - { - if (!inheritedDefaultAspects.contains(def)) - { - inheritedDefaultAspects.add(def); - } - } - - // Convert to set of names - for (AspectDefinition aspDef : inheritedDefaultAspects) - { - inheritedDefaultAspectNames.add(aspDef.getName()); - } - - // resolve archive inheritance - if (parentClass != null && archive == null) - { - // archive not explicitly set on this class and there is a parent class - inheritedArchive = ((M2ClassDefinition)parentClass).getArchive(); - } - - // resolve includedInSuperTypeQuery inheritance - if (parentClass != null && includedInSuperTypeQuery == null) - { - // archive not explicitly set on this class and there is a parent class - inheritedIncludedInSuperTypeQuery = ((M2ClassDefinition)parentClass).getIncludedInSuperTypeQuery(); - } - } - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.ClassDefinition#getModel() - */ - public ModelDefinition getModel() - { - return model; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ClassDefinition#getName() - */ - public QName getName() - { - return name; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ClassDefinition#getTitle() - */ - public String getTitle() - { - String value = M2Label.getLabel(model, "class", name, "title"); - if (value == null) - { - value = m2Class.getTitle(); - } - return value; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ClassDefinition#getDescription() - */ - public String getDescription() - { - String value = M2Label.getLabel(model, "class", name, "description"); - if (value == null) - { - value = m2Class.getDescription(); - } - return value; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ClassDefinition#getParentName() - */ - public QName getParentName() - { - return parentName; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ClassDefinition#isAspect() - */ - public boolean isAspect() - { - return (m2Class instanceof M2Aspect); - } - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.ClassDefinition#getArchive() - */ - public Boolean getArchive() - { - return archive == null ? inheritedArchive : archive; - } - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.ClassDefinition#includedInSuperTypeQuery() - */ - public Boolean getIncludedInSuperTypeQuery() - { - if(includedInSuperTypeQuery != null) - { - return includedInSuperTypeQuery; - } - if(inheritedIncludedInSuperTypeQuery != null) - { - return inheritedIncludedInSuperTypeQuery; - } - return Boolean.TRUE; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ClassDefinition#getProperties() - */ - public Map getProperties() - { - return Collections.unmodifiableMap(inheritedProperties); - } - - /** - * @see org.alfresco.service.cmr.dictionary.ClassDefinition#getDefaultValues() - */ - public Map getDefaultValues() - { - Map result = new HashMap(5); - - for(Map.Entry entry : inheritedProperties.entrySet()) - { - PropertyDefinition propertyDefinition = entry.getValue(); - String defaultValue = propertyDefinition.getDefaultValue(); - if (defaultValue != null) - { - result.put(entry.getKey(), defaultValue); - } - } - - return Collections.unmodifiableMap(result); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ClassDefinition#getAssociations() - */ - public Map getAssociations() - { - return Collections.unmodifiableMap(inheritedAssociations); - } - - /** - * @see org.alfresco.service.cmr.dictionary.ClassDefinition#getDefaultAspects() - */ - public List getDefaultAspects() - { - return inheritedDefaultAspects; - } - - /** - * @see org.alfresco.service.cmr.dictionary.ClassDefinition#getDefaultAspects(boolean) - */ - public List getDefaultAspects(boolean inherited) - { - return inherited ? getDefaultAspects() : defaultAspects; - } - - /** - * @see org.alfresco.service.cmr.dictionary.ClassDefinition#getDefaultAspectNames() - */ - public Set getDefaultAspectNames() - { - return inheritedDefaultAspectNames; - } - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.ClassDefinition#isContainer() - */ - public boolean isContainer() - { - return !inheritedChildAssociations.isEmpty(); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ClassDefinition#getChildAssociations() - */ - public Map getChildAssociations() - { - return Collections.unmodifiableMap(inheritedChildAssociations); - } - - @Override - public int hashCode() - { - return name.hashCode(); - } - - @Override - public boolean equals(Object obj) - { - if (!(obj instanceof M2ClassDefinition)) - { - return false; - } - return name.equals(((M2ClassDefinition)obj).name); - } - - /** - * return differences in class definition - * - * note: - * - checks properties for incremental updates, but does not include the diffs - * - checks assocs & child assocs for incremental updates, but does not include the diffs - * - incremental updates include changes in title/description, property default value, etc - */ - /* package */ List diffClass(ClassDefinition classDef) - { - List modelDiffs = new ArrayList(); - boolean isUpdated = false; - boolean isUpdatedIncrementally = false; - - if (this == classDef) - { - return modelDiffs; - } - - // check name - cannot be null - if (! getName().equals(classDef.getName())) - { - isUpdated = true; - } - - // check title - if (! EqualsHelper.nullSafeEquals(getTitle(), classDef.getTitle(), false)) - { - isUpdatedIncrementally = true; - } - - // check description - if (! EqualsHelper.nullSafeEquals(getDescription(), classDef.getDescription(), false)) - { - isUpdatedIncrementally = true; - } - - // check parent name - if (getParentName() != null) - { - if (! getParentName().equals(classDef.getParentName())) - { - isUpdated = true; - } - } - else if (classDef.getParentName() != null) - { - isUpdated = true; - } - - // check if aspect (or type) - if (isAspect() != classDef.isAspect()) - { - isUpdated = true; - } - - // check if container - if (isContainer() != classDef.isContainer()) - { - if (isContainer()) - { - // updated (non-incrementally) if class was a container and now is not a container - ie. all child associations removed - isUpdated = true; - } - - if (classDef.isContainer()) - { - // updated incrementally if class was not a container and now is a container - ie. some child associations added - isUpdatedIncrementally = true; - } - } - - // check all properties (including inherited properties) - Collection propertyDiffs = M2PropertyDefinition.diffPropertyLists(getProperties().values(), classDef.getProperties().values()); - - modelDiffs.addAll(propertyDiffs); - - // check all associations (including inherited associations, child associations and inherited child associations) - Collection assocDiffs = M2AssociationDefinition.diffAssocLists(getAssociations().values(), classDef.getAssociations().values()); - - modelDiffs.addAll(assocDiffs); - - // check default/mandatory aspects (including inherited default aspects) - Collection defaultAspectsDiffs = M2ClassDefinition.diffClassLists(new ArrayList(getDefaultAspects()), new ArrayList(classDef.getDefaultAspects()), M2ModelDiff.TYPE_DEFAULT_ASPECT); - - for (M2ModelDiff defaultAspectDiff : defaultAspectsDiffs) - { - // note: incremental default/mandatory aspect updates not supported yet, added for completeness - if (defaultAspectDiff.getDiffType().equals(M2ModelDiff.DIFF_UPDATED_INC)) - { - isUpdatedIncrementally = true; - } - - if (defaultAspectDiff.getDiffType().equals(M2ModelDiff.DIFF_CREATED) || defaultAspectDiff.getDiffType().equals(M2ModelDiff.DIFF_UPDATED) || defaultAspectDiff.getDiffType().equals(M2ModelDiff.DIFF_DELETED)) - { - isUpdated = true; - break; - } - } - - // check archive/inheritedArchive - if (getArchive() == null) - { - if (classDef.getArchive() != null) - { - isUpdatedIncrementally = true; - } - } - else - { - Boolean classArchive = classDef.getArchive(); - if (classArchive == null || classArchive.booleanValue() != getArchive().booleanValue()) - { - isUpdatedIncrementally = true; - } - } - - // check includedInSuperTypeQuery/inheritedIncludedInSuperTypeQuery - if (getIncludedInSuperTypeQuery() == null) - { - // belts-and-braces (currently does not return null) - if (classDef.getIncludedInSuperTypeQuery() != null) - { - isUpdatedIncrementally = true; - } - } - else - { - Boolean classIncludedInSuperTypeQuery = classDef.getIncludedInSuperTypeQuery(); - if (classIncludedInSuperTypeQuery == null || classIncludedInSuperTypeQuery.booleanValue() != getIncludedInSuperTypeQuery().booleanValue()) - { - isUpdatedIncrementally = true; - } - } - - String modelDiffType; - if (isAspect()) - { - modelDiffType = M2ModelDiff.TYPE_ASPECT; - } - else - { - modelDiffType = M2ModelDiff.TYPE_TYPE; - } - - if (isUpdated) - { - modelDiffs.add(new M2ModelDiff(name, modelDiffType, M2ModelDiff.DIFF_UPDATED)); - } - else if (isUpdatedIncrementally) - { - modelDiffs.add(new M2ModelDiff(name, modelDiffType, M2ModelDiff.DIFF_UPDATED_INC)); - } - else - { - modelDiffs.add(new M2ModelDiff(name, modelDiffType, M2ModelDiff.DIFF_UNCHANGED)); - } - - return modelDiffs; - } - - /** - * return differences in class definition lists - * - */ - /*package*/ static List diffClassLists(Collection previousClasses, Collection newClasses, String M2ModelDiffType) - { - List modelDiffs = new ArrayList(); - - for (ClassDefinition previousClass : previousClasses) - { - boolean found = false; - for (ClassDefinition newClass : newClasses) - { - if (newClass.getName().equals(previousClass.getName())) - { - modelDiffs.addAll(((M2ClassDefinition)previousClass).diffClass(newClass)); - found = true; - break; - } - } - - if (! found) - { - modelDiffs.add(new M2ModelDiff(previousClass.getName(), M2ModelDiffType, M2ModelDiff.DIFF_DELETED)); - } - } - - for (ClassDefinition newClass : newClasses) - { - boolean found = false; - for (ClassDefinition previousClass : previousClasses) - { - if (newClass.getName().equals(previousClass.getName())) - { - found = true; - break; - } - } - - if (! found) - { - modelDiffs.add(new M2ModelDiff(newClass.getName(), M2ModelDiffType, M2ModelDiff.DIFF_CREATED)); - } - } - - return modelDiffs; - } -} diff --git a/source/java/org/alfresco/repo/dictionary/M2Constraint.java b/source/java/org/alfresco/repo/dictionary/M2Constraint.java deleted file mode 100644 index 07ec6b27ab..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2Constraint.java +++ /dev/null @@ -1,132 +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.dictionary; - -import java.util.ArrayList; -import java.util.List; - -/** - * Abstract Property Constraint. - * - * @author Derek Hulley - */ -public class M2Constraint -{ - private String name; - private String ref; - private String type; - private String title; - private String description; - private List parameters = new ArrayList(2); - - /*package*/ M2Constraint() - { - } - - @Override - public String toString() - { - return this.name; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name; - } - - public String getRef() - { - return ref; - } - - public void setRef(String refName) - { - this.ref = refName; - } - - public String getType() - { - return type; - } - - public void setType(String type) - { - this.type = type; - } - - public String getTitle() - { - return title; - } - - public void setTitle(String title) - { - this.title = title; - } - - public String getDescription() - { - return description; - } - - public void setDescription(String description) - { - this.description = description; - } - - public List getParameters() - { - return parameters; - } - - public M2NamedValue createParameter(String name, String simpleValue) - { - M2NamedValue param = new M2NamedValue(); - param.setName(name); - param.setSimpleValue(simpleValue); - parameters.add(param); - return param; - } - - public M2NamedValue createParameter(String name, List listValue) - { - M2NamedValue param = new M2NamedValue(); - param.setName(name); - param.setListValue(listValue); - parameters.add(param); - return param; - } - - public void removeParameter(String name) - { - List params = new ArrayList(getParameters()); - for (M2NamedValue param : params) - { - if (param.getName().equals(name)) - { - parameters.remove(param); - } - } - } -} diff --git a/source/java/org/alfresco/repo/dictionary/M2ConstraintDefinition.java b/source/java/org/alfresco/repo/dictionary/M2ConstraintDefinition.java deleted file mode 100644 index cc63b0492a..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2ConstraintDefinition.java +++ /dev/null @@ -1,488 +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.dictionary; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.alfresco.repo.dictionary.constraint.ListOfValuesConstraint; -import org.alfresco.repo.dictionary.constraint.NumericRangeConstraint; -import org.alfresco.repo.dictionary.constraint.RegexConstraint; -import org.alfresco.repo.dictionary.constraint.RegisteredConstraint; -import org.alfresco.repo.dictionary.constraint.StringLengthConstraint; -import org.alfresco.service.cmr.dictionary.Constraint; -import org.alfresco.service.cmr.dictionary.ConstraintDefinition; -import org.alfresco.service.cmr.dictionary.DictionaryException; -import org.alfresco.service.cmr.dictionary.ModelDefinition; -import org.alfresco.service.namespace.NamespacePrefixResolver; -import org.alfresco.service.namespace.QName; -import org.alfresco.util.EqualsHelper; -import org.springframework.beans.BeanWrapper; -import org.springframework.beans.BeanWrapperImpl; -import org.springframework.beans.InvalidPropertyException; -import org.springframework.beans.PropertyAccessException; - -/** - * Compiled Property Constraint - * - * @author Derek Hulley. janv - */ -/* package */class M2ConstraintDefinition implements ConstraintDefinition -{ - private static final String PROP_SHORT_NAME = "shortName"; - private static final String PROP_TITLE = "title"; - private static final String PROP_DESCRIPTION = "description"; - - public static final String ERR_CYCLIC_REF = "d_dictionary.constraint.err.cyclic_ref"; - public static final String ERR_TYPE_AND_REF = "d_dictionary.constraint.err.type_and_ref"; - public static final String ERR_TYPE_OR_REF = "d_dictionary.constraint.err.type_or_ref"; - public static final String ERR_REF_NOT_FOUND = "d_dictionary.constraint.err.ref_not_found"; - public static final String ERR_ANON_NEEDS_PROPERTY = "d_dictionary.constraint.err.anon_needs_property"; - public static final String ERR_INVALID_TYPE = "d_dictionary.constraint.err.invalid_type"; - public static final String ERR_SIMPLE_AND_LIST = "d_dictionary.constraint.err.property_simple_and_list"; - public static final String ERR_CONSTRUCT_FAILURE = "d_dictionary.constraint.err.construct_failure"; - public static final String ERR_PROPERTY_MISMATCH = "d_dictionary.constraint.err.property_mismatch"; - public static final String ERR_RESERVED_PROPERTY = "d_dictionary.constraint.err.reserved_property"; - - private static int anonPropCount = 0; - - private ModelDefinition model; - private NamespacePrefixResolver prefixResolver; - private M2Constraint m2Constraint; - private QName name; - private Constraint constraint; - private boolean resolving; - - /* package */M2ConstraintDefinition(M2PropertyDefinition m2PropertyDef, M2Constraint m2Constraint, - NamespacePrefixResolver prefixResolver) - { - this(m2PropertyDef.getModel(), m2PropertyDef, m2Constraint, prefixResolver); - } - - /* package */M2ConstraintDefinition(ModelDefinition modelDefinition, M2PropertyDefinition m2PropertyDef, - M2Constraint m2Constraint, NamespacePrefixResolver prefixResolver) - { - this.model = modelDefinition; - this.m2Constraint = m2Constraint; - this.prefixResolver = prefixResolver; - - String constraintName = m2Constraint.getName(); - if (constraintName == null) - { - // the constraint is anonymous, so it has to be defined within the context of a property - if (m2PropertyDef == null) - { - throw new DictionaryException(ERR_ANON_NEEDS_PROPERTY); - } - // pick the name up from the property and some anonymous value - String localName = m2PropertyDef.getName().getLocalName() + "_anon_" + (++anonPropCount); - this.name = QName.createQName(m2PropertyDef.getName().getNamespaceURI(), localName); - m2Constraint.setName(this.name.getPrefixedQName(prefixResolver).toPrefixString()); - } - else - { - this.name = QName.createQName(m2Constraint.getName(), prefixResolver); - if (!model.isNamespaceDefined(name.getNamespaceURI())) - { - throw new DictionaryException("Cannot define constraint " + name.toPrefixString() + " as namespace " + name.getNamespaceURI() + " is not defined by model " + model.getName().toPrefixString()); - } - } - } - - /* package */synchronized void resolveDependencies(ModelQuery query) - { - if (resolving) - { - throw new DictionaryException(ERR_CYCLIC_REF, name.toPrefixString()); - } - // prevent circular references - try - { - resolving = true; - resolveInternal(query); - } - finally - { - resolving = false; - } - } - - private synchronized void resolveInternal(ModelQuery query) - { - if (constraint != null) - { - // already been resolved - return; - } - - String shortName = name.toPrefixString(); - String ref = m2Constraint.getRef(); - String type = m2Constraint.getType(); - - String title = m2Constraint.getTitle(); - String description = m2Constraint.getDescription(); - - if (ref != null && type != null) - { - throw new DictionaryException(ERR_TYPE_AND_REF, shortName); - } - else if (ref == null && type == null) - { - throw new DictionaryException(ERR_TYPE_OR_REF, shortName); - } - else if (ref != null) - { - // resolve the reference name - QName qnameRef = QName.createQName(ref, prefixResolver); - // ensure that the reference exists in the model - M2ConstraintDefinition constraintDef = (M2ConstraintDefinition) query.getConstraint(qnameRef); - if (constraintDef == null) - { - throw new DictionaryException(ERR_REF_NOT_FOUND, ref, shortName); - } - // make sure that the constraint definition has itself been resolved - constraintDef.resolveDependencies(query); - // just use the constraint provided by the referenced definition - this.constraint = constraintDef.getConstraint(); - - //use real constraint name instead of anonymous name - //TODO Fix backed out - breaks DictionaryDAOTest - //this.name = constraintDef.getName(); - - - if (m2Constraint.getTitle() == null) - { - m2Constraint.setTitle(constraintDef.getTitle()); - } - - if (m2Constraint.getDescription() == null) - { - m2Constraint.setDescription(constraintDef.getDescription()); - } - } - else - { - // we have to build the constraint from the type - try - { - ConstraintType constraintType = ConstraintType.valueOf(type); - constraint = constraintType.newInstance(); - } - catch (IllegalArgumentException e) - { - // try to establish it as a class - try - { - @SuppressWarnings("unchecked") - Class clazz = Class.forName(type); - constraint = (Constraint) clazz.newInstance(); - } - catch (ClassNotFoundException ee) - { - throw new DictionaryException(ERR_INVALID_TYPE, type, shortName); - } - catch (ClassCastException ee) - { - throw new DictionaryException(ERR_INVALID_TYPE, type, shortName); - } - catch (Exception ee) - { - throw new DictionaryException(ERR_CONSTRUCT_FAILURE, type, shortName); - } - } - - // property setters - BeanWrapper beanWrapper = new BeanWrapperImpl(constraint); - List constraintNamedValues = m2Constraint.getParameters(); - - if (constraintNamedValues != null) - { - for (M2NamedValue namedValue : constraintNamedValues) - { - String namedValueName = namedValue.getName(); - // Check for reserved properties - if (namedValueName.equals(PROP_SHORT_NAME)) - { - throw new DictionaryException(ERR_RESERVED_PROPERTY, PROP_SHORT_NAME, namedValueName); - } - - Object value = null; - if (namedValue.getSimpleValue() != null && namedValue.getListValue() != null) - { - throw new DictionaryException(ERR_SIMPLE_AND_LIST, shortName, namedValue.getName()); - } - else if (namedValue.getSimpleValue() != null) - { - value = namedValue.getSimpleValue(); - } - else if (namedValue.getListValue() != null) - { - value = namedValue.getListValue(); - } - try - { - beanWrapper.setPropertyValue(namedValueName, value); - } - catch (PropertyAccessException e) - { - throw new DictionaryException(ERR_PROPERTY_MISMATCH, e, namedValueName, shortName); - } - catch (InvalidPropertyException e) - { - throw new DictionaryException(ERR_PROPERTY_MISMATCH, e, namedValueName, shortName); - } - } - - // Pass in the short name as a special property, if it is available - if (beanWrapper.isWritableProperty(PROP_SHORT_NAME)) - { - try - { - beanWrapper.setPropertyValue(PROP_SHORT_NAME, shortName); - } - catch (PropertyAccessException e) - { - throw new DictionaryException(ERR_PROPERTY_MISMATCH, e, shortName, shortName); - } - catch (InvalidPropertyException e) - { - throw new DictionaryException(ERR_PROPERTY_MISMATCH, e, shortName, shortName); - } - } - - if ((title != null) && (beanWrapper.isWritableProperty(PROP_TITLE))) - { - beanWrapper.setPropertyValue(PROP_TITLE, title); - } - - if ((title != null) && (beanWrapper.isWritableProperty(PROP_DESCRIPTION))) - { - beanWrapper.setPropertyValue(PROP_DESCRIPTION, description); - } - } - - // now initialize - constraint.initialize(); - } - } - - /** - * @see #getName() - */ - @Override - public String toString() - { - return getName().toString(); - } - - public ModelDefinition getModel() - { - return model; - } - - public QName getName() - { - return name; - } - - public String getTitle() - { - String value = M2Label.getLabel(model, "constraint", name, "title"); - if (value == null) - { - value = m2Constraint.getTitle(); - } - return value; - } - - public String getDescription() - { - String value = M2Label.getLabel(model, "constraint", name, "description"); - if (value == null) - { - value = m2Constraint.getDescription(); - } - return value; - } - - public Constraint getConstraint() - { - return constraint; - } - - public QName getRef() - { - QName refQName = null; - String ref = m2Constraint.getRef(); - if (ref != null) - { - refQName = QName.createQName(ref, prefixResolver); - } - return refQName; - } - - /** - * Well-known constraint types - */ - public static enum ConstraintType - { - REGISTERED - { - @Override - protected Constraint newInstance() - { - return new RegisteredConstraint(); - } - }, - REGEX - { - @Override - protected Constraint newInstance() - { - return new RegexConstraint(); - } - }, - MINMAX - { - @Override - protected Constraint newInstance() - { - return new NumericRangeConstraint(); - } - }, - LENGTH - { - @Override - protected Constraint newInstance() - { - return new StringLengthConstraint(); - } - }, - LIST - { - @Override - protected Constraint newInstance() - { - return new ListOfValuesConstraint(); - } - }; - - /** - * @return Returns the constraint implementation - */ - protected abstract Constraint newInstance(); - } - - /* package */ M2ModelDiff diffConstraint(ConstraintDefinition conDef) - { - M2ModelDiff modelDiff = null; - boolean isUpdated = false; - boolean isUpdatedIncrementally = false; - - if (this == conDef) - { - modelDiff = new M2ModelDiff(name, M2ModelDiff.TYPE_CONSTRAINT, M2ModelDiff.DIFF_UNCHANGED); - return modelDiff; - } - - // check name - cannot be null - if (! name.equals(conDef.getName())) - { - isUpdated = true; - } - - // check title - if (! EqualsHelper.nullSafeEquals(getTitle(), conDef.getTitle(), false)) - { - isUpdatedIncrementally = true; - } - - // check description - if (! EqualsHelper.nullSafeEquals(getDescription(), conDef.getDescription(), false)) - { - isUpdatedIncrementally = true; - } - - // check type string - if (! EqualsHelper.nullSafeEquals(getConstraint().getType(), conDef.getConstraint().getType())) - { - isUpdated = true; - } - - if (isUpdated) - { - modelDiff = new M2ModelDiff(name, M2ModelDiff.TYPE_CONSTRAINT, M2ModelDiff.DIFF_UPDATED); - } - else if (isUpdatedIncrementally) - { - modelDiff = new M2ModelDiff(name, M2ModelDiff.TYPE_CONSTRAINT, M2ModelDiff.DIFF_UPDATED_INC); - } - else - { - modelDiff = new M2ModelDiff(name, M2ModelDiff.TYPE_CONSTRAINT, M2ModelDiff.DIFF_UNCHANGED); - } - - return modelDiff; - } - - /*package*/ static Collection diffConstraintLists(Collection previousConstraints, Collection newConstraints) - { - List modelDiffs = new ArrayList(); - - for (ConstraintDefinition previousConstraint : previousConstraints) - { - boolean found = false; - for (ConstraintDefinition newConstraint : newConstraints) - { - if (newConstraint.getName().equals(previousConstraint.getName())) - { - modelDiffs.add(((M2ConstraintDefinition)previousConstraint).diffConstraint(previousConstraint)); - found = true; - break; - } - } - - if (! found) - { - modelDiffs.add(new M2ModelDiff(previousConstraint.getName(), M2ModelDiff.TYPE_CONSTRAINT, M2ModelDiff.DIFF_DELETED)); - } - } - - for (ConstraintDefinition newConstraint : newConstraints) - { - boolean found = false; - for (ConstraintDefinition previousConstraint : previousConstraints) - { - if (newConstraint.getName().equals(previousConstraint.getName())) - { - found = true; - break; - } - } - - if (! found) - { - modelDiffs.add(new M2ModelDiff(newConstraint.getName(), M2ModelDiff.TYPE_CONSTRAINT, M2ModelDiff.DIFF_CREATED)); - } - } - - return modelDiffs; - } -} diff --git a/source/java/org/alfresco/repo/dictionary/M2DataType.java b/source/java/org/alfresco/repo/dictionary/M2DataType.java deleted file mode 100644 index d5248331a0..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2DataType.java +++ /dev/null @@ -1,102 +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.dictionary; - - -/** - * Property Type Definition - * - * @author David Caruana - * - */ -public class M2DataType -{ - private String name = null; - private String title = null; - private String description = null; - private String analyserClassName = null; - private String javaClassName = null; - - - /*package*/ M2DataType() - { - super(); - } - - - public String getName() - { - return name; - } - - - public void setName(String name) - { - this.name = name; - } - - - public String getTitle() - { - return title; - } - - - public void setTitle(String title) - { - this.title = title; - } - - - public String getDescription() - { - return description; - } - - - public void setDescription(String description) - { - this.description = description; - } - - - public String getAnalyserClassName() - { - return analyserClassName; - } - - - public void setAnalyserClassName(String analyserClassName) - { - this.analyserClassName = analyserClassName;; - } - - - public String getJavaClassName() - { - return javaClassName; - } - - - public void setJavaClassName(String javaClassName) - { - this.javaClassName = javaClassName;; - } - -} diff --git a/source/java/org/alfresco/repo/dictionary/M2DataTypeDefinition.java b/source/java/org/alfresco/repo/dictionary/M2DataTypeDefinition.java deleted file mode 100644 index 1df59f90d8..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2DataTypeDefinition.java +++ /dev/null @@ -1,157 +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.dictionary; - -import java.util.Locale; - -import org.springframework.extensions.surf.util.I18NUtil; -import org.alfresco.service.cmr.dictionary.DictionaryException; -import org.alfresco.service.cmr.dictionary.DataTypeDefinition; -import org.alfresco.service.cmr.dictionary.ModelDefinition; -import org.alfresco.service.namespace.NamespacePrefixResolver; -import org.alfresco.service.namespace.QName; - - -/** - * Compiled Property Type Definition - * - * @author David Caruana - * - */ -/*package*/ class M2DataTypeDefinition implements DataTypeDefinition -{ - private ModelDefinition model; - private QName name; - private M2DataType dataType; - - - /*package*/ M2DataTypeDefinition(ModelDefinition model, M2DataType propertyType, NamespacePrefixResolver resolver) - { - this.model = model; - this.name = QName.createQName(propertyType.getName(), resolver); - if (!model.isNamespaceDefined(name.getNamespaceURI())) - { - throw new DictionaryException("Cannot define data type " + name.toPrefixString() + " as namespace " + name.getNamespaceURI() + " is not defined by model " + model.getName().toPrefixString()); - } - this.dataType = propertyType; - } - - - /*package*/ void resolveDependencies(ModelQuery query) - { - // Ensure java class has been specified - String javaClass = dataType.getJavaClassName(); - if (javaClass == null) - { - throw new DictionaryException("Java class of data type " + name.toPrefixString() + " must be specified"); - } - - // Ensure java class is valid and referenceable - try - { - Class.forName(javaClass); - } - catch (ClassNotFoundException e) - { - throw new DictionaryException("Java class " + javaClass + " of data type " + name.toPrefixString() + " is invalid", e); - } - } - - /** - * @see #getName() - */ - public String toString() - { - return getName().toString(); - } - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.DataTypeDefinition#getModel() - */ - public ModelDefinition getModel() - { - return model; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.PropertyTypeDefinition#getName() - */ - public QName getName() - { - return name; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.PropertyTypeDefinition#getTitle() - */ - public String getTitle() - { - String value = M2Label.getLabel(model, "datatype", name, "title"); - if (value == null) - { - value = dataType.getTitle(); - } - return value; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.PropertyTypeDefinition#getDescription() - */ - public String getDescription() - { - String value = M2Label.getLabel(model, "datatype", name, "description"); - if (value == null) - { - value = dataType.getDescription(); - } - return value; - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.PropertyTypeDefinition#getAnalyserClassName() - */ - public String getAnalyserClassName() - { - return getAnalyserClassName(I18NUtil.getLocale()); - } - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.DataTypeDefinition#getAnalyserClassName(java.util.Locale) - */ - public String getAnalyserClassName(Locale locale) - { - String value = M2Label.getLabel(locale, model, "datatype", name, "analyzer"); - if (value == null) - { - value = dataType.getAnalyserClassName(); - } - return value; - } - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.PropertyTypeDefinition#getJavaClassName() - */ - public String getJavaClassName() - { - return dataType.getJavaClassName(); - } - -} diff --git a/source/java/org/alfresco/repo/dictionary/M2Label.java b/source/java/org/alfresco/repo/dictionary/M2Label.java deleted file mode 100644 index 69e9cbe39e..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2Label.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.dictionary; - -import java.util.Locale; - -import org.springframework.extensions.surf.util.I18NUtil; -import org.alfresco.service.cmr.dictionary.ModelDefinition; -import org.alfresco.service.namespace.QName; -import org.springframework.util.StringUtils; - - -/** - * Helper for obtaining display labels for data dictionary items - * - * @author David Caruana - */ -public class M2Label -{ - - /** - * Get label for data dictionary item given specified locale - * - * @param locale - * @param model - * @param type - * @param item - * @param label - * @return - */ - public static String getLabel(Locale locale, ModelDefinition model, String type, QName item, String label) - { - String key = model.getName().toPrefixString(); - if (type != null) - { - key += "." + type; - } - if (item != null) - { - key += "." + item.toPrefixString(); - } - key += "." + label; - key = StringUtils.replace(key, ":", "_"); - return I18NUtil.getMessage(key, locale); - } - - /** - * Get label for data dictionary item - * - * @param model - * @param type - * @param item - * @param label - * @return - */ - public static String getLabel(ModelDefinition model, String type, QName item, String label) - { - return getLabel(I18NUtil.getLocale(), model, type, item, label); - } - -} diff --git a/source/java/org/alfresco/repo/dictionary/M2Model.java b/source/java/org/alfresco/repo/dictionary/M2Model.java deleted file mode 100644 index dd8469ec24..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2Model.java +++ /dev/null @@ -1,426 +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.dictionary; - -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.List; - -import org.alfresco.service.cmr.dictionary.DictionaryException; -import org.jibx.runtime.BindingDirectory; -import org.jibx.runtime.IBindingFactory; -import org.jibx.runtime.IMarshallingContext; -import org.jibx.runtime.IUnmarshallingContext; -import org.jibx.runtime.JiBXException; - - -/** - * Model Definition. - * - * @author David Caruana - * - */ -public class M2Model -{ - private String name = null; - private String description = null; - private String author = null; - private Date published = null; - private String version; - - private List namespaces = new ArrayList(); - private List imports = new ArrayList(); - private List dataTypes = new ArrayList(); - private List types = new ArrayList(); - private List aspects = new ArrayList(); - private List constraints = new ArrayList(); - - private M2Model() - { - } - - - /** - * Construct an empty model - * - * @param name the name of the model - * @return the model - */ - public static M2Model createModel(String name) - { - M2Model model = new M2Model(); - model.name = name; - return model; - } - - - /** - * Construct a model from a dictionary xml specification - * - * @param xml the dictionary xml - * @return the model representation of the xml - */ - public static M2Model createModel(InputStream xml) - { - try - { - IBindingFactory factory = BindingDirectory.getFactory(M2Model.class); - IUnmarshallingContext context = factory.createUnmarshallingContext(); - Object obj = context.unmarshalDocument(xml, null); - return (M2Model)obj; - } - catch(JiBXException e) - { - throw new DictionaryException("Failed to parse model", e); - } - } - - - /** - * Render the model to dictionary XML - * - * @param xml the dictionary xml representation of the model - */ - public void toXML(OutputStream xml) - { - try - { - IBindingFactory factory = BindingDirectory.getFactory(M2Model.class); - IMarshallingContext context = factory.createMarshallingContext(); - context.setIndent(4); - context.marshalDocument(this, "UTF-8", null, xml); - } - catch(JiBXException e) - { - throw new DictionaryException("Failed to create M2 Model", e); - } - } - - - /** - * Create a compiled form of this model - * - * @param dictionaryDAO dictionary DAO - * @param namespaceDAO namespace DAO - * @return the compiled form of the model - */ - /*package*/ CompiledModel compile(DictionaryDAO dictionaryDAO, NamespaceDAO namespaceDAO) - { - CompiledModel compiledModel = new CompiledModel(this, dictionaryDAO, namespaceDAO); - return compiledModel; - } - - - public String getName() - { - return name; - } - - - public void setName(String name) - { - this.name = name; - } - - - public String getDescription() - { - return description; - } - - - public void setDescription(String description) - { - this.description = description; - } - - - public String getAuthor() - { - return author; - } - - - public void setAuthor(String author) - { - this.author = author; - } - - - public Date getPublishedDate() - { - return published; - } - - - public void setPublishedDate(Date published) - { - this.published = published; - } - - - public String getVersion() - { - return version; - } - - - public void setVersion(String version) - { - this.version = version; - } - - - public M2Type createType(String name) - { - M2Type type = new M2Type(); - type.setName(name); - types.add(type); - return type; - } - - - public void removeType(String name) - { - M2Type type = getType(name); - if (type != null) - { - types.remove(type); - } - } - - - public List getTypes() - { - return Collections.unmodifiableList(types); - } - - - public M2Type getType(String name) - { - for (M2Type candidate : types) - { - if (candidate.getName().equals(name)) - { - return candidate; - } - } - return null; - } - - - public M2Aspect createAspect(String name) - { - M2Aspect aspect = new M2Aspect(); - aspect.setName(name); - aspects.add(aspect); - return aspect; - } - - - public void removeAspect(String name) - { - M2Aspect aspect = getAspect(name); - if (aspect != null) - { - aspects.remove(name); - } - } - - - public List getAspects() - { - return Collections.unmodifiableList(aspects); - } - - - public M2Aspect getAspect(String name) - { - for (M2Aspect candidate : aspects) - { - if (candidate.getName().equals(name)) - { - return candidate; - } - } - return null; - } - - - public M2DataType createPropertyType(String name) - { - M2DataType type = new M2DataType(); - type.setName(name); - dataTypes.add(type); - return type; - } - - - public void removePropertyType(String name) - { - M2DataType type = getPropertyType(name); - if (type != null) - { - dataTypes.remove(name); - } - } - - - public List getPropertyTypes() - { - return Collections.unmodifiableList(dataTypes); - } - - - public M2DataType getPropertyType(String name) - { - for (M2DataType candidate : dataTypes) - { - if (candidate.getName().equals(name)) - { - return candidate; - } - } - return null; - } - - - public M2Namespace createNamespace(String uri, String prefix) - { - M2Namespace namespace = new M2Namespace(); - namespace.setUri(uri); - namespace.setPrefix(prefix); - namespaces.add(namespace); - return namespace; - } - - - public void removeNamespace(String uri) - { - M2Namespace namespace = getNamespace(uri); - if (namespace != null) - { - namespaces.remove(namespace); - } - } - - - public List getNamespaces() - { - return Collections.unmodifiableList(namespaces); - } - - - public M2Namespace getNamespace(String uri) - { - for (M2Namespace candidate : namespaces) - { - if (candidate.getUri().equals(uri)) - { - return candidate; - } - } - return null; - } - - - public M2Namespace createImport(String uri, String prefix) - { - M2Namespace namespace = new M2Namespace(); - namespace.setUri(uri); - namespace.setPrefix(prefix); - imports.add(namespace); - return namespace; - } - - - public void removeImport(String uri) - { - M2Namespace namespace = getImport(uri); - if (namespace != null) - { - imports.remove(namespace); - } - } - - - public List getImports() - { - return Collections.unmodifiableList(imports); - } - - - public M2Namespace getImport(String uri) - { - for (M2Namespace candidate : imports) - { - if (candidate.getUri().equals(uri)) - { - return candidate; - } - } - return null; - } - - public List getConstraints() - { - return Collections.unmodifiableList(constraints); - } - - public M2Constraint getConstraint(String name) - { - for (M2Constraint candidate : constraints) - { - if (candidate.getName().equals(name)) - { - return candidate; - } - } - return null; - } - - public M2Constraint createConstraint(String name, String type) - { - M2Constraint constraint = new M2Constraint(); - constraint.setName(name); - constraint.setType(type); - constraints.add(constraint); - return constraint; - } - - public void removeConstraint(String name) - { - M2Constraint constraint = getConstraint(name); - if (constraint != null) - { - constraints.remove(name); - } - } - - // Do not delete: referenced by m2binding.xml - @SuppressWarnings("unused") - private static List createList() - { - return new ArrayList(); - } - -} diff --git a/source/java/org/alfresco/repo/dictionary/M2ModelDefinition.java b/source/java/org/alfresco/repo/dictionary/M2ModelDefinition.java deleted file mode 100644 index f2317f93b0..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2ModelDefinition.java +++ /dev/null @@ -1,154 +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.dictionary; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.List; - -import org.alfresco.service.cmr.dictionary.ModelDefinition; -import org.alfresco.service.cmr.dictionary.NamespaceDefinition; -import org.alfresco.service.namespace.NamespacePrefixResolver; -import org.alfresco.service.namespace.QName; - -/** - * Compiled Model Definition - * - * @author David Caruana - * - */ -public class M2ModelDefinition implements ModelDefinition -{ - private QName name; - private M2Model model; - - - /*package*/ M2ModelDefinition(M2Model model, NamespacePrefixResolver resolver) - { - this.name = QName.createQName(model.getName(), resolver); - this.model = model; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ModelDefinition#getName() - */ - public QName getName() - { - return name; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ModelDefinition#getDescription() - */ - public String getDescription() - { - String value = M2Label.getLabel(this, null, null, "description"); - if (value == null) - { - value = model.getDescription(); - } - return value; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ModelDefinition#getAuthor() - */ - public String getAuthor() - { - return model.getAuthor(); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ModelDefinition#getPublishedDate() - */ - public Date getPublishedDate() - { - return model.getPublishedDate(); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.ModelDefinition#getVersion() - */ - public String getVersion() - { - return model.getVersion(); - } - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.ModelDefinition#getNamespaces() - */ - public Collection getNamespaces() - { - List namespaces = new ArrayList(); - for (M2Namespace namespace : model.getNamespaces()) - { - namespaces.add(new M2NamespaceDefinition(this, namespace.getUri(), namespace.getPrefix())); - } - return namespaces; - } - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.ModelDefinition#isNamespaceDefined(java.lang.String) - */ - public boolean isNamespaceDefined(String uri) - { - for (M2Namespace namespace : model.getNamespaces()) - { - if (namespace.getUri().equals(uri)) - { - return true; - } - } - return false; - } - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.ModelDefinition#getImportedNamespaces() - */ - public Collection getImportedNamespaces() - { - List namespaces = new ArrayList(); - for (M2Namespace namespace : model.getImports()) - { - namespaces.add(new M2NamespaceDefinition(this, namespace.getUri(), namespace.getPrefix())); - } - return namespaces; - } - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.ModelDefinition#isNamespaceImported(java.lang.String) - */ - public boolean isNamespaceImported(String uri) - { - for (M2Namespace namespace : model.getImports()) - { - if (namespace.getUri().equals(uri)) - { - return true; - } - } - return false; - } -} diff --git a/source/java/org/alfresco/repo/dictionary/M2ModelDiff.java b/source/java/org/alfresco/repo/dictionary/M2ModelDiff.java deleted file mode 100644 index 1f3a1036e0..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2ModelDiff.java +++ /dev/null @@ -1,101 +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.dictionary; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.service.namespace.QName; -import org.springframework.extensions.surf.util.ParameterCheck; - -/** - * Compiled Model Difference - * - * @author JanV - * - */ -public class M2ModelDiff -{ - public static final String DIFF_CREATED = "created"; - public static final String DIFF_UPDATED = "updated"; - public static final String DIFF_UPDATED_INC = "updated_inc"; // incremental update - public static final String DIFF_DELETED = "deleted"; - public static final String DIFF_UNCHANGED = "unchanged"; - - public static final String TYPE_TYPE = "TYPE"; - public static final String TYPE_ASPECT = "ASPECT"; - public static final String TYPE_DEFAULT_ASPECT = "DEFAULT_ASPECT"; - public static final String TYPE_PROPERTY = "PROPERTY"; - public static final String TYPE_ASSOCIATION = "ASSOCIATION"; - public static final String TYPE_CONSTRAINT = "TYPE_CONSTRAINT"; - - private QName elementName; - private String elementType; - private String diffType; - - public M2ModelDiff(QName elementName, String elementType, String diffType) - { - // Check that all the passed values are not null - ParameterCheck.mandatory("elementName", elementName); - ParameterCheck.mandatoryString("elementType", elementType); - ParameterCheck.mandatoryString("diffType", diffType); - - if ((!elementType.equals(TYPE_TYPE)) && - (!elementType.equals(TYPE_ASPECT)) && - (!elementType.equals(TYPE_DEFAULT_ASPECT)) && - (!elementType.equals(TYPE_PROPERTY)) && - (!elementType.equals(TYPE_ASSOCIATION)) && - (!elementType.equals(TYPE_CONSTRAINT)) - ) - { - throw new AlfrescoRuntimeException("Unknown element type = " + elementType); - } - - if ((! diffType.equals(DIFF_CREATED)) && - (! diffType.equals(DIFF_UPDATED)) && - (! diffType.equals(DIFF_UPDATED_INC)) && - (! diffType.equals(DIFF_DELETED)) && - (! diffType.equals(DIFF_UNCHANGED))) - { - throw new AlfrescoRuntimeException("Unknown diff type = " + diffType); - } - - this.elementName = elementName; - this.elementType = elementType; - this.diffType = diffType; - } - - public QName getElementName() - { - return elementName; - } - - public String getElementType() - { - return elementType; - } - - public String getDiffType() - { - return diffType; - } - - public String toString() - { - return new String(elementType + " " + elementName + " " + diffType); - } - } \ No newline at end of file diff --git a/source/java/org/alfresco/repo/dictionary/M2NamedValue.java b/source/java/org/alfresco/repo/dictionary/M2NamedValue.java deleted file mode 100644 index d5544a0d63..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2NamedValue.java +++ /dev/null @@ -1,91 +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.dictionary; - -import java.util.List; - -/** - * Definition of a named value that can be used for property injection. - * - * @author Derek Hulley - */ -public class M2NamedValue -{ - private String name; - private String simpleValue = null; - private List listValue = null; - - /*package*/ M2NamedValue() - { - } - - - @Override - public String toString() - { - return (name + "=" + (simpleValue == null ? listValue : simpleValue)); - } - - public String getName() - { - return name; - } - - /** - * @return Returns the raw, unconverted value - */ - public String getSimpleValue() - { - return simpleValue; - } - - /** - * @return Returns the list of raw, unconverted values - */ - public List getListValue() - { - return listValue; - } - - public void setName(String name) - { - this.name = name; - } - - public void setSimpleValue(String simpleValue) - { - this.simpleValue = simpleValue; - } - - public void setListValue(List listValue) - { - this.listValue = listValue; - } - - public boolean hasSimpleValue() - { - return (this.simpleValue != null); - } - - public boolean hasListValue() - { - return (this.listValue != null); - } - -} diff --git a/source/java/org/alfresco/repo/dictionary/M2Namespace.java b/source/java/org/alfresco/repo/dictionary/M2Namespace.java deleted file mode 100644 index 5f383a2c97..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2Namespace.java +++ /dev/null @@ -1,62 +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.dictionary; - - -/** - * Namespace Definition. - * - * @author David Caruana - * - */ -public class M2Namespace -{ - private String uri = null; - private String prefix = null; - - - /*package*/ M2Namespace() - { - } - - - public String getUri() - { - return uri; - } - - - public void setUri(String uri) - { - this.uri = uri; - } - - - public String getPrefix() - { - return prefix; - } - - - public void setPrefix(String prefix) - { - this.prefix = prefix; - } - -} diff --git a/source/java/org/alfresco/repo/dictionary/M2NamespaceDefinition.java b/source/java/org/alfresco/repo/dictionary/M2NamespaceDefinition.java deleted file mode 100644 index e19e349458..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2NamespaceDefinition.java +++ /dev/null @@ -1,58 +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.dictionary; - -import org.alfresco.service.cmr.dictionary.ModelDefinition; -import org.alfresco.service.cmr.dictionary.NamespaceDefinition; - - -/** - * Namespace Definition. - * - * - */ -public class M2NamespaceDefinition implements NamespaceDefinition -{ - ModelDefinition model = null; - private String uri = null; - private String prefix = null; - - - /*package*/ M2NamespaceDefinition(ModelDefinition model, String uri, String prefix) - { - this.model = model; - this.uri = uri; - this.prefix = prefix; - } - - public ModelDefinition getModel() - { - return model; - } - - public String getUri() - { - return uri; - } - - public String getPrefix() - { - return prefix; - } -} diff --git a/source/java/org/alfresco/repo/dictionary/M2Property.java b/source/java/org/alfresco/repo/dictionary/M2Property.java deleted file mode 100644 index 632b42ebfa..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2Property.java +++ /dev/null @@ -1,259 +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.dictionary; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - - -/** - * Property Definition - * - * @author David Caruana - * - */ -public class M2Property -{ - private boolean isOverride = false; - private String name = null; - private String title = null; - private String description = null; - private String propertyType = null; - private boolean isProtected = false; - private boolean isMandatory = false; - private boolean isMandatoryEnforced = false; - private boolean isMultiValued = false; - private String defaultValue = null; - private Boolean isIndexed = Boolean.TRUE; - private Boolean isIndexedAtomically = null; - private Boolean isStoredInIndex = null; - private IndexTokenisationMode indexTokenisationMode = null; - private List constraints = new ArrayList(); - - /*package*/ M2Property() - { - } - - - /*package*/ M2Property(String name) - { - this.name = name; - } - - public boolean isOverride() - { - return isOverride; - } - - public void setOverride(boolean isOverride) - { - this.isOverride = isOverride; - } - - public String getName() - { - return name; - } - - - public void setName(String name) - { - this.name = name; - } - - - public String getTitle() - { - return title; - } - - - public void setTitle(String title) - { - this.title = title; - } - - - public String getDescription() - { - return description; - } - - - public void setDescription(String description) - { - this.description = description; - } - - - public String getType() - { - return propertyType; - } - - - public void setType(String type) - { - this.propertyType = type; - } - - - public boolean isProtected() - { - return isProtected; - } - - - public void setProtected(boolean isProtected) - { - this.isProtected = isProtected; - } - - - public boolean isMandatory() - { - return isMandatory; - } - - public void setMandatory(boolean isMandatory) - { - this.isMandatory = isMandatory; - } - - public boolean isMandatoryEnforced() - { - return isMandatoryEnforced; - } - - public void setMandatoryEnforced(boolean isMandatoryEnforced) - { - this.isMandatoryEnforced = isMandatoryEnforced; - } - - public boolean isMultiValued() - { - return isMultiValued; - } - - - public void setMultiValued(boolean isMultiValued) - { - this.isMultiValued = isMultiValued; - } - - - public String getDefaultValue() - { - return defaultValue; - } - - - public void setDefaultValue(String defaultValue) - { - this.defaultValue = defaultValue; - } - - - public Boolean isIndexed() - { - return isIndexed; - } - - - public void setIndexed(boolean isIndexed) - { - this.isIndexed = Boolean.valueOf(isIndexed); - } - - - public Boolean isStoredInIndex() - { - return isStoredInIndex; - } - - - public void setStoredInIndex(boolean isStoredInIndex) - { - this.isStoredInIndex = Boolean.valueOf(isStoredInIndex); - } - - - public Boolean isIndexedAtomically() - { - return isIndexedAtomically; - } - - - public void setIndexedAtomically(boolean isIndexedAtomically) - { - this.isIndexedAtomically = Boolean.valueOf(isIndexedAtomically); - } - - - public IndexTokenisationMode getIndexTokenisationMode() - { - return indexTokenisationMode; - } - - - public void setIndexTokenisationMode(IndexTokenisationMode indexTokenisationMode) - { - this.indexTokenisationMode = indexTokenisationMode; - } - - - public List getConstraints() - { - if (constraints == null) - { - return Collections.emptyList(); - } - else - { - return constraints; - } - } - - public boolean hasConstraints() - { - return ((this.constraints != null) && (constraints.size() > 0)); - } - - public M2Constraint addConstraintRef(String refName) - { - M2Constraint constraint = new M2Constraint(); - constraint.setRef(refName); - constraints.add(constraint); - return constraint; - } - - - public void removeConstraintRef(String refName) - { - List cons = new ArrayList(getConstraints()); - for (M2Constraint con : cons) - { - if (con.getRef().equals(refName)) - { - constraints.remove(con); - } - } - } -} diff --git a/source/java/org/alfresco/repo/dictionary/M2PropertyDefinition.java b/source/java/org/alfresco/repo/dictionary/M2PropertyDefinition.java deleted file mode 100644 index 9478264aa1..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2PropertyDefinition.java +++ /dev/null @@ -1,596 +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.dictionary; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.alfresco.service.cmr.dictionary.ClassDefinition; -import org.alfresco.service.cmr.dictionary.ConstraintDefinition; -import org.alfresco.service.cmr.dictionary.DataTypeDefinition; -import org.alfresco.service.cmr.dictionary.DictionaryException; -import org.alfresco.service.cmr.dictionary.ModelDefinition; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.namespace.NamespacePrefixResolver; -import org.alfresco.service.namespace.QName; -import org.alfresco.util.EqualsHelper; - - -/** - * Compiled Property Definition - * - * @author David Caruana - */ -/*package*/ class M2PropertyDefinition implements PropertyDefinition -{ - private ClassDefinition classDef; - private M2Property m2Property; - private QName name; - private QName propertyTypeName; - private DataTypeDefinition dataType; - private List constraintDefs = Collections.emptyList(); - - /*package*/ M2PropertyDefinition( - ClassDefinition classDef, - M2Property m2Property, - NamespacePrefixResolver prefixResolver) - { - this.classDef = classDef; - this.m2Property = m2Property; - - // Resolve Names - this.name = QName.createQName(m2Property.getName(), prefixResolver); - this.propertyTypeName = QName.createQName(m2Property.getType(), prefixResolver); - } - - - /*package*/ M2PropertyDefinition( - ClassDefinition classDef, - PropertyDefinition propertyDef, - M2PropertyOverride override, - NamespacePrefixResolver prefixResolver, - Map modelConstraints) - { - this.classDef = classDef; - this.m2Property = createOverriddenProperty(propertyDef, override, prefixResolver, modelConstraints); - this.name = propertyDef.getName(); - this.dataType = propertyDef.getDataType(); - this.propertyTypeName = this.dataType.getName(); - } - - - /*package*/ void resolveDependencies( - ModelQuery query, - NamespacePrefixResolver prefixResolver, - Map modelConstraints) - { - if (propertyTypeName == null) - { - throw new DictionaryException( - "d_dictionary.property.err.property_type_not_specified", - name.toPrefixString()); - } - dataType = query.getDataType(propertyTypeName); - if (dataType == null) - { - throw new DictionaryException( - "d_dictionary.property.err.property_type_not_found", - propertyTypeName.toPrefixString(), name.toPrefixString()); - } - - // ensure content properties are not multi-valued - if (propertyTypeName.equals(DataTypeDefinition.CONTENT) && isMultiValued()) - { - throw new DictionaryException("d_dictionary.property.err.single_valued_content"); - } - - // Construct constraints - constraintDefs = buildConstraints( - m2Property.getConstraints(), - this, - prefixResolver, - modelConstraints); - } - - private static List buildConstraints( - List m2constraints, - M2PropertyDefinition m2PropertyDef, - NamespacePrefixResolver prefixResolver, - Map modelConstraints) - { - List constraints = new ArrayList(5); - Map constraintsByQName = new HashMap(7); - for (M2Constraint constraint : m2constraints) - { - ConstraintDefinition def = new M2ConstraintDefinition(m2PropertyDef, constraint, prefixResolver); - QName qname = def.getName(); - if (constraintsByQName.containsKey(qname)) - { - throw new DictionaryException( - "d_dictionary.property.err.duplicate_constraint_on_property", - def.getName().toPrefixString(), m2PropertyDef.name.toPrefixString()); - } - else if (modelConstraints.containsKey(qname)) - { - throw new DictionaryException( - "d_dictionary.model.err.duplicate_constraint_on_model", - def.getName().toPrefixString()); - } - constraintsByQName.put(qname, def); - constraints.add(def); - modelConstraints.put(qname, def); - } - // done - return constraints; - } - - /** - * Create a property definition whose values are overridden - * - * @param propertyDef the property definition to override - * @param override the overridden values - * @return the property definition - */ - private M2Property createOverriddenProperty( - PropertyDefinition propertyDef, - M2PropertyOverride override, - NamespacePrefixResolver prefixResolver, - Map modelConstraints) - { - M2Property property = new M2Property(); - property.setOverride(true); - - // Process Default Value - String defaultValue = override.getDefaultValue(); - property.setDefaultValue(defaultValue == null ? propertyDef.getDefaultValue() : defaultValue); - - // Process Mandatory Value - Boolean isOverrideMandatory = override.isMandatory(); - boolean isOverrideMandatoryEnforced = override.isMandatoryEnforced(); - if (isOverrideMandatory != null && propertyDef.isMandatory()) - { - // the override specified whether the property should be mandatory or not - // check that the mandatory enforcement is not relaxed - if (!isOverrideMandatory) - { - throw new DictionaryException( - "d_dictionary.property.err.cannot_relax_mandatory", - propertyDef.getName().toPrefixString()); - } - else if (!isOverrideMandatoryEnforced && propertyDef.isMandatoryEnforced()) - { - throw new DictionaryException( - "d_dictionary.property.err.cannot_relax_mandatory_enforcement", - propertyDef.getName().toPrefixString()); - } - } - property.setMandatory(isOverrideMandatory == null ? propertyDef.isMandatory() : isOverrideMandatory); - property.setMandatoryEnforced(isOverrideMandatoryEnforced); - - // inherit or override constraints - List overrideConstraints = override.getConstraints(); - if (overrideConstraints != null) - { - constraintDefs = buildConstraints( - overrideConstraints, - (M2PropertyDefinition) propertyDef, - prefixResolver, - modelConstraints); - } - else - { - this.constraintDefs = propertyDef.getConstraints(); - } - - // Copy all other properties as they are - property.setDescription(propertyDef.getDescription()); - property.setIndexed(propertyDef.isIndexed()); - property.setIndexedAtomically(propertyDef.isIndexedAtomically()); - property.setMultiValued(propertyDef.isMultiValued()); - property.setProtected(propertyDef.isProtected()); - property.setStoredInIndex(propertyDef.isStoredInIndex()); - property.setTitle(propertyDef.getTitle()); - property.setIndexTokenisationMode(propertyDef.getIndexTokenisationMode()); - - return property; - } - - /** - * @see #getName() - */ - @Override - public String toString() - { - StringBuffer sb = new StringBuffer(); - sb.append("Name: " + getName() + "\n"); - sb.append("Title: " + getTitle() + "\n"); - sb.append("Description: " + getDescription() + "\n"); - sb.append("Default Value: " + getDefaultValue() + "\n"); - sb.append("DataType Name: " + getDataType().getName() + "\n"); - sb.append("ContainerClass Name: " + getContainerClass().getName() + "\n"); - sb.append("isMultiValued: " + isMultiValued() + "\n"); - sb.append("isMandatory: " + isMandatory() + "\n"); - sb.append("isMandatoryEnforced: " + isMandatoryEnforced() + "\n"); - sb.append("isProtected: " + isProtected() + "\n"); - sb.append("isIndexed: " + isIndexed() + "\n"); - sb.append("isStoredInIndex: " + isStoredInIndex() + "\n"); - sb.append("isIndexedAtomically: " + isIndexedAtomically() + "\n"); - sb.append("indexTokenisationMode: " + getIndexTokenisationMode() + "\n"); - - return sb.toString(); - } - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.PropertyDefinition#getModel() - */ - public ModelDefinition getModel() - { - return classDef.getModel(); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.PropertyDefinition#getName() - */ - public QName getName() - { - return name; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.PropertyDefinition#getTitle() - */ - public String getTitle() - { - String value = M2Label.getLabel(classDef.getModel(), "property", name, "title"); - if (value == null) - { - value = m2Property.getTitle(); - } - return value; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.PropertyDefinition#getDescription() - */ - public String getDescription() - { - String value = M2Label.getLabel(classDef.getModel(), "property", name, "description"); - if (value == null) - { - value = m2Property.getDescription(); - } - return value; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.PropertyDefinition#getDefaultValue() - */ - public String getDefaultValue() - { - return m2Property.getDefaultValue(); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.PropertyDefinition#getPropertyType() - */ - public DataTypeDefinition getDataType() - { - return dataType; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.PropertyDefinition#getContainerClass() - */ - public ClassDefinition getContainerClass() - { - return classDef; - } - - /* - * (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.PropertyDefinition#isOverride() - */ - public boolean isOverride() - { - return m2Property.isOverride(); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.PropertyDefinition#isMultiValued() - */ - public boolean isMultiValued() - { - return m2Property.isMultiValued(); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.PropertyDefinition#isMandatory() - */ - public boolean isMandatory() - { - return m2Property.isMandatory(); - } - - public boolean isMandatoryEnforced() - { - return m2Property.isMandatoryEnforced(); - } - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.PropertyDefinition#isProtected() - */ - public boolean isProtected() - { - return m2Property.isProtected(); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.PropertyDefinition#isIndexed() - */ - public boolean isIndexed() - { - if(m2Property.isIndexed() == null) - { - return true; - } - else - { - return m2Property.isIndexed(); - } - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.PropertyDefinition#isStoredInIndex() - */ - public boolean isStoredInIndex() - { - if(m2Property.isStoredInIndex() == null) - { - return false; - } - else - { - return m2Property.isStoredInIndex(); - } - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.PropertyDefinition#isIndexedAtomically() - */ - public boolean isIndexedAtomically() - { - if(m2Property.isIndexedAtomically() == null) - { - return true; - } - else - { - return m2Property.isIndexedAtomically(); - } - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.PropertyDefinition#isTokenisedInIndex() - */ - public IndexTokenisationMode getIndexTokenisationMode() - { - if(m2Property.getIndexTokenisationMode() == null) - { - return IndexTokenisationMode.TRUE; - } - else - { - return m2Property.getIndexTokenisationMode(); - } - } - - - /* (non-Javadoc) - * @see org.alfresco.service.cmr.dictionary.PropertyDefinition#getConstraints() - */ - public List getConstraints() - { - return constraintDefs; - } - - /* package */ M2ModelDiff diffProperty(PropertyDefinition propDef) - { - M2ModelDiff modelDiff = null; - boolean isUpdated = false; - boolean isUpdatedIncrementally = false; - - if (this == propDef) - { - modelDiff = new M2ModelDiff(name, M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_UNCHANGED); - return modelDiff; - } - - // check name - cannot be null - if (! name.equals(propDef.getName())) - { - isUpdated = true; - } - - // check title - if (! EqualsHelper.nullSafeEquals(getTitle(), propDef.getTitle(), false)) - { - isUpdatedIncrementally = true; - } - - // check description - if (! EqualsHelper.nullSafeEquals(getDescription(), propDef.getDescription(), false)) - { - isUpdatedIncrementally = true; - } - - // check default value - if (! EqualsHelper.nullSafeEquals(getDefaultValue(), propDef.getDefaultValue(), false)) - { - isUpdatedIncrementally = true; - } - - // check datatype qname (TODO check datatype defs separately) - if (! EqualsHelper.nullSafeEquals(getDataType().getName(), propDef.getDataType().getName())) - { - isUpdated = true; - } - - // check container class qname - if (! EqualsHelper.nullSafeEquals(getContainerClass().getName(), propDef.getContainerClass().getName())) - { - isUpdated = true; - } - - // check multi-valued - if (isMultiValued() != propDef.isMultiValued()) - { - isUpdated = true; - } - - // check mandatory - if (isMandatory() != propDef.isMandatory()) - { - isUpdated = true; - } - - // check mandatory enforced - if (isMandatoryEnforced() != propDef.isMandatoryEnforced()) - { - isUpdated = true; - } - - // check protected - if (isProtected() != propDef.isProtected()) - { - isUpdated = true; - } - - // - // property indexing - is index enabled -> stored, atomic, tokenized (true, false, both) - // - // - // true - // false - // both - // - // - - if (isIndexed() != propDef.isIndexed()) - { - isUpdatedIncrementally = true; - } - - if (isStoredInIndex() != propDef.isStoredInIndex()) - { - isUpdatedIncrementally = true; - } - - if (isIndexedAtomically() != propDef.isIndexedAtomically()) - { - isUpdatedIncrementally = true; - } - - if (! EqualsHelper.nullSafeEquals(getIndexTokenisationMode().toString(), propDef.getIndexTokenisationMode().toString(), false)) - { - isUpdatedIncrementally = true; - } - - - // check override - if (isOverride() != propDef.isOverride()) - { - isUpdated = true; - } - - // TODO - check prop constraints (inline and referenced) - - if (isUpdated) - { - modelDiff = new M2ModelDiff(name, M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_UPDATED); - } - else if (isUpdatedIncrementally) - { - modelDiff = new M2ModelDiff(name, M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_UPDATED_INC); - } - else - { - modelDiff = new M2ModelDiff(name, M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_UNCHANGED); - } - - return modelDiff; - } - - /*package*/ static Collection diffPropertyLists(Collection previousProperties, Collection newProperties) - { - List modelDiffs = new ArrayList(); - - for (PropertyDefinition previousProperty : previousProperties) - { - boolean found = false; - for (PropertyDefinition newProperty : newProperties) - { - if (newProperty.getName().equals(previousProperty.getName())) - { - modelDiffs.add(((M2PropertyDefinition)previousProperty).diffProperty(newProperty)); - found = true; - break; - } - } - - if (! found) - { - modelDiffs.add(new M2ModelDiff(previousProperty.getName(), M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_DELETED)); - } - } - - for (PropertyDefinition newProperty : newProperties) - { - boolean found = false; - for (PropertyDefinition previousProperty : previousProperties) - { - if (newProperty.getName().equals(previousProperty.getName())) - { - found = true; - break; - } - } - - if (! found) - { - modelDiffs.add(new M2ModelDiff(newProperty.getName(), M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_CREATED)); - } - } - - return modelDiffs; - } -} diff --git a/source/java/org/alfresco/repo/dictionary/M2PropertyOverride.java b/source/java/org/alfresco/repo/dictionary/M2PropertyOverride.java deleted file mode 100644 index d9c90d4e2d..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2PropertyOverride.java +++ /dev/null @@ -1,86 +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.dictionary; - -import java.util.List; - - -/** - * Property override definition - * - * @author David Caruana - * - */ -public class M2PropertyOverride -{ - private String name; - private Boolean isMandatory; - private boolean isMandatoryEnforced = false; - private String defaultValue; - private List constraints; - - /*package*/ M2PropertyOverride() - { - } - - - public String getName() - { - return name; - } - - - public void setName(String name) - { - this.name = name; - } - - - public Boolean isMandatory() - { - return isMandatory; - } - - - public void setMandatory(Boolean isMandatory) - { - this.isMandatory = isMandatory; - } - - public boolean isMandatoryEnforced() - { - return isMandatoryEnforced; - } - - public String getDefaultValue() - { - return defaultValue; - } - - - public void setDefaultValue(String defaultValue) - { - this.defaultValue = defaultValue; - } - - public List getConstraints() - { - return constraints; - } -} diff --git a/source/java/org/alfresco/repo/dictionary/M2Type.java b/source/java/org/alfresco/repo/dictionary/M2Type.java deleted file mode 100644 index 802e32dde0..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2Type.java +++ /dev/null @@ -1,34 +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.dictionary; - - -/** - * Type Definition - * - * @author David Caruana - * - */ -public class M2Type extends M2Class -{ - /*package*/ M2Type() - { - super(); - } -} diff --git a/source/java/org/alfresco/repo/dictionary/M2TypeDefinition.java b/source/java/org/alfresco/repo/dictionary/M2TypeDefinition.java deleted file mode 100644 index 6160d26938..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2TypeDefinition.java +++ /dev/null @@ -1,71 +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.dictionary; - -import java.util.Map; - -import org.alfresco.service.cmr.dictionary.AssociationDefinition; -import org.alfresco.service.cmr.dictionary.ModelDefinition; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.cmr.dictionary.TypeDefinition; -import org.alfresco.service.namespace.NamespacePrefixResolver; -import org.alfresco.service.namespace.QName; - - -/** - * Compiled Type Definition - * - * @author David Caruana - */ -/*package*/ class M2TypeDefinition extends M2ClassDefinition - implements TypeDefinition -{ - /*package*/ M2TypeDefinition(ModelDefinition model, M2Type m2Type, NamespacePrefixResolver resolver, Map modelProperties, Map modelAssociations) - { - super(model, m2Type, resolver, modelProperties, modelAssociations); - } - - @Override - public String getDescription() - { - String value = M2Label.getLabel(model, "type", name, "description"); - - // if we don't have a description call the super class - if (value == null) - { - value = super.getDescription(); - } - - return value; - } - - @Override - public String getTitle() - { - String value = M2Label.getLabel(model, "type", name, "title"); - - // if we don't have a title call the super class - if (value == null) - { - value = super.getTitle(); - } - - return value; - } -} diff --git a/source/java/org/alfresco/repo/dictionary/M2XML.java b/source/java/org/alfresco/repo/dictionary/M2XML.java deleted file mode 100644 index c2b2364ccf..0000000000 --- a/source/java/org/alfresco/repo/dictionary/M2XML.java +++ /dev/null @@ -1,74 +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.dictionary; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; - -import org.alfresco.util.CachingDateFormat; - - -/** - * Support translating model from and to XML - * - * @author David Caruana - * - */ -public class M2XML -{ - - /** - * Convert XML date (of the form yyyy-MM-dd) to Date - * - * @param date the xml representation of the date - * @return the date - * @throws ParseException - */ - public static Date deserialiseDate(String date) - throws ParseException - { - Date xmlDate = null; - if (date != null) - { - SimpleDateFormat df = CachingDateFormat.getDateOnlyFormat(); - xmlDate = df.parse(date); - } - return xmlDate; - } - - - /** - * Convert date to XML date (of the form yyyy-MM-dd) - * - * @param date the date - * @return the xml representation of the date - */ - public static String serialiseDate(Date date) - { - String xmlDate = null; - if (date != null) - { - SimpleDateFormat df = CachingDateFormat.getDateOnlyFormat(); - xmlDate = df.format(date); - } - return xmlDate; - } - -} diff --git a/source/java/org/alfresco/repo/dictionary/ModelQuery.java b/source/java/org/alfresco/repo/dictionary/ModelQuery.java deleted file mode 100644 index 34ccf59d12..0000000000 --- a/source/java/org/alfresco/repo/dictionary/ModelQuery.java +++ /dev/null @@ -1,103 +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.dictionary; - -import org.alfresco.service.cmr.dictionary.AspectDefinition; -import org.alfresco.service.cmr.dictionary.AssociationDefinition; -import org.alfresco.service.cmr.dictionary.ClassDefinition; -import org.alfresco.service.cmr.dictionary.DataTypeDefinition; -import org.alfresco.service.cmr.dictionary.ConstraintDefinition; -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.cmr.dictionary.TypeDefinition; -import org.alfresco.service.namespace.QName; - - -/** - * Access to model items. - * - * @author David Caruana - * - */ -/*package*/ interface ModelQuery -{ - /** - * Gets the specified data type - * - * @param name name of the data type - * @return data type definition - */ - public DataTypeDefinition getDataType(QName name); - - /** - * Gets the data type for the specified Java Class - * - * @param javaClass the java class - * @return the data type definition (or null, if mapping is not available) - */ - public DataTypeDefinition getDataType(Class javaClass); - - /** - * Gets the specified type - * - * @param name name of the type - * @return type definition - */ - public TypeDefinition getType(QName name); - - /** - * Gets the specified aspect - * - * @param name name of the aspect - * @return aspect definition - */ - public AspectDefinition getAspect(QName name); - - /** - * Gets the specified class - * - * @param name name of the class - * @return class definition - */ - public ClassDefinition getClass(QName name); - - /** - * Gets the specified property - * - * @param name name of the property - * @return property definition - */ - public PropertyDefinition getProperty(QName name); - - /** - * Gets the specified property constraint - * - * @param name the qualified name of the property constraint - * @return - */ - public ConstraintDefinition getConstraint(QName name); - - /** - * Gets the specified association - * - * @param name name of the association - * @return association definition - */ - public AssociationDefinition getAssociation(QName name); - -} diff --git a/source/java/org/alfresco/repo/dictionary/NamespaceDAO.java b/source/java/org/alfresco/repo/dictionary/NamespaceDAO.java deleted file mode 100644 index 3e6b07c902..0000000000 --- a/source/java/org/alfresco/repo/dictionary/NamespaceDAO.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.dictionary; - -import org.alfresco.service.namespace.NamespacePrefixResolver; - - -/** - * Namespace DAO Interface. - * - * This DAO is responsible for retrieving and creating Namespace definitions. - * - * @author David Caruana - */ -public interface NamespaceDAO extends NamespacePrefixResolver -{ - /** - * Add a namespace URI - * - * @param uri the namespace uri to add - */ - public void addURI(String uri); - - /** - * Remove the specified URI - * - * @param uri the uri to remove - */ - public void removeURI(String uri); - - /** - * Add a namespace prefix - * - * @param prefix the prefix - * @param uri the uri to prefix - */ - public void addPrefix(String prefix, String uri); - - /** - * Remove a namspace prefix - * - * @param prefix the prefix to remove - */ - public void removePrefix(String prefix); - - /** - * Initialise Namespaces - */ - public void init(); - - public void afterDictionaryInit(); - - /** - * Destroy Namespaces - */ - public void destroy(); - - /** - * Register with the Dictionary - */ - public void registerDictionary(DictionaryDAO dictionaryDAO); -} diff --git a/source/java/org/alfresco/repo/dictionary/NamespaceDAOImpl.java b/source/java/org/alfresco/repo/dictionary/NamespaceDAOImpl.java deleted file mode 100644 index 27dbfade67..0000000000 --- a/source/java/org/alfresco/repo/dictionary/NamespaceDAOImpl.java +++ /dev/null @@ -1,616 +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.dictionary; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.repo.cache.SimpleCache; -import org.alfresco.repo.tenant.TenantService; -import org.alfresco.service.namespace.NamespaceException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Simple in-memory namespace DAO - */ -public class NamespaceDAOImpl implements NamespaceDAO, DictionaryListener -{ - private static final Log logger = LogFactory.getLog(NamespaceDAOImpl.class); - - /** - * Lock objects - */ - private ReadWriteLock lock = new ReentrantReadWriteLock(); - private Lock readLock = lock.readLock(); - private Lock writeLock = lock.writeLock(); - - // Internal cache (clusterable) - private SimpleCache namespaceRegistryCache; - - // used to reset the cache - private ThreadLocal namespaceRegistryThreadLocal = new ThreadLocal(); - private ThreadLocal defaultNamespaceRegistryThreadLocal = new ThreadLocal(); - - // Dependencies - private TenantService tenantService; - private DictionaryDAO dictionaryDAO; - - - public void setTenantService(TenantService tenantService) - { - this.tenantService = tenantService; - } - - public void setNamespaceRegistryCache(SimpleCache namespaceRegistryCache) - { - this.namespaceRegistryCache = namespaceRegistryCache; - } - - public void registerDictionary(DictionaryDAO dictionaryDAO) - { - this.dictionaryDAO = dictionaryDAO; - this.dictionaryDAO.register(this); - } - - - public void afterDictionaryDestroy() - { - // TODO Auto-generated method stub - } - - public void onDictionaryInit() - { - // TODO Auto-generated method stub - } - - /** - * Complete the initialisation - */ - public void afterDictionaryInit() - { - String tenantDomain = getTenantDomain(); - - try - { - NamespaceRegistry namespaceRegistry = getNamespaceRegistryLocal(tenantDomain); - - if (namespaceRegistry == null) - { - // unexpected - throw new AlfrescoRuntimeException("Failed to init namespaceRegistry " + tenantDomain); - } - - try - { - writeLock.lock(); - namespaceRegistryCache.put(tenantDomain, namespaceRegistry); - } - finally - { - writeLock.unlock(); - } - } - finally - { - try - { - readLock.lock(); - if (namespaceRegistryCache.get(tenantDomain) != null) - { - removeNamespaceLocal(tenantDomain); - } - } - finally - { - readLock.unlock(); - } - } - } - - - /** - * Initialise empty namespaces - */ - public void init() - { - String tenantDomain = getTenantDomain(); - NamespaceRegistry namespaceRegistry = initNamespaceRegistry(tenantDomain); - - if (namespaceRegistry == null) - { - // unexpected - throw new AlfrescoRuntimeException("Failed to init namespaceRegistry " + tenantDomain); - } - } - - /** - * Destroy the namespaces - */ - public void destroy() - { - String tenantDomain = getTenantDomain(); - - removeNamespaceRegistry(tenantDomain); - - if (logger.isTraceEnabled()) - { - logger.trace("Namespaces destroyed"); - } - } - - /** - * Resets the namespaces (by re-initialising the dictionary) - */ - private NamespaceRegistry reset(String tenantDomain) - { - if (dictionaryDAO == null) - { - // Unexpected - throw new AlfrescoRuntimeException("Dictionary should be registered in order to perform reset"); - } - - if (logger.isTraceEnabled()) - { - logger.trace("Resetting namespaces ..."); - } - - dictionaryDAO.init(); - - NamespaceRegistry namespaceRegistry = getNamespaceRegistry(tenantDomain); - - if (logger.isTraceEnabled()) - { - logger.trace("... resetting namespaces completed"); - } - - return namespaceRegistry; - } - - private NamespaceRegistry initNamespaceRegistry(String tenantDomain) - { - // create threadlocal, if needed - NamespaceRegistry namespaceRegistry = createNamespaceLocal(tenantDomain); - - namespaceRegistry.setUrisCache(new ArrayList()); - namespaceRegistry.setPrefixesCache(new HashMap()); - - if (logger.isTraceEnabled()) - { - logger.trace("Empty namespaces initialised: "+namespaceRegistry+" - "+namespaceRegistryThreadLocal+" ["+Thread.currentThread()+"]"); - } - - return namespaceRegistry; - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.ref.NamespacePrefixResolver#getURIs() - */ - public Collection getURIs() - { - if (! tenantService.isTenantUser()) - { - return Collections.unmodifiableCollection(getUrisCtx()); - } - else - { - // Get tenant-specific URIs - List domainUris = getUrisCtx(); - - // Get non-tenant-specific URIs (and filter out, if overridden) - List urisFiltered = new ArrayList(); - for(String uri : getUrisCtx("")) - { - if (domainUris.contains(uri)) - { - // overridden, hence skip this default prefix - continue; - } - urisFiltered.add(uri); - } - - // default (non-overridden) + tenant-specific - urisFiltered.addAll(domainUris); - - return Collections.unmodifiableCollection(urisFiltered); - } - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.ref.NamespacePrefixResolver#getPrefixes() - */ - public Collection getPrefixes() - { - if (! tenantService.isTenantUser()) - { - return Collections.unmodifiableCollection(getPrefixesCtx().keySet()); - } - else - { - // Get tenant-specific prefixes - Collection domainPrefixes = getPrefixesCtx().keySet(); - - // Get non-tenant-specific URIs (and filter out, if overridden) - List prefixesFiltered = new ArrayList(); - for(String prefix : getPrefixesCtx("").keySet()) - { - if (domainPrefixes.contains(prefix)) - { - // overridden, hence skip this default prefix - continue; - } - prefixesFiltered.add(prefix); - } - - // default (non-overridden) + tenant-specific - prefixesFiltered.addAll(domainPrefixes); - - return Collections.unmodifiableCollection(prefixesFiltered); - } - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.NamespaceDAO#addURI(java.lang.String) - */ - public void addURI(String uri) - { - if (getUrisCtx().contains(uri)) - { - throw new NamespaceException("URI " + uri + " has already been defined"); - } - getUrisCtx().add(uri); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.NamespaceDAO#addPrefix(java.lang.String, java.lang.String) - */ - public void addPrefix(String prefix, String uri) - { - if (!getUrisCtx().contains(uri)) - { - throw new NamespaceException("Namespace URI " + uri + " does not exist"); - } - getPrefixesCtx().put(prefix, uri); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.NamespaceDAO#removeURI(java.lang.String) - */ - public void removeURI(String uri) - { - getUrisCtx().remove(uri); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.dictionary.impl.NamespaceDAO#removePrefix(java.lang.String) - */ - public void removePrefix(String prefix) - { - getPrefixesCtx().remove(prefix); - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.ref.NamespacePrefixResolver#getNamespaceURI(java.lang.String) - */ - public String getNamespaceURI(String prefix) - { - if (! tenantService.isTenantUser()) - { - return getPrefixesCtx().get(prefix); - } - else - { - // first look for tenant-specific prefix - String uri = getPrefixesCtx().get(prefix); - if (uri != null) - { - // found tenant specific uri - return uri; - } - else - { - // try with default (non-tenant-specific) prefix - return getPrefixesCtx("").get(prefix); - } - } - } - - - /* (non-Javadoc) - * @see org.alfresco.repo.ref.NamespacePrefixResolver#getPrefixes(java.lang.String) - */ - public Collection getPrefixes(String URI) - { - if (! tenantService.isTenantUser()) - { - Collection uriPrefixes = new ArrayList(); - for (String key : getPrefixesCtx().keySet()) - { - String uri = getPrefixesCtx().get(key); - if ((uri != null) && (uri.equals(URI))) - { - uriPrefixes.add(key); - } - } - return uriPrefixes; - } - else - { - // check domain prefixes - Collection domainUriPrefixes = new ArrayList(); - for (String key : getPrefixesCtx().keySet()) - { - String uri = getPrefixesCtx().get(key); - if ((uri != null) && (uri.equals(URI))) - { - domainUriPrefixes.add(key); - } - } - - // check non-domain prefixes - Collection uriPrefixes = new ArrayList(); - for (String key : getPrefixesCtx("").keySet()) - { - String uri = getPrefixesCtx("").get(key); - if ((uri != null) && (uri.equals(URI))) - { - if (domainUriPrefixes != null) - { - if (domainUriPrefixes.contains(key)) - { - // overridden, hence skip this default prefix - continue; - } - } - - uriPrefixes.add(key); - } - } - - if (domainUriPrefixes != null) - { - // default (non-overridden) + domain - uriPrefixes.addAll(domainUriPrefixes); - } - - return uriPrefixes; - } - } - - - // re-entrant (eg. via reset) - private NamespaceRegistry getNamespaceRegistry(String tenantDomain) - { - NamespaceRegistry namespaceRegistry = null; - - // check threadlocal first - return if set - namespaceRegistry = getNamespaceRegistryLocal(tenantDomain); - if (namespaceRegistry != null) - { - return namespaceRegistry; // return local namespaceRegistry - } - - try - { - // check cache second - return if set - readLock.lock(); - namespaceRegistry = namespaceRegistryCache.get(tenantDomain); - - if (namespaceRegistry != null) - { - return namespaceRegistry; // return cached config - } - } - finally - { - readLock.unlock(); - } - - // reset caches - may have been invalidated (e.g. in a cluster) - namespaceRegistry = reset(tenantDomain); - - if (namespaceRegistry == null) - { - // unexpected - throw new AlfrescoRuntimeException("Failed to get namespaceRegistry " + tenantDomain); - } - - return namespaceRegistry; - } - - // create threadlocal - private NamespaceRegistry createNamespaceLocal(String tenantDomain) - { - // create threadlocal, if needed - NamespaceRegistry namespaceRegistry = getNamespaceRegistryLocal(tenantDomain); - if (namespaceRegistry == null) - { - namespaceRegistry = new NamespaceRegistry(tenantDomain); - - if (tenantDomain.equals(TenantService.DEFAULT_DOMAIN)) - { - defaultNamespaceRegistryThreadLocal.set(namespaceRegistry); - } - else - { - namespaceRegistryThreadLocal.set(namespaceRegistry); - } - } - - return namespaceRegistry; - } - - // get threadlocal - private NamespaceRegistry getNamespaceRegistryLocal(String tenantDomain) - { - NamespaceRegistry namespaceRegistry = null; - - if (tenantDomain.equals(TenantService.DEFAULT_DOMAIN)) - { - namespaceRegistry = this.defaultNamespaceRegistryThreadLocal.get(); - } - else - { - namespaceRegistry = this.namespaceRegistryThreadLocal.get(); - } - - // check to see if domain switched (eg. during login) - if ((namespaceRegistry != null) && (tenantDomain.equals(namespaceRegistry.getTenantDomain()))) - { - return namespaceRegistry; // return threadlocal, if set - } - - return null; - } - - // remove threadlocal - private void removeNamespaceLocal(String tenantDomain) - { - if (tenantDomain.equals(TenantService.DEFAULT_DOMAIN)) - { - defaultNamespaceRegistryThreadLocal.set(null); // it's in the cache, clear the threadlocal - } - else - { - defaultNamespaceRegistryThreadLocal.set(null); // it's in the cache, clear the threadlocal - namespaceRegistryThreadLocal.set(null); // it's in the cache, clear the threadlocal - } - } - - private void removeNamespaceRegistry(String tenantDomain) - { - try - { - writeLock.lock(); - if (namespaceRegistryCache.get(tenantDomain) != null) - { - namespaceRegistryCache.remove(tenantDomain); - } - - removeNamespaceLocal(tenantDomain); - } - finally - { - writeLock.unlock(); - } - } - - /** - * Get URIs from the cache (in the context of the current user's tenant domain) - * - * @return URIs - */ - private List getUrisCtx() - { - return getUrisCtx(getTenantDomain()); - } - - /** - * Get URIs from the cache - * - * @param tenantDomain - * @return URIs - */ - private List getUrisCtx(String tenantDomain) - { - return getNamespaceRegistry(tenantDomain).getUrisCache(); - } - - /** - * Get prefixes from the cache - * - * @return prefixes - */ - private Map getPrefixesCtx() - { - return getPrefixesCtx(getTenantDomain()); - } - - /** - * Get prefixes from the cache - * - * @param tenantDomain - * @return prefixes - */ - private Map getPrefixesCtx(String tenantDomain) - { - return getNamespaceRegistry(tenantDomain).getPrefixesCache(); - } - - /** - * Local helper - returns tenant domain (or empty string if default non-tenant) - */ - private String getTenantDomain() - { - return tenantService.getCurrentUserDomain(); - } - - /* package */ class NamespaceRegistry - { - private List urisCache = new ArrayList(0); - private Map prefixesCache = new HashMap(0); - - private String tenantDomain; - - public NamespaceRegistry(String tenantDomain) - { - this.tenantDomain = tenantDomain; - } - - public String getTenantDomain() - { - return tenantDomain; - } - - public List getUrisCache() - { - return urisCache; - } - - public void setUrisCache(List urisCache) - { - this.urisCache = urisCache; - } - - public Map getPrefixesCache() - { - return prefixesCache; - } - - public void setPrefixesCache(Map prefixesCache) - { - this.prefixesCache = prefixesCache; - } - } -} diff --git a/source/java/org/alfresco/repo/dictionary/DictionaryDAOTest.java b/source/java/org/alfresco/repo/dictionary/RepoDictionaryDAOTest.java similarity index 97% rename from source/java/org/alfresco/repo/dictionary/DictionaryDAOTest.java rename to source/java/org/alfresco/repo/dictionary/RepoDictionaryDAOTest.java index 30f4f727fa..0e61509b6e 100644 --- a/source/java/org/alfresco/repo/dictionary/DictionaryDAOTest.java +++ b/source/java/org/alfresco/repo/dictionary/RepoDictionaryDAOTest.java @@ -31,7 +31,6 @@ import junit.framework.TestCase; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; -import org.springframework.extensions.surf.util.I18NUtil; import org.alfresco.model.ContentModel; import org.alfresco.repo.cache.EhCacheAdapter; import org.alfresco.repo.dictionary.DictionaryDAOImpl.DictionaryRegistry; @@ -57,9 +56,10 @@ import org.alfresco.service.cmr.dictionary.PropertyDefinition; import org.alfresco.service.cmr.dictionary.TypeDefinition; import org.alfresco.service.namespace.NamespaceService; import org.alfresco.service.namespace.QName; +import org.springframework.extensions.surf.util.I18NUtil; -public class DictionaryDAOTest extends TestCase +public class RepoDictionaryDAOTest extends TestCase { public static final String TEST_RESOURCE_MESSAGES = "alfresco/messages/dictionary-messages"; diff --git a/source/java/org/alfresco/repo/dictionary/constraint/AbstractConstraint.java b/source/java/org/alfresco/repo/dictionary/constraint/AbstractConstraint.java deleted file mode 100644 index 3ed9615cd7..0000000000 --- a/source/java/org/alfresco/repo/dictionary/constraint/AbstractConstraint.java +++ /dev/null @@ -1,203 +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.dictionary.constraint; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import org.alfresco.service.cmr.dictionary.Constraint; -import org.alfresco.service.cmr.dictionary.ConstraintException; -import org.alfresco.service.cmr.dictionary.DictionaryException; -import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter; - -/** - * Base services for constraints. - * - * @author Derek Hulley - */ -public abstract class AbstractConstraint implements Constraint -{ - public static final String ERR_PROP_NOT_SET = "d_dictionary.constraint.err.property_not_set"; - public static final String ERR_EVALUATE_EXCEPTION = "d_dictionary.constraint.err.evaluate_exception"; - - - /** The constraint name. May be useful in error messages */ - private String shortName; - private String title; - - private ConstraintRegistry registry; - - /** - * Sets the constraint name. Automatically called after construction. Please excuse the strange method name as we - * want the property name to begin with an underscore to avoid property name clashes. - * - * @param shortName - * @deprecated - */ - public void set_shortName(String shortName) - { - setShortName(shortName); - } - - /** - * Sets the constraint name - * @param name - */ - public void setShortName(String name) - { - this.shortName = name; - } - - /** - * Gets the constraint name. - * - * @return the constraint name. - */ - public String getShortName() - { - return this.shortName; - } - - /** - * Optionally specify the registry that will be used to register the constraint. - * This is used when instantiating constraints outside the dictionary. - * - * @param registry the constraint registry - */ - public void setRegistry(ConstraintRegistry registry) - { - this.registry = registry; - } - - public String getType() - { - return this.getClass().getName(); - } - - public void setTitle(String title) - { - this.title = title; - } - - public String getTitle() - { - return title; - } - - public Map getParameters() - { - return new HashMap(3); - } - - /** - * {@inheritDoc} - *

- * Registers the constraint with the registry, if present. Call this method if - * you want the constraint to be auto-registered. - */ - public void initialize() - { - if (registry != null) - { - registry.register(shortName, this); - } - } - - /** - * Check that the given value is not null. - * - * @param name the name of the property - * @param value the value to check for null - * - * @throws DictionaryException if the the property is null - */ - protected void checkPropertyNotNull(String name, Object value) - { - if (value == null) - { - throw new DictionaryException(AbstractConstraint.ERR_PROP_NOT_SET, name, getShortName()); - } - } - - /** - * @see #evaluateSingleValue(Object) - * @see #evaluateCollection(Collection) - */ - @SuppressWarnings("unchecked") - public final void evaluate(Object value) - { - if (value == null) - { - // null values are never evaluated - return; - } - try - { - // ensure that we can handle collections - if (DefaultTypeConverter.INSTANCE.isMultiValued(value)) - { - Collection collection = DefaultTypeConverter.INSTANCE.getCollection(Object.class, value); - evaluateCollection(collection); - } - else - { - evaluateSingleValue(value); - } - } - catch (ConstraintException e) - { - // this can go - throw e; - } - catch (Throwable e) - { - throw new DictionaryException(AbstractConstraint.ERR_EVALUATE_EXCEPTION, this, e.getMessage()); - } - } - - /** - * Only override if there is some specific evaluation that needs to be performed on the - * collection as a whole. - * - * @param collection the collection of values to evaluate - * - * @see #evaluateSingleValue(Object) - */ - protected void evaluateCollection(Collection collection) - { - for (Object value : collection) - { - if (value == null) - { - // contract states that it will always pass - continue; - } - evaluateSingleValue(value); - } - } - - /** - * Support for evaluation of properties. The value passed in will never be a - * Collection and will never be null. - * - * @throws ConstraintException throw this when the evaluation fails - */ - protected abstract void evaluateSingleValue(Object value); -} diff --git a/source/java/org/alfresco/repo/dictionary/constraint/ConstraintRegistry.java b/source/java/org/alfresco/repo/dictionary/constraint/ConstraintRegistry.java deleted file mode 100644 index b04c78a06e..0000000000 --- a/source/java/org/alfresco/repo/dictionary/constraint/ConstraintRegistry.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.dictionary.constraint; - -import java.util.HashMap; -import java.util.Map; - -import org.alfresco.service.cmr.dictionary.Constraint; - -/** - * A registry of constraints. - * - * @author Derek Hulley - * @since 3.2 - */ -public class ConstraintRegistry -{ - private static ConstraintRegistry instance = new ConstraintRegistry(); - - private Map constraints; - - /** - * @return Returns the singleton - */ - public static ConstraintRegistry getInstance() - { - return instance; - } - - /** - * Private constructor - * @see #getInstance() - */ - private ConstraintRegistry() - { - constraints = new HashMap(13); - } - - /** - * Register the constraint by name - */ - public void register(String name, Constraint constraint) - { - if (this == instance) - { - constraints.put(name, constraint); - } - else - { - instance.register(name, constraint); - } - } - - /** - * Get the constraint by name - * - * @param name the name by which the constraint was registered - * @return Returns the constraint or null if it does not exist. - */ - public Constraint getConstraint(String name) - { - if (this == instance) - { - return constraints.get(name); - } - else - { - return instance.getConstraint(name); - } - } -} diff --git a/source/java/org/alfresco/repo/dictionary/constraint/ConstraintsTest.java b/source/java/org/alfresco/repo/dictionary/constraint/ConstraintsTest.java deleted file mode 100644 index eab56c00f9..0000000000 --- a/source/java/org/alfresco/repo/dictionary/constraint/ConstraintsTest.java +++ /dev/null @@ -1,345 +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.dictionary.constraint; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import junit.framework.TestCase; - -import org.springframework.extensions.surf.util.I18NUtil; -import org.alfresco.repo.dictionary.DictionaryDAOTest; -import org.alfresco.service.cmr.dictionary.Constraint; -import org.alfresco.service.cmr.dictionary.ConstraintException; -import org.alfresco.service.cmr.dictionary.DictionaryException; - -/** - * This file must be saved using UTF-8. - * - * @see org.alfresco.service.cmr.dictionary.Constraint - * @see org.alfresco.repo.dictionary.constraint.AbstractConstraint - * @see org.alfresco.repo.dictionary.constraint.RegexConstraint - * - * @author Derek Hulley - */ -@SuppressWarnings("unused") -public class ConstraintsTest extends TestCase -{ - @Override - protected void setUp() throws Exception - { - // register resource bundles for messages - I18NUtil.registerResourceBundle(DictionaryDAOTest.TEST_RESOURCE_MESSAGES); - } - - /** - * ensure that the default handling of checks on collections will work - */ - public void testCollections() throws Exception - { - DummyConstraint constraint = new DummyConstraint(); - constraint.initialize(); - - assertEquals("DummyConstraint type should be 'org.alfresco.repo.dictionary.constraint.ConstraintsTest$DummyConstraint'", - "org.alfresco.repo.dictionary.constraint.ConstraintsTest$DummyConstraint", - constraint.getType()); - assertNotNull("DummyConstraint should not have empty parameters", constraint.getParameters()); - assertEquals("DummyConstraint should not have empty parameters", 0, constraint.getParameters().size()); - - List dummyObjects = new ArrayList(3); - dummyObjects.add("ABC"); // correct - dummyObjects.add("DEF"); // correct - dummyObjects.add(this); // NO - try - { - constraint.evaluate(dummyObjects); - fail("Failed to detected constraint violation in collection"); - } - catch (ConstraintException e) - { - // expected - checkI18NofExceptionMessage(e); - } - // check that the two strings were properly dealt with - assertEquals("String values not checked", 2, constraint.tested.size()); - } - - public void testNull() throws Exception - { - DummyConstraint constraint = new DummyConstraint(); - constraint.initialize(); - - // a null always passes - constraint.evaluate(null); - } - - private void checkI18NofExceptionMessage(Throwable e) - { - String msg = e.getMessage(); - assertFalse("I18N of constraint message failed", msg.startsWith("d_dictionary.constraint")); - } - - private void evaluate(Constraint constraint, Object value, boolean expectFailure) throws Exception - { - try - { - constraint.evaluate(value); - if (expectFailure) - { - // it should have failed - fail("Failure did not occur: \n" + - " constraint: " + constraint + "\n" + - " value: " + value); - } - } - catch (ConstraintException e) - { - // check if we expect an error - if (expectFailure) - { - // expected - check message I18N - checkI18NofExceptionMessage(e); - } - else - { - // didn't expect it - throw e; - } - } - } - - public void testStringLengthConstraint() throws Exception - { - StringLengthConstraint constraint = new StringLengthConstraint(); - try - { - constraint.setMinLength(-1); - } - catch (DictionaryException e) - { - // expected - checkI18NofExceptionMessage(e); - } - try - { - constraint.setMaxLength(-1); - } - catch (DictionaryException e) - { - // expected - checkI18NofExceptionMessage(e); - } - constraint.setMinLength(3); - constraint.setMaxLength(6); - - assertEquals("StringLengthConstraint type should be 'LENGTH'", - "LENGTH", constraint.getType()); - assertNotNull("StringLengthConstraint should have parameters", constraint.getParameters()); - assertEquals("StringLengthConstraint should have 2 parameters", 2, constraint.getParameters().size()); - assertEquals("minLength should be 3", 3, - constraint.getParameters().get("minLength")); - assertEquals("maxLength should be 6", 6, - constraint.getParameters().get("maxLength")); - - evaluate(constraint, "abc", false); - evaluate(constraint, "abcdef", false); - evaluate(constraint, Arrays.asList("abc", "abcdef"), false); - evaluate(constraint, "ab", true); - evaluate(constraint, "abcdefg", true); - evaluate(constraint, Arrays.asList("abc", "abcdefg"), true); - } - - @SuppressWarnings("unchecked") - public void testListOfValuesConstraint() throws Exception - { - ListOfValuesConstraint constraint = new ListOfValuesConstraint(); - try - { - constraint.setAllowedValues(Collections.emptyList()); - } - catch (DictionaryException e) - { - // expected - checkI18NofExceptionMessage(e); - } - List allowedValues = Arrays.asList(new String[] {"abc", "def", "ghi"}); - constraint.setAllowedValues(allowedValues); - - assertEquals("ListOfValuesConstraint type should be 'LIST'", - "LIST", constraint.getType()); - assertNotNull("ListOfValuesConstraint should have parameters", constraint.getParameters()); - assertEquals("ListOfValuesConstraint should have 2 parameters", 2, constraint.getParameters().size()); - assertEquals("caseSensitive should be true", Boolean.TRUE, - constraint.getParameters().get("caseSensitive")); - List allowedValuesParam = (List)constraint.getParameters().get("allowedValues"); - assertEquals("Should be 3 allowable values", 3, allowedValuesParam.size()); - assertEquals("First allowable value should be 'abc'", "abc", allowedValuesParam.get(0)); - assertEquals("First allowable value should be 'def'", "def", allowedValuesParam.get(1)); - assertEquals("First allowable value should be 'ghi'", "ghi", allowedValuesParam.get(2)); - - evaluate(constraint, "def", false); - evaluate(constraint, "DEF", true); - evaluate(constraint, Arrays.asList("abc", "def"), false); - evaluate(constraint, Arrays.asList("abc", "DEF"), true); - - // now make it case-insensitive - constraint.setCaseSensitive(false); - assertEquals("caseSensitive should be false", Boolean.FALSE, - constraint.getParameters().get("caseSensitive")); - evaluate(constraint, "DEF", false); - evaluate(constraint, Arrays.asList("abc", "DEF"), false); - } - - public void testNumericRangeConstraint() throws Exception - { - NumericRangeConstraint constraint = new NumericRangeConstraint(); - constraint.initialize(); - - assertEquals("NumericRangeConstraint type should be 'MINMAX'", - "MINMAX", constraint.getType()); - assertNotNull("NumericRangeConstraint should have parameters", constraint.getParameters()); - assertEquals("NumericRangeConstraint should have 2 parameters", 2, constraint.getParameters().size()); - - // check that Double.MIN_VALUE and Double.MAX_VALUE are allowed by default - constraint.evaluate(Double.MIN_VALUE); - constraint.evaluate(Double.MAX_VALUE); - - // check that Double.NaN is not allowed by default - evaluate(constraint, Double.NaN, true); - - // set some limits and check - constraint.setMinValue(-5.0D); - constraint.setMaxValue(+5.0D); - constraint.initialize(); - - assertEquals("minValue should be -5", -5.0D, constraint.getParameters().get("minValue")); - assertEquals("maxValue should be 5", 5.0D, constraint.getParameters().get("maxValue")); - - evaluate(constraint, "-1.0", false); - evaluate(constraint, "+1.0", false); - evaluate(constraint, Arrays.asList(-1, 0, 1), false); - evaluate(constraint, "abc", true); - evaluate(constraint, 56.453E4, true); - evaluate(constraint, Arrays.asList(-1, 6), true); - } - - public void testRegexConstraint() throws Exception - { - RegexConstraint constraint = new RegexConstraint(); - constraint.setExpression("[A-Z]*"); - constraint.setRequiresMatch(true); - constraint.initialize(); - - assertEquals("RegexConstraint type should be 'REGEX'", - "REGEX", constraint.getType()); - assertNotNull("RegexConstraint should have parameters", constraint.getParameters()); - assertEquals("RegexConstraint should have 2 parameters", 2, constraint.getParameters().size()); - assertEquals("requiresMatch should be true", Boolean.TRUE, - constraint.getParameters().get("requiresMatch")); - assertEquals("expression should be [A-Z]*", "[A-Z]*", - constraint.getParameters().get("expression")); - - // do some successful stuff - evaluate(constraint, "ABC", false); - evaluate(constraint, "DEF", false); - - // now some failures - evaluate(constraint, "abc", true); - - // now a case of passing in an object that could be a string - evaluate(constraint, DummyEnum.ABC, false); - evaluate(constraint, DummyEnum.DEF, false); - evaluate(constraint, DummyEnum.abc, true); - - // now switch the requiresMatch around - constraint.setRequiresMatch(false); - constraint.initialize(); - assertEquals("requiresMatch should be false", Boolean.FALSE, - constraint.getParameters().get("requiresMatch")); - - evaluate(constraint, DummyEnum.abc, false); - } - - public void testRegexConstraintFilename() throws Exception - { - // we assume UTF-8 - String expression = new String(".*[\\\"\\*\\\\\\>\\<\\?\\/\\:\\|\\¬\\£\\%\\&\\+\\;]+.*".getBytes("UTF-8")); - String invalidChars = new String("\"*\\>.txt", true); - // ... and a valid one - evaluate(constraint, "Company Home", false); - } - - - private enum DummyEnum - { - ABC, - DEF, - abc; - } - - private class DummyConstraint extends AbstractConstraint - { - private List tested; - - @Override - public void initialize() - { - tested = new ArrayList(4); - } - - /** - * Fails on everything but String values, which pass. - * Null values cause runtime exceptions and all other failures are by - * DictionaryException. - */ - @Override - protected void evaluateSingleValue(Object value) - { - if (value == null) - { - throw new NullPointerException("Null value in dummy test"); - } - else if (value instanceof String) - { - tested.add(value); - } - else - { - throw new ConstraintException("Non-String value"); - } - } - } -} diff --git a/source/java/org/alfresco/repo/dictionary/constraint/ListOfValuesConstraint.java b/source/java/org/alfresco/repo/dictionary/constraint/ListOfValuesConstraint.java deleted file mode 100644 index 43df5b5d96..0000000000 --- a/source/java/org/alfresco/repo/dictionary/constraint/ListOfValuesConstraint.java +++ /dev/null @@ -1,178 +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.dictionary.constraint; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.alfresco.service.cmr.dictionary.ConstraintException; -import org.alfresco.service.cmr.dictionary.DictionaryException; -import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter; -import org.alfresco.service.cmr.repository.datatype.TypeConversionException; - -/** - * Constraint implementation that ensures the value is one of a constrained - * list of values. By default, this constraint is case-sensitive. - * - * @see #setAllowedValues(List) - * @see #setCaseSensitive(boolean) - * - * @author Derek Hulley - */ -public class ListOfValuesConstraint extends AbstractConstraint -{ - private static final String ERR_NO_VALUES = "d_dictionary.constraint.list_of_values.no_values"; - private static final String ERR_NON_STRING = "d_dictionary.constraint.string_length.non_string"; - private static final String ERR_INVALID_VALUE = "d_dictionary.constraint.list_of_values.invalid_value"; - - private List allowedValues; - private List allowedValuesUpper; - private boolean caseSensitive; - - public ListOfValuesConstraint() - { - caseSensitive = true; - } - - /** - * {@inheritDoc} - */ - @Override - public String getType() - { - return "LIST"; - } - - @Override - public String toString() - { - StringBuilder sb = new StringBuilder(80); - sb.append("ListOfValuesConstraint") - .append("[ allowedValues=").append(allowedValues) - .append(", caseSensitive=").append(caseSensitive) - .append("]"); - return sb.toString(); - } - - /** - * Get the allowed values. Note that these are String instances, but may - * represent non-String values. It is up to the caller to distinguish. - * - * @return Returns the values allowed - */ - public List getAllowedValues() - { - return allowedValues; - } - - /** - * Set the values that are allowed by the constraint. - * - * @param values a list of allowed values - */ - @SuppressWarnings("unchecked") - public void setAllowedValues(List allowedValues) - { - if (allowedValues == null) - { - throw new DictionaryException(ERR_NO_VALUES); - } - int valueCount = allowedValues.size(); - if (valueCount == 0) - { - throw new DictionaryException(ERR_NO_VALUES); - } - this.allowedValues = Collections.unmodifiableList(allowedValues); - // make the upper case versions - this.allowedValuesUpper = new ArrayList(valueCount); - for (String allowedValue : this.allowedValues) - { - allowedValuesUpper.add(allowedValue.toUpperCase()); - } - } - - /** - * @return Returns true if this constraint is case-sensitive (default) - */ - public boolean isCaseSensitive() - { - return caseSensitive; - } - - /** - * Set the handling of case checking. - * - * @param caseSensitive true if the constraint is case-sensitive (default), - * or false for case-insensitive. - */ - public void setCaseSensitive(boolean caseSensitive) - { - this.caseSensitive = caseSensitive; - } - - @Override - public void initialize() - { - super.initialize(); - checkPropertyNotNull("allowedValues", allowedValues); - } - - @Override - public Map getParameters() - { - Map params = new HashMap(2); - - params.put("caseSensitive", this.caseSensitive); - params.put("allowedValues", this.allowedValues); - - return params; - } - - protected void evaluateSingleValue(Object value) - { - // convert the value to a String - String valueStr = null; - try - { - valueStr = DefaultTypeConverter.INSTANCE.convert(String.class, value); - } - catch (TypeConversionException e) - { - throw new ConstraintException(ERR_NON_STRING, value); - } - // check that the value is in the set of allowed values - if (caseSensitive) - { - if (!allowedValues.contains(valueStr)) - { - throw new ConstraintException(ERR_INVALID_VALUE, value); - } - } - else - { - if (!allowedValuesUpper.contains(valueStr.toUpperCase())) - { - throw new ConstraintException(ERR_INVALID_VALUE, value); - } - } - } -} diff --git a/source/java/org/alfresco/repo/dictionary/constraint/NumericRangeConstraint.java b/source/java/org/alfresco/repo/dictionary/constraint/NumericRangeConstraint.java deleted file mode 100644 index 639aa23950..0000000000 --- a/source/java/org/alfresco/repo/dictionary/constraint/NumericRangeConstraint.java +++ /dev/null @@ -1,149 +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.dictionary.constraint; - -import java.util.HashMap; -import java.util.Map; - -import org.alfresco.service.cmr.dictionary.ConstraintException; -import org.alfresco.service.cmr.dictionary.DictionaryException; -import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter; - -/** - * Constraint implementation that ensures that the value is a numeric value bewteen a given - * minimum and maximum value. If a minimum or maximum value are not provided, then the JAVA - * Double's {@link Double#MIN_VALUE minimum value} or {@link Double#MAX_VALUE maximum value} - * are assumed. - * - * @see #setMinValue(double) - * @see #setMaxValue(double) - * @see java.lang.Double#parseDouble(java.lang.String) - * - * @author Derek Hulley - */ -public class NumericRangeConstraint extends AbstractConstraint -{ - private static final String ERR_INVALID_MIN_VALUE = "d_dictionary.constraint.numeric_range.invalid_min_value"; - private static final String ERR_INVALID_MAX_VALUE = "d_dictionary.constraint.numeric_range.invalid_max_value"; - private static final String ERR_NON_NUMERIC = "d_dictionary.constraint.numeric_range.non_numeric"; - private static final String ERR_OUT_OF_RANGE = "d_dictionary.constraint.numeric_range.out_of_range"; - - private double minValue = Double.MIN_VALUE; - private double maxValue = Double.MAX_VALUE; - - @Override - public String getType() - { - return "MINMAX"; - } - - @Override - public String toString() - { - StringBuilder sb = new StringBuilder(80); - sb.append("NumericRangeConstraint") - .append("[ minValue=").append(minValue) - .append(", maxValue=").append(maxValue) - .append("]"); - return sb.toString(); - } - - /** - * @return Returns the minimum value allowed by the constraint - */ - public double getMinValue() - { - return minValue; - } - - /** - * Set the minimum value allowed, which can be any value between - * {@link Double#MIN_VALUE} and {@link Double#MAX_VALUE}. - * - * @param minValue the minimum value allowed by the constraint - */ - public void setMinValue(double minValue) - { - if (minValue > this.maxValue) - { - throw new DictionaryException(ERR_INVALID_MIN_VALUE, minValue); - } - this.minValue = minValue; - } - - /** - * @return Returns the minimum value allowed by the constraint - */ - public double getMaxValue() - { - return maxValue; - } - - /** - * Set the maximum value allowed, which can be any value between - * {@link Double#MIN_VALUE} and {@link Double#MAX_VALUE}. - * - * @param maxValue the minimum value allowed by the constraint - */ - public void setMaxValue(double maxValue) - { - if (maxValue < this.minValue) - { - throw new DictionaryException(ERR_INVALID_MAX_VALUE, maxValue); - } - this.maxValue = maxValue; - } - - @Override - public Map getParameters() - { - Map params = new HashMap(2); - - params.put("minValue", this.minValue); - params.put("maxValue", this.maxValue); - - return params; - } - - protected void evaluateSingleValue(Object value) - { - // ensure that the value can be converted to a double - double checkValue = Double.NaN; - try - { - checkValue = DefaultTypeConverter.INSTANCE.doubleValue(value); - } - catch (NumberFormatException e) - { - throw new ConstraintException(ERR_NON_NUMERIC, value); - } - - // Infinity and NaN cannot match - if (Double.isInfinite(checkValue) || Double.isNaN(checkValue)) - { - throw new ConstraintException(ERR_OUT_OF_RANGE, checkValue, minValue, maxValue); - } - - // Check that the value is in range - if (checkValue > maxValue || checkValue < minValue) - { - throw new ConstraintException(ERR_OUT_OF_RANGE, checkValue, minValue, maxValue); - } - } -} diff --git a/source/java/org/alfresco/repo/dictionary/constraint/RegexConstraint.java b/source/java/org/alfresco/repo/dictionary/constraint/RegexConstraint.java deleted file mode 100644 index 31136401d3..0000000000 --- a/source/java/org/alfresco/repo/dictionary/constraint/RegexConstraint.java +++ /dev/null @@ -1,155 +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.dictionary.constraint; - -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.springframework.extensions.surf.util.I18NUtil; -import org.alfresco.service.cmr.dictionary.ConstraintException; -import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter; - -/** - * Constraint implementation that performs regular expression comparisons. - * Where possible, the {@link org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter type converter} - * will be used to first convert the value to a String, so the evaluation - * will be against the value's String equivalent. - *

- * The failure condition can be changed to occur either on a match or on a non-match by using - * the {@link #setRequiresMatch(boolean) requiresMatch} property. The default is true, i.e. - * failures will occur if the object value does not match the given expression. - * - * @see java.lang.String#matches(java.lang.String) - * @see java.util.regex.Pattern - * - * @author Derek Hulley - */ -public class RegexConstraint extends AbstractConstraint -{ - public static final String CONSTRAINT_REGEX_NO_MATCH = "d_dictionary.constraint.regex.no_match"; - public static final String CONSTRAINT_REGEX_MATCH = "d_dictionary.constraint.regex.match"; - public static final String CONSTRAINT_REGEX_MSG_PREFIX = "d_dictionary.constraint.regex.error."; - - private String expression; - private Pattern patternMatcher; - private boolean requiresMatch = true; - - /** - * {@inheritDoc} - */ - public String getType() - { - return "REGEX"; - } - - @Override - public String toString() - { - StringBuilder sb = new StringBuilder(80); - sb.append("RegexConstraint") - .append("[ expression=").append(expression) - .append(", requiresMatch=").append(requiresMatch) - .append("]"); - return sb.toString(); - } - - /** - * @return Returns the regular expression similar to the {@link String#matches(java.lang.String)} - */ - public String getExpression() - { - return expression; - } - - /** - * Set the regular expression used to evaluate String values - * @param regular expression similar to the {@link String#matches(java.lang.String)} argument - */ - public void setExpression(String expression) - { - this.expression = expression; - } - - /** - * @return Returns true if the value must match the regular expression - * or false if the value must not match the regular expression - */ - public boolean getRequiresMatch() - { - return requiresMatch; - } - - /** - * Set whether the regular expression must be matched or not - * - * @param requiresMatch Set to true if the value must match the regular expression - * or false if the value must not match the regular expression - */ - public void setRequiresMatch(boolean requiresMatch) - { - this.requiresMatch = requiresMatch; - } - - @Override - public Map getParameters() - { - Map params = new HashMap(2); - - params.put("expression", this.expression); - params.put("requiresMatch", this.requiresMatch); - - return params; - } - - @Override - public void initialize() - { - checkPropertyNotNull("expression", expression); - - this.patternMatcher = Pattern.compile(expression); - } - - protected void evaluateSingleValue(Object value) - { - // convert the value to a String - String valueStr = DefaultTypeConverter.INSTANCE.convert(String.class, value); - Matcher matcher = patternMatcher.matcher(valueStr); - boolean matches = matcher.matches(); - if (matches != requiresMatch) - { - // Look for a message corresponding to this constraint name - String messageId = CONSTRAINT_REGEX_MSG_PREFIX + getShortName(); - if (I18NUtil.getMessage(messageId, value) != null) - { - throw new ConstraintException(messageId, value); - } - // Otherwise, fall back to a generic (but unfriendly) message - else if (requiresMatch) - { - throw new ConstraintException(RegexConstraint.CONSTRAINT_REGEX_NO_MATCH, value, expression); - } - else - { - throw new ConstraintException(RegexConstraint.CONSTRAINT_REGEX_MATCH, value, expression); - } - } - } -} diff --git a/source/java/org/alfresco/repo/dictionary/constraint/RegisteredConstraint.java b/source/java/org/alfresco/repo/dictionary/constraint/RegisteredConstraint.java deleted file mode 100644 index 08867aab02..0000000000 --- a/source/java/org/alfresco/repo/dictionary/constraint/RegisteredConstraint.java +++ /dev/null @@ -1,129 +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.dictionary.constraint; - -import java.util.List; -import java.util.Map; - -import org.alfresco.service.cmr.dictionary.Constraint; -import org.alfresco.service.cmr.dictionary.DictionaryException; - -/** - * Constraint implementation that defers to constraints registered with the - * static instance of the {@link ConstraintRegistry}. - * - * @see #setAllowedValues(List) - * @see #setCaseSensitive(boolean) - * - * @author Derek Hulley - */ -public final class RegisteredConstraint implements Constraint -{ - private static final String ERR_NAME_NOT_REGISTERED = "d_dictionary.constraint.registered.not_registered"; - - private String shortName; - private String registeredName; - - public RegisteredConstraint() - { - } - - @Override - public String toString() - { - StringBuilder sb = new StringBuilder(80); - sb.append("RegisteredConstraint") - .append("[ registeredName=").append(registeredName) - .append(", constraint=").append(ConstraintRegistry.getInstance().getConstraint(registeredName)) - .append("]"); - return sb.toString(); - } - - public String getShortName() - { - return shortName; - } - - public void setShortName(String shortName) - { - this.shortName = shortName; - } - - /** - * Set the name of the constraint that will be used to look up the constraint - * that will be delegated to. - */ - public void setRegisteredName(String registeredName) - { - this.registeredName = registeredName; - } - - public void initialize() - { - if (registeredName == null) - { - throw new DictionaryException(AbstractConstraint.ERR_PROP_NOT_SET, "registeredName"); - } - } - - /** - * @return the constraint that matches the registered name - */ - private Constraint getConstraint() - { - Constraint constraint = ConstraintRegistry.getInstance().getConstraint(registeredName); - if (constraint == null) - { - throw new DictionaryException(ERR_NAME_NOT_REGISTERED, registeredName); - } - return constraint; - } - - /** - * Defers to the registered constraint - */ - public String getType() - { - return getConstraint().getType(); - } - - /** - * Defers to the registered constraint - */ - public String getTitle() - { - return getConstraint().getTitle(); - } - - /** - * Defers to the registered constraint - */ - public Map getParameters() - { - return getConstraint().getParameters(); - } - - /** - * Defers to the registered constraint - */ - public void evaluate(Object value) - { - getConstraint().evaluate(value); - } -} diff --git a/source/java/org/alfresco/repo/dictionary/constraint/StringLengthConstraint.java b/source/java/org/alfresco/repo/dictionary/constraint/StringLengthConstraint.java deleted file mode 100644 index 013900b69a..0000000000 --- a/source/java/org/alfresco/repo/dictionary/constraint/StringLengthConstraint.java +++ /dev/null @@ -1,148 +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.dictionary.constraint; - -import java.util.HashMap; -import java.util.Map; - -import org.alfresco.service.cmr.dictionary.ConstraintException; -import org.alfresco.service.cmr.dictionary.DictionaryException; -import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter; -import org.alfresco.service.cmr.repository.datatype.TypeConversionException; - -/** - * Constraint implementation that ensures that the length of the String value. - * - * @see #setMinLength(int) - * @see #setMaxLength(int) - * - * @author Derek Hulley - */ -public class StringLengthConstraint extends AbstractConstraint -{ - private static final String ERR_INVALID_MIN_LENGTH = "d_dictionary.constraint.string_length.invalid_min_length"; - private static final String ERR_INVALID_MAX_LENGTH = "d_dictionary.constraint.string_length.invalid_max_length"; - private static final String ERR_NON_STRING = "d_dictionary.constraint.string_length.non_string"; - private static final String ERR_INVALID_LENGTH = "d_dictionary.constraint.string_length.invalid_length"; - - private int minLength = 0; - private int maxLength = Integer.MAX_VALUE; - - /** - * {@inheritDoc} - */ - @Override - public String getType() - { - return "LENGTH"; - } - - @Override - public String toString() - { - StringBuilder sb = new StringBuilder(80); - sb.append("StringLengthConstraint") - .append("[ minLength=").append(minLength) - .append(", maxLength=").append(maxLength) - .append("]"); - return sb.toString(); - } - - /** - * @return Returns the minimum number of characters allowed - */ - public int getMinLength() - { - return minLength; - } - - /** - * Set the minimum number of characters allowed. Valid values are in - * the range [0, {@link Integer#MAX_VALUE}]. - * - * @param minLength the minimum numbers of characters allowed - */ - public void setMinLength(int minLength) - { - if (minLength > this.maxLength || minLength < 0) - { - throw new DictionaryException(ERR_INVALID_MIN_LENGTH, minLength); - } - this.minLength = minLength; - } - - /** - * @return Returns the maximum number of characters allowed - */ - public int getMaxLength() - { - return maxLength; - } - - /** - * Set the maximum number of characters allowed. Valid values are in - * the range [0, {@link Integer#MAX_VALUE}]. - * - * @param maxLength the minimum numbers of characters allowed - */ - public void setMaxLength(int maxLength) - { - if (maxLength < this.minLength) - { - throw new DictionaryException(ERR_INVALID_MAX_LENGTH, maxLength); - } - this.maxLength = maxLength; - } - - @Override - public Map getParameters() - { - Map params = new HashMap(2); - - params.put("minLength", this.minLength); - params.put("maxLength", this.maxLength); - - return params; - } - - protected void evaluateSingleValue(Object value) - { - // ensure that the value can be converted to a String - String checkValue = null; - try - { - checkValue = DefaultTypeConverter.INSTANCE.convert(String.class, value); - } - catch (TypeConversionException e) - { - throw new ConstraintException(ERR_NON_STRING, value); - } - - // Check that the value length - int length = checkValue.length(); - if (length > maxLength || length < minLength) - { - if (length > 20) - { - checkValue = checkValue.substring(0, 17) + "..."; - } - throw new ConstraintException(ERR_INVALID_LENGTH, checkValue, minLength, maxLength); - } - } -} diff --git a/source/java/org/alfresco/repo/dictionary/dictionarydaotest_model.properties b/source/java/org/alfresco/repo/dictionary/dictionarydaotest_model.properties deleted file mode 100644 index bf73f95355..0000000000 --- a/source/java/org/alfresco/repo/dictionary/dictionarydaotest_model.properties +++ /dev/null @@ -1,12 +0,0 @@ -test_dictionarydaotest.description=Model Description - -test_dictionarydaotest.class.test_base.title=Base Title -test_dictionarydaotest.class.test_base.description=Base Description - -test_dictionarydaotest.property.test_prop1.title=Prop1 Title -test_dictionarydaotest.property.test_prop1.description=Prop1 Description - -test_dictionarydaotest.association.test_assoc1.title=Assoc1 Title -test_dictionarydaotest.association.test_assoc1.description=Assoc1 Description - -test_dictionarydaotest.datatype.test_datatype.analyzer=Datatype Analyser diff --git a/source/java/org/alfresco/repo/dictionary/dictionarydaotest_model.xml b/source/java/org/alfresco/repo/dictionary/dictionarydaotest_model.xml deleted file mode 100644 index 7a23a8b096..0000000000 --- a/source/java/org/alfresco/repo/dictionary/dictionarydaotest_model.xml +++ /dev/null @@ -1,270 +0,0 @@ - - - Alfresco Content Model - Alfresco - 2005-05-30 - 1.0 - - - - - - - - - - - - - org.alfresco.repo.search.impl.lucene.analysis.AlfrescoStandardAnalyser - java.lang.Object - - - - - - - cm:reg1 - - - cm:reg2 - - - Regex1 title - Regex1 description - [A-Z]* - false - - - [a-z]* - false - - - 0 - 256 - - - 0 - 128 - - - 0 - 256 - - - - - ABC - DEF - - - true - - - - - - - Base - The Base Type - - - - - d:text - true - - - - - Prop1 Strlen1 title - Prop1 Strlen1 description - - - - - - - - - - true - false - - - test:base - false - true - - - - - true - true - - - test:referenceable - false - false - - - - - true - true - - - test:referenceable - false - false - - fred - true - - - - true - true - - - test:referenceable - false - false - - fred - true - true - - - - - test:referenceable - - - - - test:base - true - - - - d:text - true - - - - - - - - - test:referenceable - - fred - true - - - - - - an overriden default value - - - - - - - - - - - test:file - - - - test:file - false - - - - test:base - - - d:text - true - - - - - - - test:base - - - d:text - true - - - d:text - true - - - d:text - true - - - - - - - - d:text - one - - - - - - test:overridetype1 - - - two - - - - - - test:overridetype2 - - - three - - - - - - - - - Referenceable - The referenceable aspect - - - - - d:int - true - true - - true - false - - - - - - - - - - diff --git a/source/java/org/alfresco/repo/dictionary/m2binding.xml b/source/java/org/alfresco/repo/dictionary/m2binding.xml deleted file mode 100644 index 84d39710eb..0000000000 --- a/source/java/org/alfresco/repo/dictionary/m2binding.xml +++ /dev/null @@ -1,176 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/source/java/org/alfresco/repo/domain/qname/NamespaceEntity.java b/source/java/org/alfresco/repo/domain/qname/NamespaceEntity.java index 97e6c8cf81..9226ba2539 100644 --- a/source/java/org/alfresco/repo/domain/qname/NamespaceEntity.java +++ b/source/java/org/alfresco/repo/domain/qname/NamespaceEntity.java @@ -18,6 +18,7 @@ */ package org.alfresco.repo.domain.qname; +import org.alfresco.service.namespace.QName; import org.alfresco.util.EqualsHelper; /** @@ -28,7 +29,6 @@ import org.alfresco.util.EqualsHelper; */ public class NamespaceEntity { - public static final String EMPTY_URI_SUBSTITUTE = ".empty"; public static final Long CONST_LONG_ZERO = new Long(0L); private Long id; @@ -94,7 +94,7 @@ public class NamespaceEntity */ public String getUriSafe() { - if (EqualsHelper.nullSafeEquals(uri, NamespaceEntity.EMPTY_URI_SUBSTITUTE)) + if (EqualsHelper.nullSafeEquals(uri, QName.EMPTY_URI_SUBSTITUTE)) { return ""; } @@ -108,6 +108,6 @@ public class NamespaceEntity */ public void setUriSafe(String uri) { - this.uri = (uri.length() == 0) ? NamespaceEntity.EMPTY_URI_SUBSTITUTE : uri; + this.uri = (uri.length() == 0) ? QName.EMPTY_URI_SUBSTITUTE : uri; } } diff --git a/source/java/org/alfresco/repo/search/MLAnalysisMode.java b/source/java/org/alfresco/repo/search/MLAnalysisMode.java deleted file mode 100644 index 8d29dd25ab..0000000000 --- a/source/java/org/alfresco/repo/search/MLAnalysisMode.java +++ /dev/null @@ -1,925 +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.search; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Locale; -import java.util.Set; - -import org.alfresco.error.AlfrescoRuntimeException; - -/** - * Enum to specify how multi-lingual properties should be treate for indexing and search. Note that locale new Locale - * ("", "", "") is used to indicate all locales. - * - * @author andyh - */ -public enum MLAnalysisMode -{ - /** - * Only the exact locale is used. - */ - LOCALE_ONLY - { - public boolean includesAll() - { - return false; - } - - public boolean includesContained() - { - return false; - } - - public boolean includesContaining() - { - return false; - } - - public boolean includesExact() - { - return true; - } - - public boolean includesAllLanguageMatches() - { - return false; - } - - public boolean includesExactLanguageMatch() - { - return false; - } - - public boolean includesAllCountryMatches() - { - return false; - } - - public boolean includesExactCountryMatch() - { - return false; - } - - }, - - /** - * Only the exact locale and no locale === locale + all languages - */ - LOCALE_AND_ALL - { - public boolean includesAll() - { - return true; - } - - public boolean includesContained() - { - return false; - } - - public boolean includesContaining() - { - return false; - } - - public boolean includesExact() - { - return true; - } - - public boolean includesAllLanguageMatches() - { - return false; - } - - public boolean includesExactLanguageMatch() - { - return false; - } - - public boolean includesAllCountryMatches() - { - return false; - } - - public boolean includesExactCountryMatch() - { - return false; - } - }, - - /** - * Expand the locale to include all the locales that contain it. So "en_GB" would be "en_GB", "en", but not all - * languages "". - */ - LOCALE_AND_ALL_CONTAINING_LOCALES - { - public boolean includesAll() - { - return false; - } - - public boolean includesContained() - { - return false; - } - - public boolean includesContaining() - { - return true; - } - - public boolean includesExact() - { - return true; - } - - public boolean includesAllLanguageMatches() - { - return false; - } - - public boolean includesExactLanguageMatch() - { - return false; - } - - public boolean includesAllCountryMatches() - { - return false; - } - - public boolean includesExactCountryMatch() - { - return false; - } - }, - - /** - * Expand the locale to include all the locales that contain it. "en_GB" would be "en_GB", "en", and all "". - */ - LOCALE_AND_ALL_CONTAINING_LOCALES_AND_ALL - { - public boolean includesAll() - { - return true; - } - - public boolean includesContained() - { - return false; - } - - public boolean includesContaining() - { - return true; - } - - public boolean includesExact() - { - return true; - } - - public boolean includesAllLanguageMatches() - { - return false; - } - - public boolean includesExactLanguageMatch() - { - return false; - } - - public boolean includesAllCountryMatches() - { - return false; - } - - public boolean includesExactCountryMatch() - { - return false; - } - }, - - /** - * Expand to all the locales that are contained by this. "en" would expand to "en", "en_GB", "en_US", .... - */ - LOCALE_AND_ALL_CONTAINED_LOCALES - { - public boolean includesAll() - { - return false; - } - - public boolean includesContained() - { - return true; - } - - public boolean includesContaining() - { - return false; - } - - public boolean includesExact() - { - return true; - } - - public boolean includesAllLanguageMatches() - { - return false; - } - - public boolean includesExactLanguageMatch() - { - return false; - } - - public boolean includesAllCountryMatches() - { - return false; - } - - public boolean includesExactCountryMatch() - { - return false; - } - }, - - /** - * Just the all locale, "", === new Locale("", "", "") - */ - ALL_ONLY - { - public boolean includesAll() - { - return true; - } - - public boolean includesContained() - { - return false; - } - - public boolean includesContaining() - { - return false; - } - - public boolean includesExact() - { - return false; - } - - public boolean includesAllLanguageMatches() - { - return false; - } - - public boolean includesExactLanguageMatch() - { - return false; - } - - public boolean includesAllCountryMatches() - { - return false; - } - - public boolean includesExactCountryMatch() - { - return false; - } - }, - - /** - * All language matches. Only worry about language level matches for locale. - */ - - ALL_LANGUAGES - { - public boolean includesAll() - { - return false; - } - - public boolean includesContained() - { - return false; - } - - public boolean includesContaining() - { - return false; - } - - public boolean includesExact() - { - return false; - } - - public boolean includesAllLanguageMatches() - { - return true; - } - - public boolean includesExactLanguageMatch() - { - return false; - } - - public boolean includesAllCountryMatches() - { - return false; - } - - public boolean includesExactCountryMatch() - { - return false; - } - }, - - /** - * All language matches and ALL - */ - - ALL_LANGUAGES_AND_ALL - { - public boolean includesAll() - { - return true; - } - - public boolean includesContained() - { - return false; - } - - public boolean includesContaining() - { - return false; - } - - public boolean includesExact() - { - return false; - } - - public boolean includesAllLanguageMatches() - { - return true; - } - - public boolean includesExactLanguageMatch() - { - return false; - } - - public boolean includesAllCountryMatches() - { - return false; - } - - public boolean includesExactCountryMatch() - { - return false; - } - }, - - /** - * Exact language matches (do not include all sub varients of the language) - */ - - EXACT_LANGUAGE - { - public boolean includesAll() - { - return false; - } - - public boolean includesContained() - { - return false; - } - - public boolean includesContaining() - { - return false; - } - - public boolean includesExact() - { - return false; - } - - public boolean includesAllLanguageMatches() - { - return false; - } - - public boolean includesExactLanguageMatch() - { - return true; - } - - public boolean includesAllCountryMatches() - { - return false; - } - - public boolean includesExactCountryMatch() - { - return false; - } - }, - - /** - * Exact language matches (do not include all sub varients of the language) and ALL - */ - - EXACT_LANGUAGE_AND_ALL - { - public boolean includesAll() - { - return true; - } - - public boolean includesContained() - { - return false; - } - - public boolean includesContaining() - { - return false; - } - - public boolean includesExact() - { - return false; - } - - public boolean includesAllLanguageMatches() - { - return false; - } - - public boolean includesExactLanguageMatch() - { - return true; - } - - public boolean includesAllCountryMatches() - { - return false; - } - - public boolean includesExactCountryMatch() - { - return false; - } - }, - - /** - * Exact country matches (do not include all sub varients of the country) - */ - - EXACT_COUNRTY - { - public boolean includesAll() - { - return false; - } - - public boolean includesContained() - { - return false; - } - - public boolean includesContaining() - { - return false; - } - - public boolean includesExact() - { - return false; - } - - public boolean includesAllLanguageMatches() - { - return false; - } - - public boolean includesExactLanguageMatch() - { - return false; - } - - public boolean includesAllCountryMatches() - { - return false; - } - - public boolean includesExactCountryMatch() - { - return true; - } - }, - - /** - * Exact country matches (do not include all sub varients of the country) and ALL - */ - - EXACT_COUNTRY_AND_ALL - { - public boolean includesAll() - { - return true; - } - - public boolean includesContained() - { - return false; - } - - public boolean includesContaining() - { - return false; - } - - public boolean includesExact() - { - return false; - } - - public boolean includesAllLanguageMatches() - { - return false; - } - - public boolean includesExactLanguageMatch() - { - return false; - } - - public boolean includesAllCountryMatches() - { - return false; - } - - public boolean includesExactCountryMatch() - { - return true; - } - }, - - /** - * All country matches - */ - - ALL_COUNTRIES - { - public boolean includesAll() - { - return false; - } - - public boolean includesContained() - { - return false; - } - - public boolean includesContaining() - { - return false; - } - - public boolean includesExact() - { - return false; - } - - public boolean includesAllLanguageMatches() - { - return false; - } - - public boolean includesExactLanguageMatch() - { - return false; - } - - public boolean includesAllCountryMatches() - { - return true; - } - - public boolean includesExactCountryMatch() - { - return false; - } - }, - - /** - * All countries and ALL - */ - - ALL_COUNTRIES_AND_ALL - { - public boolean includesAll() - { - return true; - } - - public boolean includesContained() - { - return false; - } - - public boolean includesContaining() - { - return false; - } - - public boolean includesExact() - { - return false; - } - - public boolean includesAllLanguageMatches() - { - return false; - } - - public boolean includesExactLanguageMatch() - { - return false; - } - - public boolean includesAllCountryMatches() - { - return true; - } - - public boolean includesExactCountryMatch() - { - return false; - } - }; - - public static MLAnalysisMode getMLAnalysisMode(String mode) - { - for (MLAnalysisMode test : MLAnalysisMode.values()) - { - if (test.toString().equalsIgnoreCase(mode)) - { - return test; - } - } - throw new AlfrescoRuntimeException("Unknown ML Analysis mode " + mode); - } - - public abstract boolean includesAll(); - - public abstract boolean includesContained(); - - public abstract boolean includesContaining(); - - public abstract boolean includesExact(); - - public abstract boolean includesAllLanguageMatches(); - - public abstract boolean includesExactLanguageMatch(); - - public abstract boolean includesAllCountryMatches(); - - public abstract boolean includesExactCountryMatch(); - - public static Set getLocales(MLAnalysisMode mlAnalaysisMode, Locale locale, boolean withWildcards) - { - HashSet locales = new HashSet(); - - boolean l = locale.getLanguage().length() != 0; - boolean c = locale.getCountry().length() != 0; - boolean v = locale.getVariant().length() != 0; - - if (mlAnalaysisMode.includesAll()) - { - if (withWildcards) - { - locales.add(new Locale("", "", "")); - locales.add(new Locale("*", "", "")); - } - else - { - locales.add(new Locale("", "", "")); - } - - } - - if (mlAnalaysisMode.includesExact()) - { - locales.add(locale); - } - - if (mlAnalaysisMode.includesContaining()) - { - if (v) - { - Locale noVarient = new Locale(locale.getLanguage(), locale.getCountry(), ""); - locales.add(noVarient); - - Locale noCountry = new Locale(locale.getLanguage(), "", ""); - locales.add(noCountry); - } - if (c) - { - Locale noCountry = new Locale(locale.getLanguage(), "", ""); - locales.add(noCountry); - } - } - - if (mlAnalaysisMode.includesContained()) - { - // varients have not contained - if (!v) - { - if (!c) - { - if (!l) - { - // All - if (withWildcards) - { - locales.add(new Locale("", "", "")); - locales.add(new Locale("*", "", "")); - } - else - { - for (Locale toAdd : Locale.getAvailableLocales()) - { - locales.add(toAdd); - } - } - } - else - { - // All that match language - if (withWildcards) - { - locales.add(new Locale(locale.getLanguage(), "", "")); - locales.add(new Locale(locale.getLanguage(), "*", "")); - } - else - { - for (Locale toAdd : Locale.getAvailableLocales()) - { - if (locale.getLanguage().equals("") || locale.getLanguage().equals(toAdd.getLanguage())) - { - locales.add(toAdd); - } - } - } - } - } - else - { - if (withWildcards) - { - locales.add(new Locale(locale.getLanguage(), locale.getCountry(), "")); - locales.add(new Locale(locale.getLanguage(), locale.getCountry(), "*")); - } - else - { - // All that match language and country - for (Locale toAdd : Locale.getAvailableLocales()) - { - if ((locale.getLanguage().equals("") || locale.getLanguage().equals(toAdd.getLanguage())) - && (locale.getCountry().equals("") || locale.getCountry() - .equals(toAdd.getCountry()))) - { - locales.add(toAdd); - } - } - } - } - } - } - - if (mlAnalaysisMode.includesAllLanguageMatches()) - { - if (withWildcards) - { - locales.add(new Locale(locale.getLanguage(), "", "")); - locales.add(new Locale(locale.getLanguage(), "*", "")); - } - else - { - // All that match language - for (Locale toAdd : Locale.getAvailableLocales()) - { - if (locale.getLanguage().equals("") || locale.getLanguage().equals(toAdd.getLanguage())) - { - locales.add(toAdd); - } - } - } - } - - if (mlAnalaysisMode.includesExactLanguageMatch()) - { - if (withWildcards) - { - locales.add(new Locale(locale.getLanguage(), "", "")); - } - else - { - locales.add(new Locale(locale.getLanguage(), "", "")); - } - } - - if (mlAnalaysisMode.includesAllCountryMatches()) - { - if (withWildcards) - { - locales.add(new Locale(locale.getLanguage(), locale.getCountry(), "")); - if(locale.getCountry().equals("")) - { - locales.add(new Locale(locale.getLanguage(), "*", "")); - } - else - { - locales.add(new Locale(locale.getLanguage(), locale.getCountry(), "*")); - } - } - else - { - // All that match language - for (Locale toAdd : Locale.getAvailableLocales()) - { - if ((locale.getLanguage().equals("") || locale.getLanguage().equals(toAdd.getLanguage())) - && (locale.getCountry().equals("") || locale.getCountry().equals(toAdd.getCountry()))) - { - locales.add(toAdd); - } - } - } - } - - if (mlAnalaysisMode.includesExactCountryMatch()) - { - if (withWildcards) - { - if(locale.getCountry().equals("")) - { - locales.add(new Locale(locale.getLanguage(), "", "")); - locales.add(new Locale(locale.getLanguage(), "*", "")); - } - else - { - locales.add(new Locale(locale.getLanguage(), locale.getCountry(), "")); - } - - } - else - { - if (locale.getCountry().equals("")) - { - for (Locale toAdd : Locale.getAvailableLocales()) - { - if (locale.getLanguage().equals("") || locale.getLanguage().equals(toAdd.getLanguage())) - { - locales.add(toAdd); - } - } - } - else - { - locales.add(new Locale(locale.getLanguage(), locale.getCountry(), "")); - } - } - } - - return locales; - } -} diff --git a/source/java/org/alfresco/repo/search/impl/querymodel/QueryOptions.java b/source/java/org/alfresco/repo/search/impl/querymodel/QueryOptions.java deleted file mode 100644 index cc85739218..0000000000 --- a/source/java/org/alfresco/repo/search/impl/querymodel/QueryOptions.java +++ /dev/null @@ -1,382 +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.search.impl.querymodel; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import org.springframework.extensions.surf.util.I18NUtil; -import org.alfresco.repo.search.MLAnalysisMode; -import org.alfresco.service.cmr.repository.StoreRef; -import org.alfresco.service.cmr.search.QueryParameterDefinition; - -/** - * The options for a query - * - * @author andyh - */ -public class QueryOptions -{ - public enum Connective - { - AND, OR; - } - - private String query; - - private List stores = new ArrayList(1); - - private int maxItems = -1; - - private int skipCount = 0; - - private Connective defaultFTSConnective = Connective.AND; - - private Connective defaultFTSFieldConnective = Connective.AND; - - private int fetchSize = 1000; - - private List locales = new ArrayList(1); - - private MLAnalysisMode mlAnalaysisMode = MLAnalysisMode.EXACT_LANGUAGE_AND_ALL; - - private List queryParameterDefinitions = new ArrayList(4); - - private boolean includeInTransactionData = true; - - // By default uses the central config - private int maxPermissionChecks = -1; - - // By default uses the central config - private long maxPermissionCheckTimeMillis = -1; - - private String defaultFieldName = "TEXT"; - - /** - * Create a CMISQueryOptions instance with the default options other than the query and store ref. The query will be - * run using the locale returned by I18NUtil.getLocale() - * - * @param query - - * the query to run - * @param storeRef - - * the store against which to run the query - */ - public QueryOptions(String query, StoreRef storeRef) - { - this(query, storeRef, I18NUtil.getLocale()); - } - - /** - * Create a CMISQueryOptions instance with the default options other than the query, store ref and locale. - * - * @param query - - * the query to run - * @param storeRef - - * the store against which to run the query - */ - public QueryOptions(String query, StoreRef storeRef, Locale locale) - { - this.query = query; - this.stores.add(storeRef); - this.locales.add(locale); - } - - /** - * Get the query string - * - * @return the query - */ - public String getQuery() - { - return query; - } - - /** - * Set the query string - * - * @param query - * the query to set - */ - public void setQuery(String query) - { - this.query = query; - } - - /** - * Get the list of stores in which to run the query. Only one store is supported at the momentOnly one store is - * supported at the moment - * - * @return the stores - */ - public List getStores() - { - return stores; - } - - /** - * Set the stores against which to run the query. Only one store is supported at the moment. - * - * @param stores - * the stores to set - */ - public void setStores(List stores) - { - this.stores = stores; - } - - /** - * Get the max number of rows for the result set 0 or less is unlimited - * - * @return the maxItems - */ - public int getMaxItems() - { - return maxItems; - } - - /** - * Set the max number of rows for the result set 0 or less is unlimited - * - * @param maxItems - * the maxItems to set - */ - public void setMaxItems(int maxItems) - { - this.maxItems = maxItems; - } - - /** - * Get the skip count - the number of rows to skip at the start of the query. - * - * @return the skipCount - */ - public int getSkipCount() - { - return skipCount; - } - - /** - * Set the skip count - the number of rows to skip at the start of the query. - * - * @param skipCount - * the skipCount to set - */ - public void setSkipCount(int skipCount) - { - this.skipCount = skipCount; - } - - /** - * Get the default connective used when OR and AND are not specified for the FTS contains() function. - * - * @return the defaultFTSConnective - */ - public Connective getDefaultFTSConnective() - { - return defaultFTSConnective; - } - - /** - * Set the default connective used when OR and AND are not specified for the FTS contains() function. - * - * @param defaultFTSConnective - * the defaultFTSConnective to set - */ - public void setDefaultFTSConnective(Connective defaultFTSConnective) - { - this.defaultFTSConnective = defaultFTSConnective; - } - - /** - * As getDefaultFTSConnective() but for field groups - * - * @return the defaultFTSFieldConnective - */ - public Connective getDefaultFTSFieldConnective() - { - return defaultFTSFieldConnective; - } - - /** - * As setDefaultFTSConnective() but for field groups - * - * @param defaultFTSFieldConnective - * the defaultFTSFieldConnective to set - */ - public void setDefaultFTSFieldConnective(Connective defaultFTSFieldConnective) - { - this.defaultFTSFieldConnective = defaultFTSFieldConnective; - } - - /** - * Get the fetch size 0 - no prefetch -1 - prefetch all - * - * @return the fetchSize - */ - public int getFetchSize() - { - return fetchSize; - } - - /** - * Set the fetch size 0 - no prefetch -1 - prefetch all - * - * @param fetchSize - * the fetchSize to set - */ - public void setFetchSize(int fetchSize) - { - this.fetchSize = fetchSize; - } - - /** - * Get the list of locales to use for the query - * - * @return the locales - */ - public List getLocales() - { - return locales; - } - - /** - * sSet the list of locales to use for the query - * - * @param locales - * the locales to set - */ - public void setLocales(List locales) - { - this.locales = locales; - } - - /** - * Get the mode for multi-lingual text analaysis - * - * @return the mlAnalaysisMode - */ - public MLAnalysisMode getMlAnalaysisMode() - { - return mlAnalaysisMode; - } - - /** - * Set the mode for multi-lingual text analaysis - * - * @param mlAnalaysisMode - * the mlAnalaysisMode to set - */ - public void setMlAnalaysisMode(MLAnalysisMode mlAnalaysisMode) - { - this.mlAnalaysisMode = mlAnalaysisMode; - } - - /** - * Get the query parameters - * - * @return the queryParameterDefinitions - */ - public List getQueryParameterDefinitions() - { - return queryParameterDefinitions; - } - - /** - * Set the query parameters - * - * @param queryParameterDefinitions - * the queryParameterDefinitions to set - */ - public void setQueryParameterDefinitions(List queryParameterDefinitions) - { - this.queryParameterDefinitions = queryParameterDefinitions; - } - - /** - * Does the search include any changes made in the current transaction? - * - * @return the includeInTransactionData - */ - public boolean isIncludeInTransactionData() - { - return includeInTransactionData; - } - - /** - * Set to true if the search include any changes made in the current transaction. - * - * @param includeInTransactionData - * the includeInTransactionData to set - */ - public void setIncludeInTransactionData(boolean includeInTransactionData) - { - this.includeInTransactionData = includeInTransactionData; - } - - /** - * @return the timeout in millis for permission checks - */ - public long getMaxPermissionCheckTimeMillis() - { - return maxPermissionCheckTimeMillis; - } - - /** - * @param maxPermissionCheckTimeMillis - - * the timeout in millis for permission checks - */ - public void setMaxPermissionCheckTimeMillis(long maxPermissionCheckTimeMillis) - { - this.maxPermissionCheckTimeMillis = maxPermissionCheckTimeMillis; - } - - /** - * @return the max number of permission checks to carry out - */ - public int getMaxPermissionChecks() - { - return maxPermissionChecks; - } - - /** - * @param maxPermissionChecks - - * the max number of permission checks to carry out - */ - public void setMaxPermissionChecks(int maxPermissionChecks) - { - this.maxPermissionChecks = maxPermissionChecks; - } - - /** - * @return the default field name - */ - public String getDefaultFieldName() - { - return defaultFieldName; - } - - /** - * @param defaultFieldName - the default field name to use - */ - public void setDefaultFieldName(String defaultFieldName) - { - this.defaultFieldName = defaultFieldName; - } -} diff --git a/source/java/org/alfresco/repo/security/authentication/AlfrescoSecureContext.java b/source/java/org/alfresco/repo/security/authentication/AlfrescoSecureContext.java deleted file mode 100644 index 7a1bced153..0000000000 --- a/source/java/org/alfresco/repo/security/authentication/AlfrescoSecureContext.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.security.authentication; - -import net.sf.acegisecurity.Authentication; -import net.sf.acegisecurity.context.security.SecureContext; - -/** - * Extensions for the Alfresco security context. - * - * This is based on the Linux model and supports real, effective and stored authorities - * - * The real authority is used for auditing and reporting who the user is etc. - * The effective authority is used for permission checks. - * - * RunAs support leaves the real authority and changes only the effective authority - * That means "special" code can run code as system but still be audited as Joe - * - * In the future scrips etc can support a setUId flag and run as the owner of the script. - * If the script chooses to do this .... - * A method invocation could do the same (after entry security checks) - * - * TODO: extent runAs to take a nodeRef context - it can then set the stored atc and set this as effective if required. - * - * @author andyh - * - */ -public interface AlfrescoSecureContext extends SecureContext -{ - /** - * Get the effective authentication - used for permission checks - * @return - */ - public Authentication getEffectiveAuthentication(); - - /** - * Get the real authenticaiton - used for auditing and everything else - * @return - */ - public Authentication getRealAuthentication(); - - /** - * Set the effective authentication held by the context - * - * @param effictiveAuthentication - */ - public void setEffectiveAuthentication(Authentication effictiveAuthentication); - - /** - * Set the real authentication held by the context - * - * @param realAuthentication - */ - public void setRealAuthentication(Authentication realAuthentication); - -} diff --git a/source/java/org/alfresco/repo/security/authentication/AlfrescoSecureContextImpl.java b/source/java/org/alfresco/repo/security/authentication/AlfrescoSecureContextImpl.java deleted file mode 100644 index 2298e63a5a..0000000000 --- a/source/java/org/alfresco/repo/security/authentication/AlfrescoSecureContextImpl.java +++ /dev/null @@ -1,150 +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.security.authentication; - -import net.sf.acegisecurity.Authentication; -import net.sf.acegisecurity.context.ContextInvalidException; - -/** - * Hold an Alfresco extended security context - * - * @author andyh - * - */ -public class AlfrescoSecureContextImpl implements AlfrescoSecureContext -{ - private static final long serialVersionUID = -8893133731693272549L; - - private Authentication realAuthentication; - - private Authentication effectiveAuthentication; - - /** - * ACEGI - */ - public Authentication getAuthentication() - { - return getEffectiveAuthentication(); - } - - /** - * ACEGI - */ - public void setAuthentication(Authentication newAuthentication) - { - setEffectiveAuthentication(newAuthentication); - } - - /** - * ACEGI - */ - public void validate() throws ContextInvalidException - { - if (effectiveAuthentication == null) - { - throw new ContextInvalidException("Effective authentication not set"); - } - } - - public Authentication getEffectiveAuthentication() - { - return effectiveAuthentication; - } - - public Authentication getRealAuthentication() - { - return realAuthentication; - } - - public void setEffectiveAuthentication(Authentication effictiveAuthentication) - { - this.effectiveAuthentication = effictiveAuthentication; - } - - public void setRealAuthentication(Authentication realAuthentication) - { - this.realAuthentication = realAuthentication; - } - - @Override - public int hashCode() - { - final int PRIME = 31; - int result = 1; - result = PRIME * result + ((effectiveAuthentication == null) ? 0 : effectiveAuthentication.hashCode()); - result = PRIME * result + ((realAuthentication == null) ? 0 : realAuthentication.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) - { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final AlfrescoSecureContextImpl other = (AlfrescoSecureContextImpl) obj; - if (effectiveAuthentication == null) - { - if (other.effectiveAuthentication != null) - return false; - } - else if (!effectiveAuthentication.equals(other.effectiveAuthentication)) - return false; - if (realAuthentication == null) - { - if (other.realAuthentication != null) - return false; - } - else if (!realAuthentication.equals(other.realAuthentication)) - return false; - return true; - } - - @Override - public String toString() - { - StringBuilder builder = new StringBuilder(); - - if (realAuthentication == null) - { - builder.append("Real authenticaion = null"); - } - else - { - builder.append("Real authenticaion = " + realAuthentication.toString()); - } - builder.append(", "); - - if (effectiveAuthentication == null) - { - builder.append("Effective authenticaion = null"); - } - else - { - builder.append("Effective authenticaion = " + effectiveAuthentication.toString()); - } - builder.append(", "); - - return builder.toString(); - } - -} diff --git a/source/java/org/alfresco/repo/security/authentication/AuthenticationException.java b/source/java/org/alfresco/repo/security/authentication/AuthenticationException.java deleted file mode 100644 index cc34030b8a..0000000000 --- a/source/java/org/alfresco/repo/security/authentication/AuthenticationException.java +++ /dev/null @@ -1,46 +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.security.authentication; - -import org.alfresco.error.AlfrescoRuntimeException; - -/** - * Alfresco Authentication Exception and wrapper - * - * @author andyh - * - */ -public class AuthenticationException extends AlfrescoRuntimeException -{ - - /** - * - */ - private static final long serialVersionUID = 3546647620128092466L; - - public AuthenticationException(String msg) - { - super(msg); - } - - public AuthenticationException(String msg, Throwable cause) - { - super(msg, cause); - } -} diff --git a/source/java/org/alfresco/repo/security/authentication/AuthenticationUtil.java b/source/java/org/alfresco/repo/security/authentication/AuthenticationUtil.java deleted file mode 100644 index 5f04a75d8a..0000000000 --- a/source/java/org/alfresco/repo/security/authentication/AuthenticationUtil.java +++ /dev/null @@ -1,627 +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.security.authentication; - -import java.util.Stack; - -import net.sf.acegisecurity.Authentication; -import net.sf.acegisecurity.GrantedAuthority; -import net.sf.acegisecurity.GrantedAuthorityImpl; -import net.sf.acegisecurity.UserDetails; -import net.sf.acegisecurity.context.Context; -import net.sf.acegisecurity.context.ContextHolder; -import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken; -import net.sf.acegisecurity.providers.dao.User; - -import org.alfresco.repo.tenant.TenantService; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.util.EqualsHelper; -import org.alfresco.util.log.NDC; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.beans.factory.InitializingBean; - -/** - * Utility helper methods to change the authenticated context for threads. - */ -public class AuthenticationUtil implements InitializingBean -{ - static Log s_logger = LogFactory.getLog(AuthenticationUtil.class); - - public interface RunAsWork - { - /** - * Method containing the work to be done in the user transaction. - * - * @return Return the result of the operation - */ - Result doWork() throws Exception; - } - - private static boolean initialized = false; - - public static final String SYSTEM_USER_NAME = "System"; - private static String defaultAdminUserName = PermissionService.ADMINISTRATOR_AUTHORITY; - private static String defaultGuestUserName = PermissionService.GUEST_AUTHORITY; - private static boolean mtEnabled = false; - - /* (non-Javadoc) - * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() - */ - public void afterPropertiesSet() throws Exception - { - // at this point default admin and guest names have been assigned - initialized = true; - } - - public void setDefaultAdminUserName(String defaultAdminUserName) - { - AuthenticationUtil.defaultAdminUserName = defaultAdminUserName; - } - - public void setDefaultGuestUserName(String defaultGuestUserName) - { - AuthenticationUtil.defaultGuestUserName = defaultGuestUserName; - } - - public static void setMtEnabled(boolean mtEnabled) - { - if (!AuthenticationUtil.mtEnabled) - { - AuthenticationUtil.mtEnabled = mtEnabled; - } - } - - public static boolean isMtEnabled() - { - return AuthenticationUtil.mtEnabled; - } - - public AuthenticationUtil() - { - super(); - } - - /** - * Utility method to create an authentication token - */ - private static UsernamePasswordAuthenticationToken getAuthenticationToken(String userName, UserDetails providedDetails) - { - UserDetails ud = null; - if (userName.equals(SYSTEM_USER_NAME)) - { - GrantedAuthority[] gas = new GrantedAuthority[1]; - gas[0] = new GrantedAuthorityImpl("ROLE_SYSTEM"); - ud = new User(SYSTEM_USER_NAME, "", true, true, true, true, gas); - } - else if (userName.equalsIgnoreCase(getGuestUserName())) - { - GrantedAuthority[] gas = new GrantedAuthority[0]; - ud = new User(getGuestUserName().toLowerCase(), "", true, true, true, true, gas); - } - else - { - if (providedDetails.getUsername().equals(userName)) - { - ud = providedDetails; - } - else - { - throw new AuthenticationException("Provided user details do not match the user name"); - } - } - - UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(ud, "", ud.getAuthorities()); - auth.setDetails(ud); - auth.setAuthenticated(true); - return auth; - } - - /** - * Default implementation that makes an ACEGI object on the fly - */ - private static UserDetails getDefaultUserDetails(String userName) - { - GrantedAuthority[] gas = new GrantedAuthority[1]; - gas[0] = new GrantedAuthorityImpl("ROLE_AUTHENTICATED"); - UserDetails ud = new User(userName, "", true, true, true, true, gas); - return ud; - } - - /** - * Extract the username from the authentication. - */ - private static String getUserName(Authentication authentication) - { - if (authentication.getPrincipal() instanceof UserDetails) - { - return ((UserDetails) authentication.getPrincipal()).getUsername(); - } - else - { - return authentication.getPrincipal().toString(); - } - } - - /** - * Authenticate as the given user. The user will be authenticated and all operations - * with be run in the context of this user. - * - * @param userName the user name - * @return the authentication token - */ - public static Authentication setFullyAuthenticatedUser(String userName) - { - return setFullyAuthenticatedUser(userName, getDefaultUserDetails(userName)); - } - - private static Authentication setFullyAuthenticatedUser(String userName, UserDetails providedDetails) throws AuthenticationException - { - if (userName == null) - { - throw new AuthenticationException("Null user name"); - } - - try - { - UsernamePasswordAuthenticationToken auth = getAuthenticationToken(userName, providedDetails); - return setFullAuthentication(auth); - } - catch (net.sf.acegisecurity.AuthenticationException ae) - { - throw new AuthenticationException(ae.getMessage(), ae); - } - } - - /** - * Re-authenticate using a previously-created authentication. - */ - public static Authentication setFullAuthentication(Authentication authentication) - { - if (authentication == null) - { - clearCurrentSecurityContext(); - return null; - } - else - { - Context context = ContextHolder.getContext(); - AlfrescoSecureContext sc = null; - if ((context == null) || !(context instanceof AlfrescoSecureContext)) - { - sc = new AlfrescoSecureContextImpl(); - ContextHolder.setContext(sc); - } - else - { - sc = (AlfrescoSecureContext) context; - } - authentication.setAuthenticated(true); - // Sets real and effective - sc.setRealAuthentication(authentication); - sc.setEffectiveAuthentication(authentication); - return authentication; - } - } - - /** - * WARN: Advanced usage only.
- * Set the system user as the currently running user for authentication purposes. - * - * @return Authentication - * - * @see #setRunAsUser(String) - */ - public static Authentication setRunAsUserSystem() - { - return setRunAsUser(SYSTEM_USER_NAME); - } - - /** - * WARN: Advanced usage only.
- * Switch to the given user for all authenticated operations. The original, authenticated user - * can still be found using {@link #getAuthenticatedUser()}. - * - * @param userName the user to run as - * @return the new authentication - */ - public static Authentication setRunAsUser(String userName) - { - return setRunAsUser(userName, getDefaultUserDetails(userName)); - } - - /*package*/ static Authentication setRunAsUser(String userName, UserDetails providedDetails) throws AuthenticationException - { - if (userName == null) - { - throw new AuthenticationException("Null user name"); - } - - try - { - UsernamePasswordAuthenticationToken auth = getAuthenticationToken(userName, providedDetails); - return setRunAsAuthentication(auth); - } - catch (net.sf.acegisecurity.AuthenticationException ae) - { - throw new AuthenticationException(ae.getMessage(), ae); - } - } - - /*package*/ static Authentication setRunAsAuthentication(Authentication authentication) - { - if (authentication == null) - { - clearCurrentSecurityContext(); - return null; - } - else - { - Context context = ContextHolder.getContext(); - AlfrescoSecureContext sc = null; - if ((context == null) || !(context instanceof AlfrescoSecureContext)) - { - sc = new AlfrescoSecureContextImpl(); - ContextHolder.setContext(sc); - } - else - { - sc = (AlfrescoSecureContext) context; - } - authentication.setAuthenticated(true); - if (sc.getRealAuthentication() == null) - { - // There is no authentication in action - sc.setRealAuthentication(authentication); - } - sc.setEffectiveAuthentication(authentication); - return authentication; - } - } - - /** - * Get the current authentication for application of permissions. This includes - * the any overlay details set by {@link #setRunAsUser(String)}. - * - * @return Authentication Returns the running authentication - * @throws AuthenticationException - */ - public static Authentication getRunAsAuthentication() throws AuthenticationException - { - Context context = ContextHolder.getContext(); - if ((context == null) || !(context instanceof AlfrescoSecureContext)) - { - return null; - } - return ((AlfrescoSecureContext) context).getEffectiveAuthentication(); - } - - /** - * WARN: Advanced usage only.
- * Get the authentication for that was set by an real authentication. - * - * @return Authentication Returns the real authentication - * @throws AuthenticationException - */ - public static Authentication getFullAuthentication() throws AuthenticationException - { - Context context = ContextHolder.getContext(); - if ((context == null) || !(context instanceof AlfrescoSecureContext)) - { - return null; - } - return ((AlfrescoSecureContext) context).getRealAuthentication(); - } - - /** - * Get the user that is currently in effect for purposes of authentication. This includes - * any overlays introduced by {@link #setRunAsUser(String) runAs}. - * - * @return Returns the name of the user - * @throws AuthenticationException - */ - public static String getRunAsUser() throws AuthenticationException - { - Context context = ContextHolder.getContext(); - if ((context == null) || !(context instanceof AlfrescoSecureContext)) - { - return null; - } - AlfrescoSecureContext ctx = (AlfrescoSecureContext) context; - if (ctx.getEffectiveAuthentication() == null) - { - return null; - } - return getUserName(ctx.getEffectiveAuthentication()); - } - - public static boolean isRunAsUserTheSystemUser() - { - String runAsUser = getRunAsUser(); - if ((runAsUser != null) && isMtEnabled()) - { - // get base username - int idx = runAsUser.indexOf(TenantService.SEPARATOR); - if (idx != -1) - { - runAsUser = runAsUser.substring(0, idx); - } - } - return EqualsHelper.nullSafeEquals(runAsUser, AuthenticationUtil.SYSTEM_USER_NAME); - } - - /** - * Get the fully authenticated user. - * It returns the name of the user that last authenticated and excludes any overlay authentication set - * by {@link #runAs(org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork, String) runAs}. - * - * @return Returns the name of the authenticated user - * @throws AuthenticationException - */ - public static String getFullyAuthenticatedUser() throws AuthenticationException - { - Context context = ContextHolder.getContext(); - if ((context == null) || !(context instanceof AlfrescoSecureContext)) - { - return null; - } - AlfrescoSecureContext ctx = (AlfrescoSecureContext) context; - if (ctx.getRealAuthentication() == null) - { - return null; - } - return getUserName(ctx.getRealAuthentication()); - } - - /** - * Get the name of the system user - * - * @return system user name - */ - public static String getSystemUserName() - { - return SYSTEM_USER_NAME; - } - - /** - * Get the name of the default admin user (the admin user created during bootstrap) - * - * @return admin user name - */ - public static String getAdminUserName() - { - if (!initialized) - { - throw new IllegalStateException("AuthenticationUtil not yet initialised; default admin username not available"); - } - - if (isMtEnabled()) - { - String runAsUser = AuthenticationUtil.getRunAsUser(); - if (runAsUser != null) - { - String[] parts = splitUserTenant(runAsUser); - if (parts.length == 2) - { - return defaultAdminUserName + TenantService.SEPARATOR + parts[1]; - } - } - } - - return defaultAdminUserName; - } - - /* - * Get the name of admin role - */ - public static String getAdminRoleName() - { - return PermissionService.ADMINISTRATOR_AUTHORITY; - } - - /** - * Get the name of the Guest User - */ - public static String getGuestUserName() - { - if (!initialized) - { - throw new IllegalStateException("AuthenticationUtil not yet initialised; default guest username not available"); - } - return defaultGuestUserName; - } - - /** - * Get the name of the guest role - */ - public static String getGuestRoleName() - { - return PermissionService.GUEST_AUTHORITY; - } - - /** - * Remove the current security information - */ - public static void clearCurrentSecurityContext() - { - ContextHolder.setContext(null); - InMemoryTicketComponentImpl.clearCurrentSecurityContext(); - - NDC.remove(); - } - - /** - * Execute a unit of work as a given user. The thread's authenticated user will be returned to its normal state - * after the call. - * - * @param runAsWork - * the unit of work to do - * @param uid - * the user ID - * @return Returns the work's return value - */ - public static R runAs(RunAsWork runAsWork, String uid) - { - Authentication originalFullAuthentication = AuthenticationUtil.getFullAuthentication(); - Authentication originalRunAsAuthentication = AuthenticationUtil.getRunAsAuthentication(); - - final R result; - try - { - if (originalFullAuthentication == null) - { - AuthenticationUtil.setFullyAuthenticatedUser(uid); - } - else - { - if ((originalRunAsAuthentication != null) && (isMtEnabled())) - { - String originalRunAsUserName = getUserName(originalRunAsAuthentication); - int idx = originalRunAsUserName.indexOf(TenantService.SEPARATOR); - if ((idx != -1) && (idx < (originalRunAsUserName.length() - 1))) - { - if (uid.equals(AuthenticationUtil.getSystemUserName())) - { - uid = uid + TenantService.SEPARATOR + originalRunAsUserName.substring(idx + 1); - } - } - } - AuthenticationUtil.setRunAsUser(uid); - } - logNDC(uid); - result = runAsWork.doWork(); - return result; - } - catch (Throwable exception) - { - // Re-throw the exception - if (exception instanceof RuntimeException) - { - throw (RuntimeException) exception; - } - else - { - throw new RuntimeException("Error during run as.", exception); - } - } - finally - { - if (originalFullAuthentication == null) - { - AuthenticationUtil.clearCurrentSecurityContext(); - logNDC(null); - } - else - { - AuthenticationUtil.setFullAuthentication(originalFullAuthentication); - AuthenticationUtil.setRunAsAuthentication(originalRunAsAuthentication); - - logNDC(getUserName(originalFullAuthentication)); - } - } - } - - static class ThreadLocalStack extends ThreadLocal> { - - /* (non-Javadoc) - * @see java.lang.ThreadLocal#initialValue() - */ - @Override - protected Stack initialValue() - { - return new Stack(); - } - - } - private static ThreadLocal> threadLocalFullAuthenticationStack = new ThreadLocalStack(); - private static ThreadLocal> threadLocalRunAsAuthenticationStack = new ThreadLocalStack(); - - /** - * Push the current authentication context onto a threadlocal stack. - */ - public static void pushAuthentication() - { - Authentication originalFullAuthentication = AuthenticationUtil.getFullAuthentication(); - Authentication originalRunAsAuthentication = AuthenticationUtil.getRunAsAuthentication(); - threadLocalFullAuthenticationStack.get().push(originalFullAuthentication); - threadLocalRunAsAuthenticationStack.get().push(originalRunAsAuthentication); - } - - /** - * Pop the authentication context from a threadlocal stack. - */ - public static void popAuthentication() - { - Authentication originalFullAuthentication = threadLocalFullAuthenticationStack.get().pop(); - Authentication originalRunAsAuthentication = threadLocalRunAsAuthenticationStack.get().pop(); - if (originalFullAuthentication == null) - { - AuthenticationUtil.clearCurrentSecurityContext(); - } - else - { - AuthenticationUtil.setFullAuthentication(originalFullAuthentication); - AuthenticationUtil.setRunAsAuthentication(originalRunAsAuthentication); - } - } - - /** - * Logs the current authenticated users - */ - public static void logAuthenticatedUsers() - { - if (s_logger.isDebugEnabled()) - { - s_logger.debug( - "Authentication: \n" + - " Fully authenticated: " + AuthenticationUtil.getFullyAuthenticatedUser() + "\n" + - " Run as: " + AuthenticationUtil.getRunAsUser()); - } - } - - public static void logNDC(String userName) - { - NDC.remove(); - - if (userName != null) - { - if (isMtEnabled()) - { - String[] parts = splitUserTenant(userName); - if (parts.length == 2) - { - NDC.push("Tenant:" + parts[1] + " User:" + parts[0]); - } - else - { - NDC.push("User:" + userName); - } - } - else - { - NDC.push("User:" + userName); - } - } - } - - private static String[] splitUserTenant(String userName) - { - return userName.split(TenantService.SEPARATOR); - } -} diff --git a/source/java/org/alfresco/repo/security/authentication/InMemoryTicketComponentImpl.java b/source/java/org/alfresco/repo/security/authentication/InMemoryTicketComponentImpl.java deleted file mode 100644 index bdaa4acd43..0000000000 --- a/source/java/org/alfresco/repo/security/authentication/InMemoryTicketComponentImpl.java +++ /dev/null @@ -1,598 +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.security.authentication; - -import java.io.Serializable; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Collections; -import java.util.Date; -import java.util.HashSet; -import java.util.Set; -import java.util.zip.CRC32; - -import org.alfresco.repo.cache.SimpleCache; -import org.alfresco.service.cmr.repository.datatype.Duration; -import org.alfresco.util.GUID; -import org.apache.commons.codec.binary.Hex; -import org.safehaus.uuid.UUIDGenerator; - -/** - * Store tickets in memory. They can be distributed in a cluster via the cache - * - * @author andyh - */ -public class InMemoryTicketComponentImpl implements TicketComponent -{ - /** - * Ticket prefix - */ - public static final String GRANTED_AUTHORITY_TICKET_PREFIX = "TICKET_"; - - private static ThreadLocal currentTicket = new ThreadLocal(); - - private boolean ticketsExpire; - - private Duration validDuration; - - private boolean oneOff; - - private String guid; - - private SimpleCache ticketsCache; // Can't use Ticket as it's private - - private ExpiryMode expiryMode = ExpiryMode.AFTER_FIXED_TIME; - - /** - * IOC constructor - */ - public InMemoryTicketComponentImpl() - { - super(); - guid = GUID.generate(); - } - - /** - * Set the ticket cache to support clustering - * - * @param ticketsCache - */ - public void setTicketsCache(SimpleCache ticketsCache) - { - this.ticketsCache = ticketsCache; - } - - public String getNewTicket(String userName, String sessionId) throws AuthenticationException - { - Date expiryDate = null; - if (ticketsExpire) - { - expiryDate = Duration.add(new Date(), validDuration); - } - Ticket ticket = new Ticket(ticketsExpire ? expiryMode : ExpiryMode.DO_NOT_EXPIRE, expiryDate, userName, - validDuration, sessionId == null ? Collections. emptySet() : Collections.singleton(sessionId)); - ticketsCache.put(ticket.getTicketId(), ticket); - String ticketString = GRANTED_AUTHORITY_TICKET_PREFIX + ticket.getTicketId(); - currentTicket.set(ticketString); - return ticketString; - } - - public String validateTicket(String ticketString, String sessionId) throws AuthenticationException - { - String ticketKey = getTicketKey(ticketString); - Ticket ticket = this.ticketsCache.get(ticketKey); - if (ticket == null) - { - throw new AuthenticationException("Missing ticket for " + ticketString); - } - if (ticket.hasExpired()) - { - throw new TicketExpiredException("Ticket expired for " + ticketString); - } - // TODO: Recheck the user details here - // TODO: Strengthen ticket as GUID is predicatble - if (oneOff) - { - ticketsCache.remove(ticketKey); - } - // Make sure the association with the session is recorded - else if (sessionId != null) - { - Ticket newTicket = ticket.addSessionId(sessionId); - if (newTicket != ticket) - { - ticketsCache.put(ticketKey, newTicket); - ticket = newTicket; - } - } - currentTicket.set(ticketString); - return ticket.getUserName(); - } - - /** - * Helper method to find a ticket - * - * @param ticketString - * @return - the ticket - */ - private Ticket getTicketByTicketString(String ticketString) - { - Ticket ticket = ticketsCache.get(getTicketKey(ticketString)); - return ticket; - } - - /** - * Helper method to extract the ticket id from the ticket string - * - * @param ticketString - * @return - the ticket key - */ - private String getTicketKey(String ticketString) - { - if (ticketString == null) - { - return null; - } - else if (ticketString.length() < GRANTED_AUTHORITY_TICKET_PREFIX.length()) - { - throw new AuthenticationException(ticketString + " is an invalid ticket format"); - } - - String key = ticketString.substring(GRANTED_AUTHORITY_TICKET_PREFIX.length()); - return key; - } - - public void invalidateTicketById(String ticketString, String sessionId) - { - String ticketKey = getTicketKey(ticketString); - // If we are dissassociating the ticket from an app server session, it may still not be time to expire it, as it - // may be in use by other sessions - if (sessionId != null) - { - Ticket ticketObj = ticketsCache.get(ticketKey); - if (ticketObj != null) - { - ticketObj = ticketObj.removeSessionId(sessionId); - if (ticketObj == null) - { - ticketsCache.remove(ticketKey); - } - else - { - ticketsCache.put(ticketKey, ticketObj); - } - } - } - else - { - ticketsCache.remove(ticketKey); - } - } - - /* - * (non-Javadoc) - * @see org.alfresco.repo.security.authentication.TicketComponent#getUsersWithTickets(boolean) - */ - public Set getUsersWithTickets(boolean nonExpiredOnly) - { - Set users = new HashSet(); - for (String key : ticketsCache.getKeys()) - { - Ticket ticket = ticketsCache.get(key); - if (ticket != null) - { - if ((nonExpiredOnly == false) || (! ticket.hasExpired())) - { - users.add(ticket.getUserName()); - } - } - } - return users; - } - - /* - * (non-Javadoc) - * @see org.alfresco.repo.security.authentication.TicketComponent#countTickets(boolean) - */ - public int countTickets(boolean nonExpiredOnly) - { - if (nonExpiredOnly) - { - int count = 0; - for (String key : ticketsCache.getKeys()) - { - Ticket ticket = ticketsCache.get(key); - if (! ticket.hasExpired()) - { - count++; - } - } - return count; - } - else - { - return ticketsCache.getKeys().size(); - } - } - - /* - * (non-Javadoc) - * @see org.alfresco.repo.security.authentication.TicketComponent#invalidateTickets(boolean) - */ - public int invalidateTickets(boolean expiredOnly) - { - int count = 0; - if (! expiredOnly) - { - count = ticketsCache.getKeys().size(); - ticketsCache.clear(); - } - else - { - for (String key : ticketsCache.getKeys()) - { - Ticket ticket = ticketsCache.get(key); - if (ticket == null || ticket.hasExpired()) - { - count++; - ticketsCache.remove(key); - } - } - } - return count; - } - - public void invalidateTicketByUser(String userName) - { - Set toRemove = new HashSet(); - - for (String key : ticketsCache.getKeys()) - { - Ticket ticket = ticketsCache.get(key); - // Hack: The getKeys() call might return keys for null marker objects, yielding null values - if (ticket == null) - { - continue; - } - if (ticket.getUserName().equals(userName)) - { - toRemove.add(ticket.getTicketId()); - } - } - - for (String id : toRemove) - { - ticketsCache.remove(id); - } - } - - - @Override - public int hashCode() - { - final int PRIME = 31; - int result = 1; - result = PRIME * result + ((guid == null) ? 0 : guid.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) - { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final InMemoryTicketComponentImpl other = (InMemoryTicketComponentImpl) obj; - if (guid == null) - { - if (other.guid != null) - return false; - } - else if (!guid.equals(other.guid)) - return false; - return true; - } - - - /** - * Ticket - * - * @author andyh - */ - public static class Ticket implements Serializable - { - private static final long serialVersionUID = -5904510560161261049L; - - private ExpiryMode expires; - - private Date expiryDate; - - private String userName; - - private String ticketId; - - private String guid; - - private Duration validDuration; - - private Set sessionIds; - - private Ticket(Ticket copy, Set sessionIds) - { - this.expires = copy.expires; - this.expiryDate = copy.expiryDate; - this.userName = copy.userName; - this.validDuration = copy.validDuration; - this.guid = copy.guid; - this.ticketId = copy.ticketId; - this.sessionIds = sessionIds; - } - - Ticket(ExpiryMode expires, Date expiryDate, String userName, Duration validDuration, Set sessionIds) - { - this.expires = expires; - this.expiryDate = expiryDate; - this.userName = userName; - this.validDuration = validDuration; - this.sessionIds = sessionIds; - this.guid = UUIDGenerator.getInstance().generateRandomBasedUUID().toString(); - - String encode = (expires.toString()) + ((expiryDate == null) ? new Date().toString() : expiryDate.toString()) + userName + guid; - MessageDigest digester; - try - { - digester = MessageDigest.getInstance("SHA-1"); - this.ticketId = new String(Hex.encodeHex(digester.digest(encode.getBytes()))); - } - catch (NoSuchAlgorithmException e) - { - try - { - digester = MessageDigest.getInstance("MD5"); - this.ticketId = new String(Hex.encodeHex(digester.digest(encode.getBytes()))); - } - catch (NoSuchAlgorithmException e1) - { - CRC32 crc = new CRC32(); - crc.update(encode.getBytes()); - byte[] bytes = new byte[4]; - long value = crc.getValue(); - bytes[0] = (byte) (value & 0xFF); - value >>>= 4; - bytes[1] = (byte) (value & 0xFF); - value >>>= 4; - bytes[2] = (byte) (value & 0xFF); - value >>>= 4; - bytes[3] = (byte) (value & 0xFF); - this.ticketId = new String(Hex.encodeHex(bytes)); - } - } - } - - public Ticket addSessionId(String sessionId) - { - if (this.sessionIds.contains(sessionId)) - { - return this; - } - Set newSessionIds = new HashSet(this.sessionIds.size() * 2 + 2); - newSessionIds.addAll(this.sessionIds); - newSessionIds.add(sessionId); - return new Ticket(this, newSessionIds); - } - - public Ticket removeSessionId(String sessionId) - { - if (this.sessionIds.contains(sessionId)) - { - Set newSessionIds; - if (this.sessionIds.size() > 1) - { - newSessionIds = new HashSet(this.sessionIds.size() * 2 - 2); - newSessionIds.addAll(this.sessionIds); - newSessionIds.remove(sessionId); - return new Ticket(this, newSessionIds); - } - return null; - } - return this; - } - - /** - * Has the ticket expired - * - * @return - if expired - */ - boolean hasExpired() - { - switch (expires) - { - case AFTER_FIXED_TIME: - if ((expiryDate != null) && (expiryDate.compareTo(new Date()) < 0)) - { - return true; - } - else - { - return false; - } - - case AFTER_INACTIVITY: - Date now = new Date(); - if ((expiryDate != null) && (expiryDate.compareTo(now) < 0)) - { - return true; - } - else - { - expiryDate = Duration.add(now, validDuration); - return false; - } - - case DO_NOT_EXPIRE: - default: - return false; - } - } - - public boolean equals(Object o) - { - if (o == this) - { - return true; - } - if (!(o instanceof Ticket)) - { - return false; - } - Ticket t = (Ticket) o; - return (this.expires == t.expires) && this.expiryDate.equals(t.expiryDate) && this.userName.equals(t.userName) && this.ticketId.equals(t.ticketId); - } - - public int hashCode() - { - return ticketId.hashCode(); - } - - protected ExpiryMode getExpires() - { - return expires; - } - - protected Date getExpiryDate() - { - return expiryDate; - } - - protected String getTicketId() - { - return ticketId; - } - - protected String getUserName() - { - return userName; - } - - protected Set getSessionIds() - { - return sessionIds; - } - } - - /** - * Are tickets single use - * - * @param oneOff - */ - public void setOneOff(boolean oneOff) - { - this.oneOff = oneOff; - } - - /** - * Do tickets expire - * - * @param ticketsExpire - */ - public void setTicketsExpire(boolean ticketsExpire) - { - this.ticketsExpire = ticketsExpire; - } - - - /** - * How should tickets expire. - * @param exipryMode - */ - public void setExpiryMode(String expiryMode) - { - this.expiryMode = ExpiryMode.valueOf(expiryMode); - } - - /** - * How long are tickets valid (XML duration as a string) - * - * @param validDuration - */ - public void setValidDuration(String validDuration) - { - this.validDuration = new Duration(validDuration); - } - - public String getAuthorityForTicket(String ticketString) - { - Ticket ticket = getTicketByTicketString(ticketString); - if (ticket == null) - { - return null; - } - return ticket.getUserName(); - } - - public String getCurrentTicket(String userName, String sessionId, boolean autoCreate) - { - String ticketString = currentTicket.get(); - if (ticketString == null) - { - return autoCreate ? getNewTicket(userName, sessionId) : null; - } - String ticketKey = getTicketKey(ticketString); - Ticket ticketObj = this.ticketsCache.get(ticketKey); - if (ticketObj != null && userName.equals(ticketObj.getUserName())) - { - if (sessionId != null) - { - // A current, as yet unclaimed valid ticket. Make the association with the session now - if (ticketObj.getSessionIds().isEmpty()) - { - this.ticketsCache.put(ticketKey, ticketObj.addSessionId(sessionId)); - } - // The ticket is already claimed by at least one other session, so start a new one - else - { - return autoCreate ? getNewTicket(userName, sessionId) : null; - } - } - return ticketString; - } - else - { - return autoCreate ? getNewTicket(userName, sessionId) : null; - } - } - - public void clearCurrentTicket() - { - clearCurrentSecurityContext(); - } - - public static void clearCurrentSecurityContext() - { - currentTicket.set(null); - } - - public enum ExpiryMode - { - AFTER_INACTIVITY, AFTER_FIXED_TIME, DO_NOT_EXPIRE; - } -} diff --git a/source/java/org/alfresco/repo/security/authentication/TicketComponent.java b/source/java/org/alfresco/repo/security/authentication/TicketComponent.java deleted file mode 100644 index 8648a269c9..0000000000 --- a/source/java/org/alfresco/repo/security/authentication/TicketComponent.java +++ /dev/null @@ -1,144 +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.security.authentication; - -import java.util.Set; - - -/** - * Manage authentication tickets - * - * @author andyh - * - */ -public interface TicketComponent -{ - /** - * Register a new ticket. If a session ID is given, an association with that session ID will be recorded for the - * returned ticket. - * - * @param userName - * @param sessionId - * the app server session ID (e.g. HttpSession ID) or null if not applicable. - * @return - the ticket - * @throws AuthenticationException - */ - public String getNewTicket(String userName, String sessionId) throws AuthenticationException; - - /** - * Gets the current ticket. If a session ID is given, an association with that session ID will be recorded for the - * returned ticket. - * - * @param userName - * @param sessionId - * the app server session ID (e.g. HttpSession ID) or null if not applicable. - * @param autoCreate - * should we create one automatically if there isn't one? - * @return - the ticket - */ - public String getCurrentTicket(String userName, String sessionId, boolean autoCreate); - - /** - * Check that a certificate is valid and can be used in place of a login. Optionally records an association between - * the ticket and a given app server session Id. This is so that we don't expire tickets prematurely referenced by - * more than one application server session. Tickets may be rejected because: - *

    - *
  1. The certificate does not exists - *
  2. The status of the user has changed - *
      - *
    1. The user is locked - *
    2. The account has expired - *
    3. The credentials have expired - *
    4. The account is disabled - *
    - *
  3. The ticket may have expired - *
      - *
    1. The ticked my be invalid by timed expiry - *
    2. An attemp to reuse a once only ticket - *
    - *
- * - * @param ticket - * @param sessionId - * the app server session ID (e.g. HttpSession ID) or null if not applicable. - * @return - the user name - * @throws AuthenticationException - */ - public String validateTicket(String ticket, String sessionId) throws AuthenticationException; - - /** - * Invalidates a ticket, or disassociates it from an app server session. Once it has been disassociated from all - * sessions, the ticket will be invalidated globally. - * - * @param ticket - * @param sessionId - * the app server session ID (e.g. HttpSession ID) or null if the ticket should be - * invalidated globally. - */ - public void invalidateTicketById(String ticket, String sessionId); - - /** - * Invalidate all user tickets - * - * @param userName - */ - public void invalidateTicketByUser(String userName); - - /** - * Count tickets - * - * This may be higher than the user count, since a user can have more than one ticket/session - * - * @param nonExpiredOnly true for non expired tickets, false for all (including expired) tickets - * @return int number of tickets - */ - public int countTickets(boolean nonExpiredOnly); - - /** - * Get set of users with tickets - * - * This may be lower than the ticket count, since a user can have more than one ticket/session - * - * @param nonExpiredOnly true for non expired tickets, false for all (including expired) tickets - * @return Set set of users with (one or more) tickets - */ - public Set getUsersWithTickets(boolean nonExpiredOnly); - - /** - * Invalidate tickets - * - * @param expiredOnly true for EXPIRED tickets, false for ALL (including non-expired) tickets - * @return int count of invalidated tickets - */ - public int invalidateTickets(boolean expiredOnly); - - /** - * Get the authority for the given ticket - * - * @param ticket - * @return the authority - */ - public String getAuthorityForTicket(String ticket); - - /** - * Clear the current ticket - * - */ - public void clearCurrentTicket(); -} diff --git a/source/java/org/alfresco/repo/security/authentication/TicketExpiredException.java b/source/java/org/alfresco/repo/security/authentication/TicketExpiredException.java deleted file mode 100644 index decfe3a4e4..0000000000 --- a/source/java/org/alfresco/repo/security/authentication/TicketExpiredException.java +++ /dev/null @@ -1,39 +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.security.authentication; - -public class TicketExpiredException extends AuthenticationException -{ - - /** - * - */ - private static final long serialVersionUID = 3257572801815590969L; - - public TicketExpiredException(String msg) - { - super(msg); - } - - public TicketExpiredException(String msg, Throwable cause) - { - super(msg, cause); - } - -} diff --git a/source/java/org/alfresco/repo/tenant/SingleTServiceImpl.java b/source/java/org/alfresco/repo/tenant/SingleTServiceImpl.java deleted file mode 100644 index 0748941b3e..0000000000 --- a/source/java/org/alfresco/repo/tenant/SingleTServiceImpl.java +++ /dev/null @@ -1,181 +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.tenant; - -import org.alfresco.service.cmr.repository.AssociationRef; -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.cmr.repository.StoreRef; -import org.alfresco.service.cmr.search.SearchService; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; - -/** - * Empty Tenant Service implementation (for Single-Tenant / Single-Instance) - */ - -public class SingleTServiceImpl implements TenantService -{ - public NodeRef getName(NodeRef nodeRef) - { - return nodeRef; - } - - public NodeRef getName(NodeRef inNodeRef, NodeRef nodeRef) - { - return nodeRef; - } - - public StoreRef getName(StoreRef storeRef) - { - return storeRef; - } - - public ChildAssociationRef getName(ChildAssociationRef childAssocRef) - { - return childAssocRef; - } - - public AssociationRef getName(AssociationRef assocRef) - { - return assocRef; - } - - public StoreRef getName(String username, StoreRef storeRef) - { - return storeRef; - } - - public QName getName(QName name) - { - return name; - } - - public QName getName(NodeRef inNodeRef, QName name) - { - return name; - } - - public String getName(String name) - { - return name; - } - - public QName getBaseName(QName name, boolean forceForNonTenant) - { - return name; - } - - public NodeRef getBaseName(NodeRef nodeRef) - { - return nodeRef; - } - - public StoreRef getBaseName(StoreRef storeRef) - { - return storeRef; - } - - public ChildAssociationRef getBaseName(ChildAssociationRef childAssocRef) - { - return childAssocRef; - } - - public AssociationRef getBaseName(AssociationRef assocRef) - { - return assocRef; - } - - public String getBaseName(String name) - { - return name; - } - - - public String getBaseName(String name, boolean forceForNonTenant) - { - return name; - } - - public String getBaseNameUser(String name) - { - return name; - } - - public void checkDomainUser(String username) - { - // NOOP - } - - public void checkDomain(String name) - { - // NOOP - } - - public NodeRef getRootNode(NodeService nodeService, SearchService searchService, NamespaceService namespaceService, String rootPath, NodeRef rootNodeRef) - { - return rootNodeRef; - } - - public boolean isTenantUser() - { - return false; - } - - public boolean isTenantUser(String username) - { - return false; - } - - public boolean isTenantName(String name) - { - return false; - } - - public String getUserDomain(String username) - { - return DEFAULT_DOMAIN; - } - - public String getCurrentUserDomain() - { - return DEFAULT_DOMAIN; - } - - public String getDomain(String name) - { - return DEFAULT_DOMAIN; - } - - public String getDomainUser(String baseUsername, String tenantDomain) - { - return baseUsername; - } - - public Tenant getTenant(String tenantDomain) - { - return null; - } - - public boolean isEnabled() - { - return false; - } -} \ No newline at end of file diff --git a/source/java/org/alfresco/repo/tenant/Tenant.java b/source/java/org/alfresco/repo/tenant/Tenant.java deleted file mode 100644 index bdc435a6ea..0000000000 --- a/source/java/org/alfresco/repo/tenant/Tenant.java +++ /dev/null @@ -1,55 +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.tenant; - -/** - * Tenant - * - */ -public class Tenant -{ - private String tenantDomain; - - private boolean enabled = false; - - private String rootContentStoreDir = null; // if configured - can be null - - - public Tenant(String tenantDomain, boolean enabled, String rootContentStoreDir) - { - this.tenantDomain = tenantDomain; - this.enabled = enabled; - this.rootContentStoreDir = rootContentStoreDir; - } - - public String getTenantDomain() - { - return tenantDomain; - } - - public boolean isEnabled() - { - return enabled; - } - - public String getRootContentStoreDir() - { - return rootContentStoreDir; - } -} diff --git a/source/java/org/alfresco/repo/tenant/TenantDeployer.java b/source/java/org/alfresco/repo/tenant/TenantDeployer.java deleted file mode 100644 index ce98216bfd..0000000000 --- a/source/java/org/alfresco/repo/tenant/TenantDeployer.java +++ /dev/null @@ -1,42 +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.tenant; - - -/** - * Tenant Deployer interface. - *

- * This interface allows components to be notified of tenant events. - * Components will register with TenantAdminService. - * Also callbacks used during bootstrap (init) and shutdown (destroy) - * - */ - -public interface TenantDeployer -{ - public void onEnableTenant(); - - public void onDisableTenant(); - - // callback for bootstrap (for each tenant) - public void init(); - - // callback for shutdown (for each tenant) - public void destroy(); -} diff --git a/source/java/org/alfresco/repo/tenant/TenantService.java b/source/java/org/alfresco/repo/tenant/TenantService.java deleted file mode 100644 index fb6b634e11..0000000000 --- a/source/java/org/alfresco/repo/tenant/TenantService.java +++ /dev/null @@ -1,138 +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.tenant; - -import org.alfresco.service.cmr.repository.AssociationRef; -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.cmr.repository.StoreRef; -import org.alfresco.service.cmr.search.SearchService; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; - - -/** - * Tenant Service interface. - *

- * This interface provides methods to support either ST or MT implementations. - * - */ -public interface TenantService extends TenantUserService -{ - public static final String SEPARATOR = "@"; - - public static final String DEFAULT_DOMAIN = ""; - - /** - * @return the reference with the tenant-specific ID attached - */ - public NodeRef getName(NodeRef nodeRef); - - /** - * @return the reference with the tenant-specific ID attached - */ - public NodeRef getName(NodeRef inNodeRef, NodeRef nodeRef); - - /** - * @return the reference with the tenant-specific ID attached - */ - public StoreRef getName(StoreRef storeRef); - - /** - * @return the reference with the tenant-specific ID attached - */ - public ChildAssociationRef getName(ChildAssociationRef childAssocRef); - - /** - * @return the reference with the tenant-specific ID attached - */ - public AssociationRef getName(AssociationRef assocRef); - - /** - * @return the reference with the tenant-specific ID attached - */ - public StoreRef getName(String username, StoreRef storeRef); - - /** - * @return the reference with the tenant-specific ID attached - */ - public QName getName(QName name); - - /** - * @return the reference with the tenant-specific ID attached - */ - public QName getName(NodeRef inNodeRef, QName name); - - /** - * @return the reference with the tenant-specific ID attached - */ - public String getName(String name); - - /** - * @return the reference without the tenant-specific ID attached - */ - public QName getBaseName(QName name, boolean forceIfNonTenant); - - /** - * @return the reference without the tenant-specific ID attached - */ - public NodeRef getBaseName(NodeRef nodeRef); - - /** - * @return the reference without the tenant-specific ID attached - */ - public StoreRef getBaseName(StoreRef storeRef); - - /** - * @return the reference without the tenant-specific ID attached - */ - public ChildAssociationRef getBaseName(ChildAssociationRef childAssocRef); - - /** - * @return the reference without the tenant-specific ID attached - */ - public AssociationRef getBaseName(AssociationRef assocRef); - - /** - * @return the reference without the tenant-specific ID attached - */ - public String getBaseName(String name); - - /** - * @return the reference without the tenant-specific ID attached - */ - public String getBaseName(String name, boolean forceIfNonTenant); - - public void checkDomainUser(String username); - - public void checkDomain(String name); - - public NodeRef getRootNode(NodeService nodeService, SearchService searchService, NamespaceService namespaceService, String rootPath, NodeRef rootNodeRef); - - public boolean isTenantUser(); - - public boolean isTenantUser(String username); - - public boolean isTenantName(String name); - - public String getUserDomain(String username); - - public Tenant getTenant(String tenantDomain); -} diff --git a/source/java/org/alfresco/repo/tenant/TenantUserService.java b/source/java/org/alfresco/repo/tenant/TenantUserService.java deleted file mode 100644 index a8b1a5a3ef..0000000000 --- a/source/java/org/alfresco/repo/tenant/TenantUserService.java +++ /dev/null @@ -1,59 +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.tenant; - -/** - * Interface for Tenant User-Domain functionality. - * - * @author janv - * @author Derek Hulley - * @since 3.0 - */ -public interface TenantUserService -{ - /** - * @return the username with the tenant-specific ID attached - */ - public String getDomainUser(String baseUsername, String tenantDomain); - - /** - * @return the username without the tenant-specific ID attached - */ - public String getBaseNameUser(String name); - - /** - * @return the tenant-specific ID for current user - */ - public String getCurrentUserDomain(); - - /** - * @return the tenant-specific ID for specified username - */ - public String getUserDomain(String username); - - /** - * @return the tenant-specific ID for specified identifier - */ - public String getDomain(String name); - - /** - * @return true if the system is configured to be MT-enabled - */ - public boolean isEnabled(); -} diff --git a/source/java/org/alfresco/service/Auditable.java b/source/java/org/alfresco/service/Auditable.java deleted file mode 100644 index f96d1f9411..0000000000 --- a/source/java/org/alfresco/service/Auditable.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.service; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Annotation to defined key and parameter names for the auditing API. - * - * If this annotation is present on a public service interface it will be considered for auditing. If it is not present the method will never be audited. - * - * Note that the service name and method name can be found from the bean definition and the method invocation. - * - * @author Andy Hind - */ - -@Target(ElementType.METHOD) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface Auditable -{ - enum Key - { - NO_KEY, RETURN, ARG_0, ARG_1, ARG_2, ARG_3, ARG_4, ARG_5, ARG_6, ARG_7, ARG_8, ARG_9 - } - - /** - * The position of the key argument in the method list. - * - * @return -1 indicates there is no key - */ - Auditable.Key key() default Key.NO_KEY; - - /** - * The names of the parameters - * - * @return a String[] of parameter names, the default is an empty array. - */ - String[] parameters() default {}; - - /** - * If a method as marked as warn, it is potentially an audit hole. - * Typically a method returns an object which allows unaudited access. - * - * This is intended to mark things that appear to expose unsafe API calls. - * - * @return - */ - boolean warn() default false; - - /** - * All method parameters are recorded by default. - * This can be used to stop a parameter being written to the audit log. - * It will be entered as "******". - * - * @return - */ - boolean[] recordable() default {}; - - /** - * Return object are recorded by default. - * Setting this means they can never be recorded in the audit. - * - * @return - */ - boolean recordReturnedObject() default true; -} diff --git a/source/java/org/alfresco/service/NotAuditable.java b/source/java/org/alfresco/service/NotAuditable.java deleted file mode 100644 index 7ea4548c1e..0000000000 --- a/source/java/org/alfresco/service/NotAuditable.java +++ /dev/null @@ -1,39 +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.service; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Specifically indicate that a method is not to be audited. - * This is a marker annotation. - * - * @author Andy Hind - */ -@Target(ElementType.METHOD) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface NotAuditable -{ - -} diff --git a/source/java/org/alfresco/service/PublicService.java b/source/java/org/alfresco/service/PublicService.java deleted file mode 100644 index 545d2d8a96..0000000000 --- a/source/java/org/alfresco/service/PublicService.java +++ /dev/null @@ -1,40 +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.service; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Specifically indicate that an interface defines a public service. - * - * This is a marker annotation. - * - * @author Andy Hind - */ -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface PublicService -{ - -} diff --git a/source/java/org/alfresco/service/cmr/dictionary/AspectDefinition.java b/source/java/org/alfresco/service/cmr/dictionary/AspectDefinition.java deleted file mode 100644 index 18557a6a28..0000000000 --- a/source/java/org/alfresco/service/cmr/dictionary/AspectDefinition.java +++ /dev/null @@ -1,30 +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.service.cmr.dictionary; - - -/** - * Read-only definition of an Aspect. - * - * @author David Caruana - */ -public interface AspectDefinition extends ClassDefinition -{ - -} diff --git a/source/java/org/alfresco/service/cmr/dictionary/AssociationDefinition.java b/source/java/org/alfresco/service/cmr/dictionary/AssociationDefinition.java deleted file mode 100644 index 024ea78e72..0000000000 --- a/source/java/org/alfresco/service/cmr/dictionary/AssociationDefinition.java +++ /dev/null @@ -1,122 +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.service.cmr.dictionary; - -import org.alfresco.service.namespace.QName; - - -/** - * Read-only definition of an Association. - * - * @author David Caruana - * - */ -public interface AssociationDefinition extends ClassAttributeDefinition -{ - - /** - * @return defining model - */ - public ModelDefinition getModel(); - - /** - * @return the qualified name - */ - public QName getName(); - - /** - * @return the human-readable title - */ - public String getTitle(); - - /** - * @return the human-readable description - */ - public String getDescription(); - - /** - * Is this a child association? - * - * @return true => child, false => general relationship - */ - public boolean isChild(); - - /** - * Is this association maintained by the Repository? - * - * @return true => system maintained, false => client may maintain - */ - public boolean isProtected(); - - /** - * @return the source class - */ - public ClassDefinition getSourceClass(); - - /** - * @return the role of the source class in this association? - */ - public QName getSourceRoleName(); - - /** - * Is the source class optional in this association? - * - * @return true => cardinality > 0 - */ - public boolean isSourceMandatory(); - - /** - * Can there be many source class instances in this association? - * - * @return true => cardinality > 1, false => cardinality of 0 or 1 - */ - public boolean isSourceMany(); - - /** - * @return the target class - */ - public ClassDefinition getTargetClass(); - - /** - * @return the role of the target class in this association? - */ - public QName getTargetRoleName(); - - /** - * Is the target class optional in this association? - * - * @return true => cardinality > 0 - */ - public boolean isTargetMandatory(); - - /** - * Is the target class is mandatory, it is enforced? - * - * @return true => enforced - */ - public boolean isTargetMandatoryEnforced(); - - /** - * Can there be many target class instances in this association? - * - * @return true => cardinality > 1, false => cardinality of 0 or 1 - */ - public boolean isTargetMany(); - -} diff --git a/source/java/org/alfresco/service/cmr/dictionary/ChildAssociationDefinition.java b/source/java/org/alfresco/service/cmr/dictionary/ChildAssociationDefinition.java deleted file mode 100644 index ebac7ade01..0000000000 --- a/source/java/org/alfresco/service/cmr/dictionary/ChildAssociationDefinition.java +++ /dev/null @@ -1,44 +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.service.cmr.dictionary; - -/** - * Read-only definition of a Child Association. - * - * @author David Caruana - * - */ -public interface ChildAssociationDefinition extends AssociationDefinition -{ - - /** - * @return the required name of children (or null if none) - */ - public String getRequiredChildName(); - - /** - * @return whether duplicate child names allowed within this association? - */ - public boolean getDuplicateChildNamesAllowed(); - - /** - * @return whether timestamps should be propagated upwards along primary associations - */ - public boolean getPropagateTimestamps(); -} diff --git a/source/java/org/alfresco/service/cmr/dictionary/ClassAttributeDefinition.java b/source/java/org/alfresco/service/cmr/dictionary/ClassAttributeDefinition.java deleted file mode 100644 index aee333ba20..0000000000 --- a/source/java/org/alfresco/service/cmr/dictionary/ClassAttributeDefinition.java +++ /dev/null @@ -1,57 +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.service.cmr.dictionary; - -import org.alfresco.service.namespace.QName; - -/** - * - * @author Nick Smith - */ -public interface ClassAttributeDefinition -{ - /** - * @return defining model - */ - public ModelDefinition getModel(); - - /** - * @return the qualified name - */ - public QName getName(); - - /** - * @return the human-readable title - */ - public String getTitle(); - - /** - * @return the human-readable description - */ - public String getDescription(); - - /** - * Is this association or property maintained by the Repository? - * - * @return true => system maintained, false => client may maintain - */ - public boolean isProtected(); - -} diff --git a/source/java/org/alfresco/service/cmr/dictionary/ClassDefinition.java b/source/java/org/alfresco/service/cmr/dictionary/ClassDefinition.java deleted file mode 100644 index dc5a87ef6f..0000000000 --- a/source/java/org/alfresco/service/cmr/dictionary/ClassDefinition.java +++ /dev/null @@ -1,132 +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.service.cmr.dictionary; - -import java.io.Serializable; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.alfresco.service.namespace.QName; - -/** - * Read-only definition of a Class. - * - * @author David Caruana - */ -public interface ClassDefinition -{ - /** - * @return defining model - */ - public ModelDefinition getModel(); - - /** - * @return the qualified name of the class - */ - public QName getName(); - - /** - * @return the human-readable class title - */ - public String getTitle(); - - /** - * @return the human-readable class description - */ - public String getDescription(); - - /** - * @return the super class (or null, if this is the root) - */ - public QName getParentName(); - - /** - * @return true => aspect, false => type - */ - public boolean isAspect(); - - /** - * @return Return true if the type should be archived on delete, false if it should be - * deleted or null if not defined. - */ - public Boolean getArchive(); - - /** - * - * @return Return true if the type should be included in supertypes queries, false if not - * deleted or null if not defined. - */ - public Boolean getIncludedInSuperTypeQuery(); - - /** - * @return the properties of the class, including inherited properties - */ - public Map getProperties(); - - /** - * @return a map containing the default property values, including inherited properties - */ - public Map getDefaultValues(); - - /** - * Fetch all associations for which this is a source type, including child associations. - * - * @return the associations including inherited ones - * @see ChildAssociationDefinition - */ - public Map getAssociations(); - - /** - * @return true => this class supports child associations - */ - public boolean isContainer(); - - /** - * Fetch only child associations for which this is a source type. - * - * @return all child associations applicable to this type, including those - * inherited from super types - */ - public Map getChildAssociations(); - - /** - * Fetch all associations for which this is a target type, including child associations. - * - * @return the associations including inherited ones - */ - // TODO: public Map getTargetAssociations(); - - /** - * @return the default aspects associated with this type - */ - public List getDefaultAspects(); - - /** - * @return the set of default aspects names associated with this type - */ - public Set getDefaultAspectNames(); - - /** - * @param inherited include default aspects inherited from super types - * @return the default aspects - */ - public List getDefaultAspects(boolean inherited); - -} diff --git a/source/java/org/alfresco/service/cmr/dictionary/Constraint.java b/source/java/org/alfresco/service/cmr/dictionary/Constraint.java deleted file mode 100644 index f5dafe4dd5..0000000000 --- a/source/java/org/alfresco/service/cmr/dictionary/Constraint.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.service.cmr.dictionary; - -import java.util.Map; - - -/** - * The interface for classes that implement constraints on property values. - *

- * Implementations of the actual constraint code should must not synchronize - * or in any other way block threads. Concurrent access of the evaluation - * method is expected, but will always occur after initialization has completed. - *

- * Attention to performance is crucial for all implementations as - * instances of this class are heavily used. - *

- * The constraint implementations can provide standard setter methods that will - * be populated by bean setter injection. Once all the available properties have - * been set, the contraint will be initialized. - * - * @author Derek Hulley - */ -public interface Constraint -{ - /** - * Returns the 'type' of the constraint, this is the identifier given to - * constraint in the configuration. - * - * @return The type - */ - public String getType(); - - /** - * @return the human-readable constraint title (optional) - */ - public String getTitle(); - - /** - * Gets the constraint name. - * - * @return the constraint name. - */ - public String getShortName(); - - /** - * Returns the parameters passed to the instance of the constraint. - * - * @return Map of parameters or an empty Map if none exist - */ - public Map getParameters(); - - /** - * Initializes the constraint with appropriate values, which will depend - * on the implementation itself. This method can be implemented as a - * once-off, i.e. reinitialization does not have to be supported. - * - * @param parameters constraint parameters - */ - public void initialize(); - - /** - * Evaluates a property value according to the implementation and initialization - * parameters provided. - * - * @param value the property value to check - * - * @throws ConstraintException if the value doesn't pass all constraints - */ - public void evaluate(Object value); -} diff --git a/source/java/org/alfresco/service/cmr/dictionary/ConstraintDefinition.java b/source/java/org/alfresco/service/cmr/dictionary/ConstraintDefinition.java deleted file mode 100644 index a00887c08c..0000000000 --- a/source/java/org/alfresco/service/cmr/dictionary/ConstraintDefinition.java +++ /dev/null @@ -1,61 +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.service.cmr.dictionary; - -import org.alfresco.service.namespace.QName; - -/** - * Property constraint definition - * - * @author Derek Hulley - */ -public interface ConstraintDefinition -{ - /** - * @return defining model - */ - public ModelDefinition getModel(); - - /** - * @return Returns the qualified name of the constraint - */ - public QName getName(); - - /** - * @return the human-readable class title - */ - public String getTitle(); - - /** - * @return the human-readable class description - */ - public String getDescription(); - - /** - * @return Returns the constraint implementation - */ - public Constraint getConstraint(); - - /** - * @return Returns the referenced constraint definition, if any (null for explicit or inline constraint def) - * - * @since 3.2R - */ - public QName getRef(); -} diff --git a/source/java/org/alfresco/service/cmr/dictionary/ConstraintException.java b/source/java/org/alfresco/service/cmr/dictionary/ConstraintException.java deleted file mode 100644 index 1999283990..0000000000 --- a/source/java/org/alfresco/service/cmr/dictionary/ConstraintException.java +++ /dev/null @@ -1,36 +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.service.cmr.dictionary; - -import org.alfresco.error.AlfrescoRuntimeException; - -/** - * Thrown when property value fails to meet a property constraint. - * - * @author Derek Hulley - */ -public class ConstraintException extends AlfrescoRuntimeException -{ - private static final long serialVersionUID = -3925105163386197586L; - - public ConstraintException(String msgId, Object ... args) - { - super(msgId, args); - } -} diff --git a/source/java/org/alfresco/service/cmr/dictionary/DataTypeDefinition.java b/source/java/org/alfresco/service/cmr/dictionary/DataTypeDefinition.java deleted file mode 100644 index 1c0cce0cd3..0000000000 --- a/source/java/org/alfresco/service/cmr/dictionary/DataTypeDefinition.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.service.cmr.dictionary; - -import java.util.Locale; - -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; - - -/** - * Read-only definition of a Data Type - * - * @author David Caruana - */ -public interface DataTypeDefinition -{ - // - // Built-in Property Types - // - public QName ANY = QName.createQName(NamespaceService.DICTIONARY_MODEL_1_0_URI, "any"); - public QName TEXT = QName.createQName(NamespaceService.DICTIONARY_MODEL_1_0_URI, "text"); - public QName MLTEXT = QName.createQName(NamespaceService.DICTIONARY_MODEL_1_0_URI, "mltext"); - public QName CONTENT = QName.createQName(NamespaceService.DICTIONARY_MODEL_1_0_URI, "content"); - public QName INT = QName.createQName(NamespaceService.DICTIONARY_MODEL_1_0_URI, "int"); - public QName LONG = QName.createQName(NamespaceService.DICTIONARY_MODEL_1_0_URI, "long"); - public QName FLOAT = QName.createQName(NamespaceService.DICTIONARY_MODEL_1_0_URI, "float"); - public QName DOUBLE = QName.createQName(NamespaceService.DICTIONARY_MODEL_1_0_URI, "double"); - public QName DATE = QName.createQName(NamespaceService.DICTIONARY_MODEL_1_0_URI, "date"); - public QName DATETIME = QName.createQName(NamespaceService.DICTIONARY_MODEL_1_0_URI, "datetime"); - public QName BOOLEAN = QName.createQName(NamespaceService.DICTIONARY_MODEL_1_0_URI, "boolean"); - public QName QNAME = QName.createQName(NamespaceService.DICTIONARY_MODEL_1_0_URI, "qname"); - public QName CATEGORY = QName.createQName(NamespaceService.DICTIONARY_MODEL_1_0_URI, "category"); - public QName NODE_REF = QName.createQName(NamespaceService.DICTIONARY_MODEL_1_0_URI, "noderef"); - public QName CHILD_ASSOC_REF = QName.createQName(NamespaceService.DICTIONARY_MODEL_1_0_URI, "childassocref"); - public QName ASSOC_REF = QName.createQName(NamespaceService.DICTIONARY_MODEL_1_0_URI, "assocref"); - public QName PATH = QName.createQName(NamespaceService.DICTIONARY_MODEL_1_0_URI, "path"); - public QName LOCALE = QName.createQName(NamespaceService.DICTIONARY_MODEL_1_0_URI, "locale"); - public QName PERIOD = QName.createQName(NamespaceService.DICTIONARY_MODEL_1_0_URI, "period"); - - - /** - * @return defining model - */ - public ModelDefinition getModel(); - - /** - * @return the qualified name of the data type - */ - public QName getName(); - - /** - * @return the human-readable class title - */ - public String getTitle(); - - /** - * @return the human-readable class description - */ - public String getDescription(); - - /** - * @return the indexing analyser class - */ - public String getAnalyserClassName(); - - /** - * @return the indexing analyser class for the specified locale - */ - public String getAnalyserClassName(Locale locale); - - /** - * @return the equivalent java class name (or null, if not mapped) - */ - public String getJavaClassName(); - -} diff --git a/source/java/org/alfresco/service/cmr/dictionary/DictionaryException.java b/source/java/org/alfresco/service/cmr/dictionary/DictionaryException.java deleted file mode 100644 index fc7bb63af1..0000000000 --- a/source/java/org/alfresco/service/cmr/dictionary/DictionaryException.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.service.cmr.dictionary; - -import org.alfresco.error.AlfrescoRuntimeException; - -/** - * Base Exception of Data Dictionary Exceptions. - * - * @author David Caruana - */ -public class DictionaryException extends AlfrescoRuntimeException -{ - private static final long serialVersionUID = 3257008761007847733L; - - public DictionaryException(String msgId) - { - super(msgId); - } - - public DictionaryException(String msgId, Throwable cause) - { - super(msgId, cause); - } - - public DictionaryException(String msgId, Object ... args) - { - super(msgId, args); - } - - public DictionaryException(String msgId, Throwable cause, Object ... args) - { - super(msgId, args, cause); - } -} diff --git a/source/java/org/alfresco/service/cmr/dictionary/DictionaryService.java b/source/java/org/alfresco/service/cmr/dictionary/DictionaryService.java deleted file mode 100644 index 39504b0a85..0000000000 --- a/source/java/org/alfresco/service/cmr/dictionary/DictionaryService.java +++ /dev/null @@ -1,295 +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.service.cmr.dictionary; - -import java.util.Collection; -import java.util.Map; - -import org.alfresco.service.NotAuditable; -import org.alfresco.service.PublicService; -import org.alfresco.service.namespace.QName; - - -/** - * This interface represents the Repository Data Dictionary. The - * dictionary provides access to content meta-data such as Type - * and Aspect descriptions. - * - * Content meta-data is organised into models where each model is - * given a qualified name. This means that it is safe to develop - * independent models and bring them together into the same - * Repository without name clashes (as long their namespace is - * different). - * - * @author David Caruana - */ -@PublicService -public interface DictionaryService -{ - - /** - * @return the names of all models that have been registered with the Repository - */ - @NotAuditable - public Collection getAllModels(); - - /** - * @param model the model name to retrieve - * @return the specified model (or null, if it doesn't exist) - */ - @NotAuditable - public ModelDefinition getModel(QName model); - - /** - * @return the names of all data types that have been registered with the Repository - */ - @NotAuditable - Collection getAllDataTypes(); - - /** - * @param model the model to retrieve data types for - * @return the names of all data types defined within the specified model - */ - @NotAuditable - Collection getDataTypes(QName model); - - /** - * @param name the name of the data type to retrieve - * @return the data type definition (or null, if it doesn't exist) - */ - @NotAuditable - DataTypeDefinition getDataType(QName name); - - /** - * @param javaClass java class to find datatype for - * @return the data type definition (or null, if a mapping does not exist) - */ - @NotAuditable - DataTypeDefinition getDataType(Class javaClass); - - /** - * @return the names of all types that have been registered with the Repository - */ - @NotAuditable - Collection getAllTypes(); - - /** - * Get the sub types of the type. The returned list includes the base type which is passed in as a parameter. - * - * @param type, the qualified name of the type - * @param follow true => all sub-type descendants, false => immediate sub-type children - * @return the names of the sub types of the specified type, including the value passed in. - */ - @NotAuditable - Collection getSubTypes(QName type, boolean follow); - - /** - * @param model the model to retrieve types for - * @return the names of all types defined within the specified model - */ - @NotAuditable - Collection getTypes(QName model); - - /** - * @param name the name of the type to retrieve - * @return the type definition (or null, if it doesn't exist) - */ - @NotAuditable - TypeDefinition getType(QName name); - - /** - * Construct an anonymous type that combines the definitions of the specified - * type and aspects. - * - * @param type the type to start with - * @param aspects the aspects to combine with the type - * @return the anonymous type definition - */ - @NotAuditable - TypeDefinition getAnonymousType(QName type, Collection aspects); - - /** - * @return the names of all aspects that have been registered with the Repository - */ - @NotAuditable - Collection getAllAspects(); - - /** - * @param aspect - * @param follow true => follow up the super-class hierarchy, false => immediate sub aspects only - * @return the sub aspects of specified aspect - */ - @NotAuditable - Collection getSubAspects(QName aspect, boolean follow); - - /** - * @param model the model to retrieve aspects for - * @return the names of all aspects defined within the specified model - */ - @NotAuditable - Collection getAspects(QName model); - - /** - * @param model the model to retrieve associations for - * @return the names of all associations defined within the specified model - */ - @NotAuditable - public Collection getAssociations(QName model); - - /** - * @param name the name of the aspect to retrieve - * @return the aspect definition (or null, if it doesn't exist) - */ - @NotAuditable - AspectDefinition getAspect(QName name); - - /** - * @param name the name of the class (type or aspect) to retrieve - * @return the class definition (or null, if it doesn't exist) - */ - @NotAuditable - ClassDefinition getClass(QName name); - - /** - * Determines whether a class is a sub-class of another class - * - * @param className the sub-class to test - * @param ofClassName the class to test against - * @return true => the class is a sub-class (or itself) - */ - @NotAuditable - boolean isSubClass(QName className, QName ofClassName); - - /** - * Gets the definition of the property as defined by the specified Class. - * - * Note: A sub-class may override the definition of a property that's - * defined in a super-class. - * - * @param className the class name - * @param propertyName the property name - * @return the property definition (or null, if it doesn't exist) - */ - @NotAuditable - PropertyDefinition getProperty(QName className, QName propertyName); - - /** - * Gets the definitions of the properties defined by the specified Class. - * - * @param className the class name - * @return the property definitions - */ - @NotAuditable - Map getPropertyDefs(QName className); - - /** - * Gets the definition of the property as defined by its owning Class. - * - * @param propertyName the property name - * @return the property definition (or null, if it doesn't exist) - */ - @NotAuditable - PropertyDefinition getProperty(QName propertyName); - - /** - * Get all properties defined across all models with the given data type. - * - * Note that DataTypeDefinition.ANY will only match this type and can not be used as get all properties. - * - * If dataType is null then this method will return *ALL* properties regardless of data type. - * - * @param dataType - * @return - */ - @NotAuditable - Collection getAllProperties(QName dataType); - - /** - * Get all properties defined for the given model with the given data type. - * - * Note that DataTypeDefinition.ANY will only match this type and can not be used as get all properties. - * - * If dataType is null then this method will return *ALL* properties regardless of data type. - * - * @param dataType - * @return - */ - @NotAuditable - Collection getProperties(QName model, QName dataType); - - /** - * Get all properties for the specified model - * - * @param model - * @return - */ - Collection getProperties(QName model); - - /** - * Gets the definition of the association as defined by its owning Class. - * - * @param associationName the property name - * @return the association definition (or null, if it doesn't exist) - */ - @NotAuditable - AssociationDefinition getAssociation(QName associationName); - - /** - * Get all the association definitions - - * @return all the association qnames - */ - @NotAuditable - Collection getAllAssociations(); - - /** - * Gets the definition of the constraint - * - * @param constraintName the constraint name - * @return the constraint definition (or null, if it doesn't exist) - * - * @since 3.2.1 - */ - @NotAuditable - public ConstraintDefinition getConstraint(QName constraintQName); - - /** - * Get constraints for the specified model - * - * @param model - * @return - */ - public Collection getConstraints(QName model); - - /** - * Get constraints for the specified model - - * Optionally return referenceable (ie. non-property specific) constraints only - * - * @param model - * @param referenceableDefsOnly - * @return - * - * @since 3.2R - */ - Collection getConstraints(QName model, boolean referenceableDefsOnly); - - // TODO: Behaviour definitions - -} diff --git a/source/java/org/alfresco/service/cmr/dictionary/InvalidAspectException.java b/source/java/org/alfresco/service/cmr/dictionary/InvalidAspectException.java deleted file mode 100644 index b1704c86e5..0000000000 --- a/source/java/org/alfresco/service/cmr/dictionary/InvalidAspectException.java +++ /dev/null @@ -1,49 +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.service.cmr.dictionary; - -import org.alfresco.service.namespace.QName; - -/** - * Thrown when a reference to an aspect is incorrect. - * - * @author Derek Hulley - */ -public class InvalidAspectException extends InvalidClassException -{ - private static final long serialVersionUID = 3257290240330051893L; - - public InvalidAspectException(QName aspectName) - { - super(null, aspectName); - } - - public InvalidAspectException(String msg, QName aspectName) - { - super(msg, aspectName); - } - - /** - * @return Returns the offending aspect name - */ - public QName getAspectName() - { - return getClassName(); - } -} diff --git a/source/java/org/alfresco/service/cmr/dictionary/InvalidClassException.java b/source/java/org/alfresco/service/cmr/dictionary/InvalidClassException.java deleted file mode 100644 index 0be8590a04..0000000000 --- a/source/java/org/alfresco/service/cmr/dictionary/InvalidClassException.java +++ /dev/null @@ -1,53 +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.service.cmr.dictionary; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.service.namespace.QName; - -/** - * Thrown when an operation cannot be performed because the dictionary class - * reference does not exist. - * - */ -public class InvalidClassException extends AlfrescoRuntimeException -{ - private static final long serialVersionUID = 3256722870754293558L; - - private QName className; - - public InvalidClassException(QName className) - { - this(null, className); - } - - public InvalidClassException(String msg, QName className) - { - super(msg); - this.className = className; - } - - /** - * @return Returns the offending class name - */ - public QName getClassName() - { - return className; - } -} diff --git a/source/java/org/alfresco/service/cmr/dictionary/InvalidTypeException.java b/source/java/org/alfresco/service/cmr/dictionary/InvalidTypeException.java deleted file mode 100644 index 972f9b65b8..0000000000 --- a/source/java/org/alfresco/service/cmr/dictionary/InvalidTypeException.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.service.cmr.dictionary; - -import org.alfresco.service.namespace.QName; - -/** - * Thrown when an operation cannot be performed because a type is not recognised - * by the data dictionary - * - * @author Derek Hulley - */ -public class InvalidTypeException extends InvalidClassException -{ - private static final long serialVersionUID = 3256722870754293558L; - - public InvalidTypeException(QName typeName) - { - super("Invalid type: " + typeName, typeName); - } - - public InvalidTypeException(String msg, QName typeName) - { - super(msg, typeName); - } - - /** - * @return Returns the offending type name - */ - public QName getTypeName() - { - return getClassName(); - } -} diff --git a/source/java/org/alfresco/service/cmr/dictionary/ModelDefinition.java b/source/java/org/alfresco/service/cmr/dictionary/ModelDefinition.java deleted file mode 100644 index bbdaee0b2e..0000000000 --- a/source/java/org/alfresco/service/cmr/dictionary/ModelDefinition.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.service.cmr.dictionary; - -import java.util.Collection; -import java.util.Date; - -import org.alfresco.service.namespace.QName; - - -/** - * Read-only definition of a Model. - * - * @author David Caruana - */ -public interface ModelDefinition -{ - /** - * @return the model name - */ - public QName getName(); - - /** - * @return the model description - */ - public String getDescription(); - - /** - * @return the model author - */ - public String getAuthor(); - - /** - * @return the date when the model was published - */ - public Date getPublishedDate(); - - /** - * @return the model version - */ - public String getVersion(); - - /** - * @return the namespaces defined by this model - */ - public Collection getNamespaces(); - - /** - * @param uri namespace uri - * @return true => model defines the uri - */ - public boolean isNamespaceDefined(String uri); - - /** - * @return the namespaces imported by this model - */ - public Collection getImportedNamespaces(); - - /** - * @param uri namespace uri - * @return true => model imports the uri - */ - public boolean isNamespaceImported(String uri); -} diff --git a/source/java/org/alfresco/service/cmr/dictionary/NamespaceDefinition.java b/source/java/org/alfresco/service/cmr/dictionary/NamespaceDefinition.java deleted file mode 100644 index 612ab325cd..0000000000 --- a/source/java/org/alfresco/service/cmr/dictionary/NamespaceDefinition.java +++ /dev/null @@ -1,42 +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.service.cmr.dictionary; - - -/** - * Read-only definition of a Namespace. - * - */ -public interface NamespaceDefinition -{ - /** - * @return defining model - */ - public ModelDefinition getModel(); - - /** - * @return the namespace URI - */ - public String getUri(); - - /** - * @return the namespace Prefix - */ - public String getPrefix(); -} diff --git a/source/java/org/alfresco/service/cmr/dictionary/PropertyDefinition.java b/source/java/org/alfresco/service/cmr/dictionary/PropertyDefinition.java deleted file mode 100644 index b493ac58c7..0000000000 --- a/source/java/org/alfresco/service/cmr/dictionary/PropertyDefinition.java +++ /dev/null @@ -1,125 +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.service.cmr.dictionary; - -import java.util.List; - -import org.alfresco.repo.dictionary.IndexTokenisationMode; -import org.alfresco.service.namespace.QName; - -/** - * Read-only definition of a Property. - * - * @author David Caruana - */ -public interface PropertyDefinition extends ClassAttributeDefinition -{ - /** - * @return defining model - */ - public ModelDefinition getModel(); - - /** - * @return the qualified name of the property - */ - public QName getName(); - - /** - * @return the human-readable class title - */ - public String getTitle(); - - /** - * @return the human-readable class description - */ - public String getDescription(); - - /** - * @return the default value - */ - public String getDefaultValue(); - - /** - * @return the qualified name of the property type - */ - public DataTypeDefinition getDataType(); - - /** - * @return Returns the owning class's defintion - */ - public ClassDefinition getContainerClass(); - - public boolean isOverride(); - - /** - * @return true => multi-valued, false => single-valued - */ - public boolean isMultiValued(); - - /** - * @return true => mandatory, false => optional - */ - public boolean isMandatory(); - - /** - * @return Returns true if the system enforces the presence of - * {@link #isMandatory() mandatory} properties, or false if the - * system just marks objects that don't have all mandatory - * properties present. - */ - public boolean isMandatoryEnforced(); - - /** - * @return true => system maintained, false => client may maintain - */ - public boolean isProtected(); - - /** - * @return true => indexed, false => not indexed - */ - public boolean isIndexed(); - - /** - * @return true => stored in index - */ - public boolean isStoredInIndex(); - - /** - * @return IndexTokenisationMode.TREU => tokenised when it is indexed (the - * stored value will not be tokenised) - */ - public IndexTokenisationMode getIndexTokenisationMode(); - - /** - * All non atomic properties will be indexed at the same time. - * - * @return true => The attribute must be indexed in the commit of the - * transaction. false => the indexing will be done in the background - * and may be out of date. - */ - public boolean isIndexedAtomically(); - - /** - * Get all constraints that apply to the property value - * - * @return Returns a list of property constraint definitions - */ - public List getConstraints(); -} diff --git a/source/java/org/alfresco/service/cmr/dictionary/TypeDefinition.java b/source/java/org/alfresco/service/cmr/dictionary/TypeDefinition.java deleted file mode 100644 index a286675502..0000000000 --- a/source/java/org/alfresco/service/cmr/dictionary/TypeDefinition.java +++ /dev/null @@ -1,31 +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.service.cmr.dictionary; - - -/** - * Read-only definition of a Type - * - * @author David Caruana - */ -public interface TypeDefinition extends ClassDefinition -{ - - -} diff --git a/source/java/org/alfresco/service/cmr/repository/AbstractStoreException.java b/source/java/org/alfresco/service/cmr/repository/AbstractStoreException.java deleted file mode 100644 index bdd2bc6c04..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/AbstractStoreException.java +++ /dev/null @@ -1,61 +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.service.cmr.repository; - - -/** - * Store-related exception that keeps a handle to the store reference - * - * @author Derek Hulley - */ -public abstract class AbstractStoreException extends RuntimeException -{ - private static final long serialVersionUID = 1315634811903555316L; - - private StoreRef storeRef; - - public AbstractStoreException(StoreRef storeRef) - { - this(null, storeRef, null); - } - - public AbstractStoreException(String msg, StoreRef storeRef) - { - this(msg, storeRef, null); - } - - public AbstractStoreException(StoreRef storeRef, Throwable e) - { - this(null, storeRef, e); - } - - public AbstractStoreException(String msg, StoreRef storeRef, Throwable e) - { - super(msg, e); - this.storeRef = storeRef; - } - - /** - * @return Returns the offending store reference - */ - public StoreRef getStoreRef() - { - return storeRef; - } -} diff --git a/source/java/org/alfresco/service/cmr/repository/AssociationExistsException.java b/source/java/org/alfresco/service/cmr/repository/AssociationExistsException.java deleted file mode 100644 index 65acca6844..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/AssociationExistsException.java +++ /dev/null @@ -1,76 +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.service.cmr.repository; - -import org.alfresco.service.namespace.QName; - -/** - * Thrown when an operation could not be performed because a named association already - * exists between two nodes - * - * @author Derek Hulley - */ -public class AssociationExistsException extends RuntimeException -{ - private static final long serialVersionUID = 3256440317824874800L; - - private Long sourceNodeId; - private Long targetNodeId; - private QName qname; - - /** - * @see #AssociationExistsException(NodeRef, NodeRef, QName, Throwable) - */ - public AssociationExistsException(Long sourceNodeId, Long targetNodeId, QName qname) - { - super(); - this.sourceNodeId = sourceNodeId; - this.targetNodeId = targetNodeId; - this.qname = qname; - } - - /** - * @param sourceNodeId the source of the association - * @param targetNodeId the target of the association - * @param qname the qualified name of the association - * @param cause a causal exception - */ - public AssociationExistsException(Long sourceNodeId, Long targetNodeId, QName qname, Throwable cause) - { - super(cause); - this.sourceNodeId = sourceNodeId; - this.targetNodeId = targetNodeId; - this.qname = qname; - } - - public Long getSourceNodeId() - { - return sourceNodeId; - } - - public Long getTargetNodeId() - { - return targetNodeId; - } - - public QName getQName() - { - return qname; - } -} diff --git a/source/java/org/alfresco/service/cmr/repository/AssociationRef.java b/source/java/org/alfresco/service/cmr/repository/AssociationRef.java deleted file mode 100644 index 0b39cfd2d0..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/AssociationRef.java +++ /dev/null @@ -1,204 +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.service.cmr.repository; - -import java.io.Serializable; -import java.util.StringTokenizer; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.service.namespace.QName; -import org.alfresco.util.EqualsHelper; - -/** - * This class represents a regular, named node relationship between two nodes. - *

- * Note that the ID of the association might not be populated. - * - * @author Derek Hulley - */ -public class AssociationRef implements EntityRef, Serializable -{ - private static final long serialVersionUID = 3977867284482439475L; - - private static final String FILLER = "|"; - - private Long id; - private NodeRef sourceRef; - private QName assocTypeQName; - private NodeRef targetRef; - - /** - * Construct a representation of a source --- name ----> target relationship. - * - * @param sourceRef - * the source reference - never null - * @param assocTypeQName - * the qualified name of the association type - never null - * @param targetRef - * the target node reference - never null. - */ - public AssociationRef(NodeRef sourceRef, QName assocTypeQName, NodeRef targetRef) - { - this(null, sourceRef, assocTypeQName, targetRef); - } - - /** - * Construct a representation of a source --- name ----> target relationship. - * - * @param id - * unique identifier - may be null - * @param sourceRef - * the source reference - never null - * @param assocTypeQName - * the qualified name of the association type - never null - * @param targetRef - * the target node reference - never null. - */ - public AssociationRef(Long id, NodeRef sourceRef, QName assocTypeQName, NodeRef targetRef) - { - this.id = id; - this.sourceRef = sourceRef; - this.assocTypeQName = assocTypeQName; - this.targetRef = targetRef; - - // check - if (sourceRef == null) - { - throw new IllegalArgumentException("Source reference may not be null"); - } - if (assocTypeQName == null) - { - throw new IllegalArgumentException("QName may not be null"); - } - if (targetRef == null) - { - throw new IllegalArgumentException("Target reference may not be null"); - } - } - - /** - * @param childAssocRefStr a string of the form id|sourceNodeRef|targetNodeRef|assocTypeQName. - */ - public AssociationRef(String assocRefStr) - { - StringTokenizer tokenizer = new StringTokenizer(assocRefStr, FILLER); - if (tokenizer.countTokens() != 3 && tokenizer.countTokens() != 4) - { - throw new AlfrescoRuntimeException("Unable to parse association string: " + assocRefStr); - } - - String idStr = "0"; - if (tokenizer.countTokens() == 4) - { - idStr = tokenizer.nextToken(); - } - String sourceNodeRefStr = tokenizer.nextToken(); - String targetNodeRefStr = tokenizer.nextToken(); - String assocTypeQNameStr = tokenizer.nextToken(); - - this.id = new Long(idStr); - this.sourceRef = new NodeRef(sourceNodeRefStr); - this.targetRef = new NodeRef(targetNodeRefStr); - this.assocTypeQName = QName.createQName(assocTypeQNameStr); - } - - /** - * @return Returns a string of the form sourceNodeRef|targetNodeRef|assocTypeQName|assocQName - */ - public String toString() - { - StringBuilder sb = new StringBuilder(180); - sb.append(id).append(FILLER) - .append(sourceRef).append(FILLER) - .append(targetRef).append(FILLER) - .append(assocTypeQName); - return sb.toString(); - } - - /** - * Compares: - *

    - *
  • {@link #sourceRef}
  • - *
  • {@link #targetRef}
  • - *
  • {@link #assocTypeQName}
  • - *
- */ - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof AssociationRef)) - { - return false; - } - AssociationRef other = (AssociationRef) o; - - return (EqualsHelper.nullSafeEquals(this.sourceRef, other.sourceRef) - && EqualsHelper.nullSafeEquals(this.assocTypeQName, other.assocTypeQName) - && EqualsHelper.nullSafeEquals(this.targetRef, other.targetRef)); - } - - public int hashCode() - { - int hashCode = ((getSourceRef() == null) ? 0 : getSourceRef().hashCode()); - hashCode = 37 * hashCode + ((getTypeQName() == null) ? 0 : getTypeQName().hashCode()); - hashCode = 37 * hashCode + getTargetRef().hashCode(); - return hashCode; - } - - /** - * Gets the unique identifier for this association. - * - * @return the unique identifier for this association, or null if the ID was not - * given at the time of construction - */ - public Long getId() - { - return this.id; - } - - /** - * Get the qualified name of the source-target association - * - * @return Returns the qualified name of the source-target association. - */ - public QName getTypeQName() - { - return assocTypeQName; - } - - /** - * @return Returns the child node reference - never null - */ - public NodeRef getTargetRef() - { - return targetRef; - } - - /** - * @return Returns the parent node reference, which may be null if this - * represents the imaginary reference to the root node - */ - public NodeRef getSourceRef() - { - return sourceRef; - } -} diff --git a/source/java/org/alfresco/service/cmr/repository/ChildAssociationRef.java b/source/java/org/alfresco/service/cmr/repository/ChildAssociationRef.java deleted file mode 100644 index aff166e144..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/ChildAssociationRef.java +++ /dev/null @@ -1,264 +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.service.cmr.repository; - -import java.io.Serializable; -import java.util.StringTokenizer; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.service.namespace.QName; -import org.alfresco.util.EqualsHelper; - -/** - * This class represents a child relationship between two nodes. This - * relationship is named. - *

- * So it requires the parent node ref, the child node ref and the name of the - * child within the particular parent. - *

- * This combination is not a unique identifier for the relationship with regard - * to structure. In use this does not matter as we have no concept of order, - * particularly in the index. - * - * @author andyh - * - */ -public class ChildAssociationRef - implements EntityRef, Comparable, Serializable -{ - private static final long serialVersionUID = 4051322336257127729L; - - private static final String FILLER = "|"; - - private QName assocTypeQName; - private NodeRef parentRef; - private QName childQName; - private NodeRef childRef; - private boolean isPrimary; - private int nthSibling; - - - /** - * Construct a representation of a parent --- name ----> child relationship. - * - * @param assocTypeQName - * the type of the association - * @param parentRef - * the parent reference - may be null - * @param childQName - * the qualified name of the association - may be null - * @param childRef - * the child node reference. This must not be null. - * @param isPrimary - * true if this represents the primary parent-child relationship - * @param nthSibling - * the nth association with the same properties. Usually -1 to be - * ignored. - */ - public ChildAssociationRef( - QName assocTypeQName, - NodeRef parentRef, - QName childQName, - NodeRef childRef, - boolean isPrimary, - int nthSibling) - { - this.assocTypeQName = assocTypeQName; - this.parentRef = parentRef; - this.childQName = childQName; - this.childRef = childRef; - this.isPrimary = isPrimary; - this.nthSibling = nthSibling; - - // check - if (childRef == null) - { - throw new IllegalArgumentException("Child reference may not be null"); - } - } - - /** - * Constructs a non-primary, -1th sibling parent-child association - * reference. - * - * @see ChildAssociationRef#ChildAssocRef(QName, NodeRef, QName, NodeRef, boolean, int) - */ - public ChildAssociationRef(QName assocTypeQName, NodeRef parentRef, QName childQName, NodeRef childRef) - { - this(assocTypeQName, parentRef, childQName, childRef, false, -1); - } - - /** - * @param childAssocRefStr a string of the form parentNodeRef|childNodeRef|assocTypeQName|assocQName|isPrimary|nthSibling - */ - public ChildAssociationRef(String childAssocRefStr) - { - StringTokenizer tokenizer = new StringTokenizer(childAssocRefStr, FILLER); - if (tokenizer.countTokens() != 6) - { - throw new AlfrescoRuntimeException("Unable to parse child association string: " + childAssocRefStr); - } - String parentNodeRefStr = tokenizer.nextToken(); - String childNodeRefStr = tokenizer.nextToken(); - String assocTypeQNameStr = tokenizer.nextToken(); - String assocQNameStr = tokenizer.nextToken(); - String isPrimaryStr = tokenizer.nextToken(); - String nthSiblingStr = tokenizer.nextToken(); - - this.parentRef = new NodeRef(parentNodeRefStr); - this.childRef = new NodeRef(childNodeRefStr); - this.assocTypeQName = QName.createQName(assocTypeQNameStr); - this.childQName = QName.createQName(assocQNameStr); - this.isPrimary = Boolean.parseBoolean(isPrimaryStr); - this.nthSibling = Integer.parseInt(nthSiblingStr); - } - - /** - * @return Returns a string of the form parentNodeRef|childNodeRef|assocTypeQName|assocQName|isPrimary|nthSibling - */ - public String toString() - { - StringBuilder sb = new StringBuilder(250); - sb.append(parentRef).append(FILLER) - .append(childRef).append(FILLER) - .append(assocTypeQName).append(FILLER) - .append(childQName).append(FILLER) - .append(isPrimary).append(FILLER) - .append(nthSibling); - return sb.toString(); - } - - /** - * Compares: - *

    - *
  • {@link #assocTypeQName}
  • - *
  • {@link #parentRef}
  • - *
  • {@link #childRef}
  • - *
  • {@link #childQName}
  • - *
- */ - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof ChildAssociationRef)) - { - return false; - } - ChildAssociationRef other = (ChildAssociationRef) o; - - return (EqualsHelper.nullSafeEquals(this.assocTypeQName, other.assocTypeQName) - && EqualsHelper.nullSafeEquals(this.parentRef, other.parentRef) - && EqualsHelper.nullSafeEquals(this.childQName, other.childQName) - && EqualsHelper.nullSafeEquals(this.childRef, other.childRef)); - } - - public int hashCode() - { - int hashCode = ((getTypeQName() == null) ? 0 : getTypeQName().hashCode()); - hashCode = 37 * hashCode + ((getParentRef() == null) ? 0 : getParentRef().hashCode()); - hashCode = 37 * hashCode + ((getQName() == null) ? 0 : getQName().hashCode()); - hashCode = 37 * hashCode + getChildRef().hashCode(); - return hashCode; - } - - /** - * @see #setNthSibling(int) - */ - public int compareTo(ChildAssociationRef another) - { - int thisVal = this.nthSibling; - int anotherVal = another.nthSibling; - return (thisVal < anotherVal ? -1 : (thisVal == anotherVal ? 0 : 1)); - } - - /** - * Get the qualified name of the association type - * - * @return Returns the qualified name of the parent-child association type - * as defined in the data dictionary. It may be null if this is the - * imaginary association to the root node. - */ - public QName getTypeQName() - { - return assocTypeQName; - } - - /** - * Get the qualified name of the parent-child association - * - * @return Returns the qualified name of the parent-child association. It - * may be null if this is the imaginary association to a root node. - */ - public QName getQName() - { - return childQName; - } - - /** - * @return Returns the child node reference - never null - */ - public NodeRef getChildRef() - { - return childRef; - } - - /** - * @return Returns the parent node reference, which may be null if this - * represents the imaginary reference to the root node - */ - public NodeRef getParentRef() - { - return parentRef; - } - - /** - * @return Returns true if this represents a primary association - */ - public boolean isPrimary() - { - return isPrimary; - } - - /** - * @return Returns the nth sibling required - */ - public int getNthSibling() - { - return nthSibling; - } - - /** - * Allows post-creation setting of the ordering index. This is a helper - * so that sorted sets and lists can be easily sorted. - *

- * This index is in no way absolute and should change depending on - * the results that appear around this instance. Therefore, the sibling - * number cannot be used to construct, say, sibling number 5. Sibling - * number 5 will exist only in results where there are siblings 1 - 4. - * - * @param nthSibling the sibling index - */ - public void setNthSibling(int nthSibling) - { - this.nthSibling = nthSibling; - } -} diff --git a/source/java/org/alfresco/service/cmr/repository/ContentAccessor.java b/source/java/org/alfresco/service/cmr/repository/ContentAccessor.java deleted file mode 100644 index 9ea0f89613..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/ContentAccessor.java +++ /dev/null @@ -1,132 +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.service.cmr.repository; - -import java.util.Locale; - -import org.alfresco.repo.transaction.RetryingTransactionHelper; -import org.alfresco.service.transaction.TransactionService; - -/** - * Interface for instances that provide read and write access to content. - * - * @author Derek Hulley - */ -public interface ContentAccessor -{ - /** - * Gets the open/close state of the underlying IO Channel. - * - * @return Returns true if the underlying IO Channel is open - */ - public boolean isChannelOpen(); - - /** - * Use this method to register any interest in events against underlying - * content streams. - * {@link #getContentOutputStream() output stream}. - *

- * This method can only be used before the content stream has been retrieved. - *

- * When the stream has been closed, all listeners will be called - * within a {@link #setTransactionService(TransactionService) transaction} - - * to this end, a {@link TransactionService} must have been set as well. - * - * @param listener a listener that will be called for output stream - * event notification - * - * @see #setRetryingTransactionHelper(RetryingTransactionHelper) - */ - public void addListener(ContentStreamListener listener); - - /** - * Set the transaction helper for callbacks. - */ - public void setRetryingTransactionHelper(RetryingTransactionHelper helper); - - /** - * Gets the size of the content that this reader references. - * - * @return Returns the document byte length, or OL if the - * content doesn't {@link #exists() exist}. - */ - public long getSize(); - - /** - * Get the data representation of the content being accessed. - *

- * The content {@link #setMimetype(String) mimetype } must be set before this - * method is called as the content data requires a mimetype whenever the - * content URL is specified. - * - * @return Returns the content data - * - * @see ContentData#ContentData(String, String, long, String) - */ - public ContentData getContentData(); - - /** - * Retrieve the URL that this accessor references - * - * @return the content URL - */ - public String getContentUrl(); - - /** - * Get the content mimetype - * - * @return Returns a content mimetype - */ - public String getMimetype(); - - /** - * Set the mimetype that must be used for accessing the content - * - * @param mimetype the content mimetype - */ - public void setMimetype(String mimetype); - - /** - * Get the encoding of the content being accessed - * - * @return Returns a valid java String encoding - */ - public String getEncoding(); - - /** - * Set the String encoding for this accessor - * - * @param encoding a java-recognised encoding format - */ - public void setEncoding(String encoding); - - /** - * Get the locale of the content being accessed - * - * @return Returns a valid java Locale - */ - public Locale getLocale(); - - /** - * Set the Locale for this accessor - * - * @param locale a java-recognised locale - */ - public void setLocale(Locale locale); -} diff --git a/source/java/org/alfresco/service/cmr/repository/ContentData.java b/source/java/org/alfresco/service/cmr/repository/ContentData.java deleted file mode 100644 index 58c9456871..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/ContentData.java +++ /dev/null @@ -1,357 +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.service.cmr.repository; - -import java.io.Serializable; -import java.util.Locale; -import java.util.StringTokenizer; - -import org.springframework.extensions.surf.util.I18NUtil; -import org.alfresco.repo.content.MimetypeMap; -import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter; -import org.alfresco.util.EqualsHelper; - -/** - * The compound property representing content - * - * @author Derek Hulley - */ -public class ContentData implements Serializable -{ - private static final long serialVersionUID = 8979634213050121462L; - - private static char[] INVALID_CONTENT_URL_CHARS = new char[] {'|'}; - - private final String contentUrl; - private final String mimetype; - private final long size; - private final String encoding; - private final Locale locale; - - /** - * Construct a content property from a string - * - * @param contentPropertyStr the string representing the content details - * @return Returns a bean version of the string - */ - public static ContentData createContentProperty(String contentPropertyStr) - { - String contentUrl = null; - String mimetype = null; - long size = 0L; - String encoding = null; - Locale locale = null; - // now parse the string - StringTokenizer tokenizer = new StringTokenizer(contentPropertyStr, "|"); - while (tokenizer.hasMoreTokens()) - { - String token = tokenizer.nextToken(); - if (token.startsWith("contentUrl=")) - { - contentUrl = token.substring(11); - if (contentUrl.length() == 0) - { - contentUrl = null; - } - } - else if (token.startsWith("mimetype=")) - { - mimetype = token.substring(9); - if (mimetype.length() == 0) - { - mimetype = null; - } - } - else if (token.startsWith("size=")) - { - String sizeStr = token.substring(5); - if (sizeStr.length() > 0) - { - size = Long.parseLong(sizeStr); - } - } - else if (token.startsWith("encoding=")) - { - encoding = token.substring(9); - if (encoding.length() == 0) - { - encoding = null; - } - } - else if (token.startsWith("locale=")) - { - String localeStr = token.substring(7); - if (localeStr.length() > 0) - { - locale = I18NUtil.parseLocale(localeStr); - } - } - } - - ContentData property = new ContentData(contentUrl, mimetype, size, encoding, locale); - // done - return property; - } - - /** - * Constructs a new instance using the existing one as a template, but replacing the - * mimetype - * - * @param existing an existing set of content data, null to use default values - * @param mimetype the mimetype to set - * @return Returns a new, immutable instance of the data - */ - public static ContentData setMimetype(ContentData existing, String mimetype) - { - ContentData ret = new ContentData( - existing == null ? null : existing.contentUrl, - mimetype, - existing == null ? 0L : existing.size, - existing == null ? "UTF-8" : existing.encoding, - existing == null ? null : existing.locale); - // done - return ret; - } - - /** - * Constructs a new instance using the existing one as a template, but replacing the - * encoding. - * - * @param existing an existing set of content data, null to use default values - * @param encoding the encoding to set - * @return Returns a new, immutable instance of the data - */ - public static ContentData setEncoding(ContentData existing, String encoding) - { - ContentData ret = new ContentData( - existing == null ? null : existing.contentUrl, - existing == null ? null : existing.mimetype, - existing == null ? 0L : existing.size, - encoding, - existing == null ? null : existing.locale); - // done - return ret; - } - - /** - * Helper method to determine if the data represents any physical content or not. - * - * @param contentData the content to check (may be null) - * @return true if the value is non-null - */ - public static boolean hasContent(ContentData contentData) - { - if (contentData == null) - { - return false; - } - return contentData.contentUrl != null; - } - - /** - * Copy constructor for derived class - * - * @param original the object to copy - */ - protected ContentData(ContentData original) - { - this.contentUrl = original.contentUrl; - this.encoding = original.encoding; - this.locale = original.locale; - this.mimetype = original.mimetype; - this.size = original.size; - } - - /** - * Create a content data using the {@link I18NUtil#getLocale() default locale}. - * - * @see #ContentData(String, String, long, String, Locale) - */ - public ContentData(String contentUrl, String mimetype, long size, String encoding) - { - this(contentUrl, mimetype, size, encoding, null); - } - - /** - * Create a compound set of data representing a single instance of content. - *

- * In order to ensure data integrity, the {@link #getMimetype() mimetype} - * must be set if the {@link #getContentUrl() content URL} is set. - * - * @param contentUrl the content URL. If this value is non-null, then the - * mimetype must be supplied. - * @param mimetype the content mimetype. This is mandatory if the contentUrl is specified. - * @param size the content size. - * @param encoding the content encoding. This is mandatory if the contentUrl is specified. - * @param locale the locale of the content (may be null). If null, the - * {@link I18NUtil#getLocale() default locale} will be used. - */ - public ContentData(String contentUrl, String mimetype, long size, String encoding, Locale locale) - { - if (contentUrl != null && (mimetype == null || mimetype.length() == 0)) - { - mimetype = MimetypeMap.MIMETYPE_BINARY; - } - checkContentUrl(contentUrl, mimetype, encoding); - this.contentUrl = contentUrl; - this.mimetype = mimetype; - this.size = size; - this.encoding = encoding; - if (locale == null) - { - locale = I18NUtil.getLocale(); - } - this.locale = locale; - } - - public boolean equals(Object obj) - { - if (obj == this) - return true; - else if (obj == null) - return false; - else if (!(obj instanceof ContentData)) - return false; - ContentData that = (ContentData) obj; - return (EqualsHelper.nullSafeEquals(this.contentUrl, that.contentUrl) && - EqualsHelper.nullSafeEquals(this.mimetype, that.mimetype, true) && - this.size == that.size && - EqualsHelper.nullSafeEquals(this.encoding, that.encoding, true) && - EqualsHelper.nullSafeEquals(this.locale, that.locale)); - } - - /** - * @return Returns a string of form: contentUrl=xxx;mimetype=xxx;size=xxx;encoding=xxx - */ - public String toString() - { - StringBuilder sb = new StringBuilder(80); - sb.append("contentUrl=").append(contentUrl == null ? "" : contentUrl) - .append("|mimetype=").append(mimetype == null ? "" : mimetype) - .append("|size=").append(size) - .append("|encoding=").append(encoding == null ? "" : encoding) - .append("|locale=").append(locale == null ? "" : DefaultTypeConverter.INSTANCE.convert(String.class, locale)); - return sb.toString(); - } - - /** - * @return Returns a URL identifying the specific location of the content. - * The URL must identify, within the context of the originating content - * store, the exact location of the content. - * @throws ContentIOException - */ - public String getContentUrl() - { - return contentUrl; - } - - /** - * Checks that the content URL is correct, and also that the mimetype is - * non-null if the URL is present. - * - * @param contentUrl the content URL to check - * @param mimetype the encoding must be present if the content URL is present - * @param encoding the encoding must be valid and present if the content URL is present - */ - private void checkContentUrl(String contentUrl, String mimetype, String encoding) - { - // check the URL - if (contentUrl != null && contentUrl.length() > 0) - { - for (int i = 0; i < INVALID_CONTENT_URL_CHARS.length; i++) - { - for (int j = contentUrl.length() - 1; j > -1; j--) - { - if (contentUrl.charAt(j) == INVALID_CONTENT_URL_CHARS[i]) - { - throw new IllegalArgumentException( - "The content URL contains an invalid char: \n" + - " content URL: " + contentUrl + "\n" + - " char: " + INVALID_CONTENT_URL_CHARS[i] + "\n" + - " position: " + j); - } - } - } - - // check that mimetype is present if URL is present - if (mimetype == null) - { - throw new IllegalArgumentException("\n" + - "The content mimetype must be set whenever the URL is set: \n" + - " content URL: " + contentUrl + "\n" + - " mimetype: " + mimetype); - } - } - } - - /** - * Gets content's mimetype. - * - * @return Returns a standard mimetype for the content or null if the mimetype - * is unkown - */ - public String getMimetype() - { - return mimetype; - } - - /** - * Get the content's size - * - * @return Returns the size of the content - */ - public long getSize() - { - return size; - } - - /** - * Gets the content's encoding. - * - * @return Returns a valid Java encoding, typically a character encoding, or - * null if the encoding is unkown - */ - public String getEncoding() - { - return encoding; - } - - /** - * Get the content's locale. - * - * @return Returns a locale, or null if the locale is unknown - */ - public Locale getLocale() - { - return locale; - } - - /** - * @return hashCode - */ - public int hashCode() - { - if(contentUrl!= null) - { - return contentUrl.hashCode(); - } - return 0; - } -} - diff --git a/source/java/org/alfresco/service/cmr/repository/ContentIOException.java b/source/java/org/alfresco/service/cmr/repository/ContentIOException.java deleted file mode 100644 index 501253ac5b..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/ContentIOException.java +++ /dev/null @@ -1,45 +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.service.cmr.repository; - -import org.alfresco.error.AlfrescoRuntimeException; - - -/** - * Wraps a general Exceptions that occurred while reading or writing - * content. - * - * @see Throwable#getCause() - * - * @author Derek Hulley - */ -public class ContentIOException extends AlfrescoRuntimeException -{ - private static final long serialVersionUID = 3258130249983276087L; - - public ContentIOException(String msg) - { - super(msg); - } - - public ContentIOException(String msg, Throwable cause) - { - super(msg, cause); - } -} diff --git a/source/java/org/alfresco/service/cmr/repository/ContentReader.java b/source/java/org/alfresco/service/cmr/repository/ContentReader.java deleted file mode 100644 index 9dcb3f497c..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/ContentReader.java +++ /dev/null @@ -1,184 +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.service.cmr.repository; - -import java.io.File; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.channels.FileChannel; -import java.nio.channels.ReadableByteChannel; - -/** - * Represents a handle to read specific content. Content may only be accessed - * once per instance. - *

- * Implementations of this interface might be Serializable - * but client code could should check suitability before attempting to serialize - * it. - *

- * Implementations that are able to provide inter-VM streaming, such as accessing - * WebDAV, would be Serializable. An accessor that has to access a - * local file on the server could not provide inter-VM streaming unless it specifically - * makes remote calls and opens sockets, etc. - * - * @see org.alfresco.service.cmr.repository.ContentWriter - * - * @author Derek Hulley - */ -public interface ContentReader extends ContentAccessor -{ - /** - * Convenience method to get another reader onto the underlying content. - * - * @return Returns a reader onto the underlying content - * @throws ContentIOException - */ - public ContentReader getReader() throws ContentIOException; - - /** - * Check if the {@link ContentAccessor#getContentUrl() underlying content} is present. - * - * @return Returns true if there is content at the URL refered to by this reader - */ - public boolean exists(); - - /** - * Gets the time of the last modification of the underlying content. - * - * @return Returns the last modification time using the standard long - * time, or 0L if the content doesn't {@link #exists() exist}. - * - * @see System#currentTimeMillis() - */ - public long getLastModified(); - - /** - * Convenience method to find out if this reader has been closed. - * Once closed, the content can no longer be read. This method could - * be used to wait for a particular read operation to complete, for example. - * - * @return Return true if the content input stream has been used and closed - * otherwise false. - */ - public boolean isClosed(); - - /** - * Provides low-level access to the underlying content. - *

- * Once the stream is provided to a client it should remain active - * (subject to any timeouts) until closed by the client. - * - * @return Returns a stream that can be read at will, but must be closed when completed - * @throws ContentIOException - */ - public ReadableByteChannel getReadableChannel() throws ContentIOException; - - /** - * Provides read-only, random-access to the underlying content. In general, this method - * should be considered more expensive than the sequential-access method, - * {@link #getReadableChannel()}. - * - * @return Returns a random-access channel onto the content - * @throws ContentIOException - * - * @see #getReadableChannel() - * @see java.io.RandomAccessFile#getChannel() - */ - public FileChannel getFileChannel() throws ContentIOException; - - /** - * Get a stream to read from the underlying channel - * - * @return Returns an input stream onto the underlying channel - * @throws ContentIOException - * - * @see #getReadableChannel() - */ - public InputStream getContentInputStream() throws ContentIOException; - - /** - * Gets content from the repository. - *

- * All resources will be closed automatically. - *

- * Care must be taken that the bytes read from the stream are properly - * decoded according to the {@link ContentAccessor#getEncoding() encoding} - * property. - * - * @param os the stream to which to write the content - * @throws ContentIOException - * - * @see #getReadableChannel() - */ - public void getContent(OutputStream os) throws ContentIOException; - - /** - * Gets content from the repository direct to file - *

- * All resources will be closed automatically. - * - * @param file the file to write the content to - it will be overwritten - * @throws ContentIOException - * - * @see #getContentInputStream() - */ - public void getContent(File file) throws ContentIOException; - - /** - * Gets content from the repository direct to String. - *

- * If the {@link ContentAccessor#getEncoding() encoding } is known then it will be used - * otherwise the default system byte[] to String conversion - * will be used. - *

- * All resources will be closed automatically. - *

- * WARNING: This should only be used when the size of the content - * is known in advance. - * - * @return Returns a String representation of the content - * @throws ContentIOException - * - * @see #getContentString(int) - * @see #getContentInputStream() - * @see String#String(byte[]) - */ - public String getContentString() throws ContentIOException; - - /** - * Gets content from the repository direct to String, but limiting - * the string size to a given number of characters. - *

- * If the {@link ContentAccessor#getEncoding() encoding } is known then it will be used - * otherwise the default system byte[] to String conversion - * will be used. - *

- * All resources will be closed automatically. - * - * @param length the maximum number of characters to retrieve - * @return Returns a truncated String representation of the content - * @throws ContentIOException - * @throws java.lang.IllegalArgumentException if the length is < 0 or > {@link Integer#MAX_VALUE} - * - * @see #getContentString() - * @see #getContentInputStream() - * @see String#String(byte[]) - */ - public String getContentString(int length) throws ContentIOException; -} diff --git a/source/java/org/alfresco/service/cmr/repository/ContentStreamListener.java b/source/java/org/alfresco/service/cmr/repository/ContentStreamListener.java deleted file mode 100644 index 0261d0cd3a..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/ContentStreamListener.java +++ /dev/null @@ -1,35 +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.service.cmr.repository; - -/** - * Listens for notifications w.r.t. content. This includes receiving notifications - * of the opening and closing of the content streams. - * - * @author Derek Hulley - */ -public interface ContentStreamListener -{ - /** - * Called when the stream associated with a reader or writer is closed - * - * @throws ContentIOException - */ - public void contentStreamClosed() throws ContentIOException; -} diff --git a/source/java/org/alfresco/service/cmr/repository/ContentWriter.java b/source/java/org/alfresco/service/cmr/repository/ContentWriter.java deleted file mode 100644 index 56d2cb7d76..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/ContentWriter.java +++ /dev/null @@ -1,162 +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.service.cmr.repository; - -import java.io.File; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.channels.FileChannel; -import java.nio.channels.WritableByteChannel; - - -/** - * Represents a handle to write specific content. Content may only be accessed - * once per instance. - *

- * Implementations of this interface might be Serializable - * but client code could should check suitability before attempting to serialize - * it. - *

- * Implementations that are able to provide inter-VM streaming, such as accessing - * WebDAV, would be Serializable. An accessor that has to access a - * local file on the server could not provide inter-VM streaming unless it specifically - * makes remote calls and opens sockets, etc. - * - * @see org.alfresco.service.cmr.repository.ContentReader - * - * @author Derek Hulley - */ -public interface ContentWriter extends ContentAccessor -{ - /** - * Convenience method to get a reader onto newly written content. This - * method will return null if the content has not yet been written by the - * writer or if the output stream is still open. - * - * @return Returns a reader onto the underlying content that this writer - * will or has written to - * @throws ContentIOException - */ - public ContentReader getReader() throws ContentIOException; - - /** - * Convenience method to find out if this writer has been closed. - * Once closed, the content can no longer be written to and it become possible - * to get readers onto the written content. - * - * @return Return true if the content output stream has been used and closed - * otherwise false. - */ - public boolean isClosed(); - - /** - * Provides low-level access to write to repository content. - *

- * The channel returned to the client should remain open (subject to timeouts) - * until closed by the client. All lock detection, read-only access and other - * concurrency issues are dealt with during this operation. It remains - * possible that implementations will throw exceptions when the channel is closed. - *

- * The stream will notify any listeners according to the listener interface. - * - * @return Returns a channel with which to write content - * @throws ContentIOException - */ - public WritableByteChannel getWritableChannel() throws ContentIOException; - - /** - * Provides read-write, random-access to the underlying content. In general, this method - * should be considered more expensive than the sequential-access method, - * {@link #getWritableChannel()}. - *

- * Underlying implementations use the truncate parameter to determine the - * most effective means of providing access to the content. - * - * @param truncate true to start with zero length content - * @return Returns a random-access channel onto the content - * @throws ContentIOException - * - * @see #getWritableChannel() - * @see java.io.RandomAccessFile#getChannel() - */ - public FileChannel getFileChannel(boolean truncate) throws ContentIOException; - - /** - * Get a stream to write to the underlying channel. - * - * @return Returns an output stream onto the underlying channel - * @throws ContentIOException - * - * @see #getWritableChannel() - */ - public OutputStream getContentOutputStream() throws ContentIOException; - - /** - * Copies content from the reader. - *

- * All resources will be closed automatically. - * - * @param reader the reader acting as the source of the content - * @throws ContentIOException - * - * @see #getWritableChannel() - */ - public void putContent(ContentReader reader) throws ContentIOException; - - /** - * Puts content to the repository - *

- * All resources will be closed automatically. - * - * @param is the input stream from which the content will be read - * @throws ContentIOException - * - * @see #getWritableChannel() - */ - public void putContent(InputStream is) throws ContentIOException; - - /** - * Puts content to the repository direct from file - *

- * All resources will be closed automatically. - * - * @param file the file to load the content from - * @throws ContentIOException - * - * @see #getWritableChannel() - */ - public void putContent(File file) throws ContentIOException; - - /** - * Puts content to the repository direct from String. - *

- * If the {@link ContentAccessor#getEncoding() encoding } is known then it will be used - * otherwise the default system String to byte[] conversion - * will be used. - *

- * All resources will be closed automatically. - * - * @param content a string representation of the content - * @throws ContentIOException - * - * @see #getWritableChannel() - * @see String#getBytes(java.lang.String) - */ - public void putContent(String content) throws ContentIOException; -} diff --git a/source/java/org/alfresco/service/cmr/repository/EntityRef.java b/source/java/org/alfresco/service/cmr/repository/EntityRef.java deleted file mode 100644 index 23e9af2938..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/EntityRef.java +++ /dev/null @@ -1,35 +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.service.cmr.repository; - -import java.io.Serializable; - -/** - * A marker interface for entity reference classes. - *

- * This is used primarily as a means of ensuring type safety in collections - * of mixed type references. - * - * @see org.alfresco.service.cmr.repository.NodeService#removeChildren(NodeRef, QName) - * - * @author Derek Hulley - */ -public interface EntityRef extends Serializable -{ -} diff --git a/source/java/org/alfresco/service/cmr/repository/InvalidChildAssociationRefException.java b/source/java/org/alfresco/service/cmr/repository/InvalidChildAssociationRefException.java deleted file mode 100644 index d00df174bb..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/InvalidChildAssociationRefException.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.service.cmr.repository; - -/** - * Thrown when an operation cannot be performed because thechild association - * reference no longer exists. - * - * @author Derek Hulley - */ -public class InvalidChildAssociationRefException extends RuntimeException -{ - private static final long serialVersionUID = -7493054268618534572L; - - private ChildAssociationRef childAssociationRef; - - public InvalidChildAssociationRefException(ChildAssociationRef childAssociationRef) - { - this(null, childAssociationRef); - } - - public InvalidChildAssociationRefException(String msg, ChildAssociationRef childAssociationRef) - { - super(msg); - this.childAssociationRef = childAssociationRef; - } - - /** - * @return Returns the offending child association reference - */ - public ChildAssociationRef getChildAssociationRef() - { - return childAssociationRef; - } -} diff --git a/source/java/org/alfresco/service/cmr/repository/InvalidNodeRefException.java b/source/java/org/alfresco/service/cmr/repository/InvalidNodeRefException.java deleted file mode 100644 index dfb61bcba3..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/InvalidNodeRefException.java +++ /dev/null @@ -1,52 +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.service.cmr.repository; - - -/** - * Thrown when an operation cannot be performed because the node reference - * no longer exists. - * - * @author Derek Hulley - */ -public class InvalidNodeRefException extends RuntimeException -{ - private static final long serialVersionUID = 3689345520586273336L; - - private NodeRef nodeRef; - - public InvalidNodeRefException(NodeRef nodeRef) - { - this(null, nodeRef); - } - - public InvalidNodeRefException(String msg, NodeRef nodeRef) - { - super(msg); - this.nodeRef = nodeRef; - } - - /** - * @return Returns the offending node reference - */ - public NodeRef getNodeRef() - { - return nodeRef; - } -} diff --git a/source/java/org/alfresco/service/cmr/repository/InvalidStoreRefException.java b/source/java/org/alfresco/service/cmr/repository/InvalidStoreRefException.java deleted file mode 100644 index dfe547e14a..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/InvalidStoreRefException.java +++ /dev/null @@ -1,41 +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.service.cmr.repository; - - -/** - * Thrown when an operation cannot be performed because the store reference - * no longer exists. - * - * @author Derek Hulley - */ -public class InvalidStoreRefException extends AbstractStoreException -{ - private static final long serialVersionUID = 3258126938479409463L; - - public InvalidStoreRefException(StoreRef storeRef) - { - this("Invalid store: " + storeRef, storeRef); - } - - public InvalidStoreRefException(String msg, StoreRef storeRef) - { - super(msg, storeRef); - } -} diff --git a/source/java/org/alfresco/service/cmr/repository/MLText.java b/source/java/org/alfresco/service/cmr/repository/MLText.java deleted file mode 100644 index 8db72bd414..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/MLText.java +++ /dev/null @@ -1,193 +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.service.cmr.repository; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Locale; -import java.util.Set; - -import org.springframework.extensions.surf.util.I18NUtil; - -/** - * Class to represent a multilingual (ML) text value. - *

- * The language codes used should conform to the - * {@linkplain http://www.loc.gov/standards/iso639-2/php/English_list.php ISO639-2} - * language code standard, although there is no enforcement of the standard in this - * class. - *

- * This is a simple extension of a HashMap with a few convenience methods. - * - * @see ISO639-2 - * - * @author Philippe Dubois - * @author Derek Hulley - */ -public class MLText extends HashMap -{ - private static final long serialVersionUID = -3696135175650511841L; - - public MLText() - { - super(3, 0.75F); - } - - /** - * Construct an instance with a value corresponding to the current context locale. - * - * @param value the value for the current default locale - * - * @see I18NUtil#getLocale() - * @see #MLText(Locale, String) - * @see #getDefaultValue() - */ - public MLText(String value) - { - this(I18NUtil.getLocale(), value); - } - - /** - * Construct an instance with a value for the given locale. - * - * @param locale the locale - * @param value the value - * - * @see #getDefaultValue() - */ - public MLText(Locale locale, String value) - { - super(3, 0.75F); - super.put(locale, value); - } - - /** - * @return Returns all the language locales defined in the text - */ - public Set getLocales() - { - return keySet(); - } - - /** - * @return Returns all the values stored - */ - public Collection getValues() - { - return values(); - } - - /** - * Add a multilingual text value - * - * @param locale the language locale - * @param value the multilingual text - */ - public void addValue(Locale locale, String value) - { - put(locale, value); - } - - /** - * Retrieve a multilingual text value - * - * @param locale the language locale - */ - public String getValue(Locale locale) - { - return get(locale); - } - - /** - * Retrieves a default value from the set of available locales.
- * - * @see I18NUtil#getLocale() - * @see #getClosestValue(Locale) - */ - public String getDefaultValue() - { - // Shortcut so that we don't have to go and get the current locale - if (this.size() == 0) - { - return null; - } - // There is some hope of getting a match - Locale locale = I18NUtil.getLocale(); - return getClosestValue(locale); - } - - /** - * The given locale is used to search for a matching value according to: - *

    - *
  • An exact locale match
  • - *
  • A match of locale ISO language codes
  • - *
  • The value for the locale provided in the {@link MLText#MLText(Locale, String) constructor}
  • - *
  • An arbitrary value
  • - *
  • null
  • - *
- * - * @param locale the locale to use as the starting point of the value search - * @return Returns a default String value or null if one isn't available. - * null will only be returned if there are no values associated with - * this instance. With or without a match, the return value may be null, - * depending on the values associated with the locales. - */ - public String getClosestValue(Locale locale) - { - if (this.size() == 0) - { - return null; - } - // Use the available keys as options - Set options = keySet(); - // Get a match - Locale match = I18NUtil.getNearestLocale(locale, options); - if (match == null) - { - // No close matches for the locale - go for the default locale - locale = I18NUtil.getLocale(); - match = I18NUtil.getNearestLocale(locale, options); - if (match == null) - { - // just get any locale - match = I18NUtil.getNearestLocale(null, options); - } - } - // Did we get a match - if (match == null) - { - // We could find no locale matches - return null; - } - else - { - return get(match); - } - } - - /** - * Remove a multilingual text value - * - * @param locale the language locale - */ - public void removeValue(Locale locale) - { - remove(locale); - } -} \ No newline at end of file diff --git a/source/java/org/alfresco/service/cmr/repository/MLTextTest.java b/source/java/org/alfresco/service/cmr/repository/MLTextTest.java deleted file mode 100644 index fc6095371a..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/MLTextTest.java +++ /dev/null @@ -1,53 +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.service.cmr.repository; - -import java.util.Locale; - -import junit.framework.TestCase; - -/** - * @see org.alfresco.service.cmr.repository.MLText - * - * @author Derek Hulley - */ -public class MLTextTest extends TestCase -{ - MLText mlText; - - @Override - protected void setUp() - { - mlText = new MLText(Locale.CANADA_FRENCH, Locale.CANADA_FRENCH.toString()); - mlText.addValue(Locale.US, Locale.US.toString()); - mlText.addValue(Locale.UK, Locale.UK.toString()); - mlText.addValue(Locale.FRENCH, Locale.FRENCH.toString()); - mlText.addValue(Locale.CHINESE, Locale.CHINESE.toString()); - } - - public void testGetByLocale() - { - // check each value - assertNull("Expected nothing for German", mlText.getValue(Locale.GERMAN)); - assertEquals(Locale.US.toString(), mlText.get(Locale.US)); - assertEquals(Locale.UK.toString(), mlText.get(Locale.UK)); - assertNull("Expected no value for Japanese", mlText.getValue(Locale.JAPANESE)); - assertNotNull("Expected an arbirary value for Japanese", mlText.getClosestValue(Locale.JAPANESE)); - } -} diff --git a/source/java/org/alfresco/service/cmr/repository/MimetypeService.java b/source/java/org/alfresco/service/cmr/repository/MimetypeService.java deleted file mode 100644 index fdeee160a5..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/MimetypeService.java +++ /dev/null @@ -1,126 +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.service.cmr.repository; - -import java.util.List; -import java.util.Map; - -import org.alfresco.error.AlfrescoRuntimeException; -import org.alfresco.repo.content.encoding.ContentCharsetFinder; -import org.alfresco.service.NotAuditable; -import org.alfresco.service.PublicService; - - -/** - * This service interface provides support for Mimetypes. - * - * @author Derek Hulley - */ -@PublicService -public interface MimetypeService -{ - /** - * Get the extension for the specified mimetype - * - * @param mimetype a valid mimetype - * @return Returns the default extension for the mimetype - */ - @NotAuditable - public String getExtension(String mimetype); - - /** - * Get the mimetype for the specified extension - * - * @param extension a valid file extension - * @return Returns a valid mimetype if found, or null if does not exist - */ - @NotAuditable - public String getMimetype(String extension); - - /** - * Get all human readable mimetype descriptions indexed by mimetype extension - * - * @return the map of displays indexed by extension - */ - @NotAuditable - public Map getDisplaysByExtension(); - - /** - * Get all human readable mimetype descriptions indexed by mimetype - * - * @return the map of displays indexed by mimetype - */ - @NotAuditable - public Map getDisplaysByMimetype(); - - /** - * Get all mimetype extensions indexed by mimetype - * - * @return the map of extension indexed by mimetype - */ - @NotAuditable - public Map getExtensionsByMimetype(); - - /** - * Get all mimetypes indexed by extension - * - * @return the map of mimetypes indexed by extension - */ - @NotAuditable - public Map getMimetypesByExtension(); - - /** - * Check if a given mimetype represents a text format. - * - * @param mimetype the mimetype to check - * @return Returns true if it is text - */ - @NotAuditable - public boolean isText(String mimetype); - - /** - * Get all mimetypes - * - * @return all mimetypes - */ - @NotAuditable - public List getMimetypes(); - - /** - * Provides a non-null best guess of the appropriate mimetype given a - * filename. - * - * @param filename the name of the file with an optional file extension - * @return Returns the best guess mimetype or the mimetype for - * straight binary files if no extension could be found. - */ - @NotAuditable - public String guessMimetype(String filename); - - /** - * Provides the system default charset finder. - * - * @return Returns a character set finder that can be used to decode - * streams in order to get the encoding. - * - * @since 2.1 - */ - @NotAuditable - public ContentCharsetFinder getContentCharsetFinder(); -} diff --git a/source/java/org/alfresco/service/cmr/repository/NodeRef.java b/source/java/org/alfresco/service/cmr/repository/NodeRef.java deleted file mode 100644 index f1996b55fd..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/NodeRef.java +++ /dev/null @@ -1,211 +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.service.cmr.repository; - -import java.io.Serializable; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.alfresco.error.AlfrescoRuntimeException; - -/** - * Reference to a node - * - * @author Derek Hulley - */ -public final class NodeRef implements EntityRef, Serializable -{ - private static final long serialVersionUID = 3760844584074227768L; - private static final String URI_FILLER = "/"; - private static final Pattern nodeRefPattern = Pattern.compile(".+://.+/.+"); - - private final StoreRef storeRef; - private final String id; - - /** - * @see #NodeRef(StoreRef, String) - * @see StoreRef#StoreRef(String, String) - */ - public NodeRef(String protocol, String identifier, String id) - { - this(new StoreRef(protocol, identifier), id); - } - - /** - * Construct a Node Reference from a Store Reference and Node Id - * - * @param storeRef store reference - * @param id the manually assigned identifier of the node - */ - public NodeRef(StoreRef storeRef, String id) - { - if (storeRef == null) - { - throw new IllegalArgumentException("Store reference may not be null"); - } - if (id == null) - { - throw new IllegalArgumentException("Node id may not be null"); - } - - this.storeRef = storeRef; - this.id = id; - } - - /** - * Construct a Node Reference from a string representation of a Node Reference. - *

- * The string representation of a Node Reference is as follows: - *

- *

/
- * - * @param nodeRef the string representation of a node ref - */ - public NodeRef(String nodeRef) - { - int lastForwardSlash = nodeRef.lastIndexOf('/'); - if(lastForwardSlash == -1) - { - throw new AlfrescoRuntimeException("Invalid node ref - does not contain forward slash: " + nodeRef); - } - this.storeRef = new StoreRef(nodeRef.substring(0, lastForwardSlash)); - this.id = nodeRef.substring(lastForwardSlash+1); - } - - public String toString() - { - return storeRef.toString() + URI_FILLER + id; - } - - /** - * Override equals for this ref type - * - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object obj) - { - if (this == obj) - { - return true; - } - if (obj instanceof NodeRef) - { - NodeRef that = (NodeRef) obj; - return (this.id.equals(that.id) - && this.storeRef.equals(that.storeRef)); - } - else - { - return false; - } - } - - /** - * Hashes on ID alone. As the number of copies of a particular node will be minimal, this is acceptable - */ - public int hashCode() - { - return id.hashCode(); - } - - /** - * @return The StoreRef part of this reference - */ - public final StoreRef getStoreRef() - { - return storeRef; - } - - /** - * @return The Node Id part of this reference - */ - public final String getId() - { - return id; - } - - /** - * Determine if passed string conforms to the pattern of a node reference - * - * @param nodeRef the node reference as a string - * @return true => it matches the pattern of a node reference - */ - public static boolean isNodeRef(String nodeRef) - { - Matcher matcher = nodeRefPattern.matcher(nodeRef); - return matcher.matches(); - } - - /** - * Helper class to convey the status of a node. - * - * @author Derek Hulley - */ - public static class Status - { - private final String changeTxnId; - private final Long dbTxnId; - private final boolean deleted; - - public Status(String changeTxnId, Long dbTxnId, boolean deleted) - { - this.changeTxnId = changeTxnId; - this.dbTxnId = dbTxnId; - this.deleted = deleted; - } - /** - * @return Returns the ID of the last transaction to change the node - */ - public String getChangeTxnId() - { - return changeTxnId; - } - /** - * @return Returns the db ID of the last transaction to change the node - */ - public Long getDbTxnId() - { - return dbTxnId; - } - /** - * @return Returns true if the node has been deleted, otherwise false - */ - public boolean isDeleted() - { - return deleted; - } - - // debug display string - public String toString() - { - StringBuilder sb = new StringBuilder(50); - - sb.append("Status[") - .append("changeTxnId=") - .append(changeTxnId) - .append(", dbTxnId=") - .append(dbTxnId) - .append(", deleted=") - .append(deleted) - .append("]"); - - return sb.toString(); - } - } -} \ No newline at end of file diff --git a/source/java/org/alfresco/service/cmr/repository/NodeRefTest.java b/source/java/org/alfresco/service/cmr/repository/NodeRefTest.java deleted file mode 100644 index f1890ee445..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/NodeRefTest.java +++ /dev/null @@ -1,64 +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.service.cmr.repository; - -import junit.framework.TestCase; - -/** - * @see org.alfresco.service.cmr.repository.NodeRef - * - * @author Derek Hulley - */ -public class NodeRefTest extends TestCase -{ - - public NodeRefTest(String name) - { - super(name); - } - - public void testStoreRef() throws Exception - { - StoreRef storeRef = new StoreRef("ABC", "123"); - assertEquals("toString failure", "ABC://123", storeRef.toString()); - - StoreRef storeRef2 = new StoreRef(storeRef.getProtocol(), storeRef - .getIdentifier()); - assertEquals("equals failure", storeRef, storeRef2); - } - - public void testNodeRef() throws Exception - { - StoreRef storeRef = new StoreRef("ABC", "123"); - NodeRef nodeRef = new NodeRef(storeRef, "456"); - assertEquals("toString failure", "ABC://123/456", nodeRef.toString()); - - NodeRef nodeRef2 = new NodeRef(storeRef, "456"); - assertEquals("equals failure", nodeRef, nodeRef2); - } - - public void testNodeRefPattern() throws Exception - { - StoreRef storeRef = new StoreRef("ABC", "123"); - NodeRef nodeRef = new NodeRef(storeRef, "456"); - - assertTrue(NodeRef.isNodeRef(nodeRef.toString())); - assertFalse(NodeRef.isNodeRef("sdfsdf:sdfsdf")); - } -} diff --git a/source/java/org/alfresco/service/cmr/repository/NodeService.java b/source/java/org/alfresco/service/cmr/repository/NodeService.java deleted file mode 100644 index 9130d76d1e..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/NodeService.java +++ /dev/null @@ -1,736 +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.service.cmr.repository; - -import java.io.Serializable; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.alfresco.service.Auditable; -import org.alfresco.service.PublicService; -import org.alfresco.service.cmr.dictionary.InvalidAspectException; -import org.alfresco.service.cmr.dictionary.InvalidTypeException; -import org.alfresco.service.namespace.QName; -import org.alfresco.service.namespace.QNamePattern; - -/** - * Interface for public and internal node and store operations. - *

- * Amongst other things, this service must enforce the unique name check as mandated - * by the duplicate entity in the model. - *


- *    
- *       ...
- *       
- *          
- *             ...
- *             false
- *          
- *       
- *    
- * 
- * When duplicates are not allowed, and the cm:name property of a node changes, - * then the {@link org.alfresco.service.cmr.repository.DuplicateChildNodeNameException} - * exception must be thrown. Client code can catch this exception and deal with it - * appropriately. - * - * @author Derek Hulley - */ -@PublicService -public interface NodeService -{ - /** - * Gets a list of all available node store references - * - * @return Returns a list of store references - */ - @Auditable - public List getStores(); - - /** - * Create a new store for the given protocol and identifier. The implementation - * may create the store in any number of locations, including a database or - * Subversion. - * - * @param protocolthe implementation protocol - * @param identifier the protocol-specific identifier - * @return Returns a reference to the store - * @throws StoreExistsException - */ - @Auditable(key = Auditable.Key.RETURN, parameters = {"protocol", "identifier"}) - public StoreRef createStore(String protocol, String identifier) throws StoreExistsException; - - /** - * Delete a store and all its contents. - * - * @param storeRef the store to delete - * @throws InvalidStoreRefException if the store reference is invalid - */ - @Auditable(key= Auditable.Key.ARG_0, parameters = {"storeRef"}) - public void deleteStore(StoreRef storeRef); - - /** - * @param storeRef a reference to the store to look for - * @return Returns true if the store exists, otherwise false - */ - @Auditable(parameters = {"storeRef"}) - public boolean exists(StoreRef storeRef); - - /** - * @param nodeRef a reference to the node to look for - * @return Returns true if the node exists, otherwise false - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef"}) - public boolean exists(NodeRef nodeRef); - - /** - * Gets the ID of the last transaction that caused the node to change. This includes - * deletions, so it is possible that the node being referenced no longer exists. - * If the node never existed, then null is returned. - * - * @param nodeRef a reference to a current or previously existing node - * @return Returns the status of the node, or null if the node never existed - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef"}) - public NodeRef.Status getNodeStatus(NodeRef nodeRef); - - /** - * @param storeRef a reference to an existing store - * @return Returns a reference to the root node of the store - * @throws InvalidStoreRefException if the store could not be found - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"storeRef"}) - public NodeRef getRootNode(StoreRef storeRef) throws InvalidStoreRefException; - - /** - * @see #createNode(NodeRef, QName, QName, QName, Map) - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"parentRef", "assocTypeQName", "assocQName", "nodeTypeQName"}) - public ChildAssociationRef createNode( - NodeRef parentRef, - QName assocTypeQName, - QName assocQName, - QName nodeTypeQName) - throws InvalidNodeRefException, InvalidTypeException; - - /** - * Creates a new, non-abstract, real node as a primary child of the given parent node. - * - * @param parentRef the parent node - * @param assocTypeQName the type of the association to create. This is used - * for verification against the data dictionary. - * @param assocQName the qualified name of the association - * @param nodeTypeQName a reference to the node type - * @param properties optional map of properties to keyed by their qualified names - * @return Returns a reference to the newly created child association - * @throws InvalidNodeRefException if the parent reference is invalid - * @throws InvalidTypeException if the node type reference is not recognised - * - * @see org.alfresco.service.cmr.dictionary.DictionaryService - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"parentRef", "assocTypeQName", "assocQName", "nodeTypeQName", "properties"}) - public ChildAssociationRef createNode( - NodeRef parentRef, - QName assocTypeQName, - QName assocQName, - QName nodeTypeQName, - Map properties) - throws InvalidNodeRefException, InvalidTypeException; - - /** - * Moves the primary location of the given node. - *

- * This involves changing the node's primary parent and possibly the name of the - * association referencing it. - *

- * If the new parent is in a different store from the original, then the entire - * node hierarchy is moved to the new store. Inter-store associations are not - * affected. - * - * @param nodeToMoveRef the node to move - * @param newParentRef the new parent of the moved node - * @param assocTypeQName the type of the association to create. This is used - * for verification against the data dictionary. - * @param assocQName the qualified name of the new child association - * @return Returns a reference to the newly created child association - * @throws InvalidNodeRefException if either the parent node or move node reference is invalid - * @throws CyclicChildRelationshipException if the child partakes in a cyclic relationship after the add - * - * @see #getPrimaryParent(NodeRef) - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeToMoveRef", "newParentRef", "assocTypeQName", "assocQName"}) - public ChildAssociationRef moveNode( - NodeRef nodeToMoveRef, - NodeRef newParentRef, - QName assocTypeQName, - QName assocQName) - throws InvalidNodeRefException; - - /** - * Set the ordering index of the child association. This affects the ordering of - * of the return values of methods that return a set of children or child - * associations. - * - * @param childAssocRef the child association that must be moved in the order - * @param index an arbitrary index that will affect the return order - * - * @see #getChildAssocs(NodeRef) - * @see #getChildAssocs(NodeRef, QNamePattern, QNamePattern) - * @see ChildAssociationRef#getNthSibling() - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"childAssocRef", "index"}) - public void setChildAssociationIndex( - ChildAssociationRef childAssocRef, - int index) - throws InvalidChildAssociationRefException; - - /** - * @param nodeRef - * @return Returns the type name - * @throws InvalidNodeRefException if the node could not be found - * - * @see org.alfresco.service.cmr.dictionary.DictionaryService - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef"}) - public QName getType(NodeRef nodeRef) throws InvalidNodeRefException; - - /** - * Re-sets the type of the node. Can be called in order specialise a node to a sub-type. - * - * This should be used with caution since calling it changes the type of the node and thus - * implies a different set of aspects, properties and associations. It is the calling codes - * responsibility to ensure that the node is in a approriate state after changing the type. - * - * @param nodeRef the node reference - * @param typeQName the type QName - * - * @since 1.1 - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef", "typeQName"}) - public void setType(NodeRef nodeRef, QName typeQName) throws InvalidNodeRefException; - - /** - * Applies an aspect to the given node. After this method has been called, - * the node with have all the aspect-related properties present - * - * @param nodeRef - * @param aspectTypeQName the aspect to apply to the node - * @param aspectProperties a minimum of the mandatory properties required for - * the aspect - * @throws InvalidNodeRefException - * @throws InvalidAspectException if the class reference is not to a valid aspect - * - * @see org.alfresco.service.cmr.dictionary.DictionaryService#getAspect(QName) - * @see org.alfresco.service.cmr.dictionary.ClassDefinition#getProperties() - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef", "aspectTypeQName", "aspectProperties"}) - public void addAspect( - NodeRef nodeRef, - QName aspectTypeQName, - Map aspectProperties) - throws InvalidNodeRefException, InvalidAspectException; - - /** - * Remove an aspect and all related properties from a node - * - * @param nodeRef - * @param aspectTypeQName the type of aspect to remove - * @throws InvalidNodeRefException if the node could not be found - * @throws InvalidAspectException if the the aspect is unknown or if the - * aspect is mandatory for the class of the node - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef", "aspectTypeQName"}) - public void removeAspect(NodeRef nodeRef, QName aspectTypeQName) - throws InvalidNodeRefException, InvalidAspectException; - - /** - * Determines if a given aspect is present on a node. Aspects may only be - * removed if they are NOT mandatory. - * - * @param nodeRef - * @param aspectTypeQName - * @return Returns true if the aspect has been applied to the given node, - * otherwise false - * @throws InvalidNodeRefException if the node could not be found - * @throws InvalidAspectException if the aspect reference is invalid - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef", "aspectTypeQName"}) - public boolean hasAspect(NodeRef nodeRef, QName aspectTypeQName) - throws InvalidNodeRefException, InvalidAspectException; - - /** - * @param nodeRef - * @return Returns a set of all aspects applied to the node, including mandatory - * aspects - * @throws InvalidNodeRefException if the node could not be found - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef"}) - public Set getAspects(NodeRef nodeRef) throws InvalidNodeRefException; - - /** - * Deletes the given node. - *

- * All associations (both children and regular node associations) - * will be deleted, and where the given node is the primary parent, - * the children will also be cascade deleted. - * - * @param nodeRef reference to a node within a store - * @throws InvalidNodeRefException if the reference given is invalid - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef"}) - public void deleteNode(NodeRef nodeRef) throws InvalidNodeRefException; - - /** - * Makes a parent-child association between the given nodes. Both nodes must belong to the same store. - * - * @param parentRef the parent node - * @param childRef the child node - * @param assocTypeQName the qualified name of the association type as defined in the datadictionary - * @param qname the qualified name of the association - * @return Returns a reference to the newly created child association - * @throws InvalidNodeRefException if the parent or child nodes could not be found - * @throws CyclicChildRelationshipException if the child partakes in a cyclic relationship after the add - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"parentRef", "childRef", "assocTypeQName", "qname"}) - public ChildAssociationRef addChild( - NodeRef parentRef, - NodeRef childRef, - QName assocTypeQName, - QName qname) throws InvalidNodeRefException; - - /** - * Associates a given child node with a given collection of parents. All nodes must belong to the same store. - * - * @param parentRefs the parent nodes (there will be this many associations created). - * @param childRef the child node - * @param assocTypeQName the qualified name of the association type as defined in the datadictionary - * @param qname the qualified name of the association - * @return Returns a reference to the newly created child association - * @throws InvalidNodeRefException if the parent or child nodes could not be found - * @throws CyclicChildRelationshipException if the child partakes in a cyclic relationship after the add - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"parentRefs", "childRef", "assocTypeQName", "qname"}) - public List addChild( - Collection parentRefs, - NodeRef childRef, - QName assocTypeQName, - QName qname) throws InvalidNodeRefException; - - /** - * Severs all parent-child relationships between two nodes. - *

- * The child node will be cascade deleted if one of the associations was the - * primary association, i.e. the one with which the child node was created. - * - * @param parentRef the parent end of the association - * @param childRef the child end of the association - * @throws InvalidNodeRefException if the parent or child nodes could not be found - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"parentRef", "childRef"}) - public void removeChild(NodeRef parentRef, NodeRef childRef) throws InvalidNodeRefException; - - /** - * Remove a specific child association. - *

- * The child node will be cascade deleted if the association was the - * primary association, i.e. the one with which the child node was created. - * - * @param childAssocRef the association to remove - * @return Returns true if the association existed, otherwise false. - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"childAssocRef"}) - public boolean removeChildAssociation(ChildAssociationRef childAssocRef); - - /** - * Remove a specific secondary child association. - * - * @param childAssocRef the association to remove - * @return Returns true if the association existed, otherwise false. - * @throws IllegalArgumentException if the association is primary - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"childAssocRef"}) - public boolean removeSeconaryChildAssociation(ChildAssociationRef childAssocRef); - - /** - * @param nodeRef - * @return Returns all properties keyed by their qualified name - * @throws InvalidNodeRefException if the node could not be found - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef"}) - public Map getProperties(NodeRef nodeRef) throws InvalidNodeRefException; - - /** - * @param nodeRef - * @param qname the qualified name of the property - * @return Returns the value of the property, or null if not yet set - * @throws InvalidNodeRefException if the node could not be found - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef", "qname"}) - public Serializable getProperty(NodeRef nodeRef, QName qname) throws InvalidNodeRefException; - - /** - * Set the values of all properties to be an Serializable instances. - * The properties given must still fulfill the requirements of the class and - * aspects relevant to the node. - *

- * NOTE: Null values are allowed. - * - * @param nodeRef the node to chance - * @param properties all the properties of the node keyed by their qualified names - * @throws InvalidNodeRefException if the node could not be found - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef", "properties"}) - public void setProperties(NodeRef nodeRef, Map properties) throws InvalidNodeRefException; - - /** - * Add all given properties to the node. - *

- * NOTE: Null values are allowed and will replace the existing value. - * - * @param nodeRef the node to change - * @param properties the properties to change, keyed by their qualified names - * @throws InvalidNodeRefException if the node could not be found - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef", "properties"}) - public void addProperties(NodeRef nodeRef, Map properties) throws InvalidNodeRefException; - - /** - * Sets the value of a property to be any Serializable instance. - *

- * NOTE: Null values are allowed. - * - * @param nodeRef a reference to an existing node - * @param qname the fully qualified name of the property - * @param propertyValue the value of the property - never null - * @throws InvalidNodeRefException if the node could not be found - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef", "qname", "value"}) - public void setProperty(NodeRef nodeRef, QName qname, Serializable value) throws InvalidNodeRefException; - - /** - * Removes a property value completely. - * - * @param nodeRef a reference to an existing node - * @param qname the fully qualified name of the property - * @throws InvalidNodeRefException if the node could not be found - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef", "qname"}) - public void removeProperty(NodeRef nodeRef, QName qname) throws InvalidNodeRefException; - - /** - * @param nodeRef the child node - * @return Returns a list of all parent-child associations that exist where the given - * node is the child - * @throws InvalidNodeRefException if the node could not be found - * - * @see #getParentAssocs(NodeRef, QNamePattern, QNamePattern) - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef"}) - public List getParentAssocs(NodeRef nodeRef) throws InvalidNodeRefException; - - /** - * Gets all parent associations where the pattern of the association qualified - * name is a match - *

- * The resultant list is ordered by (a) explicit index and (b) association creation time. - * - * @param nodeRef the child node - * @param typeQNamePattern the pattern that the type qualified name of the association must match - * @param qnamePattern the pattern that the qnames of the assocs must match - * @return Returns a list of all parent-child associations that exist where the given - * node is the child - * @throws InvalidNodeRefException if the node could not be found - * - * @see ChildAssociationRef#getNthSibling() - * @see #setChildAssociationIndex(ChildAssociationRef, int) - * @see QName - * @see org.alfresco.service.namespace.RegexQNamePattern#MATCH_ALL - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef", "typeQNamePattern", "qnamePattern"}) - public List getParentAssocs(NodeRef nodeRef, QNamePattern typeQNamePattern, QNamePattern qnamePattern) - throws InvalidNodeRefException; - - /** - * Get all child associations of the given node. - *

- * The resultant list is ordered by (a) explicit index and (b) association creation time. - * - * @param nodeRef the parent node - usually a container - * @return Returns a collection of ChildAssocRef instances. If the - * node is not a container then the result will be empty. - * @throws InvalidNodeRefException if the node could not be found - * - * @see #getChildAssocs(NodeRef, QNamePattern, QNamePattern) - * @see #setChildAssociationIndex(ChildAssociationRef, int) - * @see ChildAssociationRef#getNthSibling() - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef"}) - public List getChildAssocs(NodeRef nodeRef) throws InvalidNodeRefException; - - /** - * Gets all child associations where the pattern of the association qualified - * name is a match. Using a {@link org.alfresco.service.namespace.RegexQNamePattern#MATCH_ALL wildcard} - * for the type and a specific {@link QName qualified name} for the association is - * akin to using the XPath browse expression ./{url}localname in the context of the - * parent node. - * - * @param nodeRef the parent node - usually a container - * @param typeQNamePattern the pattern that the type qualified name of the association must match - * @param qnamePattern the pattern that the qnames of the assocs must match - * @return Returns a list of ChildAssociationRef instances. If the - * node is not a container then the result will be empty. - * @throws InvalidNodeRefException if the node could not be found - * - * @see QName - * @see org.alfresco.service.namespace.RegexQNamePattern#MATCH_ALL - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef", "typeQNamePattern", "qnamePattern"}) - public List getChildAssocs( - NodeRef nodeRef, - QNamePattern typeQNamePattern, - QNamePattern qnamePattern) - throws InvalidNodeRefException; - - /** - * Gets all child associations where the pattern of the association qualified - * name is a match. Using a {@link org.alfresco.service.namespace.RegexQNamePattern#MATCH_ALL wildcard} - * for the type and a specific {@link QName qualified name} for the association is - * akin to using the XPath browse expression ./{url}localname in the context of the - * parent node. - * - * @param nodeRef the parent node - usually a container - * @param typeQNamePattern the pattern that the type qualified name of the association must match - * @param qnamePattern the pattern that the qnames of the assocs must match - * @param preload should the nodes be preloaded into the cache? - * @return Returns a list of ChildAssociationRef instances. If the - * node is not a container then the result will be empty. - * @throws InvalidNodeRefException if the node could not be found - * - * @see QName - * @see org.alfresco.service.namespace.RegexQNamePattern#MATCH_ALL - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef", "typeQNamePattern", "qnamePattern"}) - public List getChildAssocs( - NodeRef nodeRef, - QNamePattern typeQNamePattern, - QNamePattern qnamePattern, - boolean preload) - throws InvalidNodeRefException; - - /** - * Retrieve immediate children of a given node where the child nodes are in the given inclusive list - * and not in the given exclusive list. - * - * @param nodeRef the parent node - usually a container - * @param childNodeTypes the types that the children may be. Subtypes are not automatically calculated - * and the list must therefore be exhaustive. - * @return Returns a list of ChildAssociationRef instances. - * @throws InvalidNodeRefException if the node could not be found - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef", "childNodeTypes"}) - public List getChildAssocs(NodeRef nodeRef, Set childNodeTypeQNames); - - /** - * Get the node with the given name within the context of the parent node. The name - * is case-insensitive as Alfresco has to support case-insensitive clients as standard. - *

- * That API method getChildByName only works for associations that don't allow duplicate child names. - * See cm:folder and the duplicate tag. Child associations without this allow duplicate - * child names and therefore it is possible to have multiple children with the same name stored against - * the given association type. - * - * @param nodeRef the parent node - usuall a container - * @param assocTypeQName the type of the association - * @param childName the name of the node as per the property cm:name - * @return Returns the child node or null if not found - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef", "assocTypeQName", "childName"}) - public NodeRef getChildByName( - NodeRef nodeRef, - QName assocTypeQName, - String childName); - - /** - * Get the nodes with the given names within the context of the parent node. - * - * {@inheritDoc #getChildByName(NodeRef, QName, String)} - * - * @param childNames a collection of up to 1000 child names to match on - * - * @see {@link #getChildByName(NodeRef, QName, String)} - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef", "assocTypeQName", "childName"}) - public List getChildrenByName( - NodeRef nodeRef, - QName assocTypeQName, - Collection childNames); - - /** - * Fetches the primary parent-child relationship. - *

- * For a root node, the parent node reference will be null. - * - * @param nodeRef - * @return Returns the primary parent-child association of the node - * @throws InvalidNodeRefException if the node could not be found - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef"}) - public ChildAssociationRef getPrimaryParent(NodeRef nodeRef) throws InvalidNodeRefException; - - /** - * Gets the set of child associations of a certain parent node without parent associations of a certain type to - * other nodes with the same parent! In effect the 'orphans' with respect to a certain association type. - * - * @param parent - * the parent node reference - * @param assocTypeQName - * the association type QName - * @return a set of child associations - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"parent", "assocTypeQName"}) - public Collection getChildAssocsWithoutParentAssocsOfType(final NodeRef parent, - final QName assocTypeQName); - - /** - * - * @param sourceRef a reference to a real node - * @param targetRef a reference to a node - * @param assocTypeQName the qualified name of the association type - * @return Returns a reference to the new association - * @throws InvalidNodeRefException if either of the nodes could not be found - * @throws AssociationExistsException - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"sourceRef", "targetRef", "assocTypeQName"}) - public AssociationRef createAssociation(NodeRef sourceRef, NodeRef targetRef, QName assocTypeQName) - throws InvalidNodeRefException, AssociationExistsException; - - /** - * - * @param sourceRef the associaton source node - * @param targetRef the association target node - * @param assocTypeQName the qualified name of the association type - * @throws InvalidNodeRefException if either of the nodes could not be found - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"sourceRef", "targetRef", "assocTypeQName"}) - public void removeAssociation(NodeRef sourceRef, NodeRef targetRef, QName assocTypeQName) - throws InvalidNodeRefException; - - /** - * Gets an association by ID. - * - * @param assocId - * the association id - * @return the association, or null if it does not exist - */ - public AssociationRef getAssoc(Long id); - - /** - * Fetches all associations from the given source where the associations' - * qualified names match the pattern provided. - * - * @param sourceRef the association source - * @param qnamePattern the association qname pattern to match against - * @return Returns a list of NodeAssocRef instances for which the - * given node is a source - * @throws InvalidNodeRefException if the source node could not be found - * - * @see QName - * @see org.alfresco.service.namespace.RegexQNamePattern#MATCH_ALL - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"sourceRef", "qnamePattern"}) - public List getTargetAssocs(NodeRef sourceRef, QNamePattern qnamePattern) - throws InvalidNodeRefException; - - /** - * Fetches all associations to the given target where the associations' - * qualified names match the pattern provided. - * - * @param targetRef the association target - * @param qnamePattern the association qname pattern to match against - * @return Returns a list of NodeAssocRef instances for which the - * given node is a target - * @throws InvalidNodeRefException - * - * @see QName - * @see org.alfresco.service.namespace.RegexQNamePattern#MATCH_ALL - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"targetRef", "qnamePattern"}) - public List getSourceAssocs(NodeRef targetRef, QNamePattern qnamePattern) - throws InvalidNodeRefException; - - /** - * The root node has an entry in the path(s) returned. For this reason, there - * will always be at least one path element in the returned path(s). - * The first element will have a null parent reference and qname. - * - * @param nodeRef - * @return Returns the path to the node along the primary node path - * @throws InvalidNodeRefException if the node could not be found - * - * @see #getPaths(NodeRef, boolean) - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef"}) - public Path getPath(NodeRef nodeRef) throws InvalidNodeRefException; - - /** - * The root node has an entry in the path(s) returned. For this reason, there - * will always be at least one path element in the returned path(s). - * The first element will have a null parent reference and qname. - * - * @param nodeRef - * @param primaryOnly true if only the primary path must be retrieved. If true, the - * result will have exactly one entry. - * @return Returns a List of all possible paths to the given node - * @throws InvalidNodeRefException if the node could not be found - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"nodeRef", "primaryOnly"}) - public List getPaths(NodeRef nodeRef, boolean primaryOnly) throws InvalidNodeRefException; - - /** - * Get the node where archived items will have gone when deleted from the given store. - * - * @param storeRef the store that items were deleted from - * @return Returns the archive node parent - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"storeRef"}) - public NodeRef getStoreArchiveNode(StoreRef storeRef); - - /** - * Restore an individual node (along with its sub-tree nodes) to the target location. - * The archived node must have the {@link org.alfresco.model.ContentModel#ASPECT_ARCHIVED archived aspect} - * set against it. - * - * @param archivedNodeRef the archived node - * @param destinationParentNodeRef the parent to move the node into - * or null to use the original - * @param assocTypeQName the primary association type name to use in the new location - * or null to use the original - * @param assocQName the primary association name to use in the new location - * or null to use the original - * @return Returns the reference to the newly created node - */ - @Auditable(key = Auditable.Key.ARG_0 ,parameters = {"archivedNodeRef", "destinationParentNodeRef", "assocTypeQName", "assocQName"}) - public NodeRef restoreNode( - NodeRef archivedNodeRef, - NodeRef destinationParentNodeRef, - QName assocTypeQName, - QName assocQName); -} diff --git a/source/java/org/alfresco/service/cmr/repository/Path.java b/source/java/org/alfresco/service/cmr/repository/Path.java deleted file mode 100644 index 975edebc18..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/Path.java +++ /dev/null @@ -1,577 +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.service.cmr.repository; - -import java.io.Serializable; -import java.util.Iterator; -import java.util.LinkedList; - -import org.alfresco.model.ContentModel; -import org.alfresco.service.cmr.security.AccessStatus; -import org.alfresco.service.cmr.security.PermissionService; -import org.alfresco.service.namespace.NamespacePrefixResolver; -import org.alfresco.service.namespace.QName; -import org.alfresco.util.ISO9075; - -/** - * Representation of a simple path e.g. - *

- *   /x/y/z
- * 
- * In the above example, there will be 4 elements, the first being a reference - * to the root node, followed by qname elements for x, y and z. - *

- * Methods and constructors are available to construct a Path instance - * from a path string or by building the path incrementally, including the ability to - * append and prepend path elements. - *

- * Path elements supported: - *

    - *
  • /{namespace}name fully qualified element
  • - *
  • /name element using default namespace
  • - *
  • /{namespace}name[n] nth sibling
  • - *
  • /name[n] nth sibling using default namespace
  • - *
  • /descendant-or-self::node() descendent or self
  • - *
  • /. self
  • - *
  • /.. parent
  • - *
- * - * @author Derek Hulley - */ -public final class Path implements Iterable, Serializable -{ - private static final long serialVersionUID = 3905520514524328247L; - private LinkedList elements; - - public Path() - { - // use linked list so as random access is not required, but both prepending and appending is - elements = new LinkedList(); - } - - /** - * @return Returns a typed iterator over the path elements - */ - public Iterator iterator() - { - return elements.iterator(); - } - - /** - * Add a path element to the beginning of the path. This operation is useful in cases where - * a path is built by traversing up a hierarchy. - * - * @param pathElement - * @return Returns this instance of the path - */ - public Path prepend(Path.Element pathElement) - { - elements.addFirst(pathElement); - return this; - } - - /** - * Merge the given path into the beginning of this path. - * - * @param path - * @return Returns this instance of the path - */ - public Path prepend(Path path) - { - elements.addAll(0, path.elements); - return this; - } - - /** - * Appends a path element to the end of the path - * - * @param pathElement - * @return Returns this instance of the path - */ - public Path append(Path.Element pathElement) - { - elements.addLast(pathElement); - return this; - } - - /** - * Append the given path of this path. - * - * @param path - * @return Returns this instance of the path - */ - public Path append(Path path) - { - elements.addAll(path.elements); - return this; - } - - /** - * @return Returns the first element in the path or null if the path is empty - */ - public Element first() - { - return elements.getFirst(); - } - - /** - * @return Returns the last element in the path or null if the path is empty - */ - public Element last() - { - return elements.getLast(); - } - - public int size() - { - return elements.size(); - } - - public Element get(int n) - { - return elements.get(n); - } - - /** - * @return Returns a string path made up of the component elements of this instance - */ - public String toString() - { - StringBuilder sb = new StringBuilder(128); - for (Element element : elements) - { - if((sb.length() > 1) || ((sb.length() == 1) && (sb.charAt(0) != '/'))) - { - sb.append("/"); - } - sb.append(element.getElementString()); - } - return sb.toString(); - } - - /** - * @return Returns a string path made up of the component elements of this instance (prefixed where appropriate) - */ - public String toPrefixString(NamespacePrefixResolver resolver) - { - StringBuilder sb = new StringBuilder(128); - for (Element element : elements) - { - if((sb.length() > 1) || ((sb.length() == 1) && (sb.charAt(0) != '/'))) - { - sb.append("/"); - } - sb.append(element.getPrefixedString(resolver)); - } - return sb.toString(); - } - - /** - * Return the human readable form of the specified node Path. Slow version of the method - * that extracts the name of each node in the Path from the supplied NodeService. - * - * @return human readable form of the Path excluding the final element - */ - public String toDisplayPath(NodeService nodeService, PermissionService permissionService) - { - StringBuilder buf = new StringBuilder(64); - - for (int i=0; i (elements.size() -1)) - { - throw new IndexOutOfBoundsException("Start index " + start + " must be between 0 and " + (elements.size() -1)); - } - if (end < 0 || end > (elements.size() -1)) - { - throw new IndexOutOfBoundsException("End index " + end + " must be between 0 and " + (elements.size() -1)); - } - if (end < start) - { - throw new IndexOutOfBoundsException("End index " + end + " cannot be before start index " + start); - } - Path subPath = new Path(); - for (int i = start; i <= end; i++) - { - subPath.append(this.get(i)); - } - return subPath; - } - - /** - * Override equals to check equality of Path instances - */ - public boolean equals(Object o) - { - if(o == this) - { - return true; - } - if(!(o instanceof Path)) - { - return false; - } - Path other = (Path)o; - return this.elements.equals(other.elements); - } - - /** - * Override hashCode to check hash equality of Path instances - */ - public int hashCode() - { - return elements.hashCode(); - } - - /** - * Represents a path element. - *

- * In /x/y/z, elements are x, y and z. - */ - public abstract static class Element implements Serializable - { - /** - * @return Returns the path element portion including leading '/' and never null - */ - public abstract String getElementString(); - - /** - * @param resolver namespace prefix resolver - * @return the path element portion (with namespaces converted to prefixes) - */ - public String getPrefixedString(NamespacePrefixResolver resolver) - { - return getElementString(); - } - - /** - * @see #getElementString() - */ - public String toString() - { - return getElementString(); - } - } - - /** - * Represents a qualified path between a parent and a child node, - * including the sibling to retrieve e.g. /{namespace}name[5] - */ - public static class ChildAssocElement extends Element - { - private static final long serialVersionUID = 3689352104636790840L; - - private ChildAssociationRef ref; - - /** - * @param ref a reference to the specific parent-child association - */ - public ChildAssocElement(ChildAssociationRef ref) - { - this.ref = ref; - } - - @Override - public String getElementString() - { - return createElementString(null); - } - - @Override - public String getPrefixedString(NamespacePrefixResolver resolver) - { - return createElementString(resolver); - } - - public ChildAssociationRef getRef() - { - return ref; - } - - @Override - public boolean equals(Object o) - { - if(o == this) - { - return true; - } - if(!(o instanceof ChildAssocElement)) - { - return false; - } - ChildAssocElement other = (ChildAssocElement)o; - return this.ref.equals(other.ref); - } - - @Override - public int hashCode() - { - return ref.hashCode(); - } - - private String createElementString(NamespacePrefixResolver resolver) - { - StringBuilder sb = new StringBuilder(32); - if (ref.getParentRef() == null) - { - sb.append("/"); - } - else - { - // a parent is present - sb.append(resolver == null ? ISO9075.getXPathName(ref.getQName()) : ISO9075.getXPathName(ref.getQName(), resolver)); - } - if (ref.getNthSibling() > -1) - { - sb.append("[").append(ref.getNthSibling()).append("]"); - } - return sb.toString(); - } - } - - /** - * Represents a qualified path to an attribute, - * including the sibling for repeated properties/attributes to retrieve e.g. /@{namespace}name[5] - */ - public static class AttributeElement extends Element - { - private static final long serialVersionUID = 3256727281668863544L; - - private QName attribute; - private int position = -1; - - /** - * @param ref a reference to the specific parent-child association - */ - public AttributeElement(QName attribute) - { - this.attribute = attribute; - } - - public AttributeElement(QName attribute, int position) - { - this(attribute); - this.position = position; - } - - @Override - public String getElementString() - { - return createElementString(null); - } - - @Override - public String getPrefixedString(NamespacePrefixResolver resolver) - { - return createElementString(resolver); - } - - private String createElementString(NamespacePrefixResolver resolver) - { - StringBuilder sb = new StringBuilder(32); - sb.append("@").append(resolver == null ? ISO9075.getXPathName(attribute) : ISO9075.getXPathName(attribute, resolver)); - - if (position > -1) - { - sb.append("[").append(position).append("]"); - } - return sb.toString(); - } - - public QName getQName() - { - return attribute; - } - - public int position() - { - return position; - } - - public boolean equals(Object o) - { - if(o == this) - { - return true; - } - if(!(o instanceof AttributeElement)) - { - return false; - } - AttributeElement other = (AttributeElement)o; - return this.getQName().equals(other.getQName()) && (this.position() == other.position()); - } - - public int hashCode() - { - return getQName().hashCode()*32 + position(); - } - - } - - /** - * Represents the // or /descendant-or-self::node() xpath element - */ - public static class DescendentOrSelfElement extends Element - { - private static final long serialVersionUID = 3258410616875005237L; - - public String getElementString() - { - return "descendant-or-self::node()"; - } - - public boolean equals(Object o) - { - if(o == this) - { - return true; - } - if(!(o instanceof DescendentOrSelfElement)) - { - return false; - } - return true; - } - - public int hashCode() - { - return "descendant-or-self::node()".hashCode(); - } - - } - - /** - * Represents the /. xpath element - */ - public static class SelfElement extends Element - { - private static final long serialVersionUID = 3834311739151300406L; - - public String getElementString() - { - return "."; - } - - public boolean equals(Object o) - { - if(o == this) - { - return true; - } - if(!(o instanceof SelfElement)) - { - return false; - } - return true; - } - - public int hashCode() - { - return ".".hashCode(); - } - } - - /** - * Represents the /.. xpath element - */ - public static class ParentElement extends Element - { - private static final long serialVersionUID = 3689915080477456179L; - - public String getElementString() - { - return ".."; - } - - public boolean equals(Object o) - { - if(o == this) - { - return true; - } - if(!(o instanceof ParentElement)) - { - return false; - } - return true; - } - - public int hashCode() - { - return "..".hashCode(); - } - } -} diff --git a/source/java/org/alfresco/service/cmr/repository/PathTest.java b/source/java/org/alfresco/service/cmr/repository/PathTest.java deleted file mode 100644 index 1bfd94f8e2..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/PathTest.java +++ /dev/null @@ -1,113 +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.service.cmr.repository; - -import org.alfresco.service.namespace.QName; - -import junit.framework.TestCase; - -/** - * @see org.alfresco.service.cmr.repository.Path - * - * @author Derek Hulley - */ -public class PathTest extends TestCase -{ - private Path absolutePath; - private Path relativePath; - private QName typeQName; - private QName qname; - private StoreRef storeRef; - private NodeRef parentRef; - private NodeRef childRef; - - public PathTest(String name) - { - super(name); - } - - public void setUp() throws Exception - { - super.setUp(); - absolutePath = new Path(); - relativePath = new Path(); - typeQName = QName.createQName("http://www.alfresco.org/PathTest/1.0", "testType"); - qname = QName.createQName("http://www.google.com", "documentx"); - storeRef = new StoreRef("x", "y"); - parentRef = new NodeRef(storeRef, "P"); - childRef = new NodeRef(storeRef, "C"); - } - - public void testQNameElement() throws Exception - { - // plain - Path.Element element = new Path.ChildAssocElement(new ChildAssociationRef(typeQName, parentRef, qname, childRef)); - assertEquals("Element string incorrect", - qname.toString(), - element.getElementString()); - // sibling - element = new Path.ChildAssocElement(new ChildAssociationRef(typeQName, parentRef, qname, childRef, true, 5)); - assertEquals("Element string incorrect", "{http://www.google.com}documentx[5]", element.getElementString()); - } - - public void testElementTypes() throws Exception - { - Path.Element element = new Path.DescendentOrSelfElement(); - assertEquals("DescendentOrSelf element incorrect", - "descendant-or-self::node()", - element.getElementString()); - - element = new Path.ParentElement(); - assertEquals("Parent element incorrect", "..", element.getElementString()); - - element = new Path.SelfElement(); - assertEquals("Self element incorrect", ".", element.getElementString()); - } - - public void testAppendingAndPrepending() throws Exception - { - Path.Element element0 = new Path.ChildAssocElement(new ChildAssociationRef(null, null, null, parentRef)); - Path.Element element1 = new Path.ChildAssocElement(new ChildAssociationRef(typeQName, parentRef, qname, childRef, true, 4)); - Path.Element element2 = new Path.DescendentOrSelfElement(); - Path.Element element3 = new Path.ParentElement(); - Path.Element element4 = new Path.SelfElement(); - // append them all to the path - absolutePath.append(element0).append(element1).append(element2).append(element3).append(element4); - relativePath.append(element1).append(element2).append(element3).append(element4); - // check - assertEquals("Path appending didn't work", - "/{http://www.google.com}documentx[4]/descendant-or-self::node()/../.", - absolutePath.toString()); - - // copy the path - Path copy = new Path(); - copy.append(relativePath).append(relativePath); - // check - assertEquals("Path appending didn't work", - relativePath.toString() + "/" + relativePath.toString(), - copy.toString()); - - // prepend - relativePath.prepend(element2); - // check - assertEquals("Prepending didn't work", - "descendant-or-self::node()/{http://www.google.com}documentx[4]/descendant-or-self::node()/../.", - relativePath.toString()); - } -} \ No newline at end of file diff --git a/source/java/org/alfresco/service/cmr/repository/Period.java b/source/java/org/alfresco/service/cmr/repository/Period.java deleted file mode 100644 index 25fe480dbf..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/Period.java +++ /dev/null @@ -1,182 +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.service.cmr.repository; - -import java.io.Serializable; -import java.util.Date; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Implementation for the period data type "d:period" A period is specified by the period type and an optional - * expression. The string value is periodType|expression Examples are: none day - one day day|3 - 3 days week - one week - * week|1 - one week week|2 - two weeks month year monthend quarterend The period type specifies a period - * implementation. This is registered with this class and is used to when adding the period to a date, handles any - * processing of the expression, reports if the expression is not required, optional or mandatory. - * - * @author andyh - */ -@SuppressWarnings("unchecked") -public class Period implements Serializable -{ - /** - * - */ - private static final long serialVersionUID = -7978001474638355909L; - - // Providers do not serialize - transient private static ConcurrentHashMap providers = new ConcurrentHashMap(); - - /** - * Register a provider - * @param periodProvider - */ - public static void registerProvider(PeriodProvider periodProvider) - { - providers.put(periodProvider.getPeriodType(), periodProvider); - } - - /** - * Find a provider - * @param periodType - * @return the provider - * @throws IllegalStateException of there is no implementation - */ - public static PeriodProvider getProvider(String periodType) - { - PeriodProvider provider = providers.get(periodType); - if (provider == null) - { - throw new IllegalStateException("No period provider for period type " + periodType); - } - return provider; - } - - /** - * Get the set of registered providers - * @return - the set of registered providers - */ - public static Set getProviderNames() - { - return providers.keySet(); - } - - private String periodType; - - private String expression; - - /** - * Create a period without an accompanying expression. - * - * @param period - */ - public Period(String period) - { - String[] parts = period.split("\\|", 2); - periodType = parts[0]; - if (parts.length == 2) - { - expression = parts[1]; - } - } - - /** - * @return the periodType - */ - public String getPeriodType() - { - return periodType; - } - - /** - * @return the expression - */ - public String getExpression() - { - return expression; - } - - /** - * Calculate the next date for this period given the a start date. - * - * @param date - * @return the next date. - */ - public Date getNextDate(Date date) - { - if (periodType == null || periodType.length() == 0) - { - return null; - } - - PeriodProvider provider = getProvider(periodType); - return provider.getNextDate(date, expression != null ? expression : provider.getDefaultExpression()); - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + ((expression == null) ? 0 : expression.hashCode()); - result = prime * result + ((periodType == null) ? 0 : periodType.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) - { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final Period other = (Period) obj; - if (expression == null) - { - if (other.expression != null) - return false; - } - else if (!expression.equals(other.expression)) - return false; - if (periodType == null) - { - if (other.periodType != null) - return false; - } - else if (!periodType.equals(other.periodType)) - return false; - return true; - } - - @Override - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append(periodType); - if (expression != null) - { - builder.append("|"); - builder.append(expression); - } - return builder.toString(); - } - -} diff --git a/source/java/org/alfresco/service/cmr/repository/PeriodProvider.java b/source/java/org/alfresco/service/cmr/repository/PeriodProvider.java deleted file mode 100644 index 590e5bf83f..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/PeriodProvider.java +++ /dev/null @@ -1,90 +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.service.cmr.repository; - -import java.util.Date; - -import org.alfresco.service.namespace.QName; - -/** - * Provider API for period implementations - * @author andyh - * - */ -public interface PeriodProvider -{ - /** - * Period expression multiplicity - * @author andyh - * - */ - public enum ExpressionMutiplicity - { - /** - * There is no expression - */ - NONE, - /** - * An expression is optional - */ - OPTIONAL, - /** - * An expression is mandatory - */ - MANDATORY - } - - /** - * Get the name for the period. - * @return - period name - */ - public String getPeriodType(); - - /** - * Gets the display label for the period. - * @return display label - */ - public String getDisplayLabel(); - - /** - * Get the next date - the provided date + period - * @param date - * @param expression - * @return the next date in the period - */ - public Date getNextDate(Date date, String expression); - - /** - * Is the expression required etc ... - * @return the multiplicity - */ - public ExpressionMutiplicity getExpressionMutiplicity(); - - /** - * Get the default expression - this could be null - * @return - the default expression. - */ - public String getDefaultExpression(); - - /** - * Return the Alfresco data type QName to which the string value of the expression will be converted. - * @return the alfresco data type or null if an expression is not allowed. - */ - public QName getExpressionDataType(); -} diff --git a/source/java/org/alfresco/service/cmr/repository/StoreExistsException.java b/source/java/org/alfresco/service/cmr/repository/StoreExistsException.java deleted file mode 100644 index df6b47779d..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/StoreExistsException.java +++ /dev/null @@ -1,36 +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.service.cmr.repository; - - -/** - * Thrown when an operation cannot be performed because the store reference - * no longer exists. - * - * @author Derek Hulley - */ -public class StoreExistsException extends AbstractStoreException -{ - private static final long serialVersionUID = 3906369320370975030L; - - public StoreExistsException(StoreRef storeRef, Throwable e) - { - super(storeRef, e); - } -} diff --git a/source/java/org/alfresco/service/cmr/repository/StoreRef.java b/source/java/org/alfresco/service/cmr/repository/StoreRef.java deleted file mode 100644 index 09a00517cc..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/StoreRef.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.service.cmr.repository; - -import java.io.Serializable; - -import org.alfresco.error.AlfrescoRuntimeException; - -/** - * Reference to a node store - * - * @author Derek Hulley - */ -public final class StoreRef implements EntityRef, Serializable -{ - private static final long serialVersionUID = 3905808565129394486L; - - public static final String PROTOCOL_WORKSPACE = "workspace"; - public static final String PROTOCOL_ARCHIVE = "archive"; - public static final String PROTOCOL_AVM = "avm"; - public static final String PROTOCOL_TEST = "test"; - - public static final StoreRef STORE_REF_WORKSPACE_SPACESSTORE = new StoreRef(PROTOCOL_WORKSPACE, "SpacesStore"); - public static final StoreRef STORE_REF_ARCHIVE_SPACESSTORE = new StoreRef(PROTOCOL_ARCHIVE, "SpacesStore"); - - public static final String URI_FILLER = "://"; - - private final String protocol; - private final String identifier; - - /** - * @param protocol - * well-known protocol for the store, e.g. workspace or - * versionstore - * @param identifier - * the identifier, which may be specific to the protocol - */ - public StoreRef(String protocol, String identifier) - { - if (protocol == null) - { - throw new IllegalArgumentException("Store protocol may not be null"); - } - if (identifier == null) - { - throw new IllegalArgumentException("Store identifier may not be null"); - } - - this.protocol = protocol; - this.identifier = identifier; - } - - public StoreRef(String string) - { - int dividerPatternPosition = string.indexOf(URI_FILLER); - if(dividerPatternPosition == -1) - { - throw new AlfrescoRuntimeException("Invalid store ref: Does not contain " + URI_FILLER + " " + string); - } - this.protocol = string.substring(0, dividerPatternPosition); - this.identifier = string.substring(dividerPatternPosition+3); - } - - public String toString() - { - return protocol + URI_FILLER + identifier; - } - - public boolean equals(Object obj) - { - if (this == obj) - { - return true; - } - if (obj instanceof StoreRef) - { - StoreRef that = (StoreRef) obj; - return (this.protocol.equals(that.protocol) - && this.identifier.equals(that.identifier)); - } else - { - return false; - } - } - - /** - * Creates a hashcode from both the {@link #getProtocol()} and {@link #getIdentifier()} - */ - public int hashCode() - { - return (protocol.hashCode() + identifier.hashCode()); - } - - public String getProtocol() - { - return protocol; - } - - public String getIdentifier() - { - return identifier; - } -} \ No newline at end of file diff --git a/source/java/org/alfresco/service/cmr/repository/XPathException.java b/source/java/org/alfresco/service/cmr/repository/XPathException.java deleted file mode 100644 index a27eb117fc..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/XPathException.java +++ /dev/null @@ -1,36 +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.service.cmr.repository; - -import org.alfresco.error.AlfrescoRuntimeException; - -public class XPathException extends AlfrescoRuntimeException -{ - private static final long serialVersionUID = 3544955454552815923L; - - public XPathException(String msg) - { - super(msg); - } - - public XPathException(String msg, Throwable cause) - { - super(msg, cause); - } -} diff --git a/source/java/org/alfresco/service/cmr/repository/datatype/DefaultTypeConverter.java b/source/java/org/alfresco/service/cmr/repository/datatype/DefaultTypeConverter.java deleted file mode 100644 index 0d67079366..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/datatype/DefaultTypeConverter.java +++ /dev/null @@ -1,892 +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.service.cmr.repository.datatype; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.sql.Timestamp; -import java.text.DecimalFormat; -import java.text.ParseException; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; - -import org.alfresco.service.cmr.repository.AssociationRef; -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.ContentData; -import org.alfresco.service.cmr.repository.ContentReader; -import org.alfresco.service.cmr.repository.ContentWriter; -import org.alfresco.service.cmr.repository.EntityRef; -import org.alfresco.service.cmr.repository.MLText; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.Path; -import org.alfresco.service.cmr.repository.Period; -import org.alfresco.service.cmr.repository.StoreRef; -import org.alfresco.service.namespace.QName; -import org.alfresco.util.VersionNumber; -import org.springframework.extensions.surf.exception.PlatformRuntimeException; -import org.springframework.extensions.surf.util.I18NUtil; -import org.springframework.extensions.surf.util.ISO8601DateFormat; - -/** - * Support for generic conversion between types. - * - * Additional conversions may be added. Basic inter-operability supported. - * - * Direct conversion and two stage conversions via Number are supported. We do - * not support conversion by any route at the moment - * - * TODO: Add support for Path - * - * TODO: Add support for lucene - * - * TODO: Add suport to check of a type is convertable - * - * TODO: Support for dynamically managing conversions - * - * @author andyh - * - */ -@SuppressWarnings("unchecked") -public class DefaultTypeConverter -{ - /** - * Default Type Converter - */ - public static TypeConverter INSTANCE = new TypeConverter(); - - /** - * Initialise default set of Converters - */ - static - { - - // - // From string - // - - INSTANCE.addConverter(String.class, Class.class, new TypeConverter.Converter() - { - public Class convert(String source) - { - try - { - return Class.forName(source); - } - catch (ClassNotFoundException e) - { - throw new TypeConversionException("Failed to convert string to class: " + source, e); - } - } - }); - - INSTANCE.addConverter(String.class, Boolean.class, new TypeConverter.Converter() - { - public Boolean convert(String source) - { - return Boolean.valueOf(source); - } - }); - - INSTANCE.addConverter(String.class, Character.class, new TypeConverter.Converter() - { - public Character convert(String source) - { - if ((source == null) || (source.length() == 0)) - { - return null; - } - return Character.valueOf(source.charAt(0)); - } - }); - - INSTANCE.addConverter(String.class, Number.class, new TypeConverter.Converter() - { - public Number convert(String source) - { - try - { - return DecimalFormat.getNumberInstance().parse(source); - } - catch (ParseException e) - { - throw new TypeConversionException("Failed to parse number " + source, e); - } - } - }); - - INSTANCE.addConverter(String.class, Byte.class, new TypeConverter.Converter() - { - public Byte convert(String source) - { - return Byte.valueOf(source); - } - }); - - INSTANCE.addConverter(String.class, Short.class, new TypeConverter.Converter() - { - public Short convert(String source) - { - return Short.valueOf(source); - } - }); - - INSTANCE.addConverter(String.class, Integer.class, new TypeConverter.Converter() - { - public Integer convert(String source) - { - return Integer.valueOf(source); - } - }); - - INSTANCE.addConverter(String.class, Long.class, new TypeConverter.Converter() - { - public Long convert(String source) - { - return Long.valueOf(source); - } - }); - - INSTANCE.addConverter(String.class, Float.class, new TypeConverter.Converter() - { - public Float convert(String source) - { - return Float.valueOf(source); - } - }); - - INSTANCE.addConverter(String.class, Double.class, new TypeConverter.Converter() - { - public Double convert(String source) - { - return Double.valueOf(source); - } - }); - - INSTANCE.addConverter(String.class, BigInteger.class, new TypeConverter.Converter() - { - public BigInteger convert(String source) - { - return new BigInteger(source); - } - }); - - INSTANCE.addConverter(String.class, BigDecimal.class, new TypeConverter.Converter() - { - public BigDecimal convert(String source) - { - return new BigDecimal(source); - } - }); - - INSTANCE.addConverter(String.class, Date.class, new TypeConverter.Converter() - { - public Date convert(String source) - { - try - { - Date date = ISO8601DateFormat.parse(source); - return date; - } - catch (PlatformRuntimeException e) - { - throw new TypeConversionException("Failed to convert date " + source + " to string", e); - } - } - }); - - INSTANCE.addConverter(String.class, Duration.class, new TypeConverter.Converter() - { - public Duration convert(String source) - { - return new Duration(source); - } - }); - - INSTANCE.addConverter(String.class, QName.class, new TypeConverter.Converter() - { - public QName convert(String source) - { - return QName.createQName(source); - } - }); - - INSTANCE.addConverter(String.class, ContentData.class, new TypeConverter.Converter() - { - public ContentData convert(String source) - { - return ContentData.createContentProperty(source); - } - - }); - - INSTANCE.addConverter(String.class, NodeRef.class, new TypeConverter.Converter() - { - public NodeRef convert(String source) - { - return new NodeRef(source); - } - - }); - - INSTANCE.addConverter(String.class, StoreRef.class, new TypeConverter.Converter() - { - public StoreRef convert(String source) - { - return new StoreRef(source); - } - - }); - - INSTANCE.addConverter(String.class, ChildAssociationRef.class, new TypeConverter.Converter() - { - public ChildAssociationRef convert(String source) - { - return new ChildAssociationRef(source); - } - - }); - - INSTANCE.addConverter(String.class, AssociationRef.class, new TypeConverter.Converter() - { - public AssociationRef convert(String source) - { - return new AssociationRef(source); - } - - }); - - INSTANCE.addConverter(String.class, InputStream.class, new TypeConverter.Converter() - { - public InputStream convert(String source) - { - try - { - return new ByteArrayInputStream(source.getBytes("UTF-8")); - } - catch (UnsupportedEncodingException e) - { - throw new TypeConversionException("Encoding not supported", e); - } - } - }); - - INSTANCE.addConverter(String.class, MLText.class, new TypeConverter.Converter() - { - public MLText convert(String source) - { - return new MLText(source); - } - }); - - INSTANCE.addConverter(String.class, Locale.class, new TypeConverter.Converter() - { - public Locale convert(String source) - { - return I18NUtil.parseLocale(source); - } - }); - - INSTANCE.addConverter(String.class, Period.class, new TypeConverter.Converter() - { - public Period convert(String source) - { - return new Period(source); - } - }); - - INSTANCE.addConverter(String.class, VersionNumber.class, new TypeConverter.Converter() - { - public VersionNumber convert(String source) - { - return new VersionNumber(source); - } - }); - - // - // From Locale - // - - INSTANCE.addConverter(Locale.class, String.class, new TypeConverter.Converter() - { - public String convert(Locale source) - { - String localeStr = source.toString(); - if (localeStr.length() < 6) - { - localeStr += "_"; - } - return localeStr; - } - }); - - - // - // From VersionNumber - // - - INSTANCE.addConverter(VersionNumber.class, String.class, new TypeConverter.Converter() - { - public String convert(VersionNumber source) - { - return source.toString(); - } - }); - - - // - // From MLText - // - - INSTANCE.addConverter(MLText.class, String.class, new TypeConverter.Converter() - { - public String convert(MLText source) - { - return source.getDefaultValue(); - } - }); - - // - // From enum - // - - INSTANCE.addConverter(Enum.class, String.class, new TypeConverter.Converter() - { - public String convert(Enum source) - { - return source.toString(); - } - }); - - // From Period - - INSTANCE.addConverter(Period.class, String.class, new TypeConverter.Converter() - { - public String convert(Period source) - { - return source.toString(); - } - }); - - // From Class - - INSTANCE.addConverter(Class.class, String.class, new TypeConverter.Converter() - { - public String convert(Class source) - { - return source.getName(); - } - }); - - // - // Number to Subtypes and Date - // - - INSTANCE.addConverter(Number.class, Boolean.class, new TypeConverter.Converter() - { - public Boolean convert(Number source) - { - return new Boolean(source.longValue() > 0); - } - }); - - INSTANCE.addConverter(Number.class, Byte.class, new TypeConverter.Converter() - { - public Byte convert(Number source) - { - return Byte.valueOf(source.byteValue()); - } - }); - - INSTANCE.addConverter(Number.class, Short.class, new TypeConverter.Converter() - { - public Short convert(Number source) - { - return Short.valueOf(source.shortValue()); - } - }); - - INSTANCE.addConverter(Number.class, Integer.class, new TypeConverter.Converter() - { - public Integer convert(Number source) - { - return Integer.valueOf(source.intValue()); - } - }); - - INSTANCE.addConverter(Number.class, Long.class, new TypeConverter.Converter() - { - public Long convert(Number source) - { - return Long.valueOf(source.longValue()); - } - }); - - INSTANCE.addConverter(Number.class, Float.class, new TypeConverter.Converter() - { - public Float convert(Number source) - { - return Float.valueOf(source.floatValue()); - } - }); - - INSTANCE.addConverter(Number.class, Double.class, new TypeConverter.Converter() - { - public Double convert(Number source) - { - return Double.valueOf(source.doubleValue()); - } - }); - - INSTANCE.addConverter(Number.class, Date.class, new TypeConverter.Converter() - { - public Date convert(Number source) - { - return new Date(source.longValue()); - } - }); - - INSTANCE.addConverter(Number.class, String.class, new TypeConverter.Converter() - { - public String convert(Number source) - { - return source.toString(); - } - }); - - INSTANCE.addConverter(Number.class, BigInteger.class, new TypeConverter.Converter() - { - public BigInteger convert(Number source) - { - if (source instanceof BigDecimal) - { - return ((BigDecimal) source).toBigInteger(); - } - else - { - return BigInteger.valueOf(source.longValue()); - } - } - }); - - INSTANCE.addConverter(Number.class, BigDecimal.class, new TypeConverter.Converter() - { - public BigDecimal convert(Number source) - { - if (source instanceof BigInteger) - { - return new BigDecimal((BigInteger) source); - } - else - { - return BigDecimal.valueOf(source.longValue()); - } - } - }); - - INSTANCE.addDynamicTwoStageConverter(Number.class, String.class, InputStream.class); - - // - // Date, Timestamp -> - // - - INSTANCE.addConverter(Timestamp.class, Date.class, new TypeConverter.Converter() - { - public Date convert(Timestamp source) - { - return new Date(source.getTime()); - } - }); - - INSTANCE.addConverter(Date.class, Number.class, new TypeConverter.Converter() - { - public Number convert(Date source) - { - return Long.valueOf(source.getTime()); - } - }); - - INSTANCE.addConverter(Date.class, String.class, new TypeConverter.Converter() - { - public String convert(Date source) - { - try - { - return ISO8601DateFormat.format(source); - } - catch (PlatformRuntimeException e) - { - throw new TypeConversionException("Failed to convert date " + source + " to string", e); - } - } - }); - - INSTANCE.addConverter(Date.class, Calendar.class, new TypeConverter.Converter() - { - public Calendar convert(Date source) - { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(source); - return calendar; - } - }); - - INSTANCE.addDynamicTwoStageConverter(Date.class, String.class, InputStream.class); - - // - // Boolean -> - // - - final Long LONG_FALSE = new Long(0L); - final Long LONG_TRUE = new Long(1L); - INSTANCE.addConverter(Boolean.class, Long.class, new TypeConverter.Converter() - { - public Long convert(Boolean source) - { - return source.booleanValue() ? LONG_TRUE : LONG_FALSE; - } - }); - - INSTANCE.addConverter(Boolean.class, String.class, new TypeConverter.Converter() - { - public String convert(Boolean source) - { - return source.toString(); - } - }); - - INSTANCE.addDynamicTwoStageConverter(Boolean.class, String.class, InputStream.class); - - // - // Character -> - // - - INSTANCE.addConverter(Character.class, String.class, new TypeConverter.Converter() - { - public String convert(Character source) - { - return source.toString(); - } - }); - - INSTANCE.addDynamicTwoStageConverter(Character.class, String.class, InputStream.class); - - // - // Duration -> - // - - INSTANCE.addConverter(Duration.class, String.class, new TypeConverter.Converter() - { - public String convert(Duration source) - { - return source.toString(); - } - - }); - - INSTANCE.addDynamicTwoStageConverter(Duration.class, String.class, InputStream.class); - - // - // Byte - // - - INSTANCE.addConverter(Byte.class, String.class, new TypeConverter.Converter() - { - public String convert(Byte source) - { - return source.toString(); - } - }); - - INSTANCE.addDynamicTwoStageConverter(Byte.class, String.class, InputStream.class); - - // - // Short - // - - INSTANCE.addConverter(Short.class, String.class, new TypeConverter.Converter() - { - public String convert(Short source) - { - return source.toString(); - } - }); - - INSTANCE.addDynamicTwoStageConverter(Short.class, String.class, InputStream.class); - - // - // Integer - // - - INSTANCE.addConverter(Integer.class, String.class, new TypeConverter.Converter() - { - public String convert(Integer source) - { - return source.toString(); - } - }); - - INSTANCE.addDynamicTwoStageConverter(Integer.class, String.class, InputStream.class); - - // - // Long - // - - INSTANCE.addConverter(Long.class, String.class, new TypeConverter.Converter() - { - public String convert(Long source) - { - return source.toString(); - } - }); - - INSTANCE.addDynamicTwoStageConverter(Long.class, String.class, InputStream.class); - - // - // Float - // - - INSTANCE.addConverter(Float.class, String.class, new TypeConverter.Converter() - { - public String convert(Float source) - { - return source.toString(); - } - }); - - INSTANCE.addDynamicTwoStageConverter(Float.class, String.class, InputStream.class); - - // - // Double - // - - INSTANCE.addConverter(Double.class, String.class, new TypeConverter.Converter() - { - public String convert(Double source) - { - return source.toString(); - } - }); - - INSTANCE.addDynamicTwoStageConverter(Double.class, String.class, InputStream.class); - - // - // BigInteger - // - - INSTANCE.addConverter(BigInteger.class, String.class, new TypeConverter.Converter() - { - public String convert(BigInteger source) - { - return source.toString(); - } - }); - - INSTANCE.addDynamicTwoStageConverter(BigInteger.class, String.class, InputStream.class); - - // - // Calendar - // - - INSTANCE.addConverter(Calendar.class, Date.class, new TypeConverter.Converter() - { - public Date convert(Calendar source) - { - return source.getTime(); - } - }); - - INSTANCE.addConverter(Calendar.class, String.class, new TypeConverter.Converter() - { - public String convert(Calendar source) - { - try - { - return ISO8601DateFormat.format(source.getTime()); - } - catch (PlatformRuntimeException e) - { - throw new TypeConversionException("Failed to convert date " + source + " to string", e); - } - } - }); - - // - // BigDecimal - // - - INSTANCE.addConverter(BigDecimal.class, String.class, new TypeConverter.Converter() - { - public String convert(BigDecimal source) - { - return source.toString(); - } - }); - - INSTANCE.addDynamicTwoStageConverter(BigDecimal.class, String.class, InputStream.class); - - // - // QName - // - - INSTANCE.addConverter(QName.class, String.class, new TypeConverter.Converter() - { - public String convert(QName source) - { - return source.toString(); - } - }); - - INSTANCE.addDynamicTwoStageConverter(QName.class, String.class, InputStream.class); - - // - // EntityRef (NodeRef, ChildAssociationRef, NodeAssociationRef) - // - - INSTANCE.addConverter(EntityRef.class, String.class, new TypeConverter.Converter() - { - public String convert(EntityRef source) - { - return source.toString(); - } - }); - - INSTANCE.addDynamicTwoStageConverter(EntityRef.class, String.class, InputStream.class); - - // - // ContentData - // - - INSTANCE.addConverter(ContentData.class, String.class, new TypeConverter.Converter() - { - public String convert(ContentData source) - { - return source.toString(); - } - }); - - INSTANCE.addDynamicTwoStageConverter(ContentData.class, String.class, InputStream.class); - - // - // Path - // - - INSTANCE.addConverter(Path.class, String.class, new TypeConverter.Converter() - { - public String convert(Path source) - { - return source.toString(); - } - }); - - INSTANCE.addDynamicTwoStageConverter(Path.class, String.class, InputStream.class); - - // - // Content Reader - // - - INSTANCE.addConverter(ContentReader.class, InputStream.class, new TypeConverter.Converter() - { - public InputStream convert(ContentReader source) - { - return source.getContentInputStream(); - } - }); - - INSTANCE.addConverter(ContentReader.class, String.class, new TypeConverter.Converter() - { - public String convert(ContentReader source) - { - // Getting the string from the ContentReader binary is meaningless - return source.toString(); - } - }); - - // - // Content Writer - // - - INSTANCE.addConverter(ContentWriter.class, String.class, new TypeConverter.Converter() - { - public String convert(ContentWriter source) - { - return source.toString(); - } - }); - - // - // Input Stream - // - - INSTANCE.addConverter(InputStream.class, String.class, new TypeConverter.Converter() - { - public String convert(InputStream source) - { - try - { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - byte[] buffer = new byte[8192]; - int read; - while ((read = source.read(buffer)) > 0) - { - out.write(buffer, 0, read); - } - byte[] data = out.toByteArray(); - return new String(data, "UTF-8"); - } - catch (UnsupportedEncodingException e) - { - throw new TypeConversionException("Cannot convert input stream to String.", e); - } - catch (IOException e) - { - throw new TypeConversionException("Conversion from stream to string failed", e); - } - finally - { - if (source != null) - { - try { source.close(); } catch(IOException e) {}; - } - } - } - }); - - INSTANCE.addDynamicTwoStageConverter(InputStream.class, String.class, Date.class); - - INSTANCE.addDynamicTwoStageConverter(InputStream.class, String.class, Double.class); - - INSTANCE.addDynamicTwoStageConverter(InputStream.class, String.class, Long.class); - - INSTANCE.addDynamicTwoStageConverter(InputStream.class, String.class, Boolean.class); - - INSTANCE.addDynamicTwoStageConverter(InputStream.class, String.class, QName.class); - - INSTANCE.addDynamicTwoStageConverter(InputStream.class, String.class, Path.class); - - INSTANCE.addDynamicTwoStageConverter(InputStream.class, String.class, NodeRef.class); - - } - -} diff --git a/source/java/org/alfresco/service/cmr/repository/datatype/DefaultTypeConverterTest.java b/source/java/org/alfresco/service/cmr/repository/datatype/DefaultTypeConverterTest.java deleted file mode 100644 index fa4bc496af..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/datatype/DefaultTypeConverterTest.java +++ /dev/null @@ -1,327 +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.service.cmr.repository.datatype; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.Locale; - -import junit.framework.TestCase; - -import org.alfresco.service.cmr.repository.MLText; -import org.alfresco.service.cmr.repository.Period; -import org.alfresco.util.VersionNumber; -import org.springframework.extensions.surf.util.ISO8601DateFormat; - -public class DefaultTypeConverterTest extends TestCase -{ - - public DefaultTypeConverterTest() - { - super(); - } - - public DefaultTypeConverterTest(String arg0) - { - super(arg0); - } - - public void testPrimitives() - { - assertEquals(Boolean.valueOf(false), DefaultTypeConverter.INSTANCE.convert(Boolean.class, false)); - assertEquals(Boolean.valueOf(true), DefaultTypeConverter.INSTANCE.convert(Boolean.class, true)); - assertEquals(Character.valueOf('a'), DefaultTypeConverter.INSTANCE.convert(Character.class, 'a')); - assertEquals(Byte.valueOf("3"), DefaultTypeConverter.INSTANCE.convert(Byte.class, (byte) 3)); - assertEquals(Short.valueOf("4"), DefaultTypeConverter.INSTANCE.convert(Short.class, (short) 4)); - assertEquals(Integer.valueOf("5"), DefaultTypeConverter.INSTANCE.convert(Integer.class, (int) 5)); - assertEquals(Long.valueOf("6"), DefaultTypeConverter.INSTANCE.convert(Long.class, (long) 6)); - assertEquals(Float.valueOf("7.1"), DefaultTypeConverter.INSTANCE.convert(Float.class, (float) 7.1)); - assertEquals(Double.valueOf("123.123"), DefaultTypeConverter.INSTANCE.convert(Double.class, (double) 123.123)); - } - - public void testNoConversion() - { - assertEquals(Boolean.valueOf(false), DefaultTypeConverter.INSTANCE.convert(Boolean.class, Boolean.valueOf(false))); - assertEquals(Boolean.valueOf(true), DefaultTypeConverter.INSTANCE.convert(Boolean.class, Boolean.valueOf(true))); - assertEquals(Character.valueOf('w'), DefaultTypeConverter.INSTANCE.convert(Character.class, Character.valueOf('w'))); - assertEquals(Byte.valueOf("3"), DefaultTypeConverter.INSTANCE.convert(Byte.class, Byte.valueOf("3"))); - assertEquals(Short.valueOf("4"), DefaultTypeConverter.INSTANCE.convert(Short.class, Short.valueOf("4"))); - assertEquals(Integer.valueOf("5"), DefaultTypeConverter.INSTANCE.convert(Integer.class, Integer.valueOf("5"))); - assertEquals(Long.valueOf("6"), DefaultTypeConverter.INSTANCE.convert(Long.class, Long.valueOf("6"))); - assertEquals(Float.valueOf("7.1"), DefaultTypeConverter.INSTANCE.convert(Float.class, Float.valueOf("7.1"))); - assertEquals(Double.valueOf("123.123"), DefaultTypeConverter.INSTANCE.convert(Double.class, Double.valueOf("123.123"))); - assertEquals(Double.valueOf("123.123"), DefaultTypeConverter.INSTANCE.convert(Double.class, Double.valueOf("123.123"))); - assertEquals(new BigInteger("1234567890123456789"), DefaultTypeConverter.INSTANCE.convert(BigInteger.class, new BigInteger("1234567890123456789"))); - assertEquals(new BigDecimal("12345678901234567890.12345678901234567890"), DefaultTypeConverter.INSTANCE.convert(BigDecimal.class, new BigDecimal("12345678901234567890.12345678901234567890"))); - Date date = new Date(); - assertEquals(date, DefaultTypeConverter.INSTANCE.convert(Date.class, date)); - assertEquals(new Duration("P25D"), DefaultTypeConverter.INSTANCE.convert(Duration.class, new Duration("P25D"))); - assertEquals("woof", DefaultTypeConverter.INSTANCE.convert(String.class, "woof")); - } - - public void testToString() - { - assertEquals("true", DefaultTypeConverter.INSTANCE.convert(String.class, new Boolean(true))); - assertEquals("false", DefaultTypeConverter.INSTANCE.convert(String.class, new Boolean(false))); - assertEquals("v", DefaultTypeConverter.INSTANCE.convert(String.class, Character.valueOf('v'))); - assertEquals("3", DefaultTypeConverter.INSTANCE.convert(String.class, Byte.valueOf("3"))); - assertEquals("4", DefaultTypeConverter.INSTANCE.convert(String.class, Short.valueOf("4"))); - assertEquals("5", DefaultTypeConverter.INSTANCE.convert(String.class, Integer.valueOf("5"))); - assertEquals("6", DefaultTypeConverter.INSTANCE.convert(String.class, Long.valueOf("6"))); - assertEquals("7.1", DefaultTypeConverter.INSTANCE.convert(String.class, Float.valueOf("7.1"))); - assertEquals("123.123", DefaultTypeConverter.INSTANCE.convert(String.class, Double.valueOf("123.123"))); - assertEquals("1234567890123456789", DefaultTypeConverter.INSTANCE.convert(String.class, new BigInteger("1234567890123456789"))); - assertEquals("12345678901234567890.12345678901234567890", DefaultTypeConverter.INSTANCE.convert(String.class, new BigDecimal("12345678901234567890.12345678901234567890"))); - Date date = new Date(); - assertEquals(ISO8601DateFormat.format(date), DefaultTypeConverter.INSTANCE.convert(String.class, date)); - assertEquals("P0Y25D", DefaultTypeConverter.INSTANCE.convert(String.class, new Duration("P0Y25D"))); - assertEquals("woof", DefaultTypeConverter.INSTANCE.convert(String.class, "woof")); - // MLText - MLText mlText = new MLText("woof"); - mlText.addValue(Locale.SIMPLIFIED_CHINESE, "缂"); - assertEquals("woof", DefaultTypeConverter.INSTANCE.convert(String.class, mlText)); - // Locale - assertEquals("fr_FR_", DefaultTypeConverter.INSTANCE.convert(String.class, Locale.FRANCE)); - // VersionNumber - assertEquals("1.2.3", DefaultTypeConverter.INSTANCE.convert(String.class, new VersionNumber("1.2.3"))); - // Period - assertEquals("period", DefaultTypeConverter.INSTANCE.convert(String.class, new Period("period"))); - assertEquals("period|12", DefaultTypeConverter.INSTANCE.convert(String.class, new Period("period|12"))); - // Java Class - assertEquals(this.getClass(), DefaultTypeConverter.INSTANCE.convert(Class.class, this.getClass().getName())); - } - - public void testFromString() - { - assertEquals(Boolean.valueOf(true), DefaultTypeConverter.INSTANCE.convert(Boolean.class, "True")); - assertEquals(Boolean.valueOf(false), DefaultTypeConverter.INSTANCE.convert(Boolean.class, "woof")); - assertEquals(Character.valueOf('w'), DefaultTypeConverter.INSTANCE.convert(Character.class, "w")); - assertEquals(Byte.valueOf("3"), DefaultTypeConverter.INSTANCE.convert(Byte.class, "3")); - assertEquals(Short.valueOf("4"), DefaultTypeConverter.INSTANCE.convert(Short.class, "4")); - assertEquals(Integer.valueOf("5"), DefaultTypeConverter.INSTANCE.convert(Integer.class, "5")); - assertEquals(Long.valueOf("6"), DefaultTypeConverter.INSTANCE.convert(Long.class, "6")); - assertEquals(Float.valueOf("7.1"), DefaultTypeConverter.INSTANCE.convert(Float.class, "7.1")); - assertEquals(Double.valueOf("123.123"), DefaultTypeConverter.INSTANCE.convert(Double.class, "123.123")); - assertEquals(new BigInteger("1234567890123456789"), DefaultTypeConverter.INSTANCE.convert(BigInteger.class, "1234567890123456789")); - assertEquals(new BigDecimal("12345678901234567890.12345678901234567890"), DefaultTypeConverter.INSTANCE.convert(BigDecimal.class, "12345678901234567890.12345678901234567890")); - GregorianCalendar cal = new GregorianCalendar(); - cal.set(Calendar.YEAR, 2004); - cal.set(Calendar.MONTH, 3); - cal.set(Calendar.DAY_OF_MONTH, 12); - cal.set(Calendar.HOUR, 0); - cal.set(Calendar.MINUTE, 0); - cal.set(Calendar.SECOND, 0); - cal.set(Calendar.MILLISECOND, 0); - String isoDate = ISO8601DateFormat.format(cal.getTime()); - assertEquals(isoDate, ISO8601DateFormat.format(DefaultTypeConverter.INSTANCE.convert(Date.class, isoDate))); - assertEquals(new Duration("P25D"), DefaultTypeConverter.INSTANCE.convert(Duration.class, "P25D")); - assertEquals("woof", DefaultTypeConverter.INSTANCE.convert(String.class, "woof")); - - MLText converted = DefaultTypeConverter.INSTANCE.convert(MLText.class, "woof"); - assertEquals("woof", converted.getValue(Locale.getDefault())); - - assertEquals(Locale.FRANCE, DefaultTypeConverter.INSTANCE.convert(Locale.class, "fr_FR")); - assertEquals(Locale.FRANCE, DefaultTypeConverter.INSTANCE.convert(Locale.class, "fr_FR_")); - - assertEquals(new VersionNumber("1.2.3"), DefaultTypeConverter.INSTANCE.convert(VersionNumber.class, "1.2.3")); - - assertEquals(new Period("period"), DefaultTypeConverter.INSTANCE.convert(Period.class, "period")); - assertEquals(new Period("period|12"), DefaultTypeConverter.INSTANCE.convert(Period.class, "period|12")); - // Java Class - assertEquals(this.getClass().getName(), DefaultTypeConverter.INSTANCE.convert(String.class, this.getClass())); - } - - public void testPrimativeAccessors() - { - assertEquals(false, DefaultTypeConverter.INSTANCE.convert(Boolean.class, false).booleanValue()); - assertEquals(true, DefaultTypeConverter.INSTANCE.convert(Boolean.class, true).booleanValue()); - assertEquals('a', DefaultTypeConverter.INSTANCE.convert(Character.class, 'a').charValue()); - assertEquals((byte) 3, DefaultTypeConverter.INSTANCE.convert(Byte.class, (byte) 3).byteValue()); - assertEquals((short) 4, DefaultTypeConverter.INSTANCE.convert(Short.class, (short) 4).shortValue()); - assertEquals((int) 5, DefaultTypeConverter.INSTANCE.convert(Integer.class, (int) 5).intValue()); - assertEquals((long) 6, DefaultTypeConverter.INSTANCE.convert(Long.class, (long) 6).longValue()); - assertEquals((float) 7.1, DefaultTypeConverter.INSTANCE.convert(Float.class, (float) 7.1).floatValue()); - assertEquals((double) 123.123, DefaultTypeConverter.INSTANCE.convert(Double.class, (double) 123.123).doubleValue()); - } - - public void testInterConversions() - { - assertEquals(Byte.valueOf("1"), DefaultTypeConverter.INSTANCE.convert(Byte.class, Byte.valueOf("1"))); - assertEquals(Short.valueOf("2"), DefaultTypeConverter.INSTANCE.convert(Short.class, Byte.valueOf("2"))); - assertEquals(Integer.valueOf("3"), DefaultTypeConverter.INSTANCE.convert(Integer.class, Byte.valueOf("3"))); - assertEquals(Long.valueOf("4"), DefaultTypeConverter.INSTANCE.convert(Long.class, Byte.valueOf("4"))); - assertEquals(Float.valueOf("5"), DefaultTypeConverter.INSTANCE.convert(Float.class, Byte.valueOf("5"))); - assertEquals(Double.valueOf("6"), DefaultTypeConverter.INSTANCE.convert(Double.class, Byte.valueOf("6"))); - assertEquals(new BigInteger("7"), DefaultTypeConverter.INSTANCE.convert(BigInteger.class, Byte.valueOf("7"))); - assertEquals(new BigDecimal("8"), DefaultTypeConverter.INSTANCE.convert(BigDecimal.class, Byte.valueOf("8"))); - - assertEquals(Byte.valueOf("1"), DefaultTypeConverter.INSTANCE.convert(Byte.class, Short.valueOf("1"))); - assertEquals(Short.valueOf("2"), DefaultTypeConverter.INSTANCE.convert(Short.class, Short.valueOf("2"))); - assertEquals(Integer.valueOf("3"), DefaultTypeConverter.INSTANCE.convert(Integer.class, Short.valueOf("3"))); - assertEquals(Long.valueOf("4"), DefaultTypeConverter.INSTANCE.convert(Long.class, Short.valueOf("4"))); - assertEquals(Float.valueOf("5"), DefaultTypeConverter.INSTANCE.convert(Float.class, Short.valueOf("5"))); - assertEquals(Double.valueOf("6"), DefaultTypeConverter.INSTANCE.convert(Double.class, Short.valueOf("6"))); - assertEquals(new BigInteger("7"), DefaultTypeConverter.INSTANCE.convert(BigInteger.class, Short.valueOf("7"))); - assertEquals(new BigDecimal("8"), DefaultTypeConverter.INSTANCE.convert(BigDecimal.class, Short.valueOf("8"))); - - assertEquals(Byte.valueOf("1"), DefaultTypeConverter.INSTANCE.convert(Byte.class, Integer.valueOf("1"))); - assertEquals(Short.valueOf("2"), DefaultTypeConverter.INSTANCE.convert(Short.class, Integer.valueOf("2"))); - assertEquals(Integer.valueOf("3"), DefaultTypeConverter.INSTANCE.convert(Integer.class, Integer.valueOf("3"))); - assertEquals(Long.valueOf("4"), DefaultTypeConverter.INSTANCE.convert(Long.class, Integer.valueOf("4"))); - assertEquals(Float.valueOf("5"), DefaultTypeConverter.INSTANCE.convert(Float.class, Integer.valueOf("5"))); - assertEquals(Double.valueOf("6"), DefaultTypeConverter.INSTANCE.convert(Double.class, Integer.valueOf("6"))); - assertEquals(new BigInteger("7"), DefaultTypeConverter.INSTANCE.convert(BigInteger.class, Integer.valueOf("7"))); - assertEquals(new BigDecimal("8"), DefaultTypeConverter.INSTANCE.convert(BigDecimal.class, Integer.valueOf("8"))); - - assertEquals(Boolean.TRUE, DefaultTypeConverter.INSTANCE.convert(Boolean.class, Long.valueOf("1"))); - assertEquals(Boolean.FALSE, DefaultTypeConverter.INSTANCE.convert(Boolean.class, Long.valueOf("0"))); - assertEquals(Byte.valueOf("1"), DefaultTypeConverter.INSTANCE.convert(Byte.class, Long.valueOf("1"))); - assertEquals(Short.valueOf("2"), DefaultTypeConverter.INSTANCE.convert(Short.class, Long.valueOf("2"))); - assertEquals(Integer.valueOf("3"), DefaultTypeConverter.INSTANCE.convert(Integer.class, Long.valueOf("3"))); - assertEquals(Long.valueOf("4"), DefaultTypeConverter.INSTANCE.convert(Long.class, Long.valueOf("4"))); - assertEquals(Float.valueOf("5"), DefaultTypeConverter.INSTANCE.convert(Float.class, Long.valueOf("5"))); - assertEquals(Double.valueOf("6"), DefaultTypeConverter.INSTANCE.convert(Double.class, Long.valueOf("6"))); - assertEquals(new BigInteger("7"), DefaultTypeConverter.INSTANCE.convert(BigInteger.class, Long.valueOf("7"))); - assertEquals(new BigDecimal("8"), DefaultTypeConverter.INSTANCE.convert(BigDecimal.class, Long.valueOf("8"))); - - assertEquals(Byte.valueOf("1"), DefaultTypeConverter.INSTANCE.convert(Byte.class, Float.valueOf("1"))); - assertEquals(Short.valueOf("2"), DefaultTypeConverter.INSTANCE.convert(Short.class, Float.valueOf("2"))); - assertEquals(Integer.valueOf("3"), DefaultTypeConverter.INSTANCE.convert(Integer.class, Float.valueOf("3"))); - assertEquals(Long.valueOf("4"), DefaultTypeConverter.INSTANCE.convert(Long.class, Float.valueOf("4"))); - assertEquals(Float.valueOf("5"), DefaultTypeConverter.INSTANCE.convert(Float.class, Float.valueOf("5"))); - assertEquals(Double.valueOf("6"), DefaultTypeConverter.INSTANCE.convert(Double.class, Float.valueOf("6"))); - assertEquals(new BigInteger("7"), DefaultTypeConverter.INSTANCE.convert(BigInteger.class, Float.valueOf("7"))); - assertEquals(new BigDecimal("8"), DefaultTypeConverter.INSTANCE.convert(BigDecimal.class, Float.valueOf("8"))); - - assertEquals(Byte.valueOf("1"), DefaultTypeConverter.INSTANCE.convert(Byte.class, Double.valueOf("1"))); - assertEquals(Short.valueOf("2"), DefaultTypeConverter.INSTANCE.convert(Short.class, Double.valueOf("2"))); - assertEquals(Integer.valueOf("3"), DefaultTypeConverter.INSTANCE.convert(Integer.class, Double.valueOf("3"))); - assertEquals(Long.valueOf("4"), DefaultTypeConverter.INSTANCE.convert(Long.class, Double.valueOf("4"))); - assertEquals(Float.valueOf("5"), DefaultTypeConverter.INSTANCE.convert(Float.class, Double.valueOf("5"))); - assertEquals(Double.valueOf("6"), DefaultTypeConverter.INSTANCE.convert(Double.class, Double.valueOf("6"))); - assertEquals(new BigInteger("7"), DefaultTypeConverter.INSTANCE.convert(BigInteger.class, Double.valueOf("7"))); - assertEquals(new BigDecimal("8"), DefaultTypeConverter.INSTANCE.convert(BigDecimal.class, Double.valueOf("8"))); - - assertEquals(Byte.valueOf("1"), DefaultTypeConverter.INSTANCE.convert(Byte.class, new BigInteger("1"))); - assertEquals(Short.valueOf("2"), DefaultTypeConverter.INSTANCE.convert(Short.class, new BigInteger("2"))); - assertEquals(Integer.valueOf("3"), DefaultTypeConverter.INSTANCE.convert(Integer.class, new BigInteger("3"))); - assertEquals(Long.valueOf("4"), DefaultTypeConverter.INSTANCE.convert(Long.class, new BigInteger("4"))); - assertEquals(Float.valueOf("5"), DefaultTypeConverter.INSTANCE.convert(Float.class, new BigInteger("5"))); - assertEquals(Double.valueOf("6"), DefaultTypeConverter.INSTANCE.convert(Double.class, new BigInteger("6"))); - assertEquals(new BigInteger("7"), DefaultTypeConverter.INSTANCE.convert(BigInteger.class, new BigInteger("7"))); - assertEquals(new BigDecimal("8"), DefaultTypeConverter.INSTANCE.convert(BigDecimal.class, new BigInteger("8"))); - - assertEquals(Byte.valueOf("1"), DefaultTypeConverter.INSTANCE.convert(Byte.class, new BigDecimal("1"))); - assertEquals(Short.valueOf("2"), DefaultTypeConverter.INSTANCE.convert(Short.class, new BigDecimal("2"))); - assertEquals(Integer.valueOf("3"), DefaultTypeConverter.INSTANCE.convert(Integer.class, new BigDecimal("3"))); - assertEquals(Long.valueOf("4"), DefaultTypeConverter.INSTANCE.convert(Long.class, new BigDecimal("4"))); - assertEquals(Float.valueOf("5"), DefaultTypeConverter.INSTANCE.convert(Float.class, new BigDecimal("5"))); - assertEquals(Double.valueOf("6"), DefaultTypeConverter.INSTANCE.convert(Double.class, new BigDecimal("6"))); - assertEquals(new BigInteger("7"), DefaultTypeConverter.INSTANCE.convert(BigInteger.class, new BigDecimal("7"))); - assertEquals(new BigDecimal("8"), DefaultTypeConverter.INSTANCE.convert(BigDecimal.class, new BigDecimal("8"))); - } - - public void testDate() - { - Date date = new Date(101); - - assertEquals(Byte.valueOf("101"), DefaultTypeConverter.INSTANCE.convert(Byte.class, date)); - assertEquals(Short.valueOf("101"), DefaultTypeConverter.INSTANCE.convert(Short.class, date)); - assertEquals(Integer.valueOf("101"), DefaultTypeConverter.INSTANCE.convert(Integer.class, date)); - assertEquals(Long.valueOf("101"), DefaultTypeConverter.INSTANCE.convert(Long.class, date)); - assertEquals(Float.valueOf("101"), DefaultTypeConverter.INSTANCE.convert(Float.class, date)); - assertEquals(Double.valueOf("101"), DefaultTypeConverter.INSTANCE.convert(Double.class, date)); - assertEquals(new BigInteger("101"), DefaultTypeConverter.INSTANCE.convert(BigInteger.class, date)); - assertEquals(new BigDecimal("101"), DefaultTypeConverter.INSTANCE.convert(BigDecimal.class, date)); - - assertEquals(date, DefaultTypeConverter.INSTANCE.convert(Date.class, (byte)101)); - assertEquals(date, DefaultTypeConverter.INSTANCE.convert(Date.class, (short)101)); - assertEquals(date, DefaultTypeConverter.INSTANCE.convert(Date.class, (int)101)); - assertEquals(date, DefaultTypeConverter.INSTANCE.convert(Date.class, (long)101)); - assertEquals(date, DefaultTypeConverter.INSTANCE.convert(Date.class, (float)101)); - assertEquals(date, DefaultTypeConverter.INSTANCE.convert(Date.class, (double)101)); - - assertEquals(date, DefaultTypeConverter.INSTANCE.convert(Date.class, new BigInteger("101"))); - assertEquals(date, DefaultTypeConverter.INSTANCE.convert(Date.class, (Object)(new BigDecimal("101")))); - - assertEquals(101, DefaultTypeConverter.INSTANCE.intValue(date)); - } - - public void testMultiValue() - { - ArrayList list = makeList(); - - assertEquals(true, DefaultTypeConverter.INSTANCE.isMultiValued(list)); - assertEquals(14, DefaultTypeConverter.INSTANCE.size(list)); - - for(String stringValue: DefaultTypeConverter.INSTANCE.getCollection(String.class, list)) - { - System.out.println("Value is "+stringValue); - } - - } - - private ArrayList makeList() - { - ArrayList list = new ArrayList(); - list.add(Boolean.valueOf(true)); - list.add(Boolean.valueOf(false)); - list.add(Character.valueOf('q')); - list.add(Byte.valueOf("1")); - list.add(Short.valueOf("2")); - list.add(Integer.valueOf("3")); - list.add(Long.valueOf("4")); - list.add(Float.valueOf("5")); - list.add(Double.valueOf("6")); - list.add(new BigInteger("7")); - list.add(new BigDecimal("8")); - list.add(new Date()); - list.add(new Duration("P5Y0M")); - list.add("Hello mum"); - return list; - } - - public void testSingleValuseAsMultiValue() - { - Integer integer = Integer.valueOf(43); - - assertEquals(false, DefaultTypeConverter.INSTANCE.isMultiValued(integer)); - assertEquals(1, DefaultTypeConverter.INSTANCE.size(integer)); - - for(String stringValue: DefaultTypeConverter.INSTANCE.getCollection(String.class, integer)) - { - System.out.println("Value is "+stringValue); - } - - } - - public void testNullAndEmpty() - { - assertNull(DefaultTypeConverter.INSTANCE.convert(Boolean.class, null)); - ArrayList list = new ArrayList(); - assertNotNull(DefaultTypeConverter.INSTANCE.convert(Boolean.class, list)); - list.add(null); - assertNotNull(DefaultTypeConverter.INSTANCE.convert(Boolean.class, list)); - - } -} diff --git a/source/java/org/alfresco/service/cmr/repository/datatype/Duration.java b/source/java/org/alfresco/service/cmr/repository/datatype/Duration.java deleted file mode 100644 index 3ab367d4b6..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/datatype/Duration.java +++ /dev/null @@ -1,1016 +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.service.cmr.repository.datatype; - -import java.io.IOException; -import java.io.Serializable; -import java.io.StreamTokenizer; -import java.io.StringReader; -import java.math.BigDecimal; -import java.text.DateFormat; -import java.text.NumberFormat; -import java.text.ParsePosition; -import java.util.Calendar; -import java.util.Date; - -import org.alfresco.util.CachingDateFormat; - -/** - * This data type represents duration/interval/period as defined by the XMLSchema type - * duration. - * - * The lexical representation of duration is - * PnYnMnDTnHnMnS. - * - * P is a literal value that starts the expression - * nY is an integer number of years followed by the literal Y - * nM is an integer number of months followed by the literal M - * nD is an integer number of days followed by the literal D - * T is the literal that separates the date and time - * nH is an integer number of hours followed by a literal H - * nM is an integer number of minutes followed by a literal M - * nS is a decimal number of seconds followed by a literal S - * - * Any numbers and designator may be absent if the value is zero. - * A minus sign may appear before the literal P to indicate a negative duration. - * If no time items are present the literal T must not appear. - * - * - * This implementation is immutable and thread safe. - * - * There are two forms of duration common on database types. - * The code contains warnings wheer these are relevant. - * - * @author andyh - */ -public class Duration implements Comparable, Serializable -{ - - static final long serialVersionUID = 3274526442325176068L; - - public static final String XML_DAY = "P1D"; - public static final String XML_WEEK = "P7D"; - public static final String XML_TWO_WEEKS = "P14D"; - public static final String XML_MONTH = "P1M"; - public static final String XML_QUARTER = "P3M"; - public static final String XML_SIX_MONTHS = "P6M"; - public static final String XML_YEAR = "P1Y"; - - public static final Duration DAY = new Duration(XML_DAY); - public static final Duration WEEK = new Duration(XML_WEEK); - public static final Duration TWO_WEEKS = new Duration(XML_TWO_WEEKS); - public static final Duration MONTH = new Duration(XML_MONTH); - public static final Duration QUARTER = new Duration(XML_QUARTER); - public static final Duration SIX_MONTHS = new Duration(XML_SIX_MONTHS); - public static final Duration YEAR = new Duration(XML_YEAR); - - private static final String s_parse = "-PYMDTHmS"; - - private boolean m_positive = true; - private int m_years = 0; - private int m_months = 0; - private int m_days = 0; - private int m_hours = 0; - private int m_mins = 0; - private int m_seconds = 0; - private int m_nanos = 0; - - // Date duration arithmetic - - /** - * Add a duration to a date and return the date plus the specified increment. - * - * @param date - the initial date - * @param duration - the duration to add on to the date (the duration may be negative) - * @return the adjusted date. - */ - public static Date add(Date date, Duration duration) - { - Calendar c = Calendar.getInstance(); - c.setTime(date); - c.add(Calendar.YEAR, (duration.m_positive ? 1 : -1) * duration.m_years); - c.add(Calendar.MONTH, (duration.m_positive ? 1 : -1) * duration.m_months); - c.add(Calendar.DATE, (duration.m_positive ? 1 : -1) * duration.m_days); - c.add(Calendar.HOUR_OF_DAY, (duration.m_positive ? 1 : -1) * duration.m_hours); - c.add(Calendar.MINUTE, (duration.m_positive ? 1 : -1) * duration.m_mins); - c.add(Calendar.SECOND, (duration.m_positive ? 1 : -1) * duration.m_seconds); - c.add(Calendar.MILLISECOND, (duration.m_positive ? 1 : -1) * duration.m_nanos / 1000000); - return c.getTime(); - } - - /** - * Subtract a period for a given date - * - * @param date - the intial date - * @param duration - the diration to subtract - * @return the adjusted date. - */ - - public static Date subtract(Date date, Duration duration) - { - return add(date, duration.unaryMinus()); - } - - - - /** - * Constructor for Duration - a zero value duration - */ - - public Duration() - { - super(); - } - - /** - * Construct a Duration from the XMLSchema definition - */ - - public Duration(String duration) - { - - if (duration.equals("P")) - { - throw new RuntimeException("Invalid period: P"); - } - - if (!duration.startsWith("P") && !duration.startsWith("-P")) - { - throw new RuntimeException("Invalid period: must start with P or -P"); - } - else - { - boolean dateMode = true; - int last = -1; - Double nval = null; - StringReader reader = new StringReader(duration); - StreamTokenizer tok = new StreamTokenizer(reader); - tok.resetSyntax(); - tok.eolIsSignificant(true); - tok.parseNumbers(); - tok.ordinaryChars('-', '-'); - tok.ordinaryChars('P', 'P'); - tok.ordinaryChars('Y', 'Y'); - tok.ordinaryChars('M', 'M'); - tok.ordinaryChars('D', 'D'); - tok.ordinaryChars('T', 'T'); - tok.ordinaryChars('H', 'H'); - tok.ordinaryChars('m', 'm'); - tok.ordinaryChars('S', 'S'); - - int token; - try - { - while ((token = tok.nextToken()) != StreamTokenizer.TT_EOF) - { - if (token == StreamTokenizer.TT_NUMBER) - { - nval = new Double(tok.nval); - } - else if (token == StreamTokenizer.TT_EOF) - { - throw new RuntimeException("Invalid EOF in Duration"); - } - else if (token == StreamTokenizer.TT_EOL) - { - throw new RuntimeException("Invalid EOL in Duration"); - } - else if (token == StreamTokenizer.TT_WORD) - { - throw new RuntimeException("Invalid text in Duration: " + tok.sval); - } - else - { - if (tok.ttype == '-') - { - last = checkIndex(last, "-"); - m_positive = false; - } - else if (tok.ttype == 'P') - { - last = checkIndex(last, "P"); - // nothing - } - else if (tok.ttype == 'Y') - { - last = checkIndex(last, "Y"); - if (nval != null) - { - m_years = nval.intValue(); - } - else - { - throw new RuntimeException("IO Error parsing Duration: " + duration); - } - nval = null; - } - else if (tok.ttype == 'M') - { - if (dateMode) - { - last = checkIndex(last, "M"); - if (nval != null) - { - m_months = nval.intValue(); - } - else - { - throw new RuntimeException("IO Error parsing Duration: " + duration); - } - nval = null; - } - else - { - last = checkIndex(last, "m"); - if (nval != null) - { - m_mins = nval.intValue(); - } - else - { - throw new RuntimeException("IO Error parsing Duration: " + duration); - } - nval = null; - } - } - else if (tok.ttype == 'D') - { - last = checkIndex(last, "D"); - if (nval != null) - { - m_days = nval.intValue(); - } - else - { - throw new RuntimeException("IO Error parsing Duration: " + duration); - } - nval = null; - } - else if (tok.ttype == 'T') - { - last = checkIndex(last, "T"); - dateMode = false; - nval = null; - } - else if (tok.ttype == 'H') - { - last = checkIndex(last, "H"); - if (nval != null) - { - m_hours = nval.intValue(); - } - else - { - throw new RuntimeException("IO Error parsing Duration: " + duration); - } - nval = null; - } - else if (tok.ttype == 'S') - { - last = checkIndex(last, "S"); - if (nval != null) - { - m_seconds = nval.intValue(); - m_nanos = (int) ((long) (nval.doubleValue() * 1000000000) % 1000000000); - } - else - { - throw new RuntimeException("IO Error parsing Duration: " + duration); - } - nval = null; - } - else - { - throw new RuntimeException("IO Error parsing Duration: " + duration); - } - } - } - } - catch (IOException e) - { - throw new RuntimeException("IO Error parsing Duration: " + duration); - } - catch (RuntimeException e) - { - throw new RuntimeException("IO Error parsing Duration: " + duration, e); - } - } - } - - /** - * Simple index to check identifiers appear in order - */ - - private int checkIndex(int last, String search) - { - if ((search == null) || (search.length() == 0)) - { - throw new RuntimeException("Null or zero length serach"); - } - int index = s_parse.indexOf(search); - if (index > last) - { - return index; - } - else - { - throw new RuntimeException("Illegal position for identifier " + search); - } - } - - /** - * Create a duration given a date. The duration is between the two dates provided. - * - * Sadly, it works out the duration by incrementing the lower calendar until it matches - * the higher. - */ - - public Duration(Date date) - { - this(date, new Date()); - } - - /** - * Create a duration betweeen two dates expressed as strings. - * Uses the standard XML date form. - * - * @param start - the date at the start of the period - * @param end - the date at the end of the period - */ - - public Duration(String start, String end) - { - this(parseDate(start), parseDate(end)); - } - - - /** - * Helper method to parse eaets from strings - * @param stringDate - * @return - */ - private static Date parseDate(String stringDate) - { - DateFormat df = CachingDateFormat.getDateFormat(); - df.setLenient(true); - Date date; - - ParsePosition pp = new ParsePosition(0); - date = df.parse(stringDate, pp); - if ((pp.getIndex() < stringDate.length()) || (date == null)) - { - date = new Date(); - } - return date; - - } - - /** - * Construct a preiod between the two given dates - * - * @param start_in - * @param end_in - */ - public Duration(Date start_in, Date end_in) - { - boolean positive = true; - Date start; - Date end; - if (start_in.before(end_in)) - { - start = start_in; - end = end_in; - positive = true; - } - else - { - start = end_in; - end = start_in; - positive = false; - } - Calendar cstart = Calendar.getInstance(); - cstart.setTime(start); - Calendar cend = Calendar.getInstance(); - cend.setTime(end); - - int millis = cend.get(Calendar.MILLISECOND) - cstart.get(Calendar.MILLISECOND); - if (millis < 0) - { - millis += cstart.getActualMaximum(Calendar.MILLISECOND)+1; - } - cstart.add(Calendar.MILLISECOND, millis); - - int seconds = cend.get(Calendar.SECOND) - cstart.get(Calendar.SECOND); - if (seconds < 0) - { - seconds += cstart.getActualMaximum(Calendar.SECOND)+1; - } - cstart.add(Calendar.SECOND, seconds); - - int minutes = cend.get(Calendar.MINUTE) - cstart.get(Calendar.MINUTE); - if (minutes < 0) - { - minutes += cstart.getActualMaximum(Calendar.MINUTE)+1; - } - cstart.add(Calendar.MINUTE, minutes); - - int hours = cend.get(Calendar.HOUR_OF_DAY) - cstart.get(Calendar.HOUR_OF_DAY); - if (hours < 0) - { - hours += cstart.getActualMaximum(Calendar.HOUR_OF_DAY)+1; - } - cstart.add(Calendar.HOUR_OF_DAY, hours); - - int days = cend.get(Calendar.DAY_OF_MONTH) - cstart.get(Calendar.DAY_OF_MONTH); - if (days < 0) - { - days += cstart.getActualMaximum(Calendar.DAY_OF_MONTH)+1; - } - cstart.add(Calendar.DAY_OF_MONTH, days); - - int months = cend.get(Calendar.MONTH) - cstart.get(Calendar.MONTH); - if (months < 0) - { - months += cstart.getActualMaximum(Calendar.MONTH)+1; - } - cstart.add(Calendar.MONTH, months); - - int years = cend.get(Calendar.YEAR) - cstart.get(Calendar.YEAR); - //cstart.add(Calendar.YEAR, years); - - m_positive = positive; - m_years = years; - m_months = months; - m_days = days; - m_hours = hours; - m_mins = minutes; - m_seconds = seconds; - m_nanos = millis * 1000000; - - } - - /** - * Construct a duration from months seconds and nanos - * Checks sign and fixes up seconds and nano. - * Treats year-month abd day-sec as separate chunks - */ - - public Duration(boolean positive_in, long months_in, long seconds_in, long nanos_in) - { - - boolean positive = positive_in; - long months = months_in; - long seconds = seconds_in + nanos_in / 1000000000; - long nanos = nanos_in % 1000000000; - - // Fix up seconds and nanos to be of the same sign - - if ((seconds > 0) && (nanos < 0)) - { - seconds -= 1; - nanos += 1000000000; - } - else if ((seconds < 0) && (nanos > 0)) - { - seconds += 1; - nanos -= 1000000000; - } - - // seconds and nanos now the same sign - sum to test overall sign - - if ((months < 0) && (seconds + nanos < 0)) - { - // switch sign - positive = !positive; - months = -months; - seconds = -seconds; - nanos = -nanos; - } - else if ((months == 0) && (seconds + nanos < 0)) - { - // switch sign - positive = !positive; - months = -months; - seconds = -seconds; - nanos = -nanos; - } - else if ((months > 0) && (seconds + nanos < 0)) - { - throw new RuntimeException("Can not convert to period - incompatible signs for year_to_momth and day_to_second elements"); - } - else if ((months < 0) && (seconds + nanos > 0)) - { - throw new RuntimeException("Can not convert to period - incompatible signs for year_to_momth and day_to_second elements"); - } - else - { - // All +ve - } - - m_positive = positive; - m_years = (int) (months / 12); - m_months = (int) (months % 12); - - m_days = (int) (seconds / (3600 * 24)); - seconds -= m_days * 3600 * 24; - m_hours = (int) (seconds / 3600); - seconds -= m_hours * 3600; - m_mins = (int) (seconds / 60); - seconds -= m_mins * 60; - m_seconds = (int) seconds; - m_nanos = (int) nanos; - - } - - - // Duration arithmetic - - /** - * Add two durations together - */ - - public Duration add(Duration add) - { - - long months = (this.m_positive ? 1 : -1) * this.getTotalMonths() + (add.m_positive ? 1 : -1) * add.getTotalMonths(); - long seconds = (this.m_positive ? 1 : -1) * this.getTotalSeconds() + (add.m_positive ? 1 : -1) * add.getTotalSeconds(); - long nanos = (this.m_positive ? 1 : -1) * this.getTotalNanos() + (add.m_positive ? 1 : -1) * add.getTotalNanos(); - - Duration result = new Duration(true, months, seconds, nanos); - return result; - } - - /** - * Subtract one duration from another - */ - - public Duration subtract(Duration sub) - { - long months = (this.m_positive ? 1 : -1) * this.getTotalMonths() - (sub.m_positive ? 1 : -1) * sub.getTotalMonths(); - long seconds = (this.m_positive ? 1 : -1) * this.getTotalSeconds() - (sub.m_positive ? 1 : -1) * sub.getTotalSeconds(); - long nanos = (this.m_positive ? 1 : -1) * this.getTotalNanos() - (sub.m_positive ? 1 : -1) * sub.getTotalNanos(); - Duration result = new Duration(true, months, seconds, nanos); - return result; - } - - /** - * Negate the duration - */ - - public Duration unaryMinus() - { - Duration result = new Duration(!this.m_positive, this.getTotalMonths(), this.getTotalSeconds(), this.getTotalNanos()); - return result; - } - - /** - * Divide the duration - if year-month drops the day-second part of the duration - */ - - public Duration divide(int d) - { - if (isYearToMonth()) - { - long months = getTotalMonths(); - months /= d; - Duration result = new Duration(m_positive, months, 0, 0); - return result; - } - else - { - long seconds = getTotalSeconds(); - long nanos = (seconds * (1000000000 / d)) % 1000000000; - nanos += getTotalNanos() / d; - seconds /= d; - Duration result = new Duration(m_positive, 0, seconds, nanos); - return result; - } - } - - /** - * Helper method to get the total number of months - year-month - */ - - private long getTotalMonths() - { - return m_years * 12 + m_months; - } - - /** - * Helper method to get the total number of seconds - */ - - private long getTotalSeconds() - { - return m_seconds + m_mins * 60 + m_hours * 3600 + m_days * 3600 * 24; - } - - /** - * Helper method to get the total number of nanos (does not include seconds_ - */ - - private long getTotalNanos() - { - return m_nanos; - } - - /** - * Check if is year-month - */ - - public boolean isYearToMonth() - { - return (m_years != 0) || (m_months != 0); - } - - /** - * Check if is day-sec - */ - - public boolean isDayToSec() - { - return ((m_years == 0) && (m_months == 0)); - } - - /** - * Check if it includes time - */ - - public boolean hasTime() - { - return (m_hours != 0) || (m_mins != 0) || (m_seconds != 0) || (m_nanos != 0); - } - - /** - * Extract the year to month part - */ - - public Duration getYearToMonth() - { - Duration result = new Duration(m_positive, getTotalMonths(), 0, 0); - return result; - } - - /** - * Extract the day to sec part. - */ - - public Duration getDayToYear() - { - Duration result = new Duration(m_positive, 0, getTotalSeconds(), getTotalNanos()); - return result; - } - - /** - * Compare two durations - */ - - public int compareTo(Object o) - { - if (!(o instanceof Duration)) - { - throw new RuntimeException("Can not compare Duration and " + o.getClass().getName()); - } - - Duration d = (Duration) o; - if (this.m_positive != d.m_positive) - { - return (m_positive ? 1 : -1); - } - - if (this.getTotalMonths() != d.getTotalMonths()) - { - return (m_positive ? 1 : -1) * ((int) (this.getTotalMonths() - d.getTotalMonths())); - } - else if (this.getTotalSeconds() != d.getTotalSeconds()) - { - return (m_positive ? 1 : -1) * ((int) (this.getTotalSeconds() - d.getTotalSeconds())); - } - else if (this.getTotalNanos() != d.getTotalNanos()) - { - return (m_positive ? 1 : -1) * ((int) (this.getTotalNanos() - d.getTotalNanos())); - } - else - { - return 0; - } - } - - /** - * @see java.lang.Object#equals(Object) - */ - - public boolean equals(Object o) - { - if (this == o) - return true; - if (!(o instanceof Duration)) - return false; - Duration d = (Duration) o; - return (this.m_positive == d.m_positive) && (this.getTotalMonths() == d.getTotalMonths()) && (this.getTotalSeconds() == d.getTotalSeconds()) && (this.getTotalNanos() == d.getTotalNanos()); - - } - - /** - * @see java.lang.Object#hashCode() - */ - - public int hashCode() - { - int hash = 17; - hash = 37 * hash + (m_positive ? 1 : -1); - hash = 37 * hash + (int) getTotalMonths(); - hash = 37 * hash + (int) getTotalSeconds(); - hash = 37 * hash + (int) getTotalNanos(); - return hash; - } - - /** - * Produce the XML Schema string - * - * @see java.lang.Object#toString() - */ - - public String toString() - { - StringBuffer buffer = new StringBuffer(128); - if (!m_positive) - { - buffer.append("-"); - } - buffer.append("P"); - // Always include years as just P on its own is invalid - buffer.append(m_years).append("Y"); - - if (m_months != 0) - { - buffer.append(m_months).append("M"); - } - if (m_days != 0) - { - buffer.append(m_days).append("D"); - } - if (hasTime()) - { - buffer.append("T"); - if (m_hours != 0) - { - buffer.append(m_hours).append("H"); - } - if (m_mins != 0) - { - buffer.append(m_mins).append("M"); - } - if ((m_seconds != 0) || (m_nanos != 0)) - { - BigDecimal a = new BigDecimal(m_seconds); - BigDecimal b = new BigDecimal(m_nanos); - a = a.add(b.divide(new BigDecimal(1000000000), 9, BigDecimal.ROUND_HALF_EVEN)); - NumberFormat nf = NumberFormat.getInstance(); - buffer.append(nf.format(a)); - buffer.append("S"); - } - - } - - return buffer.toString(); - } - - /** - * Format in human readable form - * - * TODO: I18n - */ - - public String formattedString() - { - StringBuffer buffer = new StringBuffer(128); - if (!m_positive) - { - buffer.append("-"); - } - if (m_years != 0) - { - if (buffer.length() > 0) - buffer.append(" "); - buffer.append(m_years); - buffer.append((m_years == 1) ? " Year" : " Years"); - - } - if (m_months != 0) - { - if (buffer.length() > 0) - buffer.append(" "); - buffer.append(m_months); - buffer.append((m_months == 1) ? " Month" : " Months"); - } - if (m_days != 0) - { - if (buffer.length() > 0) - buffer.append(" "); - buffer.append(m_days); - buffer.append((m_days == 1) ? " Day" : " Days"); - } - if (hasTime()) - { - if (m_hours != 0) - { - if (buffer.length() > 0) - buffer.append(" "); - buffer.append(m_hours); - buffer.append((m_hours == 1) ? " Hour" : " Hours"); - } - if (m_mins != 0) - { - if (buffer.length() > 0) - buffer.append(" "); - buffer.append(m_mins); - buffer.append((m_mins == 1) ? " Minute" : " Minutes"); - } - if ((m_seconds != 0) || (m_nanos != 0)) - { - if (buffer.length() > 0) - buffer.append(" "); - BigDecimal a = new BigDecimal(m_seconds); - BigDecimal b = new BigDecimal(m_nanos); - a = a.add(b.divide(new BigDecimal(1000000000), 9, BigDecimal.ROUND_HALF_EVEN)); - NumberFormat nf = NumberFormat.getInstance(); - String formatted = nf.format(a); - buffer.append(formatted); - buffer.append(formatted.equals("1") ? " Second" : " Seconds"); - } - - } - - return buffer.toString(); - } - - - /** - * TODO: Tests that should be moved into a unit test - * - * @param args - */ - public static void main(String[] args) - { - Duration diff = new Duration("2002-04-02T01:01:01", "2003-03-01T00:00:00"); - System.out.println("Diff " + diff); - - try - { - Duration test = new Duration("P"); - System.out.println("Just P" + test); - } - catch (RuntimeException e) - { - e.printStackTrace(); - } - - try - { - Duration test2 = new Duration("P Jones"); - System.out.println("P Jones" + test2); - } - catch (RuntimeException e) - { - e.printStackTrace(); - } - - try - { - Duration test2 = new Duration("P12Y Jones"); - System.out.println("P Jones" + test2); - } - catch (RuntimeException e) - { - e.printStackTrace(); - } - - try - { - Duration test = new Duration("PPPPPPPPPPPPPP"); - System.out.println("Just many P" + test); - } - catch (RuntimeException e) - { - e.printStackTrace(); - } - - try - { - Duration test = new Duration("PY"); - System.out.println("PY" + test); - } - catch (RuntimeException e) - { - e.printStackTrace(); - } - - try - { - Duration test = new Duration("PM"); - System.out.println("PM" + test); - } - catch (RuntimeException e) - { - e.printStackTrace(); - } - - try - { - Duration test = new Duration("PP"); - System.out.println("PP" + test); - } - catch (RuntimeException e) - { - e.printStackTrace(); - } - - Date now = new Date(); - Calendar c = Calendar.getInstance(); - c.setTime(now); - c.add(Calendar.YEAR, -1); - c.add(Calendar.MONTH, +2); - c.add(Calendar.DAY_OF_MONTH, -3); - c.add(Calendar.HOUR_OF_DAY, +4); - c.add(Calendar.MINUTE, -5); - c.add(Calendar.SECOND, +6); - c.add(Calendar.MILLISECOND, -7); - - diff = new Duration(c.getTime(), now); - System.out.println("V: " + diff); - - Duration diff2 = new Duration(now, c.getTime()); - System.out.println("V: " + diff2); - - Duration a1 = new Duration("P2Y6M"); - Duration a2 = new Duration("P1DT2H3M1.5S"); - - Duration d = new Duration("P2Y6M5DT12H35M30.100S"); - System.out.println("V: " + d); - System.out.println("F: " + d.formattedString()); - System.out.println(" D: " + d.divide(2)); - System.out.println(" +: " + d.add(a1)); - System.out.println(" +: " + d.add(a1.add(a2))); - d = new Duration("P1DT2H3M1.5S"); - System.out.println("V: " + d); - System.out.println("F: " + d.formattedString()); - System.out.println(" D: " + d.divide(2)); - System.out.println(" +: " + d.add(a1)); - System.out.println(" +: " + d.add(a1.add(a2))); - d = new Duration("PT1.5S"); - System.out.println("V: " + d); - System.out.println("F: " + d.formattedString()); - System.out.println(" D: " + d.divide(2)); - System.out.println(" +: " + d.add(a1)); - System.out.println(" +: " + d.add(a1.add(a2))); - d = new Duration("P20M"); - System.out.println("V: " + d); - System.out.println("F: " + d.formattedString()); - System.out.println(" D: " + d.divide(2)); - System.out.println(" +: " + d.add(a1)); - System.out.println(" +: " + d.add(a1.add(a2))); - d = new Duration("P0Y20M0D"); - System.out.println("V: " + d); - System.out.println("F: " + d.formattedString()); - System.out.println(" D: " + d.divide(2)); - System.out.println(" +: " + d.add(a1)); - System.out.println(" +: " + d.add(a1.add(a2))); - d = new Duration("-P60D"); - System.out.println("V: " + d); - System.out.println("F: " + d.formattedString()); - System.out.println(" D: " + d.divide(10)); - System.out.println(" +: " + d.add(a2)); - //System.out.println(" +: " + d.add(a1)); - - - d = new Duration("P1H"); - System.out.println("V: " + d); - System.out.println("F: " + d.formattedString()); - System.out.println(" D: " + d.divide(10)); - System.out.println(" +: " + d.add(a2)); - - d = new Duration("PT1H"); - System.out.println("V: " + d); - System.out.println("F: " + d.formattedString()); - System.out.println(" D: " + d.divide(10)); - System.out.println(" +: " + d.add(a2)); - - } -} diff --git a/source/java/org/alfresco/service/cmr/repository/datatype/TypeConversionException.java b/source/java/org/alfresco/service/cmr/repository/datatype/TypeConversionException.java deleted file mode 100644 index bb2d0fe38c..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/datatype/TypeConversionException.java +++ /dev/null @@ -1,41 +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.service.cmr.repository.datatype; - - -/** - * Base Exception of Type Converter Exceptions. - * - * @author David Caruana - */ -public class TypeConversionException extends RuntimeException -{ - private static final long serialVersionUID = 3257008761007847733L; - - public TypeConversionException(String msg) - { - super(msg); - } - - public TypeConversionException(String msg, Throwable cause) - { - super(msg, cause); - } - -} diff --git a/source/java/org/alfresco/service/cmr/repository/datatype/TypeConverter.java b/source/java/org/alfresco/service/cmr/repository/datatype/TypeConverter.java deleted file mode 100644 index 6b1e6b130c..0000000000 --- a/source/java/org/alfresco/service/cmr/repository/datatype/TypeConverter.java +++ /dev/null @@ -1,625 +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.service.cmr.repository.datatype; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import org.alfresco.service.cmr.dictionary.DataTypeDefinition; -import org.alfresco.service.cmr.dictionary.DictionaryException; -import org.springframework.extensions.surf.util.ParameterCheck; - - -/** - * Support for generic conversion between types. - * - * Additional conversions may be added. - * - * Direct conversion and two stage conversions via Number are supported. We do - * not support conversion by any route at the moment - */ -public class TypeConverter -{ - - /** - * General conversion method to Object types (note it cannot support - * conversion to primary types due the restrictions of reflection. Use the - * static conversion methods to primitive types) - * - * @param propertyType - the target property type - * @param value - the value to be converted - * @return - the converted value as the correct type - */ - @SuppressWarnings("unchecked") - public final Object convert(DataTypeDefinition propertyType, Object value) - { - ParameterCheck.mandatory("Property type definition", propertyType); - - // Convert property type to java class - Class javaClass = null; - String javaClassName = propertyType.getJavaClassName(); - try - { - javaClass = Class.forName(javaClassName); - } - catch (ClassNotFoundException e) - { - throw new DictionaryException("Java class " + javaClassName + " of property type " + propertyType.getName() + " is invalid", e); - } - - return convert(javaClass, value); - } - - /** - * General conversion method to Object types (note it cannot support - * conversion to primary types due the restrictions of reflection. Use the - * static conversion methods to primitive types) - * - * @param The target type for the result of the conversion - * @param c - a class for the target type - * @param value - the value to be converted - * @return - the converted value as the correct type - * @throws TypeConversionException if the conversion cannot be performed - */ - @SuppressWarnings("unchecked") - public final T convert(Class c, Object value) - { - if(value == null) - { - return null; - } - - // Primative types - if (c.isPrimitive()) - { - // We can not suport primitive type conversion - throw new TypeConversionException("Can not convert direct to primitive type " + c.getName()); - } - - // Check if we already have the correct type - if (c.isInstance(value)) - { - return c.cast(value); - } - - // Find the correct conversion - if available and do the converiosn - Converter converter = getConverter(value, c); - if (converter == null) - { - throw new TypeConversionException( - "There is no conversion registered for the value: \n" + - " value class: " + value.getClass().getName() + "\n" + - " to class: " + c.getName() + "\n" + - " value: " + value.toString()); - } - - return (T) converter.convert(value); - } - - /** - * General conversion method to convert collection contents to the specified - * type. Wrapper around the Collection version for arrays. - * - * @param propertyType - the target property type - * @param value - the value to be converted - * @return - the converted value as the correct type - * @throws DictionaryException if the property type's registered java class is invalid - * @throws TypeConversionException if the conversion cannot be performed - */ - @SuppressWarnings("unchecked") - public final Collection convert(DataTypeDefinition propertyType, Object[] values) - { - if(values == null) { - return convert(propertyType, (Collection)null); - } else { - // Turn the array into a Collection, then convert as that - ArrayList c = new ArrayList(); - c.ensureCapacity(values.length); - for(Object v : values) { - c.add(v); - } - // Convert - return convert(propertyType, c); - } - } - - /** - * General conversion method to convert collection contents to the specified - * type. - * - * @param propertyType - the target property type - * @param value - the value to be converted - * @return - the converted value as the correct type - * @throws DictionaryException if the property type's registered java class is invalid - * @throws TypeConversionException if the conversion cannot be performed - */ - @SuppressWarnings("unchecked") - public final Collection convert(DataTypeDefinition propertyType, Collection values) - { - ParameterCheck.mandatory("Property type definition", propertyType); - - // Convert property type to java class - Class javaClass = null; - String javaClassName = propertyType.getJavaClassName(); - try - { - javaClass = Class.forName(javaClassName); - } - catch (ClassNotFoundException e) - { - throw new DictionaryException("Java class " + javaClassName + " of property type " + propertyType.getName() + " is invalid", e); - } - - return convert(javaClass, values); - } - - /** - * General conversion method to convert collection contents to the specified - * type. - * - * @param The target type for the result of the conversion - * @param c - a class for the target type - * @param value - the collection to be converted - * @return - the converted collection - * @throws TypeConversionException if the conversion cannot be performed - */ - public final Collection convert(Class c, Collection values) - { - if(values == null) - { - return null; - } - - Collection converted = new ArrayList(values.size()); - for (Object value : values) - { - converted.add(convert(c, value)); - } - - return converted; - } - - /** - * Get the boolean value for the value object - * May have conversion failure - * - * @param value - * @return - */ - public final boolean booleanValue(Object value) - { - return convert(Boolean.class, value).booleanValue(); - } - - /** - * Get the char value for the value object - * May have conversion failure - * - * @param value - * @return - */ - public final char charValue(Object value) - { - return convert(Character.class, value).charValue(); - } - - /** - * Get the byte value for the value object - * May have conversion failure - * - * @param value - * @return - */ - public final byte byteValue(Object value) - { - if (value instanceof Number) - { - return ((Number) value).byteValue(); - } - return convert(Byte.class, value).byteValue(); - } - - /** - * Get the short value for the value object - * May have conversion failure - * - * @param value - * @return - */ - public final short shortValue(Object value) - { - if (value instanceof Number) - { - return ((Number) value).shortValue(); - } - return convert(Short.class, value).shortValue(); - } - - /** - * Get the int value for the value object - * May have conversion failure - * - * @param value - * @return - */ - public final int intValue(Object value) - { - if (value instanceof Number) - { - return ((Number) value).intValue(); - } - return convert(Integer.class, value).intValue(); - } - - /** - * Get the long value for the value object - * May have conversion failure - * - * @param value - * @return - */ - public final long longValue(Object value) - { - if (value instanceof Number) - { - return ((Number) value).longValue(); - } - return convert(Long.class, value).longValue(); - } - - /** - * Get the bollean value for the value object - * May have conversion failure - * - * @param float - * @return - */ - public final float floatValue(Object value) - { - if (value instanceof Number) - { - return ((Number) value).floatValue(); - } - return convert(Float.class, value).floatValue(); - } - - /** - * Get the bollean value for the value object - * May have conversion failure - * - * @param double - * @return - */ - public final double doubleValue(Object value) - { - if (value instanceof Number) - { - return ((Number) value).doubleValue(); - } - return convert(Double.class, value).doubleValue(); - } - - /** - * Is the value multi valued - * - * @param value - * @return true - if the underlyinf is a collection of values and not a singole value - */ - public final boolean isMultiValued(Object value) - { - return (value instanceof Collection); - } - - /** - * Get the number of values represented - * - * @param value - * @return 1 for normal values and the size of the collection for MVPs - */ - public final int size(Object value) - { - if (value instanceof Collection) - { - return ((Collection) value).size(); - } - else - { - return 1; - } - } - - /** - * Get a collection for the passed value - * - * @param value - * @return - */ - private final Collection createCollection(Object value) - { - Collection coll; - if (isMultiValued(value)) - { - coll = (Collection) value; - } - else - { - ArrayList list = new ArrayList(1); - list.add(value); - coll = list; - } - return coll; - } - - /** - * Get a collection for the passed value converted to the specified type - * - * @param c - * @param value - * @return - */ - public final Collection getCollection(Class c, Object value) - { - Collection coll = createCollection(value); - return convert(c, coll); - } - - /** - * Add a converter to the list of those available - * - * @param - * @param - * @param source - * @param destination - * @param converter - */ - public final void addConverter(Class source, Class destination, Converter converter) - { - Map map = conversions.get(source); - if (map == null) - { - map = new HashMap(); - conversions.put(source, map); - } - map.put(destination, converter); - } - - /** - * Add a dynamic two stage converter - * @param from - * @param intermediate - * @param to - * @param source - * @param intermediate - * @param destination - */ - public final Converter addDynamicTwoStageConverter(Class source, Class intermediate, Class destination) - { - Converter converter = new TypeConverter.DynamicTwoStageConverter(source, intermediate, destination); - addConverter(source, destination, converter); - return converter; - } - - /** - * Find conversion for the specified object - * - * Note: Takes into account the class of the object and any interfaces it may - * also support. - * - * @param - * @param - * @param source - * @param dest - * @return - */ - @SuppressWarnings("unchecked") - public final Converter getConverter(Object value, Class dest) - { - Converter converter = null; - if (value == null) - { - return null; - } - - // find via class of value - Class valueClass = value.getClass(); - converter = getConverter(valueClass, dest); - if (converter != null) - { - return converter; - } - - // find via supported interfaces of value - do - { - Class[] ifClasses = valueClass.getInterfaces(); - for (Class ifClass : ifClasses) - { - converter = getConverter(ifClass, dest); - if (converter != null) - { - return converter; - } - } - valueClass = valueClass.getSuperclass(); - } - while (valueClass != null); - - return null; - } - - /** - * Find a conversion for a specific Class - * - * @param - * @param - * @param source - * @param dest - * @return - */ - public Converter getConverter(Class source, Class dest) - { - Converter converter = null; - Class clazz = source; - do - { - Map map = conversions.get(clazz); - if (map == null) - { - continue; - } - converter = map.get(dest); - - if (converter == null) - { - // attempt to establish converter from source to dest via Number - Converter first = map.get(Number.class); - Converter second = null; - if (first != null) - { - map = conversions.get(Number.class); - if (map != null) - { - second = map.get(dest); - } - } - if (second != null) - { - converter = new TwoStageConverter(first, second); - } - } - } - while ((converter == null) && ((clazz = clazz.getSuperclass()) != null)); - - return converter; - } - - /** - * Map of conversion - */ - private Map> conversions = new HashMap>(); - - - // Support for pluggable conversions - - /** - * Conversion interface - * - * @author andyh - * - * @param From type - * @param To type - */ - public interface Converter - { - public T convert(F source); - } - - /** - * Support for chaining conversions - * - * @author andyh - * - * @param From Type - * @param Intermediate type - * @param To Type - */ - public static class TwoStageConverter implements Converter - { - Converter first; - - Converter second; - - TwoStageConverter(Converter first, Converter second) - { - this.first = first; - this.second = second; - } - - @SuppressWarnings("unchecked") - public T convert(F source) - { - return (T) second.convert((I) first.convert(source)); - } - } - - /** - * Support for chaining conversions - * - * @author David Caruana - * - * @param From Type - * @param Intermediate type - * @param To Type - */ - protected class DynamicTwoStageConverter implements Converter - { - Class from; - Class intermediate; - Class to; - - DynamicTwoStageConverter(Class from, Class intermediate, Class to) - { - this.from = from; - this.intermediate = intermediate; - this.to = to; - } - - /** - * @return from class - */ - public Class getFrom() - { - return from; - } - - /** - * @return intermediate class - */ - public Class getIntermediate() - { - return intermediate; - } - - /** - * @return to class - */ - public Class getTo() - { - return to; - } - - @SuppressWarnings("unchecked") - public T convert(F source) - { - Converter iConverter = TypeConverter.this.getConverter(from, intermediate); - Converter tConverter = TypeConverter.this.getConverter(intermediate, to); - if (iConverter == null || tConverter == null) - { - throw new TypeConversionException("Cannot convert from " + from.getName() + " to " + to.getName()); - } - - Object iValue = iConverter.convert(source); - Object tValue = tConverter.convert(iValue); - return (T)tValue; - } - } - -} diff --git a/source/java/org/alfresco/service/cmr/search/LimitBy.java b/source/java/org/alfresco/service/cmr/search/LimitBy.java deleted file mode 100644 index 1b72240720..0000000000 --- a/source/java/org/alfresco/service/cmr/search/LimitBy.java +++ /dev/null @@ -1,42 +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.service.cmr.search; - -/** - * Enum to describe how the maximum size of the returned result set should be determined. - * - * @author Andy Hind - */ -public enum LimitBy -{ - /** - * The final number of search results is not important. - */ - UNLIMITED, - /** - * Limit the total number of search results returned after pruning by permissions. - */ - FINAL_SIZE, - /** - * Limit the number of results that will be passed through for permission checks.
- * Used internally to prevent excessive permission checking - * (see property lucene.query.maxInitialSearchResults). - */ - NUMBER_OF_PERMISSION_EVALUATIONS; -} \ No newline at end of file diff --git a/source/java/org/alfresco/service/cmr/search/NamedQueryParameterDefinition.java b/source/java/org/alfresco/service/cmr/search/NamedQueryParameterDefinition.java deleted file mode 100644 index a5ceadfacb..0000000000 --- a/source/java/org/alfresco/service/cmr/search/NamedQueryParameterDefinition.java +++ /dev/null @@ -1,40 +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.service.cmr.search; - -import org.alfresco.service.namespace.QName; - -public interface NamedQueryParameterDefinition -{ - - /** - * Get the name of this parameter. It could be used as the well known name for the parameter. - * - * Not null - * - * @return - */ - public QName getQName(); - - /** - * Get the query parameter definition - * @return - */ - public QueryParameterDefinition getQueryParameterDefinition(); -} diff --git a/source/java/org/alfresco/service/cmr/search/PermissionEvaluationMode.java b/source/java/org/alfresco/service/cmr/search/PermissionEvaluationMode.java deleted file mode 100644 index c3e58f1ca0..0000000000 --- a/source/java/org/alfresco/service/cmr/search/PermissionEvaluationMode.java +++ /dev/null @@ -1,29 +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.service.cmr.search; - -/** - * Enum to control how permissions are evaluated. - * - * @author Andy Hind - */ -public enum PermissionEvaluationMode -{ - EAGER; // LAZY -} \ No newline at end of file diff --git a/source/java/org/alfresco/service/cmr/search/QueryParameter.java b/source/java/org/alfresco/service/cmr/search/QueryParameter.java deleted file mode 100644 index d644ed04dd..0000000000 --- a/source/java/org/alfresco/service/cmr/search/QueryParameter.java +++ /dev/null @@ -1,57 +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.service.cmr.search; - -import java.io.Serializable; - -import org.alfresco.service.namespace.QName; - -/** - * Encapsulates a query parameter - * - * @author andyh - * - */ -public class QueryParameter -{ - private QName qName; - - private Serializable value; - - public QueryParameter(QName qName, Serializable value) - { - this.qName = qName; - this.value = value; - } - - public QName getQName() - { - return qName; - } - - - public Serializable getValue() - { - return value; - } - - - - -} diff --git a/source/java/org/alfresco/service/cmr/search/QueryParameterDefinition.java b/source/java/org/alfresco/service/cmr/search/QueryParameterDefinition.java deleted file mode 100644 index 8c84c6c1a2..0000000000 --- a/source/java/org/alfresco/service/cmr/search/QueryParameterDefinition.java +++ /dev/null @@ -1,58 +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.service.cmr.search; - -import org.alfresco.service.cmr.dictionary.PropertyDefinition; -import org.alfresco.service.cmr.dictionary.DataTypeDefinition; - -public interface QueryParameterDefinition extends NamedQueryParameterDefinition -{ - /** - * This parameter may apply to a well known property type. - * - * May be null - * - * @return - */ - public PropertyDefinition getPropertyDefinition(); - - /** - * Get the property type definition for this parameter. - * It could come from the property type definition if there is one - * - * Not null - * - * @return - */ - public DataTypeDefinition getDataTypeDefinition(); - - /** - * Get the default value for this parameter. - * - * @return - */ - public String getDefault(); - - /** - * Has this parameter got a default value? - * - * @return - */ - public boolean hasDefaultValue(); -} diff --git a/source/java/org/alfresco/service/cmr/search/ResultSet.java b/source/java/org/alfresco/service/cmr/search/ResultSet.java deleted file mode 100644 index 0b49cacdaf..0000000000 --- a/source/java/org/alfresco/service/cmr/search/ResultSet.java +++ /dev/null @@ -1,36 +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.service.cmr.search; - - -/** - * This is the common interface for both row (Alfresco node) and column (CMIS style property or function) based results. - * The meta-data for the results sets contains the detailed info on what columns are available. For row based result - * sets there is no selector - all the nodes returned do not have to have a specific type or aspect. For example, an FTS - * search on properties of type d:content has no type constraint implied or otherwise. Searches against properties have - * an implied type, but as there can be more than one property -> more than one type or aspect implied (eg via OR in FTS - * or lucene) they are ignored An iterable result set from a searcher query. Implementations must implement the - * indexes for row lookup as zero-based. - * - * @author andyh - */ -public interface ResultSet extends ResultSetSPI // Specific iterator over ResultSetRows -{ - -} diff --git a/source/java/org/alfresco/service/cmr/search/ResultSetColumn.java b/source/java/org/alfresco/service/cmr/search/ResultSetColumn.java deleted file mode 100644 index 031a3e6813..0000000000 --- a/source/java/org/alfresco/service/cmr/search/ResultSetColumn.java +++ /dev/null @@ -1,49 +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.service.cmr.search; - -import org.alfresco.service.namespace.QName; - -/** - * The metadata for a column in a result set. - * All columns should have a data type, they may have a property type. - * - * @author andyh - * - */ -public interface ResultSetColumn -{ - /** - * The column name - * @return - the column name - */ - public String getName(); - - /** - * The type of the column - * @return - the data type for the column - */ - public QName getDataType(); - - /** - * The property definition if there is one for the column - * @return - the property definition or null if it does not make sense for the column - */ - public QName getPropertyType(); -} diff --git a/source/java/org/alfresco/service/cmr/search/ResultSetMetaData.java b/source/java/org/alfresco/service/cmr/search/ResultSetMetaData.java deleted file mode 100644 index f1b555cbe3..0000000000 --- a/source/java/org/alfresco/service/cmr/search/ResultSetMetaData.java +++ /dev/null @@ -1,102 +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.service.cmr.search; - - -/** - * Meta Data associated with a result set. - * - * @author Andy Hind - */ -public interface ResultSetMetaData -{ - - /** - * Return how, in fact, the result set was limited. - * This may not be how it was requested. - * - * If a limit of 100 were requested and there were 100 or less actual results - * this will report LimitBy.UNLIMITED. - * - * @return - */ - public LimitBy getLimitedBy(); - - /** - * Return how permission evaluations are being made. - * - * @return - */ - public PermissionEvaluationMode getPermissionEvaluationMode(); - - /** - * Get the parameters that were specified to define this search. - * - * @return - */ - public SearchParameters getSearchParameters(); - - /** - * Get the result set type - * @return - */ - public ResultSetType getResultSetType(); - - /** - * The selector meta-data. - * @return - the selector meta-data. - */ - public ResultSetSelector[] getSelectors(); - - - /** - * The column meta-data. - * @return - the column meta-data. - */ - public ResultSetColumn[] getColumns(); - - /** - * Get the names of the selectors. - * @return - the selector names. - */ - public String[] getSelectorNames(); - - /** - * Get the column names. - * @return - the names of the columns. - */ - public String[] getColumnNames(); - - /** - * Get the selector meta-data by name. - * @param name - * @return - the selector meta-data. - */ - public ResultSetSelector getSelector(String name); - - /** - * Get the column meta-data by column name. - * @param name - * @return - the column meta-data. - */ - public ResultSetColumn getColumn(String name); - - - -} diff --git a/source/java/org/alfresco/service/cmr/search/ResultSetRow.java b/source/java/org/alfresco/service/cmr/search/ResultSetRow.java deleted file mode 100644 index c56cf097fa..0000000000 --- a/source/java/org/alfresco/service/cmr/search/ResultSetRow.java +++ /dev/null @@ -1,132 +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.service.cmr.search; - -import java.io.Serializable; -import java.util.Map; - -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.Path; -import org.alfresco.service.namespace.QName; - -/** - * A row in a result set - * - * TODO: Support for other non attribute features such as parents and path - * - * @author andyh - * - */ -public interface ResultSetRow -{ - /** - * Get the values of all available node properties. These are only properties - * that were stored in the query results and can vary depending on the query - * language that was used. - * - * @return Returns all the available node properties - */ - public Map getValues(); - - /** - * Get the data for a single column - * @param columnName - * @return the value - */ - public Serializable getValue(String columnName); - - /** - * Get a node property value by name - * - * @param qname the property name - * @return Returns the node property for the given name - */ - public Serializable getValue(QName qname); - - /** - * The reference to the node that equates to this row in the result set - * - * @return Returns the reference to the node that makes this result - */ - public NodeRef getNodeRef(); - - - /** - * Gets the node refs - * @return a map of selector name to node ref - */ - public Map getNodeRefs(); - - - /** - * Gets the node ref related to the named selector - * @param selectorName - * @return the node ref - */ - public NodeRef getNodeRef(String selectorName); - - /** - * Get the score for this row in the result set - * - * @return Returns the score for this row in the resultset - */ - public float getScore(); // Score is score + rank + potentially other - // stuff - - /** - * Get the scores . - * @return a map of selector name to score. - */ - public Map getScores(); - - /** - * Get the score related to the named selector. - * @param selectorName - * @return - the score. - */ - public float getScore(String selectorName); - - - /** - * Get the containing result set - * - * @return Returns the containing resultset - */ - public ResultSet getResultSet(); - - /** - * @return Returns the name of the child association leading down to the - * node represented by this row - */ - public QName getQName(); - - /** - * Get the index of this result set in the result set - * If you want the overall position in paged reults you have to add the skipCount fo the result set. - * @return - */ - public int getIndex(); - - /** - * @return Returns the child assoc ref for this row - */ - public ChildAssociationRef getChildAssocRef(); - -} diff --git a/source/java/org/alfresco/service/cmr/search/ResultSetSPI.java b/source/java/org/alfresco/service/cmr/search/ResultSetSPI.java deleted file mode 100644 index 146cc87824..0000000000 --- a/source/java/org/alfresco/service/cmr/search/ResultSetSPI.java +++ /dev/null @@ -1,132 +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.service.cmr.search; - -import java.util.List; - -import org.alfresco.service.cmr.repository.ChildAssociationRef; -import org.alfresco.service.cmr.repository.NodeRef; - -/** - * This is the common interface for both row (Alfresco node) and column (CMIS style property or function) based results. - * The meta-data for the results sets contains the detailed info on what columns are available. For row based result - * sets there is no selector - all the nodes returned do not have to have a specific type or aspect. For example, an FTS - * search on properties of type d:content has no type constraint implied or otherwise. Searches against properties have - * an implied type, but as there can be more than one property -> more than one type or aspect implied (eg via OR in FTS - * or lucene) they are ignored An iterable result set from a searcher query. Implementations must implement the - * indexes for row lookup as zero-based. - * - * @author andyh - * @param - * @param - */ -public interface ResultSetSPI extends Iterable // Specific iterator over ResultSetRows -{ - /** - * Get the number of rows in this result set. This will be less than or equal to the maximum number of rows - * requested or the full length of the results set if no restriction on length are specified. If a skip count is - * given, the length represents the number of results after the skip count and does not include the items skipped. - * - * @return the number of results. -1 means unknown and can be returned for lazy evaluations of permissions when the - * actual size is not known and evaluated upon request. - */ - public int length(); - - /** - * Get the id of the node at the given index (if there is only one selector or no selector) - * - * @param n - * zero-based index - * @return return the the node ref for the row if there is only one selector - * @throws AmbiguousSelectorException - */ - public NodeRef getNodeRef(int n); - - /** - * Get the score for the node at the given position (if there is only one selector or no selector) - * - * @param n - * zero-based index - * @return return the score for the row if there is only one selector - * @throws AmbiguousSelectorException - */ - public float getScore(int n); - - /** - * Close the result set and release any resources held/ The result set is bound to the transaction and will auto - * close at the end of the transaction. - */ - public void close(); - - /** - * Get a row from the result set by row index, starting at 0. - * - * @param i - * zero-based index - * @return return the row - */ - public ROW getRow(int i); - - /** - * Get a list of all the node refs in the result set (if there is only one selector or no selector) - * - * @return the node refs if there is only one selector or no selector * - * @throws AmbiguousSelectorException - */ - public List getNodeRefs(); - - /** - * Get a list of all the child associations in the results set. (if there is only one selectoror no selector) - * - * @return the child assoc refs if there is only one selector or no selector * - * @throws AmbiguousSelectorException - */ - public List getChildAssocRefs(); - - /** - * Get the child assoc ref for a particular row. (if there is only one selectoror no selector) - * - * @param n - * zero-based index - * @return the child assoc ref for the row if there is only one selector or no selector - */ - public ChildAssociationRef getChildAssocRef(int n); - - /** - * Get the meta data for the results set. - * - * @return the metadata - */ - public MD getResultSetMetaData(); - - /** - * Get the start point for this results set in the overall set of rows that match the query - this will be equal to - * the skip count set when executing the query, and zero if this is not set. - * - * @return the position of the first result in the overall result set - */ - public int getStart(); - - /** - * Was this result set curtailed - are there more pages to the result set? - * - * @return true if there are more pages in the result set - */ - public boolean hasMore(); -} diff --git a/source/java/org/alfresco/service/cmr/search/ResultSetSelector.java b/source/java/org/alfresco/service/cmr/search/ResultSetSelector.java deleted file mode 100644 index 8cfb423db8..0000000000 --- a/source/java/org/alfresco/service/cmr/search/ResultSetSelector.java +++ /dev/null @@ -1,42 +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.service.cmr.search; - -import org.alfresco.service.namespace.QName; - -/** - * The metadata for a ResultSet selector. - * - * @author andyh - * - */ -public interface ResultSetSelector -{ - /** - * The unique name for the selector. - * @return - the unique name for the selector - */ - public String getName(); - - /** - * Get the Alfresco type QName for the type or aspect - * @return - the type or aspect - */ - public QName getType(); -} diff --git a/source/java/org/alfresco/service/cmr/search/ResultSetType.java b/source/java/org/alfresco/service/cmr/search/ResultSetType.java deleted file mode 100644 index 6e41ef9aa5..0000000000 --- a/source/java/org/alfresco/service/cmr/search/ResultSetType.java +++ /dev/null @@ -1,36 +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.service.cmr.search; - -/** - * The two types of result set - column based and Node Ref based. - * @author andyh - * - */ -public enum ResultSetType -{ - /** - * Just the node ref is available for each row in the results. - */ - NODE_REF, - /** - * The node ref is available and a specified list of columns. - */ - COLUMN_AND_NODE_REF -} diff --git a/source/java/org/alfresco/service/cmr/search/SearchParameters.java b/source/java/org/alfresco/service/cmr/search/SearchParameters.java deleted file mode 100644 index 158fdf1414..0000000000 --- a/source/java/org/alfresco/service/cmr/search/SearchParameters.java +++ /dev/null @@ -1,798 +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.service.cmr.search; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import org.alfresco.repo.search.MLAnalysisMode; -import org.alfresco.repo.search.impl.querymodel.QueryOptions; -import org.alfresco.service.cmr.repository.StoreRef; -import org.alfresco.service.namespace.NamespaceService; - -/** - * This class provides parameters to define a search. TODO - paging of results page number and page size - paging - * isolation - REPEATABLE READ, READ COMMITTED, may SEE ONCE tracking node refs in previous result sets - how long - * repeatable read may be held - limit by the number of permission evaluations - * - * @author Andy Hind - */ -public class SearchParameters -{ - /* - * The default limit if someone asks for a limited result set but does not say how to limit.... - */ - private static int DEFAULT_LIMIT = 500; - - private static int DEFAULT_BULK_FETCH_SIZE = 1000; - - /* - * Standard sort definitions for sorting in document and score order. - */ - /** - * Sort in the order docs were added to the index - oldest docs first - */ - public static final SortDefinition SORT_IN_DOCUMENT_ORDER_ASCENDING = new SortDefinition(SortDefinition.SortType.DOCUMENT, null, true); - - /** - * Sort in the reverse order docs were added to the index - new/updateed docs first - */ - public static final SortDefinition SORT_IN_DOCUMENT_ORDER_DESCENDING = new SortDefinition(SortDefinition.SortType.DOCUMENT, null, false); - - /** - * Sort in ascending score - */ - public static final SortDefinition SORT_IN_SCORE_ORDER_ASCENDING = new SortDefinition(SortDefinition.SortType.SCORE, null, false); - - /** - * Sort in descending score order - */ - public static final SortDefinition SORT_IN_SCORE_ORDER_DESCENDING = new SortDefinition(SortDefinition.SortType.SCORE, null, true); - - /** - * An emum defining if the default action is to "and" or "or" unspecified components in the query register. Not all - * search implementations will support this. - */ - public enum Operator - { - /** - * OR - */ - OR, - /** - * AND - */ - AND - } - - /* - * Expose as constants - */ - /** - * OR - */ - public static final Operator OR = Operator.OR; - - /** - * AND - */ - public static final Operator AND = Operator.AND; - - /* - * The parameters that can be set - */ - private String language; - - private String query; - - private ArrayList stores = new ArrayList(1); - - private ArrayList queryParameterDefinitions = new ArrayList(1); - - private boolean excludeDataInTheCurrentTransaction = false; - - private ArrayList sortDefinitions = new ArrayList(1); - - private ArrayList locales = new ArrayList(); - - private MLAnalysisMode mlAnalaysisMode = null; // Pick up from config if null - - private LimitBy limitBy = LimitBy.UNLIMITED; - - private PermissionEvaluationMode permissionEvaluation = PermissionEvaluationMode.EAGER; - - private int limit = DEFAULT_LIMIT; - - private HashSet allAttributes = new HashSet(); - - private HashSet textAttributes = new HashSet(); - - private boolean bulkFetch = true; - - private int bulkFetchSize = DEFAULT_BULK_FETCH_SIZE; - - private int maxItems = -1; - - private int skipCount = 0; - - private Operator defaultFTSOperator = Operator.OR; - - private Operator defaultFTSFieldOperator = Operator.OR; - - private Map queryTemplates = new HashMap(); - - private String namespace = NamespaceService.CONTENT_MODEL_1_0_URI; - - // By default uses the central config - private int maxPermissionChecks = -1; - - // By default uses the central config - private long maxPermissionCheckTimeMillis = -1; - - private String defaultFieldName = "TEXT"; - - /** - * Default constructor - */ - public SearchParameters() - { - super(); - } - - /** - * Construct from Query Options - * - * @param options - */ - public SearchParameters(QueryOptions options) - { - setBulkFetch(options.getFetchSize() > 0); - setBulkFetchSize(options.getFetchSize()); - setSkipCount(options.getSkipCount()); - setMaxPermissionChecks(options.getMaxPermissionChecks()); - setMaxPermissionCheckTimeMillis(options.getMaxPermissionCheckTimeMillis()); - if (options.getMaxItems() >= 0) - { - setLimitBy(LimitBy.FINAL_SIZE); - setLimit(options.getMaxItems()); - setMaxItems(options.getMaxItems()); - } - else - { - setLimitBy(LimitBy.UNLIMITED); - } - } - - /** - * Get the search language - * - * @return - string id of search language - */ - public String getLanguage() - { - return language; - } - - /** - * Get the query. - * - * @return - the query string - */ - public String getQuery() - { - return query; - } - - /** - * Set the query language. - * - * @param language - - * the query language. - */ - public void setLanguage(String language) - { - this.language = language; - } - - /** - * Set the query string. - * - * @param query - - * the query string. - */ - public void setQuery(String query) - { - this.query = query; - } - - /** - * Set the stores to be supported - currently there can be only one. Searching across multiple stores is on the todo - * list. - * - * @param store - */ - public void addStore(StoreRef store) - { - if (stores.size() != 0) - { - throw new IllegalStateException("At the moment, there can only be one store set for the search"); - } - stores.add(store); - } - - /** - * Add parameter definitions for the query - used to parameterise the query string - * - * @param queryParameterDefinition - */ - public void addQueryParameterDefinition(QueryParameterDefinition queryParameterDefinition) - { - queryParameterDefinitions.add(queryParameterDefinition); - } - - /** - * If true, any data in the current transaction will be ignored in the search. You will not see anything you have - * added in the current transaction. By default you will see data in the current transaction. This effectively gives - * read committed isolation. There is a performance overhead for this, at least when using lucene. This flag may be - * set to avoid that performance hit if you know you do not want to find results that are yet to be committed (this - * includes creations, deletions and updates) - * - * @param excludeDataInTheCurrentTransaction - */ - public void excludeDataInTheCurrentTransaction(boolean excludeDataInTheCurrentTransaction) - { - this.excludeDataInTheCurrentTransaction = excludeDataInTheCurrentTransaction; - } - - /** - * Add a sort to the query (for those query languages that do not support it directly) The first sort added is - * treated as primary, the second as secondary etc. A helper method to create SortDefinitions. - * - * @param field - - * this is initially a direct attribute on a node not an attribute on the parent etc TODO: It could be a - * relative path at some time. - * @param ascending - - * true to sort ascending, false for descending. - */ - public void addSort(String field, boolean ascending) - { - addSort(new SortDefinition(SortDefinition.SortType.FIELD, field, ascending)); - } - - /** - * Add a sort definition. - * - * @param sortDefinition - - * the sort definition to add. Use the static member variables for sorting in score and index order. - */ - public void addSort(SortDefinition sortDefinition) - { - sortDefinitions.add(sortDefinition); - } - - /** - * Is data in the current transaction excluded from the search. - * - * @return - true if data in the current transaction is ignored - */ - public boolean excludeDataInTheCurrentTransaction() - { - return excludeDataInTheCurrentTransaction; - } - - /** - * Get the query parameters that apply to this query. - * - * @return - the parameter - */ - public ArrayList getQueryParameterDefinitions() - { - return queryParameterDefinitions; - } - - /** - * Get the sort definitions that apply to this query. - * - * @return - the sort definitions - */ - public ArrayList getSortDefinitions() - { - return sortDefinitions; - } - - /** - * Get the stores in which this query should find results. - * - * @return - the list of stores - */ - public ArrayList getStores() - { - return stores; - } - - /** - * Set the default operator for query elements when they are not explicit in the query. - * - * @param defaultOperator - */ - public void setDefaultOperator(Operator defaultOperator) - { - this.defaultFTSOperator = defaultOperator; - this.defaultFTSFieldOperator = defaultOperator; - } - - /** - * Get the default operator for query elements when they are not explicit in the query. - * - * @return the default operator - */ - public Operator getDefaultOperator() - { - return getDefaultFTSOperator(); - } - - /** - * Get how the result set should be limited - * - * @return how the result set will be or was limited - */ - public LimitBy getLimitBy() - { - return limitBy; - } - - /** - * Set how the result set should be limited. - * - * @param limitBy - */ - public void setLimitBy(LimitBy limitBy) - { - this.limitBy = limitBy; - } - - /** - * Get when permissions are evaluated. - * - * @return - how permissions are evaluated - */ - public PermissionEvaluationMode getPermissionEvaluation() - { - return permissionEvaluation; - } - - /** - * Set when permissions are evaluated. - * - * @param permissionEvaluation - */ - public void setPermissionEvaluation(PermissionEvaluationMode permissionEvaluation) - { - this.permissionEvaluation = permissionEvaluation; - } - - /** - * If limiting the result set in some way, get the limiting value used. - * - * @return the limit - */ - public int getLimit() - { - return limit; - } - - /** - * If limiting the result set in some way, set the limiting value used. - * - * @param limit - */ - public void setLimit(int limit) - { - this.limit = limit; - } - - /** - * The way in which multilingual fields are treated durig a search. By default, only the specified locale is used - * and it must be an exact match. - * - * @return - how locale related text is tokenised - */ - public MLAnalysisMode getMlAnalaysisMode() - { - return mlAnalaysisMode; - } - - /** - * Set the way in which multilingual fields are treated durig a search. This controls in which locales an - * multilingual fields will match. - * - * @param mlAnalaysisMode - */ - public void setMlAnalaysisMode(MLAnalysisMode mlAnalaysisMode) - { - this.mlAnalaysisMode = mlAnalaysisMode; - } - - /** - * Add a locale to include for multi-lingual text searches. If non are set, the default is to use the user's locale. - * - * @param locale - */ - public void addLocale(Locale locale) - { - locales.add(locale); - } - - /** - * Get the locales used for multi-lingual text searches. - * - * @return - the locales - */ - public List getLocales() - { - return Collections.unmodifiableList(locales); - } - - /** - * Add a field for TEXT expansion - * - * @param attribute - - * field/attribute in the index - */ - public void addTextAttribute(String attribute) - { - textAttributes.add(attribute); - } - - /** - * Get the text attributes used for text expansion. - * - * @return the text attributes used for text expansion - */ - public Set getTextAttributes() - { - return Collections.unmodifiableSet(textAttributes); - } - - /** - * Add a field for ALL expansion - * - * @param attribute - - * field/attribute in the index - */ - public void addAllAttribute(String attribute) - { - allAttributes.add(attribute); - } - - /** - * Get the text attributes used for ALL expansion. - * - * @return the text attributes used for ALL expansion - */ - public Set getAllAttributes() - { - return Collections.unmodifiableSet(allAttributes); - } - - /** - * Bulk fetch results in the cache - * - * @param bulkFetch - */ - public void setBulkFetch(boolean bulkFetch) - { - this.bulkFetch = bulkFetch; - } - - /** - * Do we bulk fetch - * - * @return - true if we do - */ - public boolean getBulkFetch() - { - return bulkFetch; - } - - /** - * Set the bulk fetch size - * - * @param bulkFetchSize - */ - public void setBulkFetchSize(int bulkFetchSize) - { - this.bulkFetchSize = bulkFetchSize; - } - - /** - * Get the bulk fetch size. - * - * @return the fetch size - */ - public int getBulkFecthSize() - { - return bulkFetchSize; - } - - /** - * Get the max number of rows for the result set 0 or less is unlimited - * - * @return the maxItems - */ - public int getMaxItems() - { - return maxItems; - } - - /** - * Set the max number of rows for the result set. - * A negative value implies unlimited - * 0 will return no results. - * - * @param maxItems - * the maxItems to set - */ - public void setMaxItems(int maxItems) - { - this.maxItems = maxItems; - } - - /** - * Get the skip count - the number of rows to skip at the start of the query. - * - * @return the skipCount - */ - public int getSkipCount() - { - return skipCount; - } - - /** - * Set the skip count - the number of rows to skip at the start of the query. - * - * @param skipCount - * the skipCount to set - */ - public void setSkipCount(int skipCount) - { - this.skipCount = skipCount; - } - - /** - * Get the default connective used when OR and AND are not specified for the FTS contains() function. - * - * @return the defaultFTSConnective - */ - public Operator getDefaultFTSOperator() - { - return defaultFTSOperator; - } - - /** - * Set the default connective used when OR and AND are not specified for the FTS contains() function. - * - * @param defaultFTSOperator - * the defaultFTSOperator to set - */ - public void setDefaultFTSOperator(Operator defaultFTSOperator) - { - this.defaultFTSOperator = defaultFTSOperator; - } - - /** - * As getDefaultFTSConnective() but for field groups - * - * @return the defaultFTSFieldConnective - */ - public Operator getDefaultFTSFieldOperator() - { - return defaultFTSFieldOperator; - } - - /** - * As setDefaultFTSConnective() but for field groups - * - * @param defaultFTSFieldOperator - * the defaultFTSFieldOperator to set - */ - public void setDefaultFTSFieldConnective(Operator defaultFTSFieldOperator) - { - this.defaultFTSFieldOperator = defaultFTSFieldOperator; - } - - /** - * Get the default namespace. - * - * @return the default namspace uri or prefix. - */ - public String getNamespace() - { - return namespace; - } - - /** - * Set the default namespace - * - * @param namespace - - * the uri or prefix for the default namespace. - */ - public void setNamespace(String namespace) - { - this.namespace = namespace; - } - - /** - * Get the query templates - * - * @return - the query templates - */ - public Map getQueryTemplates() - { - return queryTemplates; - } - - /** - * Add/replace a query template Not all languages support query templates - * - * @param name - * @param template - * @return any removed template or null - */ - public String addQueryTemplate(String name, String template) - { - return queryTemplates.put(name, template); - } - - public long getMaxPermissionCheckTimeMillis() - { - return maxPermissionCheckTimeMillis; - } - - public void setMaxPermissionCheckTimeMillis(long maxPermissionCheckTimeMillis) - { - this.maxPermissionCheckTimeMillis = maxPermissionCheckTimeMillis; - } - - public int getMaxPermissionChecks() - { - return maxPermissionChecks; - } - - public void setMaxPermissionChecks(int maxPermissionChecks) - { - this.maxPermissionChecks = maxPermissionChecks; - } - - public int getBulkFetchSize() - { - return bulkFetchSize; - } - - /** - * A helper class for sort definition. Encapsulated using the lucene sortType, field name and a flag for - * ascending/descending. - * - * @author Andy Hind - */ - public static class SortDefinition - { - - /** - * What is used for the sort - * - * @author andyh - */ - public enum SortType - { - /** - * A Field - */ - FIELD, - /** - * Doc number - */ - DOCUMENT, - /** - * Score - */ - SCORE - }; - - SortType sortType; - - String field; - - boolean ascending; - - SortDefinition(SortType sortType, String field, boolean ascending) - { - this.sortType = sortType; - this.field = field; - this.ascending = ascending; - } - - /** - * Is ascending - * - * @return true if ascending - */ - public boolean isAscending() - { - return ascending; - } - - /** - * Field - * - * @return - the field - */ - public String getField() - { - return field; - } - - /** - * What is used for the sort - * - * @return sort type - */ - public SortType getSortType() - { - return sortType; - } - - } - - /** - * @return the default field name - */ - public String getDefaultFieldName() - { - return defaultFieldName; - } - - /** - * @param defaultFieldName - the default field name to use - */ - public void setDefaultFieldName(String defaultFieldName) - { - this.defaultFieldName = defaultFieldName; - } - - @Override - public String toString() - { - return "SearchParameters [allAttributes=" - + allAttributes + ", bulkFetch=" + bulkFetch + ", bulkFetchSize=" + bulkFetchSize + ", defaultFTSFieldOperator=" + defaultFTSFieldOperator - + ", defaultFTSOperator=" + defaultFTSOperator + ", defaultFieldName=" + defaultFieldName + ", excludeDataInTheCurrentTransaction=" - + excludeDataInTheCurrentTransaction + ", language=" + language + ", limit=" + limit + ", limitBy=" + limitBy + ", locales=" + locales + ", maxItems=" + maxItems - + ", maxPermissionCheckTimeMillis=" + maxPermissionCheckTimeMillis + ", maxPermissionChecks=" + maxPermissionChecks + ", mlAnalaysisMode=" + mlAnalaysisMode - + ", namespace=" + namespace + ", permissionEvaluation=" + permissionEvaluation + ", query=" + query + ", queryParameterDefinitions=" + queryParameterDefinitions - + ", queryTemplates=" + queryTemplates + ", skipCount=" + skipCount + ", sortDefinitions=" + sortDefinitions + ", stores=" + stores + ", textAttributes=" - + textAttributes + "]"; - } - -} diff --git a/source/java/org/alfresco/service/cmr/search/SearchService.java b/source/java/org/alfresco/service/cmr/search/SearchService.java deleted file mode 100644 index 9fbf9f61eb..0000000000 --- a/source/java/org/alfresco/service/cmr/search/SearchService.java +++ /dev/null @@ -1,262 +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.service.cmr.search; - -import java.io.Serializable; -import java.util.List; - -import org.alfresco.service.Auditable; -import org.alfresco.service.PublicService; -import org.alfresco.service.cmr.repository.InvalidNodeRefException; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.StoreRef; -import org.alfresco.service.cmr.repository.XPathException; -import org.alfresco.service.namespace.NamespacePrefixResolver; -import org.alfresco.service.namespace.QName; - -/** - * This encapsulates the execution of search against different indexing - * mechanisms. - * - * Canned queries have been translated into the query string by this stage. - * Handling of parameterisation is left to the implementation. - * - * @author Andy hind - * - */ -@PublicService -public interface SearchService -{ - public static final String LANGUAGE_LUCENE = "lucene"; - - public static final String LANGUAGE_XPATH = "xpath"; - - public static final String LANGUAGE_JCR_XPATH = "jcr-xpath"; - - public static final String LANGUAGE_FTS_ALFRESCO = "fts-alfresco"; - - public static final String LANGUAGE_CMIS_STRICT = "cmis-strict"; - - public static final String LANGUAGE_CMIS_ALFRESCO = "cmis-alfresco"; - - /** - * Search against a store. Pulls back all attributes on each node. Does not - * allow parameterisation. - * - * @param store - - * the store against which to search - * @param language - - * the query language - * @param query - - * the query string - which may include parameters - * @return Returns the query results - */ - @Auditable(key = Auditable.Key.ARG_0, parameters = {"store", "language", "query"}) - public ResultSet query(StoreRef store, String language, String query); - - /** - * Search against a store. - * - * @param store - - * the store against which to search - * @param language - - * the query language - * @param query - - * the query string - which may include parameters - * @param queryParameterDefinition - - * query parameter definitions - the default value is used for - * the value. - * @return Returns the query results - */ - @Auditable(key = Auditable.Key.ARG_0, parameters = {"store", "language", "query", "queryParameterDefinitions"}) - public ResultSet query(StoreRef store, String language, String query, - QueryParameterDefinition[] queryParameterDefintions); - - - /** - * Execute a canned query - * - * @param store - - * the store against which to search - * @param queryId - - * the query identifier - * @param queryParameters - - * parameterisation for the canned query - * @return Returns the query results - */ - @Auditable(key = Auditable.Key.ARG_0, parameters = {"store", "queryId", "queryParameters"}) - public ResultSet query(StoreRef store, QName queryId, QueryParameter[] queryParameters); - - /** - * Search using the given SearchParameters - */ - - @Auditable(key = Auditable.Key.ARG_0, parameters = {"searchParameters"}) - public ResultSet query(SearchParameters searchParameters); - - /** - * Select nodes using an xpath expression. - * - * @param contextNodeRef - - * the context node for relative expressions etc - * @param xpath - - * the xpath string to evaluate - * @param parameters - - * parameters to bind in to the xpath expression - * @param namespacePrefixResolver - - * prefix to namespace mappings - * @param followAllParentLinks - - * if false ".." follows only the primary parent links, if true - * it follows all - * @return a list of all the child assoc relationships to the selected nodes - */ - @Auditable( - key = Auditable.Key.ARG_0, - parameters = {"contextNodeRef", "xpath", "parameters", "namespacePrefixResolver", "followAllParentLinks"}, - recordable = {true, true, true, false, true}) - public List selectNodes(NodeRef contextNodeRef, String xpath, QueryParameterDefinition[] parameters, - NamespacePrefixResolver namespacePrefixResolver, boolean followAllParentLinks) - throws InvalidNodeRefException, XPathException; - - /** - * Select nodes using an xpath expression. - * - * @param contextNodeRef - - * the context node for relative expressions etc - * @param xpath - - * the xpath string to evaluate - * @param parameters - - * parameters to bind in to the xpath expression - * @param namespacePrefixResolver - - * prefix to namespace mappings - * @param followAllParentLinks - - * if false ".." follows only the primary parent links, if true - * it follows all - * @param langauage - - * the xpath variant - * @return a list of all the child assoc relationships to the selected nodes - */ - @Auditable( - key = Auditable.Key.ARG_0, - parameters = {"contextNodeRef", "xpath", "parameters", "namespacePrefixResolver", "followAllParentLinks", "language"}, - recordable = {true, true, true, false, true, true}) - public List selectNodes(NodeRef contextNodeRef, String xpath, QueryParameterDefinition[] parameters, - NamespacePrefixResolver namespacePrefixResolver, boolean followAllParentLinks, String language) - throws InvalidNodeRefException, XPathException; - - /** - * Select properties using an xpath expression - * - * @param contextNodeRef - - * the context node for relative expressions etc - * @param xpath - - * the xpath string to evaluate - * @param parameters - - * parameters to bind in to the xpath expression - * @param namespacePrefixResolver - - * prefix to namespace mappings - * @param followAllParentLinks - - * if false ".." follows only the primary parent links, if true - * it follows all - * @return a list of property values - */ - @Auditable( - key = Auditable.Key.ARG_0, - parameters = {"contextNodeRef", "xpath", "parameters", "namespacePrefixResolver", "followAllParentLinks"}, - recordable = {true, true, true, false, true}) - public List selectProperties(NodeRef contextNodeRef, String xpath, - QueryParameterDefinition[] parameters, NamespacePrefixResolver namespacePrefixResolver, - boolean followAllParentLinks) throws InvalidNodeRefException, XPathException; - - /** - * Select properties using an xpath expression - * - * @param contextNodeRef - - * the context node for relative expressions etc - * @param xpath - - * the xpath string to evaluate - * @param parameters - - * parameters to bind in to the xpath expression - * @param namespacePrefixResolver - - * prefix to namespace mappings - * @param followAllParentLinks - - * if false ".." follows only the primary parent links, if true - * it follows all - * @param langauage - - * the xpath variant - * @return a list of property values - */ - @Auditable( - key = Auditable.Key.ARG_0, - parameters = {"contextNodeRef", "xpath", "parameters", "namespacePrefixResolver", "followAllParentLinks", "language"}, - recordable = {true, true, true, false, true, true}) - public List selectProperties(NodeRef contextNodeRef, String xpath, - QueryParameterDefinition[] parameters, NamespacePrefixResolver namespacePrefixResolver, - boolean followAllParentLinks, String language) throws InvalidNodeRefException, XPathException; - - /** - * Search for string pattern in both the node text (if present) and node - * properties - * - * @param nodeRef - * the node to get - * @param propertyQName - * the name of the property - * @param googleLikePattern - * a Google-like pattern to search for in the property value - * @return Returns true if the pattern could be found - uses the default OR operator - */ - @Auditable(key = Auditable.Key.ARG_0, parameters = {"nodeRef", "propertyQName", "googleLikePattern"}) - public boolean contains(NodeRef nodeRef, QName propertyQName, String googleLikePattern) - throws InvalidNodeRefException; - - /** - * Search for string pattern in both the node text (if present) and node - * properties - * - * @param nodeRef - * the node to get - * @param propertyQName - * the name of the property - * @param googleLikePattern - * a Google-like pattern to search for in the property value - * @return Returns true if the pattern could be found - */ - @Auditable(key = Auditable.Key.ARG_0, parameters = {"nodeRef", "propertyQName", "googleLikePattern", "defaultOperator"}) - public boolean contains(NodeRef nodeRef, QName propertyQName, String googleLikePattern, SearchParameters.Operator defaultOperator) - throws InvalidNodeRefException; - - /** - * Search for string pattern in both the node text (if present) and node - * properties - * - * @param nodeRef - * the node to get - * @param propertyQName - * the name of the property (mandatory) - * @param sqlLikePattern - * a SQL-like pattern to search for - * @param includeFTS - - * include full text search matches in the like test - * @return Returns true if the pattern could be found - */ - @Auditable(key = Auditable.Key.ARG_0, parameters = {"nodeRef", "propertyQName", "sqlLikePattern", "includeFTS"}) - public boolean like(NodeRef nodeRef, QName propertyQName, String sqlLikePattern, boolean includeFTS) - throws InvalidNodeRefException; -} diff --git a/source/java/org/alfresco/service/cmr/security/AccessPermission.java b/source/java/org/alfresco/service/cmr/security/AccessPermission.java deleted file mode 100644 index 706e4a7fab..0000000000 --- a/source/java/org/alfresco/service/cmr/security/AccessPermission.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.service.cmr.security; - - -/** - * The interface used to support reporting back if permissions are allowed or - * denied. - * - * @author Andy Hind - */ -public interface AccessPermission -{ - /** - * The permission. - * - * @return - */ - public String getPermission(); - - /** - * Get the Access enumeration value - * - * @return - */ - public AccessStatus getAccessStatus(); - - - /** - * Get the authority to which this permission applies. - * - * @return - */ - public String getAuthority(); - - - /** - * Get the type of authority to which this permission applies. - * - * @return - */ - public AuthorityType getAuthorityType(); - - - /** - * At what position in the inheritance chain for permissions is this permission set? - * = 0 -> Set direct on the object. - * > 0 -> Inherited - * < 0 -> We don't know and are using this object for reporting (e.g. the actual permissions that apply to a node for the current user) - * @return - */ - public int getPosition(); - - /** - * Is this an inherited permission entry? - * @return - */ - public boolean isInherited(); - - /** - * Is this permission set on the object? - * @return - */ - public boolean isSetDirectly(); -} diff --git a/source/java/org/alfresco/service/cmr/security/AccessStatus.java b/source/java/org/alfresco/service/cmr/security/AccessStatus.java deleted file mode 100644 index 8ca2060af0..0000000000 --- a/source/java/org/alfresco/service/cmr/security/AccessStatus.java +++ /dev/null @@ -1,29 +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.service.cmr.security; - -/** - * Enumeration used to indicate access status. - * - * @author Andy Hind - */ -public enum AccessStatus -{ - DENIED, ALLOWED, UNDETERMINED; -} diff --git a/source/java/org/alfresco/service/cmr/security/AuthorityType.java b/source/java/org/alfresco/service/cmr/security/AuthorityType.java deleted file mode 100644 index cc02046f0a..0000000000 --- a/source/java/org/alfresco/service/cmr/security/AuthorityType.java +++ /dev/null @@ -1,315 +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.service.cmr.security; - -/** - * The types of authority that are available. - *

- *

- * Available types are: - *

    - *
  1. USER - an authority that identifies a user - *
  2. GROUP - an authority that identifies a group - *
  3. OWNER - the special authority that applies to the owner of a node - *
  4. EVERYONE - the special authority that is interpreted as everyone - *
  5. GUEST - the special authority that applies to a GUEST (An unknown, unauthenticated user) - *
  6. WILDCARD - the set of all authorities (including the guest user) - *
- * - * @author Andy Hind - */ -public enum AuthorityType -{ - ADMIN - { - public boolean isFixedString() - { - return true; - } - - public String getFixedString() - { - return PermissionService.ADMINISTRATOR_AUTHORITY; - } - - public boolean isPrefixed() - { - return false; - } - - public String getPrefixString() - { - return ""; - } - - public int getOrderPosition() - { - return 0; - } - }, - - EVERYONE - { - public boolean isFixedString() - { - return true; - } - - public String getFixedString() - { - return PermissionService.ALL_AUTHORITIES; - } - - public boolean isPrefixed() - { - return false; - } - - public String getPrefixString() - { - return ""; - } - - public int getOrderPosition() - { - return 1; - } - }, - OWNER - { - public boolean isFixedString() - { - return true; - } - - public String getFixedString() - { - return PermissionService.OWNER_AUTHORITY; - } - - public boolean isPrefixed() - { - return false; - } - - public String getPrefixString() - { - return ""; - } - - public int getOrderPosition() - { - return 2; - } - }, - GUEST - { - public boolean isFixedString() - { - return true; - } - - public String getFixedString() - { - return PermissionService.GUEST_AUTHORITY; - } - - public boolean isPrefixed() - { - return false; - } - - public String getPrefixString() - { - return ""; - } - - public int getOrderPosition() - { - return 3; - } - }, - GROUP - { - public boolean isFixedString() - { - return false; - } - - public String getFixedString() - { - return ""; - } - - public boolean isPrefixed() - { - return true; - } - - public String getPrefixString() - { - return PermissionService.GROUP_PREFIX; - } - - public int getOrderPosition() - { - return 4; - } - }, - ROLE - { - - public boolean isFixedString() - { - return false; - } - - public String getFixedString() - { - return ""; - } - - public boolean isPrefixed() - { - return true; - } - - public String getPrefixString() - { - return PermissionService.ROLE_PREFIX; - } - - public int getOrderPosition() - { - return 5; - } - }, - USER - { - public boolean isFixedString() - { - return false; - } - - public String getFixedString() - { - return ""; - } - - public boolean isPrefixed() - { - return false; - } - - public String getPrefixString() - { - return ""; - } - - public int getOrderPosition() - { - return 6; - } - }, - WILDCARD - { - public boolean isFixedString() - { - return false; - } - - public String getFixedString() - { - return ""; - } - - public boolean isPrefixed() - { - return false; - } - - public String getPrefixString() - { - return ""; - } - - public int getOrderPosition() - { - return 7; - } - }; - - public abstract boolean isFixedString(); - - public abstract String getFixedString(); - - public abstract boolean isPrefixed(); - - public abstract String getPrefixString(); - - public abstract int getOrderPosition(); - - public boolean equals(String authority) - { - return equals(getAuthorityType(authority)); - } - - public static AuthorityType getAuthorityType(String authority) - { - AuthorityType authorityType; - - if(null == authority) - { - authorityType = AuthorityType.WILDCARD; - } - else - { - if (authority.equals(PermissionService.ADMINISTRATOR_AUTHORITY)) - { - authorityType = AuthorityType.ADMIN; - } - if (authority.equals(PermissionService.ALL_AUTHORITIES)) - { - authorityType = AuthorityType.EVERYONE; - } - else if (authority.equals(PermissionService.OWNER_AUTHORITY)) - { - authorityType = AuthorityType.OWNER; - } - else if (authority.equalsIgnoreCase(PermissionService.GUEST_AUTHORITY)) - { - authorityType = AuthorityType.GUEST; - } - else if (authority.startsWith(PermissionService.GROUP_PREFIX)) - { - authorityType = AuthorityType.GROUP; - } - else if (authority.startsWith(PermissionService.ROLE_PREFIX)) - { - authorityType = AuthorityType.ROLE; - } - else - { - authorityType = AuthorityType.USER; - } - } - - return authorityType; - } -} diff --git a/source/java/org/alfresco/service/cmr/security/PermissionContext.java b/source/java/org/alfresco/service/cmr/security/PermissionContext.java deleted file mode 100644 index 310a6fed79..0000000000 --- a/source/java/org/alfresco/service/cmr/security/PermissionContext.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.service.cmr.security; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.alfresco.service.namespace.QName; - -public class PermissionContext -{ - private QName type; - - private HashSet aspects = new HashSet(); - - private Map properties = new HashMap(); - - private Map> dynamicAuthorityAssignment = new HashMap>(); - - private Map additionalContext = new HashMap(); - - private Long storeAcl = null; - - public PermissionContext(QName type) - { - this.type = type; - } - - public HashSet getAspects() - { - return aspects; - } - - public Map> getDynamicAuthorityAssignment() - { - return dynamicAuthorityAssignment; - } - - public void addDynamicAuthorityAssignment(String user, String dynamicAuthority) - { - Set dynamicAuthorities = dynamicAuthorityAssignment.get(user); - if(dynamicAuthorities == null) - { - dynamicAuthorities = new HashSet(); - dynamicAuthorityAssignment.put(user, dynamicAuthorities); - } - dynamicAuthorities.add(dynamicAuthority); - } - - public Map getAdditionalContext() - { - return additionalContext; - } - - public Map getProperties() - { - return properties; - } - - public QName getType() - { - return type; - } - - public Long getStoreAcl() - { - return storeAcl; - } - - public void setStoreAcl(Long storeAcl) - { - this.storeAcl = storeAcl; - } - - - -} diff --git a/source/java/org/alfresco/service/cmr/security/PermissionService.java b/source/java/org/alfresco/service/cmr/security/PermissionService.java deleted file mode 100644 index 9e94e028be..0000000000 --- a/source/java/org/alfresco/service/cmr/security/PermissionService.java +++ /dev/null @@ -1,362 +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.service.cmr.security; - -import java.util.Map; -import java.util.Set; - -import org.alfresco.service.Auditable; -import org.alfresco.service.PublicService; -import org.alfresco.service.cmr.repository.NodeRef; -import org.alfresco.service.cmr.repository.StoreRef; -import org.alfresco.service.namespace.QName; - -/** - * The public API for a permission service The implementation may be changed in the application configuration - * - * @author Andy Hind - */ -@PublicService -public interface PermissionService -{ - /** - * Prefixes used for authorities of type role. This is intended for external roles, e.g. those set by ACEGI - * implementations It is only used for admin at the moment - which is done outside the usual permission assignments - * at the moment. It could be a dynamic authority. - */ - public static final String ROLE_PREFIX = "ROLE_"; - - /** - * Prefix used for authorities of type group. - */ - public static final String GROUP_PREFIX = "GROUP_"; - - /** - * The group that contains everyone except guest. - */ - public static final String ALL_AUTHORITIES = "GROUP_EVERYONE"; - - /** - * The dynamic authority used for ownership - */ - public static final String OWNER_AUTHORITY = "ROLE_OWNER"; - - /** - * The authority that all owners of WCM stores have. - */ - public static final String WCM_STORE_OWNER_AUTHORITY = "ROLE_WCM_STORE_OWNER"; - - /** - * The dynamic authority used for the ownership of locks. - */ - public static final String LOCK_OWNER_AUTHORITY = "ROLE_LOCK_OWNER"; - - /** - * The admin authority - currently a role. - */ - public static final String ADMINISTRATOR_AUTHORITY = "ROLE_ADMINISTRATOR"; - - /** - * The guest authority - */ - public static final String GUEST_AUTHORITY = "ROLE_GUEST"; - - /** - * The permission for all - not defined in the model. Repsected in the code. - */ - public static final String ALL_PERMISSIONS = "All"; - - // Constants for permissions/permission groups defined in the standard permission model. - - public static final String FULL_CONTROL = "FullControl"; - - public static final String READ = "Read"; - - public static final String WRITE = "Write"; - - public static final String DELETE = "Delete"; - - public static final String ADD_CHILDREN = "AddChildren"; - - public static final String READ_PROPERTIES = "ReadProperties"; - - public static final String READ_CHILDREN = "ReadChildren"; - - public static final String WRITE_PROPERTIES = "WriteProperties"; - - public static final String DELETE_NODE = "DeleteNode"; - - public static final String DELETE_CHILDREN = "DeleteChildren"; - - public static final String CREATE_CHILDREN = "CreateChildren"; - - public static final String LINK_CHILDREN = "LinkChildren"; - - public static final String DELETE_ASSOCIATIONS = "DeleteAssociations"; - - public static final String READ_ASSOCIATIONS = "ReadAssociations"; - - public static final String CREATE_ASSOCIATIONS = "CreateAssociations"; - - public static final String READ_PERMISSIONS = "ReadPermissions"; - - public static final String CHANGE_PERMISSIONS = "ChangePermissions"; - - public static final String EXECUTE = "Execute"; - - public static final String READ_CONTENT = "ReadContent"; - - public static final String WRITE_CONTENT = "WriteContent"; - - public static final String EXECUTE_CONTENT = "ExecuteContent"; - - public static final String TAKE_OWNERSHIP = "TakeOwnership"; - - public static final String SET_OWNER = "SetOwner"; - - public static final String COORDINATOR = "Coordinator"; - - public static final String CONTRIBUTOR = "Contributor"; - - public static final String EDITOR = "Editor"; - - public static final String CONSUMER = "Consumer"; - - public static final String LOCK = "Lock"; - - public static final String UNLOCK = "Unlock"; - - public static final String CHECK_OUT = "CheckOut"; - - public static final String CHECK_IN = "CheckIn"; - - public static final String CANCEL_CHECK_OUT = "CancelCheckOut"; - - public static final String ASPECTS = "Aspects"; - - public static final String PROPERTIES = "Properties"; - - public static final String WCM_CONTENT_MANAGER = "ContentManager"; - - public static final String WCM_CONTENT_PUBLISHER = "ContentPublisher"; - - public static final String WCM_CONTENT_CONTRIBUTOR = "ContentContributor"; - - public static final String WCM_CONTENT_REVIEWER = "ContentReviewer"; - - public static final String FLATTEN = "Flatten"; - - /** - * Get the Owner Authority - * - * @return the owner authority - */ - @Auditable - public String getOwnerAuthority(); - - /** - * Get the All Authorities - * - * @return the All authorities - */ - @Auditable - public String getAllAuthorities(); - - /** - * Get the All Permission - * - * @return the All permission - */ - @Auditable - public String getAllPermission(); - - /** - * Get all the AccessPermissions that are granted/denied to the current authentication for the given node - * - * @param nodeRef - - * the reference to the node - * @return the set of allowed permissions - */ - @Auditable(key = Auditable.Key.ARG_0, parameters = { "nodeRef" }) - public Set getPermissions(NodeRef nodeRef); - - /** - * Get all the AccessPermissions that are set for anyone for the given node - * - * @param nodeRef - - * the reference to the node - * @return the set of allowed permissions - */ - @Auditable(key = Auditable.Key.ARG_0, parameters = { "nodeRef" }) - public Set getAllSetPermissions(NodeRef nodeRef); - - /** - * Get the permissions that can be set for a given node - * - * @param nodeRef - * @return - */ - @Auditable(key = Auditable.Key.ARG_0, parameters = { "nodeRef" }) - public Set getSettablePermissions(NodeRef nodeRef); - - /** - * Get the permissions that can be set for a given type - * - * @param type - * @return - set of permissions - */ - @Auditable(parameters = { "type" }) - public Set getSettablePermissions(QName type); - - /** - * Check that the given authentication has a particular permission for the given node. (The default behaviour is to - * inherit permissions) - * - * @param nodeRef - * @param permission - * @return - access status - */ - @Auditable(key = Auditable.Key.ARG_0, parameters = { "nodeRef", "permission" }) - public AccessStatus hasPermission(NodeRef nodeRef, String permission); - - /** - * Check if a permission is allowed on an acl. - * @param aclID - * @param context - * @param permission - * @return the access status - */ - @Auditable(parameters = { "aclID", "context", "permission" }) - public AccessStatus hasPermission(Long aclID, PermissionContext context, String permission); - - /** - * Delete all the permission assigned to the node - * - * @param nodeRef - */ - @Auditable(key = Auditable.Key.ARG_0, parameters = { "nodeRef" }) - public void deletePermissions(NodeRef nodeRef); - - /** - * Delete all permission for the given authority. - * - * @param nodeRef - * @param authority - * (if null then this will match all authorities) - */ - @Auditable(key = Auditable.Key.ARG_0, parameters = { "nodeRef", "authority" }) - public void clearPermission(NodeRef nodeRef, String authority); - - /** - * Find and delete a access control entry by node, authentication and permission. It is possible to delete - *
    - *
  1. a specific permission; - *
  2. all permissions for an authority (if the permission is null); - *
  3. entries for all authorities that have a specific permission (if the authority is null); and - *
  4. all permissions set for the node (if both the permission and authority are null). - *
- * - * @param nodeRef - * the node that the entry applies to - * @param authority - * the authority recipient (if null then this will match all authorities) - * @param permission - * the entry permission (if null then this will match all permissions) - */ - @Auditable(key = Auditable.Key.ARG_0, parameters = { "nodeRef", "authority", "permission" }) - public void deletePermission(NodeRef nodeRef, String authority, String permission); - - /** - * Set a specific permission on a node. - * - * @param nodeRef - * @param authority - * @param permission - * @param allow - */ - @Auditable(key = Auditable.Key.ARG_0, parameters = { "nodeRef", "authority", "permission", "allow" }) - public void setPermission(NodeRef nodeRef, String authority, String permission, boolean allow); - - /** - * Set the global inheritance behaviour for permissions on a node. - * - * @param nodeRef - * @param inheritParentPermissions - */ - @Auditable(key = Auditable.Key.ARG_0, parameters = { "nodeRef", "inheritParentPermissions" }) - public void setInheritParentPermissions(NodeRef nodeRef, boolean inheritParentPermissions); - - /** - * Return the global inheritance behaviour for permissions on a node. - * - * @param nodeRef - * @return inheritParentPermissions - */ - @Auditable(key = Auditable.Key.ARG_0, parameters = { "nodeRef" }) - public boolean getInheritParentPermissions(NodeRef nodeRef); - - - /** - * Add a permission mask to a store - * - * @param storeRef - * @param authority - * @param permission - * @param allow - */ - @Auditable(key = Auditable.Key.ARG_0, parameters = { "storeRef", "authority", "permission", "allow" }) - public void setPermission(StoreRef storeRef, String authority, String permission, boolean allow); - - /** - * Remove part of a permission mask on a store - * @param storeRef - * @param authority - * @param permission - */ - @Auditable(key = Auditable.Key.ARG_0, parameters = { "storeRef", "authority", "permission" }) - public void deletePermission(StoreRef storeRef, String authority, String permission); - - /** - * Clear all permission masks for an authority on a store - * - * @param storeRef - * @param authority - */ - @Auditable(key = Auditable.Key.ARG_0, parameters = { "storeRef", "authority" }) - public void clearPermission(StoreRef storeRef, String authority); - - /** - * Remove all permission mask on a store - * - * @param storeRef - */ - @Auditable(key = Auditable.Key.ARG_0, parameters = { "storeRef" }) - public void deletePermissions(StoreRef storeRef); - - - /** - * Get all the AccessPermissions that are set for anyone for the given node - * - * @param storeRef - - * the reference to the store - * @return the set of allowed permissions - */ - @Auditable(key = Auditable.Key.ARG_0, parameters = { "storeRef" }) - public Set getAllSetPermissions(StoreRef storeRef); -} \ No newline at end of file diff --git a/source/java/org/alfresco/service/namespace/DynamicNameSpaceResolverTest.java b/source/java/org/alfresco/service/namespace/DynamicNameSpaceResolverTest.java deleted file mode 100644 index 37e9f071f4..0000000000 --- a/source/java/org/alfresco/service/namespace/DynamicNameSpaceResolverTest.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.service.namespace; - -import junit.framework.TestCase; - -public class DynamicNameSpaceResolverTest extends TestCase -{ - - public DynamicNameSpaceResolverTest() - { - super(); - } - - public void testOne() - { - DynamicNamespacePrefixResolver dnpr = new DynamicNamespacePrefixResolver(null); - dnpr.registerNamespace("one", "http:/namespace/one"); - dnpr.registerNamespace("two", "http:/namespace/two"); - dnpr.registerNamespace("three", "http:/namespace/three"); - dnpr.registerNamespace("oneagain", "http:/namespace/one"); - dnpr.registerNamespace("four", "http:/namespace/one"); - dnpr.registerNamespace("four", "http:/namespace/four"); - - assertEquals("http:/namespace/one", dnpr.getNamespaceURI("one")); - assertEquals("http:/namespace/two", dnpr.getNamespaceURI("two")); - assertEquals("http:/namespace/three", dnpr.getNamespaceURI("three")); - assertEquals("http:/namespace/one", dnpr.getNamespaceURI("oneagain")); - assertEquals("http:/namespace/four", dnpr.getNamespaceURI("four")); - assertEquals(null, dnpr.getNamespaceURI("five")); - - dnpr.unregisterNamespace("four"); - assertEquals(null, dnpr.getNamespaceURI("four")); - - assertEquals(0, dnpr.getPrefixes("http:/namespace/four").size()); - assertEquals(1, dnpr.getPrefixes("http:/namespace/two").size()); - assertEquals(2, dnpr.getPrefixes("http:/namespace/one").size()); - - - } - - - public void testTwo() - { - DynamicNamespacePrefixResolver dnpr1 = new DynamicNamespacePrefixResolver(null); - dnpr1.registerNamespace("one", "http:/namespace/one"); - dnpr1.registerNamespace("two", "http:/namespace/two"); - dnpr1.registerNamespace("three", "http:/namespace/three"); - dnpr1.registerNamespace("oneagain", "http:/namespace/one"); - dnpr1.registerNamespace("four", "http:/namespace/one"); - dnpr1.registerNamespace("four", "http:/namespace/four"); - dnpr1.registerNamespace("five", "http:/namespace/five"); - dnpr1.registerNamespace("six", "http:/namespace/six"); - - DynamicNamespacePrefixResolver dnpr2 = new DynamicNamespacePrefixResolver(dnpr1); - dnpr2.registerNamespace("a", "http:/namespace/one"); - dnpr2.registerNamespace("b", "http:/namespace/two"); - dnpr2.registerNamespace("c", "http:/namespace/three"); - dnpr2.registerNamespace("d", "http:/namespace/one"); - dnpr2.registerNamespace("e", "http:/namespace/one"); - dnpr2.registerNamespace("f", "http:/namespace/four"); - dnpr2.registerNamespace("five", "http:/namespace/one"); - dnpr2.registerNamespace("six", "http:/namespace/seven"); - - assertEquals("http:/namespace/one", dnpr2.getNamespaceURI("one")); - assertEquals("http:/namespace/two", dnpr2.getNamespaceURI("two")); - assertEquals("http:/namespace/three", dnpr2.getNamespaceURI("three")); - assertEquals("http:/namespace/one", dnpr2.getNamespaceURI("oneagain")); - assertEquals("http:/namespace/four", dnpr2.getNamespaceURI("four")); - assertEquals("http:/namespace/one", dnpr2.getNamespaceURI("five")); - dnpr2.unregisterNamespace("five"); - - assertEquals("http:/namespace/five", dnpr2.getNamespaceURI("five")); - assertEquals("http:/namespace/one", dnpr2.getNamespaceURI("a")); - assertEquals("http:/namespace/two", dnpr2.getNamespaceURI("b")); - assertEquals("http:/namespace/three", dnpr2.getNamespaceURI("c")); - assertEquals("http:/namespace/one", dnpr2.getNamespaceURI("d")); - assertEquals("http:/namespace/one", dnpr2.getNamespaceURI("e")); - assertEquals("http:/namespace/four", dnpr2.getNamespaceURI("f")); - - assertEquals(5, dnpr2.getPrefixes("http:/namespace/one").size()); - assertEquals(2, dnpr2.getPrefixes("http:/namespace/two").size()); - assertEquals(2, dnpr2.getPrefixes("http:/namespace/three").size()); - assertEquals(2, dnpr2.getPrefixes("http:/namespace/four").size()); - assertEquals(1, dnpr2.getPrefixes("http:/namespace/five").size()); - assertEquals(0, dnpr2.getPrefixes("http:/namespace/six").size()); - assertEquals(1, dnpr2.getPrefixes("http:/namespace/seven").size()); - } - -} diff --git a/source/java/org/alfresco/service/namespace/DynamicNamespacePrefixResolver.java b/source/java/org/alfresco/service/namespace/DynamicNamespacePrefixResolver.java deleted file mode 100644 index f95c412dbf..0000000000 --- a/source/java/org/alfresco/service/namespace/DynamicNamespacePrefixResolver.java +++ /dev/null @@ -1,138 +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.service.namespace; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; - -/** - * A delegating namespace prefix resolver which allows local over rides from the - * delegate. Allows standard/default prefixes to be available but over ridden as - * required. - * - * @author andyh - */ -public class DynamicNamespacePrefixResolver implements NamespaceService -{ - /** - * The delegate - */ - private NamespacePrefixResolver delegate; - - /** - * The map uris keyed by prefix - */ - private HashMap map = new HashMap(); - - - public DynamicNamespacePrefixResolver(NamespacePrefixResolver delegate) - { - super(); - this.delegate = delegate; - } - - public DynamicNamespacePrefixResolver() - { - this(null); - } - - - /** - * Add prefix to name space mapping override - * - * @param prefix - * @param uri - */ - public void registerNamespace(String prefix, String uri) - { - map.put(prefix, uri); - } - - /** - * Remove a prefix to namespace mapping - * - * @param prefix - */ - public void unregisterNamespace(String prefix) - { - map.remove(prefix); - } - - // NameSpacePrefix Resolver - - public String getNamespaceURI(String prefix) throws NamespaceException - { - String uri = map.get(prefix); - if ((uri == null) && (delegate != null)) - { - uri = delegate.getNamespaceURI(prefix); - } - return uri; - } - - public Collection getPrefixes(String namespaceURI) throws NamespaceException - { - Collection prefixes = new ArrayList(); - for (String key : map.keySet()) - { - String uri = map.get(key); - if ((uri != null) && (uri.equals(namespaceURI))) - { - prefixes.add(key); - } - } - // Only add if not over ridden here (if identical already added) - if (delegate != null) - { - for (String prefix : delegate.getPrefixes(namespaceURI)) - { - if (!map.containsKey(prefix)) - { - prefixes.add(prefix); - } - } - } - return prefixes; - } - - public Collection getPrefixes() - { - Set prefixes = new HashSet(); - if(delegate != null) - { - prefixes.addAll(delegate.getPrefixes()); - } - prefixes.addAll(map.keySet()); - return prefixes; - } - - public Collection getURIs() - { - Set uris = new HashSet(); - if(delegate != null) - { - uris.addAll(delegate.getURIs()); - } - uris.addAll(map.keySet()); - return uris; - } -} diff --git a/source/java/org/alfresco/service/namespace/InvalidQNameException.java b/source/java/org/alfresco/service/namespace/InvalidQNameException.java deleted file mode 100644 index 39bbab94fc..0000000000 --- a/source/java/org/alfresco/service/namespace/InvalidQNameException.java +++ /dev/null @@ -1,35 +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.service.namespace; - - -public class InvalidQNameException extends NamespaceException -{ - private static final long serialVersionUID = 7851788938794302629L; - - public InvalidQNameException(String msg) - { - super(msg); - } - - public InvalidQNameException(String msg, Throwable cause) - { - super(msg, cause); - } -} diff --git a/source/java/org/alfresco/service/namespace/NamespaceException.java b/source/java/org/alfresco/service/namespace/NamespaceException.java deleted file mode 100644 index 8af5b53ad0..0000000000 --- a/source/java/org/alfresco/service/namespace/NamespaceException.java +++ /dev/null @@ -1,35 +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.service.namespace; - - -public class NamespaceException extends RuntimeException -{ - private static final long serialVersionUID = 7851788938794302629L; - - public NamespaceException(String msg) - { - super(msg); - } - - public NamespaceException(String msg, Throwable cause) - { - super(msg, cause); - } -} diff --git a/source/java/org/alfresco/service/namespace/NamespacePrefixResolver.java b/source/java/org/alfresco/service/namespace/NamespacePrefixResolver.java deleted file mode 100644 index a5dffcb888..0000000000 --- a/source/java/org/alfresco/service/namespace/NamespacePrefixResolver.java +++ /dev/null @@ -1,73 +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.service.namespace; - -import java.io.Serializable; -import java.util.Collection; - -import org.alfresco.service.Auditable; -import org.alfresco.service.PublicService; - -/** - * The NamespacePrefixResolver provides a mapping between - * namespace prefixes and namespace URIs. - * - * @author David Caruana - */ -@PublicService -public interface NamespacePrefixResolver -{ - /** - * Gets the namespace URI registered for the given prefix - * - * @param prefix prefix to lookup - * @return the namespace - * @throws NamespaceException if prefix has not been registered - */ - @Auditable(parameters = {"prefix"}) - public String getNamespaceURI(String prefix) - throws NamespaceException; - - /** - * Gets the registered prefixes for the given namespace URI - * - * @param namespaceURI namespace URI to lookup - * @return the prefixes (or empty collection, if no prefixes registered against URI) - * @throws NamespaceException if URI has not been registered - */ - @Auditable(parameters = {"namespaceURI"}) - public Collection getPrefixes(String namespaceURI) - throws NamespaceException; - - /** - * Gets all registered Prefixes - * - * @return collection of all registered namespace prefixes - */ - @Auditable - Collection getPrefixes(); - - /** - * Gets all registered Uris - * - * @return collection of all registered namespace uris - */ - @Auditable - Collection getURIs(); -} diff --git a/source/java/org/alfresco/service/namespace/NamespacePrefixResolverProvider.java b/source/java/org/alfresco/service/namespace/NamespacePrefixResolverProvider.java deleted file mode 100644 index 23d899187d..0000000000 --- a/source/java/org/alfresco/service/namespace/NamespacePrefixResolverProvider.java +++ /dev/null @@ -1,38 +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.service.namespace; - -import java.io.Serializable; - -/** - * Provides support for serializable objects such as the QNameMap that require a - * NamespacePrefixResolver to be available. Ensures that the objects can remain - * serializable themselves and still maintain a valid NamespacePrefixResolver. - * - * @author Kevin Roast - */ -public interface NamespacePrefixResolverProvider extends Serializable -{ - /** - * Get an object that implements the NamespacePrefixResolver interface - * - * @return NamespacePrefixResolver - */ - NamespacePrefixResolver getNamespacePrefixResolver(); -} \ No newline at end of file diff --git a/source/java/org/alfresco/service/namespace/NamespaceService.java b/source/java/org/alfresco/service/namespace/NamespaceService.java deleted file mode 100644 index 4330c2076f..0000000000 --- a/source/java/org/alfresco/service/namespace/NamespaceService.java +++ /dev/null @@ -1,148 +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.service.namespace; - -import org.alfresco.service.Auditable; -import org.alfresco.service.PublicService; - - - -/** - * Namespace Service. - * - * The Namespace Service provides access to and definition of namespace - * URIs and Prefixes. - * - * @author David Caruana - */ -@PublicService -public interface NamespaceService extends NamespacePrefixResolver -{ - /** Default Namespace URI */ - static final String DEFAULT_URI = ""; - - /** Default Namespace Prefix */ - static final String DEFAULT_PREFIX = ""; - - /** Default Alfresco URI */ - static final String ALFRESCO_URI = "http://www.alfresco.org"; - - /** Default Alfresco Prefix */ - static final String ALFRESCO_PREFIX = "alf"; - - /** Dictionary Model URI */ - static final String DICTIONARY_MODEL_1_0_URI = "http://www.alfresco.org/model/dictionary/1.0"; - - /** Dictionary Model Prefix */ - static final String DICTIONARY_MODEL_PREFIX = "d"; - - /** System Model URI */ - static final String SYSTEM_MODEL_1_0_URI = "http://www.alfresco.org/model/system/1.0"; - - /** System Model Prefix */ - static final String SYSTEM_MODEL_PREFIX = "sys"; - - /** Content Model URI */ - static final String CONTENT_MODEL_1_0_URI = "http://www.alfresco.org/model/content/1.0"; - - /** Content Model Prefix */ - static final String CONTENT_MODEL_PREFIX = "cm"; - - /** Application Model URI */ - static final String APP_MODEL_1_0_URI = "http://www.alfresco.org/model/application/1.0"; - - /** Application Model Prefix */ - static final String APP_MODEL_PREFIX = "app"; - - /** Business Process Model URI */ - static final String BPM_MODEL_1_0_URI = "http://www.alfresco.org/model/bpm/1.0"; - - /** Business Process Model Prefix */ - static final String BPM_MODEL_PREFIX = "bpm"; - - /** Workflow Model URI */ - static final String WORKFLOW_MODEL_1_0_URI = "http://www.alfresco.org/model/workflow/1.0"; - - /** Workflow Model Prefix */ - static final String WORKFLOW_MODEL_PREFIX = "wf"; - - /** Alfresco Forums URI */ - static final String FORUMS_MODEL_1_0_URI = "http://www.alfresco.org/model/forum/1.0"; - - /** Alfresco Forums Prefix */ - static final String FORUMS_MODEL_PREFIX = "fm"; - - /** Rendition Model URI */ - static final String RENDITION_MODEL_1_0_URI = "http://www.alfresco.org/model/rendition/1.0"; - - /** Alfresco View Namespace URI */ - static final String REPOSITORY_VIEW_1_0_URI = "http://www.alfresco.org/view/repository/1.0"; - - /** Alfresco View Namespace Prefix */ - static final String REPOSITORY_VIEW_PREFIX = "view"; - - /** Alfresco security URI */ - static final String SECURITY_MODEL_1_0_URI = "http://www.alfresco.org/model/security/1.0"; - - /** Alfresco security Prefix */ - static final String SECURITY_MODEL_PREFIX = "security"; - - /** Alfresco WCM URI */ - static final String WCM_MODEL_1_0_URI = "http://www.alfresco.org/model/wcmmodel/1.0"; - - /** Alfresco WCM Prefix */ - static final String WCM_MODEL_PREFIX = "wcm"; - - /** WCM Application Model URI */ - static final String WCMAPP_MODEL_1_0_URI = "http://www.alfresco.org/model/wcmappmodel/1.0"; - - /** WCM Application Model Prefix */ - static final String WCMAPP_MODEL_PREFIX = "wca"; - - /** Email Server Application Model URI */ - static final String EMAILSERVER_MODEL_URI = "http://www.alfresco.org/model/emailserver/1.0"; - - /** Email Server Application Model Prefix */ - static final String EMAILSERVER_MODEL_PREFIX = "emailserver"; - - /** WCM Workflow Model Prefix */ - static final String WCMWF_MODEL = "wcmwf"; - - /** WCM Workflow Model URI */ - static final String WCMWF_MODEL_1_0_URI = "http://www.alfresco.org/model/wcmworkflow/1.0"; - - /** - * Register a prefix for namespace uri. - * - * @param prefix - * @param uri - */ - @Auditable(parameters = {"prefix", "uri"}) - public void registerNamespace(String prefix, String uri); - - - /** - * Unregister a prefix. - * - * @param prefix - */ - @Auditable(parameters = {"prefix"}) - public void unregisterNamespace(String prefix); - -} diff --git a/source/java/org/alfresco/service/namespace/NamespaceServiceMemoryImpl.java b/source/java/org/alfresco/service/namespace/NamespaceServiceMemoryImpl.java deleted file mode 100644 index c3d16b4fd1..0000000000 --- a/source/java/org/alfresco/service/namespace/NamespaceServiceMemoryImpl.java +++ /dev/null @@ -1,67 +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.service.namespace; - -import java.util.Collection; - -import org.alfresco.util.OneToManyHashBiMap; - -/** - * A basic implementation of the NamespaceService interface intended for use in - * unit tests. This implementation does not persist any changes beyond the - * lifetime of the object. - * - * @author Nick Smith - */ -public class NamespaceServiceMemoryImpl implements NamespaceService -{ - // URI to Prefix map. - private final OneToManyHashBiMap map = new OneToManyHashBiMap(); - - public void registerNamespace(String prefix, String uri) - { - map.putSingleValue(uri, prefix); - } - - public void unregisterNamespace(String prefix) - { - map.removeValue(prefix); - } - - public String getNamespaceURI(String prefix) throws NamespaceException - { - return map.getKey(prefix); - } - - public Collection getPrefixes(String namespaceURI) throws NamespaceException - { - return map.get(namespaceURI); - } - - public Collection getPrefixes() - { - return map.flatValues(); - } - - public Collection getURIs() - { - return map.keySet(); - } - -} \ No newline at end of file diff --git a/source/java/org/alfresco/service/namespace/QName.java b/source/java/org/alfresco/service/namespace/QName.java deleted file mode 100644 index be29b97ffe..0000000000 --- a/source/java/org/alfresco/service/namespace/QName.java +++ /dev/null @@ -1,507 +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.service.namespace; - -import java.io.Serializable; -import java.util.Collection; - -import org.alfresco.repo.domain.qname.NamespaceEntity; - -/** - * QName represents the qualified name of a Repository item. Each - * QName consists of a local name qualified by a namespace. - *

- * The {@link org.alfresco.service.namespace.QNamePattern QNamePattern} is implemented - * to allow instances of this class to be used for direct pattern matching where - * required on interfaces. - * - * @author David Caruana - * - */ -public final class QName implements QNamePattern, Serializable, Cloneable, Comparable -{ - private static final long serialVersionUID = 3977016258204348976L; - - private final String namespaceURI; // never null - private final String localName; // never null - private int hashCode; - private final String prefix; - - public static final char NAMESPACE_PREFIX = ':'; - public static final char NAMESPACE_BEGIN = '{'; - public static final char NAMESPACE_END = '}'; - public static final int MAX_LENGTH = 100; - - - /** - * Create a QName - * - * (With no prefix) - * - * @param namespaceURI the qualifying namespace (maybe null or empty string) - * @param localName the local name - * @return the QName - */ - public static QName createQName(String namespaceURI, String localName) - throws InvalidQNameException - { - if (localName == null || localName.length() == 0) - { - throw new InvalidQNameException("A QName must consist of a local name"); - } - return new QName(namespaceURI, localName, null); - } - - - /** - * Create a QName - * - * @param prefix namespace prefix (maybe null or empty string) - * @param localName local name - * @param prefixResolver lookup to resolve mappings between prefix and namespace - * @return the QName - */ - public static QName createQName(String prefix, String localName, NamespacePrefixResolver prefixResolver) - throws InvalidQNameException, NamespaceException - { - // Validate Arguments - if (localName == null || localName.length() == 0) - { - throw new InvalidQNameException("A QName must consist of a local name"); - } - if (prefixResolver == null) - { - throw new IllegalArgumentException("A Prefix Resolver must be specified"); - } - if (prefix == null) - { - prefix = NamespaceService.DEFAULT_PREFIX; - } - - // Calculate namespace URI and create QName - String uri = prefixResolver.getNamespaceURI(prefix); - if (uri == null) - { - throw new NamespaceException("Namespace prefix " + prefix + " is not mapped to a namespace URI"); - } - return new QName(uri, localName, prefix); - } - - - /** - * Create a QName (from prefix format) prefix:localName - * - * @param qname qualified name of the following format prefix:localName - * @param prefixResolver lookup to resolve mappings between prefix and namespace - * @return the QName - */ - public static QName createQName(String qname, NamespacePrefixResolver prefixResolver) - throws InvalidQNameException, NamespaceException - { - QName name = null; - if (qname != null) - { - int colonIndex = qname.indexOf(NAMESPACE_PREFIX); - String prefix = (colonIndex == -1) ? NamespaceService.DEFAULT_PREFIX : qname.substring(0, colonIndex); - String localName = (colonIndex == -1) ? qname : qname.substring(colonIndex +1); - name = createQName(prefix, localName, prefixResolver); - } - return name; - } - - - /** - * Create a QName from its internal string representation of the following format: - * - * {namespaceURI}localName - * - * @param qname the string representation of the QName - * @return the QName - * @throws IllegalArgumentException - * @throws InvalidQNameException - */ - public static QName createQName(String qname) - throws InvalidQNameException - { - if (qname == null || qname.length() == 0) - { - throw new InvalidQNameException("Argument qname is mandatory"); - } - - String namespaceURI = null; - String localName = null; - - // Parse namespace - int namespaceBegin = qname.indexOf(NAMESPACE_BEGIN); - int namespaceEnd = -1; - if (namespaceBegin != -1) - { - if (namespaceBegin != 0) - { - throw new InvalidQNameException("QName '" + qname + "' must start with a namespaceURI"); - } - namespaceEnd = qname.indexOf(NAMESPACE_END, namespaceBegin + 1); - if (namespaceEnd == -1) - { - throw new InvalidQNameException("QName '" + qname + "' is missing the closing namespace " + NAMESPACE_END + " token"); - } - namespaceURI = qname.substring(namespaceBegin + 1, namespaceEnd); - } - - // Parse name - localName = qname.substring(namespaceEnd + 1); - if (localName == null || localName.length() == 0) - { - throw new InvalidQNameException("QName '" + qname + "' must consist of a local name"); - } - - // Construct QName - return new QName(namespaceURI, localName, null); - } - - - /** - * Create a valid local name from the specified name - * - * @param name name to create valid local name from - * @return valid local name - */ - public static String createValidLocalName(String name) - { - // Validate length - if (name == null || name.length() == 0) - { - throw new IllegalArgumentException("Local name cannot be null or empty."); - } - if (name.length() > MAX_LENGTH) - { - name = name.substring(0, MAX_LENGTH); - } - - return name; - } - - - /** - * Create a QName - * - * @param qname qualified name of the following format prefix:localName - * @return string array where index 0 => prefix and index 1 => local name - */ - public static String[] splitPrefixedQName(String qname) - throws InvalidQNameException, NamespaceException - { - if (qname != null) - { - int colonIndex = qname.indexOf(NAMESPACE_PREFIX); - String prefix = (colonIndex == -1) ? NamespaceService.DEFAULT_PREFIX : qname.substring(0, colonIndex); - String localName = (colonIndex == -1) ? qname : qname.substring(colonIndex +1); - return new String[] { prefix, localName }; - } - return null; - } - - - /** - * Construct QName - * - * @param namespace qualifying namespace (maybe null or empty string) - * @param name qualified name - * @param prefix prefix (maybe null or empty string) - */ - private QName(String namespace, String name, String prefix) - { - this.namespaceURI = ((namespace == null) || (namespace.equals(NamespaceEntity.EMPTY_URI_SUBSTITUTE))) ? NamespaceService.DEFAULT_URI : namespace; - this.prefix = prefix; - this.localName = name; - this.hashCode = 0; - } - - @Override - public Object clone() throws CloneNotSupportedException - { - return super.clone(); - } - - /** - * Gets the name - * - * @return the name - */ - public String getLocalName() - { - return this.localName; - } - - - /** - * Gets the namespace - * - * @return the namespace (empty string when not specified, but never null) - */ - public String getNamespaceURI() - { - return this.namespaceURI; - } - - - /** - * Gets a prefix resolved version of this QName - * - * @param resolver namespace prefix resolver - * @return QName with prefix resolved - */ - public QName getPrefixedQName(NamespacePrefixResolver resolver) - { - Collection prefixes = resolver.getPrefixes(namespaceURI); - if (prefixes.size() == 0) - { - throw new NamespaceException("A namespace prefix is not registered for uri " + namespaceURI); - } - String resolvedPrefix = prefixes.iterator().next(); - if (prefix != null && prefix.equals(resolvedPrefix)) - { - return this; - } - return new QName(namespaceURI, localName, resolvedPrefix); - } - - - /** - * Two QNames are equal only when both their name and namespace match. - * - * Note: The prefix is ignored during the comparison. - */ - public boolean equals(Object object) - { - if (this == object) - { - return true; - } - if (object instanceof QName) - { - QName other = (QName)object; - // namespaceURI and localname are not allowed to be null - return (this.localName.equals(other.localName) && - this.namespaceURI.equals(other.namespaceURI)); - } - return false; - } - - /** - * Performs a direct comparison between qnames. - * - * @see #equals(Object) - */ - public boolean isMatch(QName qname) - { - return this.equals(qname); - } - - /** - * Calculate hashCode. Follows pattern used by String where hashCode is - * cached (QName is immutable). - */ - public int hashCode() - { - if (this.hashCode == 0) - { - // the hashcode assignment is atomic - it is only an integer - this.hashCode = ((37 * localName.hashCode()) + namespaceURI.hashCode()); - } - return this.hashCode; - } - - - /** - * Render string representation of QName using format: - * - * {namespace}name - * - * @return the string representation - */ - public String toString() - { - return new StringBuilder(80).append(NAMESPACE_BEGIN) - .append(namespaceURI) - .append(NAMESPACE_END) - .append(localName).toString(); - } - - /** - * Uses the {@link #getNamespaceURI() namespace URI} and then the {@link #getLocalName() localname} - * to do the comparison i.e. the comparison is alphabetical. - */ - public int compareTo(QName qname) - { - int namespaceComparison = this.namespaceURI.compareTo(qname.namespaceURI); - if (namespaceComparison != 0) - { - return namespaceComparison; - } - // Namespaces are the same. Do comparison on localname - return this.localName.compareTo(qname.localName); - } - - - /** - * Render string representation of QName using format: - * - * prefix:name - * - * @return the string representation - */ - public String toPrefixString() - { - return (prefix == null) ? localName : prefix + NAMESPACE_PREFIX + localName; - } - - - /** - * Getter version of toPrefixString() - * - * @return the string representation of QName - */ - public String getPrefixString() - { - return toPrefixString(); - } - - - /** - * Render string representation of QName using format: - * - * prefix:name - * - * according to namespace prefix mappings of specified namespace resolver. - * - * @param prefixResolver namespace prefix resolver - * - * @return the string representation - */ - public String toPrefixString(NamespacePrefixResolver prefixResolver) - { - Collection prefixes = prefixResolver.getPrefixes(namespaceURI); - if (prefixes.size() == 0) - { - throw new NamespaceException("A namespace prefix is not registered for uri " + namespaceURI); - } - String prefix = prefixes.iterator().next(); - if (prefix.equals(NamespaceService.DEFAULT_PREFIX)) - { - return localName; - } - else - { - return prefix + NAMESPACE_PREFIX + localName; - } - } - - - /** - * Creates a QName representation for the given String. If the String has no namespace the Alfresco namespace is - * added. If the String has a prefix an attempt to resolve the prefix to the full URI will be made. - * - * @param str The string to convert - * @return A QName representation of the given string - */ - public static QName resolveToQName(NamespacePrefixResolver prefixResolver, String str) - { - QName qname = null; - - if (str == null || str.length() == 0) - { - throw new IllegalArgumentException("str parameter is mandatory"); - } - - if (str.charAt(0) == (NAMESPACE_BEGIN)) - { - // create QName directly - qname = createQName(str); - } - else if (str.indexOf(NAMESPACE_PREFIX) != -1) - { - // extract the prefix and try and resolve using the - // namespace service - int end = str.indexOf(NAMESPACE_PREFIX); - String prefix = str.substring(0, end); - String localName = str.substring(end + 1); - String uri = prefixResolver.getNamespaceURI(prefix); - - if (uri != null) - { - qname = createQName(uri, localName); - } - } - else - { - // there's no namespace so prefix with Alfresco's Content Model - qname = createQName(NamespaceService.CONTENT_MODEL_1_0_URI, str); - } - - return qname; - } - - - /** - * Creates a string representation of a QName for the given string. If the given string already has a namespace, - * either a URL or a prefix, nothing the given string is returned. If it does not have a namespace the Alfresco - * namespace is added. - * - * @param str - * The string to convert - * - * @return A QName String representation of the given string - */ - public static String resolveToQNameString(NamespacePrefixResolver prefixResolver, String str) - { - String result = str; - - if (str == null || str.length() == 0) - { - throw new IllegalArgumentException("str parameter is mandatory"); - } - - if (str.charAt(0) != NAMESPACE_BEGIN) - { - if (str.indexOf(NAMESPACE_PREFIX) != -1) - { - // get the prefix and resolve to the uri - int end = str.indexOf(NAMESPACE_PREFIX); - String prefix = str.substring(0, end); - String localName = str.substring(end + 1); - String uri = prefixResolver.getNamespaceURI(prefix); - - if (uri != null) - { - result = new StringBuilder(64).append(NAMESPACE_BEGIN).append(uri).append(NAMESPACE_END) - .append(localName).toString(); - } - } - else - { - // there's no namespace so prefix with Alfresco's Content Model - result = new StringBuilder(64).append(NAMESPACE_BEGIN).append(NamespaceService.CONTENT_MODEL_1_0_URI) - .append(NAMESPACE_END).append(str).toString(); - } - } - - return result; - } -} diff --git a/source/java/org/alfresco/service/namespace/QNameMap.java b/source/java/org/alfresco/service/namespace/QNameMap.java deleted file mode 100644 index 5c48a4c17d..0000000000 --- a/source/java/org/alfresco/service/namespace/QNameMap.java +++ /dev/null @@ -1,199 +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.service.namespace; - -import java.io.Serializable; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * A Map that holds as it's key a QName stored in it's internal String representation. - * Calls to get and put automatically map the key to and from the QName representation. - * - * @author gavinc - */ -public class QNameMap implements Map, Cloneable, Serializable -{ - private static final long serialVersionUID = -6578946123712939602L; - - protected static Log logger = LogFactory.getLog(QNameMap.class); - protected Map contents = new HashMap(16, 1.0f); - protected NamespacePrefixResolverProvider provider = null; - - - /** - * Constructor - * - * @param provider Mandatory NamespacePrefixResolverProvider helper - */ - public QNameMap(NamespacePrefixResolverProvider provider) - { - if (provider == null) - { - throw new IllegalArgumentException("NamespacePrefixResolverProvider is mandatory."); - } - this.provider = provider; - } - - /** - * Constructor for Serialization mechanism - */ - protected QNameMap() - { - super(); - } - - - /** - * Helper to return a NamespacePrefixResolver instance - should -always- be used - * rather than holding onto a reference on the heap. - * - * @return NamespacePrefixResolver - */ - protected final NamespacePrefixResolver getResolver() - { - return this.provider.getNamespacePrefixResolver(); - } - - /** - * @see java.util.Map#size() - */ - public final int size() - { - return this.contents.size(); - } - - /** - * @see java.util.Map#isEmpty() - */ - public boolean isEmpty() - { - return this.contents.isEmpty(); - } - - /** - * @see java.util.Map#containsKey(java.lang.Object) - */ - public boolean containsKey(Object key) - { - return (this.contents.containsKey(QName.resolveToQNameString(getResolver(), key.toString()))); - } - - /** - * @see java.util.Map#containsValue(java.lang.Object) - */ - public boolean containsValue(Object value) - { - return this.contents.containsValue(value); - } - - /** - * @see java.util.Map#get(java.lang.Object) - */ - public Object get(Object key) - { - String qnameKey = QName.resolveToQNameString(getResolver(), key.toString()); - Object obj = this.contents.get(qnameKey); - - return obj; - } - - /** - * @see java.util.Map#put(K, V) - */ - public Object put(Object key, Object value) - { - return this.contents.put(QName.resolveToQNameString(getResolver(), key.toString()), value); - } - - /** - * @see java.util.Map#remove(java.lang.Object) - */ - public Object remove(Object key) - { - return this.contents.remove(QName.resolveToQNameString(getResolver(), key.toString())); - } - - /** - * @see java.util.Map#putAll(java.util.Map) - */ - public void putAll(Map t) - { - for (Object key : t.keySet()) - { - this.put(key, t.get(key)); - } - } - - /** - * @see java.util.Map#clear() - */ - public void clear() - { - this.contents.clear(); - } - - /** - * @see java.util.Map#keySet() - */ - public Set keySet() - { - return this.contents.keySet(); - } - - /** - * @see java.util.Map#values() - */ - public Collection values() - { - return this.contents.values(); - } - - /** - * @see java.util.Map#entrySet() - */ - public Set entrySet() - { - return this.contents.entrySet(); - } - - /** - * Override Object.toString() to provide useful debug output - */ - public String toString() - { - return this.contents.toString(); - } - - /** - * Shallow copy the map by copying keys and values into a new QNameMap - */ - public Object clone() - { - QNameMap map = new QNameMap(provider); - map.putAll(this); - - return map; - } -} diff --git a/source/java/org/alfresco/service/namespace/QNamePattern.java b/source/java/org/alfresco/service/namespace/QNamePattern.java deleted file mode 100644 index c57d72a7ad..0000000000 --- a/source/java/org/alfresco/service/namespace/QNamePattern.java +++ /dev/null @@ -1,43 +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.service.namespace; - - -/** - * Provides pattern matching against {@link org.alfresco.service.namespace.QName qnames}. - *

- * Implementations will use different mechanisms to match against the - * {@link org.alfresco.service.namespace.QName#getNamespaceURI() namespace} and - * {@link org.alfresco.service.namespace.QName#getLocalName()() localname}. - * - * @see org.alfresco.service.namespace.QName - * - * @author Derek Hulley - */ -public interface QNamePattern -{ - /** - * Checks if the given qualified name matches the pattern represented - * by this instance - * - * @param qname the instance to check - * @return Returns true if the qname matches this pattern - */ - public boolean isMatch(QName qname); -} diff --git a/source/java/org/alfresco/service/namespace/QNamePatternTest.java b/source/java/org/alfresco/service/namespace/QNamePatternTest.java deleted file mode 100644 index 933aa016de..0000000000 --- a/source/java/org/alfresco/service/namespace/QNamePatternTest.java +++ /dev/null @@ -1,73 +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.service.namespace; - - -import junit.framework.TestCase; - -/** - * Tests the various implementations of the - * {@link org.alfresco.service.namespace.QNamePattern}. - * - * @author Derek Hulley - */ -public class QNamePatternTest extends TestCase -{ - private static final String TEST_NAMESPACE = "http://www.alfresco.org/QNamePatternTest"; - - QName check1; - QName check2; - QName check3; - - public QNamePatternTest(String name) - { - super(name); - } - - public void setUp() throws Exception - { - check1 = QName.createQName(null, "ABC"); - check2 = QName.createQName(TEST_NAMESPACE, "XYZ"); - check3 = QName.createQName(TEST_NAMESPACE, "ABC"); - } - - public void testSimpleQNamePattern() throws Exception - { - QNamePattern pattern = QName.createQName(TEST_NAMESPACE, "ABC"); - - // check - assertFalse("Simple match failed: " + check1, pattern.isMatch(check1)); - assertFalse("Simple match failed: " + check2, pattern.isMatch(check2)); - assertTrue("Simple match failed: " + check3, pattern.isMatch(check3)); - } - - public void testRegexQNamePatternMatcher() throws Exception - { - QNamePattern pattern = new RegexQNamePattern(".*alfresco.*", "A.?C"); - - // check - assertFalse("Regex match failed: " + check1, pattern.isMatch(check1)); - assertFalse("Regex match failed: " + check2, pattern.isMatch(check2)); - assertTrue("Regex match failed: " + check3, pattern.isMatch(check3)); - - assertTrue("All match failed: " + check1, RegexQNamePattern.MATCH_ALL.isMatch(check1)); - assertTrue("All match failed: " + check2, RegexQNamePattern.MATCH_ALL.isMatch(check2)); - assertTrue("All match failed: " + check3, RegexQNamePattern.MATCH_ALL.isMatch(check3)); - } -} diff --git a/source/java/org/alfresco/service/namespace/QNameTest.java b/source/java/org/alfresco/service/namespace/QNameTest.java deleted file mode 100644 index d6a088cd29..0000000000 --- a/source/java/org/alfresco/service/namespace/QNameTest.java +++ /dev/null @@ -1,264 +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.service.namespace; - -import java.util.Collection; -import java.util.HashSet; - -import junit.framework.TestCase; - - - -/** - * @see org.alfresco.service.namespace.QName - * - * @author David Caruana - */ -public class QNameTest extends TestCase -{ - - public QNameTest(String name) - { - super(name); - } - - - public void testInvalidQName() throws Exception - { - try - { - QName qname = QName.createQName(""); - fail("Missing local name was not caught"); - } - catch (InvalidQNameException e) - { - } - - try - { - QName qname = QName.createQName("invalid{}name"); - fail("Namespace not at start was not caught"); - } - catch (InvalidQNameException e) - { - } - - try - { - QName qname = QName.createQName("{name"); - fail("Missing closing namespace token was not caught"); - } - catch (InvalidQNameException e) - { - } - - try - { - QName qname = QName.createQName("{}"); - fail("Missing local name after namespace was not caught"); - } - catch (InvalidQNameException e) - { - } - - try - { - QName qname = QName.createQName("{}name"); - } - catch (InvalidQNameException e) - { - fail("Empty namespace is valid"); - } - - try - { - QName qname = QName.createQName("{namespace}name"); - assertEquals("namespace", qname.getNamespaceURI()); - assertEquals("name", qname.getLocalName()); - } - catch (InvalidQNameException e) - { - fail("Valid namespace has been thrown out"); - } - - try - { - QName qname = QName.createQName((String) null, (String) null); - fail("Null name was not caught"); - } - catch (InvalidQNameException e) - { - } - - try - { - QName qname = QName.createQName((String) null, ""); - fail("Empty name was not caught"); - } - catch (InvalidQNameException e) - { - } - - } - - - public void testConstruction() - { - QName qname1 = QName.createQName("namespace1", "name1"); - assertEquals("namespace1", qname1.getNamespaceURI()); - assertEquals("name1", qname1.getLocalName()); - - QName qname2 = QName.createQName("{namespace2}name2"); - assertEquals("namespace2", qname2.getNamespaceURI()); - assertEquals("name2", qname2.getLocalName()); - - QName qname3 = QName.createQName(null, "name3"); - assertEquals("", qname3.getNamespaceURI()); - - QName qname4 = QName.createQName("", "name4"); - assertEquals("", qname4.getNamespaceURI()); - - QName qname5 = QName.createQName("{}name5"); - assertEquals("", qname5.getNamespaceURI()); - - QName qname6 = QName.createQName("name6"); - assertEquals("", qname6.getNamespaceURI()); - } - - - public void testStringRepresentation() - { - QName qname1 = QName.createQName("namespace", "name1"); - assertEquals("{namespace}name1", qname1.toString()); - - QName qname2 = QName.createQName("", "name2"); - assertEquals("{}name2", qname2.toString()); - - QName qname3 = QName.createQName("{namespace}name3"); - assertEquals("{namespace}name3", qname3.toString()); - - QName qname4 = QName.createQName("{}name4"); - assertEquals("{}name4", qname4.toString()); - - QName qname5 = QName.createQName("name5"); - assertEquals("{}name5", qname5.toString()); - } - - - public void testEquality() - { - QName qname1 = QName.createQName("namespace", "name"); - QName qname2 = QName.createQName("namespace", "name"); - QName qname3 = QName.createQName("{namespace}name"); - assertEquals(qname1, qname2); - assertEquals(qname1, qname3); - assertEquals(qname1.hashCode(), qname2.hashCode()); - assertEquals(qname1.hashCode(), qname3.hashCode()); - - QName qname4 = QName.createQName("", "name"); - QName qname5 = QName.createQName("", "name"); - QName qname6 = QName.createQName(null, "name"); - assertEquals(qname4, qname5); - assertEquals(qname4, qname6); - assertEquals(qname4.hashCode(), qname5.hashCode()); - assertEquals(qname4.hashCode(), qname6.hashCode()); - - QName qname7 = QName.createQName("namespace", "name"); - QName qname8 = QName.createQName("namespace", "differentname"); - assertFalse(qname7.equals(qname8)); - assertFalse(qname7.hashCode() == qname8.hashCode()); - - QName qname9 = QName.createQName("namespace", "name"); - QName qname10 = QName.createQName("differentnamespace", "name"); - assertFalse(qname9.equals(qname10)); - assertFalse(qname9.hashCode() == qname10.hashCode()); - } - - - public void testPrefix() - { - try - { - QName noResolver = QName.createQName(NamespaceService.ALFRESCO_PREFIX, "alfresco prefix", null); - fail("Null resolver was not caught"); - } - catch (IllegalArgumentException e) - { - } - - NamespacePrefixResolver mockResolver = new MockNamespacePrefixResolver(); - QName qname1 = QName.createQName(NamespaceService.ALFRESCO_PREFIX, "alfresco prefix", mockResolver); - assertEquals(NamespaceService.ALFRESCO_URI, qname1.getNamespaceURI()); - QName qname2 = QName.createQName("", "default prefix", mockResolver); - assertEquals(NamespaceService.DEFAULT_URI, qname2.getNamespaceURI()); - QName qname3 = QName.createQName(null, "null default prefix", mockResolver); - assertEquals(NamespaceService.DEFAULT_URI, qname3.getNamespaceURI()); - - try - { - QName qname4 = QName.createQName("garbage", "garbage prefix", mockResolver); - fail("Invalid Prefix was not caught"); - } - catch (NamespaceException e) - { - } - } - - - private static class MockNamespacePrefixResolver - implements NamespacePrefixResolver - { - - public String getNamespaceURI(String prefix) - { - if (prefix.equals(NamespaceService.DEFAULT_PREFIX)) - { - return NamespaceService.DEFAULT_URI; - } - else if (prefix.equals(NamespaceService.ALFRESCO_PREFIX)) - { - return NamespaceService.ALFRESCO_URI; - } - throw new NamespaceException("Prefix " + prefix + " not registered"); - } - - public Collection getPrefixes(String namespaceURI) - { - throw new NamespaceException("URI " + namespaceURI + " not registered"); - } - - public Collection getPrefixes() - { - HashSet prefixes = new HashSet(); - prefixes.add(NamespaceService.DEFAULT_PREFIX); - prefixes.add(NamespaceService.ALFRESCO_PREFIX); - return prefixes; - } - - public Collection getURIs() - { - HashSet uris = new HashSet(); - uris.add(NamespaceService.DEFAULT_URI); - uris.add(NamespaceService.ALFRESCO_URI); - return uris; - } - - } - -} diff --git a/source/java/org/alfresco/service/namespace/RegexQNamePattern.java b/source/java/org/alfresco/service/namespace/RegexQNamePattern.java deleted file mode 100644 index 1afd60b20c..0000000000 --- a/source/java/org/alfresco/service/namespace/RegexQNamePattern.java +++ /dev/null @@ -1,140 +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.service.namespace; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - - -/** - * Provides matching between {@link org.alfresco.service.namespace.QName qnames} using - * regular expression matching. - *

- * A simple {@link #MATCH_ALL convenience} pattern matcher is also provided that - * will match any qname. - * - * @see java.lang.String#matches(java.lang.String) - * - * @author Derek Hulley - */ -public class RegexQNamePattern implements QNamePattern -{ - private static final Log logger = LogFactory.getLog(RegexQNamePattern.class); - - /** A helper pattern matcher that will match all qnames */ - public static final QNamePattern MATCH_ALL = new QNamePattern() - { - public boolean isMatch(QName qname) - { - return true; - } - - @Override - public boolean equals(Object obj) - { - // this is equal if the object's class is the same as this instances - if (obj == null) - { - return false; - } - else if (obj.getClass().equals(this.getClass())) - { - return true; - } - else - { - return false; - } - } - - }; - - private String namespaceUriPattern; - private String localNamePattern; - private String combinedPattern; - - /** - * @param namespaceUriPattern a regex pattern that will be applied to the namespace URI - * @param localNamePattern a regex pattern that will be applied to the local name - */ - public RegexQNamePattern(String namespaceUriPattern, String localNamePattern) - { - this.namespaceUriPattern = namespaceUriPattern; - this.localNamePattern = localNamePattern; - this.combinedPattern = null; - } - - /** - * @param combinedPattern a regex pattern that will be applied to the full qname - * string representation - * - * @see QName#toString() - */ - public RegexQNamePattern(String combinedPattern) - { - this.combinedPattern = combinedPattern; - this.namespaceUriPattern = null; - this.localNamePattern = null; - } - - public String toString() - { - StringBuilder sb = new StringBuilder(56); - sb.append("RegexQNamePattern["); - if (combinedPattern != null) - { - sb.append(" pattern=").append(combinedPattern); - } - else - { - sb.append(" uri=").append(namespaceUriPattern); - sb.append(", localname=").append(localNamePattern); - } - sb.append(" ]"); - return sb.toString(); - } - - /** - * @param qname the value to check against this pattern - * @return Returns true if the regex pattern provided match thos of the provided qname - */ - public boolean isMatch(QName qname) - { - boolean match = false; - if (combinedPattern != null) - { - String qnameStr = qname.toString(); - match = qnameStr.matches(combinedPattern); - } - else - { - match = (qname.getNamespaceURI().matches(namespaceUriPattern) && - qname.getLocalName().matches(localNamePattern)); - } - // done - if (logger.isDebugEnabled()) - { - logger.debug("QName matching: \n" + - " matcher: " + this + "\n" + - " qname: " + qname + "\n" + - " result: " + match); - } - return match; - } -} diff --git a/source/java/org/alfresco/util/ISO9075.java b/source/java/org/alfresco/util/ISO9075.java deleted file mode 100644 index 7018fe9b6a..0000000000 --- a/source/java/org/alfresco/util/ISO9075.java +++ /dev/null @@ -1,228 +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.util; - -import java.util.Collection; - -import org.alfresco.service.namespace.NamespaceException; -import org.alfresco.service.namespace.NamespacePrefixResolver; -import org.alfresco.service.namespace.NamespaceService; -import org.alfresco.service.namespace.QName; - -import org.apache.xerces.util.XMLChar; - -/** - * Support for the ISO 9075 encoding of XML element names. - * - * @author Andy Hind - */ -public class ISO9075 -{ - /* - * Mask for hex encoding - */ - private static final int MASK = (1 << 4) - 1; - - /* - * Digits used string encoding - */ - private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', - 'f' }; - - /** - * Private constructor - * - */ - private ISO9075() - { - super(); - } - - /** - * Encode a string according to ISO 9075 - * - * @param toEncode - * @return - */ - public static String encode(String toEncode) - { - if ((toEncode == null) || (toEncode.length() == 0)) - { - return toEncode; - } - else if (XMLChar.isValidName(toEncode) && (toEncode.indexOf("_x") == -1) && (toEncode.indexOf(':') == -1)) - { - return toEncode; - } - else - { - StringBuilder builder = new StringBuilder(toEncode.length()); - for (int i = 0; i < toEncode.length(); i++) - { - char c = toEncode.charAt(i); - // First requires special test - if (i == 0) - { - if (XMLChar.isNCNameStart(c)) - { - // The first character may be the _ at the start of an - // encoding pattern - if (matchesEncodedPattern(toEncode, i)) - { - // Encode the first _ - encode('_', builder); - } - else - { - // Just append - builder.append(c); - } - } - else - { - // Encode an invalid start character for an XML element - // name. - encode(c, builder); - } - } - else if (!XMLChar.isNCName(c)) - { - encode(c, builder); - } - else - { - if (matchesEncodedPattern(toEncode, i)) - { - // '_' must be encoded - encode('_', builder); - } - else - { - builder.append(c); - } - } - } - return builder.toString(); - } - - } - - private static boolean matchesEncodedPattern(String string, int position) - { - return (string.length() >= position + 6) - && (string.charAt(position) == '_') && (string.charAt(position + 1) == 'x') - && isHexChar(string.charAt(position + 2)) && isHexChar(string.charAt(position + 3)) - && isHexChar(string.charAt(position + 4)) && isHexChar(string.charAt(position + 5)) - && (string.charAt(position + 6) == '_'); - } - - private static boolean isHexChar(char c) - { - switch (c) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - case 'a': - case 'b': - case 'c': - case 'd': - case 'e': - case 'f': - case 'A': - case 'B': - case 'C': - case 'D': - case 'E': - case 'F': - return true; - default: - return false; - } - } - - public static String decode(String toDecode) - { - if ((toDecode == null) || (toDecode.length() < 7) || (toDecode.indexOf("_x") < 0)) - { - return toDecode; - } - StringBuffer decoded = new StringBuffer(); - for (int i = 0, l = toDecode.length(); i < l; i++) - { - if (matchesEncodedPattern(toDecode, i)) - { - decoded.append(((char) Integer.parseInt(toDecode.substring(i + 2, i + 6), 16))); - i += 6;// then one added for the loop to mkae the length of 7 - } - else - { - decoded.append(toDecode.charAt(i)); - } - } - return decoded.toString(); - } - - private static void encode(char c, StringBuilder builder) - { - char[] buf = new char[] { '_', 'x', '0', '0', '0', '0', '_' }; - int charPos = 6; - do - { - buf[--charPos] = DIGITS[c & MASK]; - c >>>= 4; - } - while (c != 0); - builder.append(buf); - } - - public static String getXPathName(QName qName, NamespacePrefixResolver nspr) - { - - Collection prefixes = nspr.getPrefixes(qName.getNamespaceURI()); - if (prefixes.size() == 0) - { - throw new NamespaceException("A namespace prefix is not registered for uri " + qName.getNamespaceURI()); - } - String prefix = prefixes.iterator().next(); - if (prefix.equals(NamespaceService.DEFAULT_PREFIX)) - { - return ISO9075.encode(qName.getLocalName()); - } - else - { - return prefix + ":" + ISO9075.encode(qName.getLocalName()); - } - - } - - public static String getXPathName(QName qName) - { - - return "{" + qName.getNamespaceURI() + "}" + ISO9075.encode(qName.getLocalName()); - - } -} diff --git a/source/java/org/alfresco/util/ISO9075Test.java b/source/java/org/alfresco/util/ISO9075Test.java deleted file mode 100644 index 1a2ffc913e..0000000000 --- a/source/java/org/alfresco/util/ISO9075Test.java +++ /dev/null @@ -1,131 +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.util; - -import junit.framework.TestCase; - -public class ISO9075Test extends TestCase -{ - - public ISO9075Test() - { - super(); - } - - public ISO9075Test(String arg0) - { - super(arg0); - } - - public void testEncoding() - { - assertEquals("My2Documents", ISO9075.encode("My2Documents")); - assertEquals("My_x002f_Documents", ISO9075.encode("My/Documents")); - assertEquals("My_Documents", ISO9075.encode("My_Documents")); - assertEquals("My_x0020_Documents", ISO9075.encode("My Documents")); - assertEquals("My_x0020Documents", ISO9075.encode("My_x0020Documents")); - assertEquals("My_x005f_x0020_Documents", ISO9075.encode("My_x0020_Documents")); - assertEquals("_x005f_x0020_Documents", ISO9075.encode("_x0020_Documents")); - assertEquals("_x0040__x005f_x0020_Documents", ISO9075.encode("@_x0020_Documents")); - assertEquals("Andy_x0027_s_x0020_Bits_x0020__x0026__x0020_Bobs_x0020__xabcd__x005c_", ISO9075 - .encode("Andy's Bits & Bobs \uabcd\\")); - assertEquals( - "_x0020__x0060__x00ac__x00a6__x0021__x0022__x00a3__x0024__x0025__x005e__x0026__x002a__x0028__x0029_-__x003d__x002b__x0009__x000a__x005c__x0000__x005b__x005d__x007b__x007d__x003b__x0027__x0023__x003a__x0040__x007e__x002c_._x002f__x003c__x003e__x003f__x005c__x007c_", - ISO9075.encode(" `\u00ac\u00a6!\"\u00a3$%^&*()-_=+\t\n\\\u0000[]{};'#:@~,./<>?\\|")); - assertEquals("\u0123_x4567_\u8900_xabcd__xefff__xT65A_", ISO9075 - .encode("\u0123\u4567\u8900\uabcd\uefff_xT65A_")); - assertEquals("_x003a_", ISO9075.encode(":")); - } - - public void testDeEncoding() - { - assertEquals("MyDocuments", ISO9075.decode("MyDocuments")); - assertEquals("My_Documents", ISO9075.decode("My_Documents")); - assertEquals("My Documents", ISO9075.decode("My_x0020_Documents")); - assertEquals("My_x0020Documents", ISO9075.decode("My_x0020Documents")); - assertEquals("My_x0020_Documents", ISO9075.decode("My_x005f_x0020_Documents")); - assertEquals("_x0020_Documents", ISO9075.decode("_x005f_x0020_Documents")); - assertEquals("@_x0020_Documents", ISO9075.decode("_x0040__x005f_x0020_Documents")); - assertEquals("Andy's Bits & Bobs \uabcd", ISO9075 - .decode("Andy_x0027_s_x0020_Bits_x0020__x0026__x0020_Bobs_x0020__xabcd_")); - assertEquals("Andy's Bits & Bobs \uabcd\\", ISO9075 - .decode("Andy_x0027_s_x0020_Bits_x0020__x0026__x0020_Bobs_x0020__xabcd__x005c_")); - assertEquals( - " `\u00ac\u00a6!\"\u00a3$%^&*()-_=+\t\n\\\u0000[]{};'#:@~,./<>?\\|", - ISO9075 - .decode("_x0020__x0060__x00ac__x00a6__x0021__x0022__x00a3__x0024__x0025__x005e__x0026__x002a__x0028__x0029_-__x003d__x002b__x0009__x000a__x005c__x0000__x005b__x005d__x007b__x007d__x003b__x0027__x0023__x003a__x0040__x007e__x002c_._x002f__x003c__x003e__x003f__x005c__x007c_")); - assertEquals("\u0123\u4567\u8900\uabcd\uefff_xT65A_", ISO9075 - .decode("\u0123_x4567_\u8900_xabcd__xefff__xT65A_")); - } - - public void testDeEncodingUpperCase() - { - - assertEquals("My_x0020_Documents", ISO9075.decode("My_x005F_x0020_Documents")); - assertEquals("_x0020_Documents", ISO9075.decode("_x005F_x0020_Documents")); - assertEquals("@_x0020_Documents", ISO9075.decode("_x0040__x005F_x0020_Documents")); - assertEquals("Andy's Bits & Bobs \uabcd\\", ISO9075 - .decode("Andy_x0027_s_x0020_Bits_x0020__x0026__x0020_Bobs_x0020__xabcd__x005C_")); - assertEquals( - " `\u00ac\u00a6!\"\u00a3$%^&*()-_=+\t\n\\\u0000[]{};'#:@~,./<>?\\|", - ISO9075 - .decode("_x0020__x0060__x00AC__x00A6__x0021__x0022__x00A3__x0024__x0025__x005E__x0026__x002A__x0028__x0029_-__x003D__x002B__x0009__x000A__x005C__x0000__x005B__x005D__x007B__x007D__x003B__x0027__x0023__x003A__x0040__x007E__x002C_._x002F__x003C__x003E__x003F__x005C__x007C_")); - assertEquals("\u0123\u4567\u8900\uabcd\uefff_xT65A_", ISO9075 - .decode("\u0123_x4567_\u8900_xABCD__xEFFF__xT65A_")); - } - - public void testRoundTrip1() - { - assertEquals("MyDocuments", ISO9075.decode(ISO9075.encode("MyDocuments"))); - assertEquals("My_Documents", ISO9075.decode(ISO9075.encode("My_Documents"))); - assertEquals("My Documents", ISO9075.decode(ISO9075.encode("My Documents"))); - assertEquals("My_x0020Documents", ISO9075.decode(ISO9075.encode("My_x0020Documents"))); - assertEquals("My_x0020_Documents", ISO9075.decode(ISO9075.encode("My_x0020_Documents"))); - assertEquals("_x0020_Documents", ISO9075.decode(ISO9075.encode("_x0020_Documents"))); - assertEquals("@_x0020_Documents", ISO9075.decode(ISO9075.encode("@_x0020_Documents"))); - assertEquals("Andy's Bits & Bobs \uabcd", ISO9075.decode(ISO9075.encode("Andy's Bits & Bobs \uabcd"))); - assertEquals("Andy's Bits & Bobs \uabcd\\", ISO9075.decode(ISO9075.encode("Andy's Bits & Bobs \uabcd\\"))); - assertEquals( - " `\u00ac\u00a6!\"\u00a3$%^&*()-_=+\t\n\\\u0000[]{};'#:@~,./<>?\\|", - ISO9075.decode(ISO9075.encode(" `\u00ac\u00a6!\"\u00a3$%^&*()-_=+\t\n\\\u0000[]{};'#:@~,./<>?\\|"))); - assertEquals("\u0123\u4567\u8900\uabcd\uefff_xT65A_", ISO9075.decode(ISO9075.encode("\u0123\u4567\u8900\uabcd\uefff_xT65A_"))); - } - - public void testRoundTrip2() - { - assertEquals("MyDocuments", ISO9075.encode(ISO9075.decode("MyDocuments"))); - assertEquals("My_Documents", ISO9075.encode(ISO9075.decode("My_Documents"))); - assertEquals("My_x0020_Documents", ISO9075.encode(ISO9075.decode("My_x0020_Documents"))); - assertEquals("My_x0020Documents", ISO9075.encode(ISO9075.decode("My_x0020Documents"))); - assertEquals("My_x005f_x0020_Documents", ISO9075.encode(ISO9075.decode("My_x005f_x0020_Documents"))); - assertEquals("_x005f_x0020_Documents", ISO9075.encode(ISO9075.decode("_x005f_x0020_Documents"))); - assertEquals("_x0040__x005f_x0020_Documents", ISO9075.encode(ISO9075.decode("_x0040__x005f_x0020_Documents"))); - assertEquals("Andy_x0027_s_x0020_Bits_x0020__x0026__x0020_Bobs_x0020__xabcd_", ISO9075.encode(ISO9075 - .decode("Andy_x0027_s_x0020_Bits_x0020__x0026__x0020_Bobs_x0020__xabcd_"))); - assertEquals("Andy_x0027_s_x0020_Bits_x0020__x0026__x0020_Bobs_x0020__xabcd__x005c_", ISO9075.encode(ISO9075 - .decode("Andy_x0027_s_x0020_Bits_x0020__x0026__x0020_Bobs_x0020__xabcd__x005c_"))); - assertEquals( - "_x0020__x0060__x00ac__x00a6__x0021__x0022__x00a3__x0024__x0025__x005e__x0026__x002a__x0028__x0029_-__x003d__x002b__x0009__x000a__x005c__x0000__x005b__x005d__x007b__x007d__x003b__x0027__x0023__x003a__x0040__x007e__x002c_._x002f__x003c__x003e__x003f__x005c__x007c_", - ISO9075.encode(ISO9075 - .decode("_x0020__x0060__x00ac__x00a6__x0021__x0022__x00a3__x0024__x0025__x005e__x0026__x002a__x0028__x0029_-__x003d__x002b__x0009__x000a__x005c__x0000__x005b__x005d__x007b__x007d__x003b__x0027__x0023__x003a__x0040__x007e__x002c_._x002f__x003c__x003e__x003f__x005c__x007c_"))); - assertEquals("\u0123_x4567_\u8900_xabcd__xefff__xT65A_", ISO9075.encode(ISO9075 - .decode("\u0123_x4567_\u8900_xabcd__xefff__xT65A_"))); - } - -}