alfresco-community-repo/source/java/org/alfresco/repo/domain/propval/AbstractPropertyValueDAOImpl.java
Derek Hulley 4872eb9909 Merged BRANCHES/DEV/V3.3-DAO-REFACTOR-5 to HEAD:
20678: DAO5 branch: Preparation for merge back to HEAD
   20689: Merged DAO4 to DAO5
        - Removed all 'dbscripts/create/3.x/SomeDialect' and replaced with 'dbscripts/create/SomeDialect'
          DB create scripts are taken from latest DAO4
        - TODO: FixAuthoritiesCrcValuesPatch needs query implementation in PatchDAO
        Merged DAO3 to DAO4
           - Reapplied fixes for ALF-713 (race condition on Usages)
           19350: Merged BRANCHES/DEV/V3.3-DAO-REFACTOR-2 to BRANCHES/DEV/V3.3-DAO-REFACTOR-3:
               18939: SAIL-4 :2nd stage branch for DAO refactor off HEAD rev 18898
               18948: Merged V3.3-DAO-REFACTOR to V3.3-DAO-REFACTOR-2
                    18202: Dev branch for DAO refactor
                    18252: SAIL-233: QName.hbm.xml
                    18295: Added missing CREATE TABLE statements for QName-related code
                    18324: SAIL-234: Node.hbm.xml: Node aspects initial integration
                    18355: Added 'setValue' method to manually update the cached value
                    18356: MV property stressing lowered to speed test up
                    18357: SAIL-234: Node.hbm.xml
                    18376: Pulled all Alfresco-related create SQL into script
                    18389: SAIL-234: Permissions DAO refactor - initial checkpoint
                    18390: Formatting only (line-endings)
                    18400: SAIL-234: Node.hbm.xml
                    18418: SAIL-234: Node.hbm.xml: 'alf_node_assoc' CRUD
                    18429: SAIL-234: Node.hbm.xml: Cleaned out all Hibernate references to NodeAssocImpl
                    18457: SAIL-234: Permissions DAO refactor
               18959: Merged DEV/V3.3-DAO-REFACTOR to DEV/V3.3-DAO-REFACTOR-2
                    18479: SAIL-234: Node.hbm.xml - fix updateNode (missing id when saving oldDummyNode)
                    18482: SAIL-235: remove Permissions.hbm.xml
                    18517: SAIL-235: Permissions DAO refactor
                    18523: SAIL-234: Node.hbm.xml
                    18524: SAIL-235: Permissions DAO refactor
               18960: Merged DEV/V3.3-DAO-REFACTOR to DEV/V3.3-DAO-REFACTOR-2
                    18533: Flipped back to Windows line endings
                    18535: Formatting-only (eol)
                    18540: Formatting-only (eol)
                    18541: SAIL-235: Permissions DAO refactor
                    18543: SAIL-234: Node.hbm.xml: Start alf_store changes
                    18567: SAIL-235: Permissions DAO refactor
                    18596: SAIL-305:  Alfresco DDL - formatted/rationalized and added missing indexes & fk constraints
                    18603: SAIL-311: Minor cleanup for schema upgrade scripts (V3.3)
                    18604: SAIL-311: Remove empty dirs
                    18619: SAIL-274: Locale.hbm.xml
                    18621: Added method to create default ACL
                    18622: SAIL-234: Node.hbm.xml: Store, Transaction, Server and some node
                    18624: Formatting only (eol)
                    18631: SAIL-235: Permissions DAO refactor
                    18633: SAIL-235: Permissions DAO refactor - do not expose CRUD for AceContext (or AuthorityAlias) since currently unused
                    18639: getLocale(Locale) should return null if it doesn't exist
                    18640: SAIL-234 NodeDAO: More replacement of node queries and updates
                    18648: SAIL-310: Create SQL script for core repo tables (All DB ports)
                    18651: SAIL-234 NodeDAO: Moves across stores handle presence of target deleted nodes
               18961: Merged DEV/V3.3-DAO-REFACTOR to DEV/V3.3-DAO-REFACTOR-2
                    18658: SAIL-274 Locale DAO: Missing getValueKey() method
                    18662: SAIL-235: Permissions DAO refactor - further cleanup (of DbAccessControlList usage, including copyACLs)
                    18664: DB scripts porting for PostgreSQL finished.
                    18668: SAIL-234 Node DAO: Note in case Transaction Change ID is dropped from indexes
                    18669: SAIL-234 Node DAO: deleteNode and archive (store move) fixes
                    18672: DB scripts porting for Oracle finished. 
                    18675: SAIL-235: Permissions DAO refactor 
                    18677: DB scripts porting for DB2 finished.
               18964: Merged DEV/V3.3-DAO-REFACTOR to DEV/V3.3-DAO-REFACTOR-2
                    18687: Execute a callback with retries
                    18688: SAIL-234 Node DAO: Child association creation
                    18690: SAIL-234 Node DAO: Comment out raw creation of stores as it breaks subsequent bootstrap checks
                    18691: SAIL-234 Node DAO: More replacement of alf_child_assoc handling
                    18713: Commented about needing a more efficient removeChildAssociation method
                    18714: SAIL-234 Node DAO: Replaced queries on alf_child_assoc
                    18715: SAIL-234 Node DAO: More alf_child_assoc query replacement
                    18727: SAIL-234 Node DAO: alf_child_assoc queries complete
                    18737: SAIL-234 Node DAO: Tweaks to newNode and implemented prependPaths
                    18741: SAIL-234 and SAIL-334: Moved UsageDelta Hibernate code and queries over to UsageDeltaDAO
                    18748: SAIL-234 Node DAO: fix NPE (EditionServiceImplTest)
                    18769: SAIL-234 Node DAO: alf_node_properties ground work
                    18786: SAIL-234 Node DAO: alf_node_properties and cm:auditable properties
                    18810: Added EqualsHelper.getMapComparison
                    18813: TransactionalCache propagates cache clears and removals during rollback
                    18826: SAIL-234 Node DAO: Moved over sundry references to NodeDaoService to NodeDAO
                    18849: SAIL-237: UsageDelta.hbm.xml - eol formatting only (including removal of unwanted svn:eol-style=native property)
                    18869: SAIL-234 NodeDAO: Fixed more references to 'nodeDaoService'
                    18895: SAIL-234 NodeDAO: Queries for alf_transaction
                    18899: SAIL-234 Node DAO: Fixed bean fetching for 'nodeDAO'
                    18909: SAIL-234 NodeDAO: Fixes to getNodeRefStatus and various txn queries
                    18916: SAIL-234 NodeDAO: Fixed moveNode alf_child_assoc updates
                    18922: SAIL-235: DAO refactoring: Permission.hbm.xml
                    18930: SAIL-235: DAO refactoring: Permission.hbm.xml
                    18932: SAIL-234 NodeDAO: Fixing up gotchas, javadocs and some naming
                    18933: SAIL-234 NodeDAO: Minor neatening
                    18935: SAIL-234 Node DAO: Caches for ID to NodeRef and StoreRef
                    18936: EHCache config files line endings
                    18938: SAIL-237: Usage DAO refactor - initial checkpoint
                    18945: SAIL-235: DAO refactoring: Permission.hbm.xml. Move Node.
               18975: Fix for move-node ACL jiggery-pokery
               19067: SAIL-4: fix VersionHistoryImpl.getSuccessors (causing VersionServiceImplTest.testGetVersionHistorySameWorkspace failure)
               19068: SAIL-234: fix VersionMigratorTest.testMigrateOneVersion
               19074: SAIL-237: Usage DAO - update to common iBatis mapping pattern(s) to ease DB porting
               19076: SAIL-231: Activities DAO - update to common iBatis mapping pattern(s)
               19077: SAIL-232: AppliedPatch DAO - minor cleanup (comments & formatting only)
               19092: Merging HEAD to DEV/V3.3-DAO-REFACTOR-2
                     18973: Temporarily comment out AVMTestSuite and run AVM tests individually
                     19056: AVM unit test improvements
               19097: SAIL-235: DAO refactoring: Permission.hbm.xml: Additional index to support queries to find the id and acl id for the primary children of a node.
               19185: SAIL-238: Permissions DAO - (minor) update to common iBatis mapping pattern
               19289: SAIL-234 NodeDAO: Node cache replaces NodeRef cache
               19302: SAIL-234 Node DAO: Added cache for node properties
               19318: SAIL-4: AVM DAO - (minor) update to common iBatis mapping pattern
   20690: Merged BRANCHES/DEV/V3.3-DAO-REFACTOR-4 to BRANCHES/DEV/V3.3-DAO-REFACTOR-5:
        20063: (RECORD ONLY) DAO refactor branch V4
        20146: Merged BRANCHES/DEV/V3.3-DAO-REFACTOR-3 to BRANCHES/DEV/V3.3-DAO-REFACTOR-4:
             19401: SAIL-234 Node DAO: Fix permission service tests (setPrimaryChildrenSharedAclId needs to invalidate nodesCache)
             19428: Fixed TransactionalCache issue with null and NullValueMarker
             19429: Took empty cm:content creation out of FileFolderService#createImpl
             19430: SAIL-234 Node DAO: Tweaks around caching and cm:auditable
             19431: SAIL-4 DAO Refactor: Exception thrown when attempting writes in read-only txn have changed
             19436: SAIL-234 Node DAO: Fix NPE during cm:auditable update
             19475: Allow debugging of code without stepping into trivial stuff
             19476: Follow-up on 19429 by ensuring CIFS/FTP set a  mimetype on the ContentWriter
             19477: SAIL-234 Node DAO: Leverage DAO better for NodeService.addProperties
             19478: SAIL-234 NodeDAO: Added toString() for ParentAssocsInfo (cache value for parent assocs)
             19479: SAIL-234 Node DAO: Fixed for parent association and property caches
             19480: Made TransactionAwareSingleton bind-key a GUID
             19481: SAIL-234 Node DAO: Reinstated 100K collection property tests
             19482: SAIL-234 Node DAO: Node and property cache fixes highlighted by unit tests
             19483: SAIL-234 Node DAO: Start on NodeBulkLoader implementation
             19595: SAIL-234 Node DAO: Fix moveNode to detect cyclic relationship prior to updating ACLs for moved tree FileFolderServiceImplTest.testETHREEOH_3088_MoveIntoSelf)
        20147: Merged BRANCHES/DEV/V3.3-DAO-REFACTOR-3 to BRANCHES/DEV/V3.3-DAO-REFACTOR-4:
             19602: (RECORD ONLY) Reintegrated with HEAD up to rev 19433
             19621: (RECORD ONLY) SAIL-347
             19683: (RECORD ONLY) Reverse-merged 19621 for SAIL-347
             19722: (RECORD ONLY) Merged /alfresco/HEAD:r19434-19721
        20150: Merged BRANCHES/DEV/V3.3-DAO-REFACTOR-3 to BRANCHES/DEV/V3.3-DAO-REFACTOR-4:
             19741: Merged DEV\V3.3-DAO-REFACTOR-2 to DEV\V3.3-DAO-REFACTOR-3
                   19739: Extended "move" tests
             19743: Fix AuditableAspectTest.testAddAspect (to allow for node modified date tolerance)
             19748: Remaining part of merge from HEAD to V3.3-DAO-REFACTOR-3
                   19367: Merged BRANCHES/V3.2 to HEAD:
                       19286: Fix for ALF-626 "Using 'null' as an authority argument in clearPermissions() cause a java.lang.NullPointerException"
             19755: SAIL-234 Node DAO: Fix RepoAdminServiceImplTest.testConcurrentDynamicModelDelete (handle InvalidNodeRefException after getChildAssocs)
   20692: Merged BRANCHES/DEV/V3.3-DAO-REFACTOR-4 to BRANCHES/DEV/V3.3-DAO-REFACTOR-5:
        - Retired all 1.3 and 1.4 upgrade scripts ... R.I.P.
        - Fixed CRC patch for Authorities (only tested on MySQL)
        - Fixed SQL patch revision numbers and bumped version schema number up
        20158: Merged BRANCHES/DEV/V3.3-DAO-REFACTOR-3 to BRANCHES/DEV/V3.3-DAO-REFACTOR-4:
             19773: SQL mappings and scripts: SAIL-310, SAIL-304, SAIL-303 and SAIL-347
             19774: Futher fix for SAIL-310: Sequence patch must take into account sequences created for 3.3
             19851: SAIL-371 (SAIL-294) NodeDAO fallout: Fix QName and Namespace read/write handling and bean name in unit test
        20183: Merged DAO3 to DAO4
             19852: SAIL-370: Remove LinkValidation
             19853: SAIL-239 (SAIL-294) Attributes.hbm.xml: Added ability to attach arbitrary property to unique context
             19857: SAIL-373 Fallout from Permissions DAO refactor (SAIL-235)
             19864: SAIL-239 (SAIL-294): Removed AttributeService RMI API
             19865: More SAIL-239 (SAIL-294): Removed AttributeService RMI API
        20208: DAO-refactor implementation of ALF-2712 query improvements
        20209: Merged BRANCHES/DEV/V3.3-DAO-REFACTOR-3 to BRANCHES/DEV/V3.3-DAO-REFACTOR-4:
             20060: Removal of AttributeService for SAIL-239 (SAIL-294)
        20348: SAIL-371 (SAIL-294): Protect collection properties during map insert and retrieval
        20547: SAIL-371 (SAIL-294) Attributes.hbm.xml: implement getAttributes + fixes
        20573: SAIL-371 (SAIL-294): NodeDAO: Fix unit tests and other fallout
        20597: SAIL-239 Attributes.hbm.xml: WCM/AVM locking test fixes (wip)
        20598: SAIL-239 Attributes.hbm.xml: WCM/AVM locking test fixes (wip) - fix AssetServiceImplTest.testSimpleLockFile NPE
        20600: Fix PropertyValueDAOTest.testPropertyValue_Enum (follow-on to r20060 for SAIL-239 - which introduces ENUM prop vals)
        20601: Fix UsageDAOTest.testCreateAndDeleteUsageDeltas NPE (would also affect ContentStoreCleanerScalabilityRunner)
        20603: Fix CMISPropertyServiceTest.* (fallout from r20146 <- r19429 <- Took empty cm:content creation out of FileFolderService#createImpl)
        20604: SAIL-371 (SAIL-294): NodeDAO: Fix unit tests - TransferServiceImplTest.*
        20618: SAIL-371 (SAIL-294): NodeDAO: AuditableAspectTest (fix testCreateNodeWithAuditableProperties_ALF_2565 + add remove aspect test)
        20624: SAIL-371 (SAIL-294): NodeDAO: Fix unit tests - UserUsageTest.*
        20626: Fixed random keys for RuleTrigger NodeRef tracking
        20635: SAIL-371 (SAIL-294): NodeDAO: Fix unit tests - PersonTest.testSplitDuplicates
        20642: SAIL-371 (SAIL-294) DAO: Fixed CacheTest
        20643: Removed must of the 'distribute' target's dependencies.  Not for HEAD
        20645: Follow-on to r20643 (Removed most of the 'distribute' target's dependencies.  Not for HEAD)
        20654: SAIL-371 (SAIL-294): NodeDAO: DMDeploymentTargetTest.* (do not try to remove mandatory aspects)
        20655: SAIL-371 (SAIL-294): NodeDAO: Initial fix for TaggingServiceImplTest.testTagScopeUpdateViaNodePolicies (+ minor test cleanup)
        20657: SAIL-371 (SAIL-294): NodeDAO: Fix unit tests - VersionMigratorTest.testMigrateOneVersion (cm:accessed not returned if null)
        20658: Merged (back merge only - no merge info) BRANCHES/V3.3 to BRANCHES/DEV/V3.3-DAO-REFACTOR-4:
             20090: Dynamic models: minor improvements to DictionaryModelType
             20554: Improvement to model delete validation (investigating intermittent failure of RepoAdminServiceImplTest.testSimpleDynamicModelViaNodeService)
        20662: SAIL-371 (SAIL-294): NodeDAO: Fix unit tests - RecordsManagementAuditServiceImplTest.* (we now ignore attempt to update 'cm:modifier' prop so update 'cm:title' prop instead)
        20666: SAIL-371 (SAIL-294): NodeDAO: Fix unit tests - ADMLuceneTest.*
        20668: SAIL-239 (SAIL-294) - delete WCM locks + tests (follow-on to r20060)
        20674: SAIL-371 (SAIL-294) NodeDAO fallout: Cleaner and additional checks for ContentStoreCleaner
        20675: SAIL-371 (SAIL-294) NodeDAO fallout: Fixed handling of ContentData


git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@20693 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
2010-06-17 19:35:49 +00:00

1397 lines
52 KiB
Java

/*
* 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 <http://www.gnu.org/licenses/>.
*/
package org.alfresco.repo.domain.propval;
import java.io.Serializable;
import java.sql.Savepoint;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.alfresco.repo.cache.SimpleCache;
import org.alfresco.repo.cache.lookup.EntityLookupCache;
import org.alfresco.repo.cache.lookup.EntityLookupCache.EntityLookupCallbackDAOAdaptor;
import org.alfresco.repo.domain.CrcHelper;
import org.alfresco.repo.domain.control.ControlDAO;
import org.alfresco.repo.domain.propval.PropertyValueEntity.PersistedType;
import org.alfresco.repo.domain.schema.SchemaBootstrap;
import org.alfresco.util.Pair;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataIntegrityViolationException;
/**
* Abstract implementation for Property Value DAO.
* <p>
* This provides basic services such as caching, but defers to the underlying implementation
* for CRUD operations.
*
* @author Derek Hulley
* @since 3.2
*/
public abstract class AbstractPropertyValueDAOImpl implements PropertyValueDAO
{
private static final String CACHE_REGION_PROPERTY_CLASS = "PropertyClass";
private static final String CACHE_REGION_PROPERTY_DATE_VALUE = "PropertyDateValue";
private static final String CACHE_REGION_PROPERTY_STRING_VALUE = "PropertyStringValue";
private static final String CACHE_REGION_PROPERTY_DOUBLE_VALUE = "PropertyDoubleValue";
private static final String CACHE_REGION_PROPERTY_SERIALIZABLE_VALUE = "PropertySerializableValue";
private static final String CACHE_REGION_PROPERTY_VALUE = "PropertyValue";
private static final String CACHE_REGION_PROPERTY = "Property";
protected final Log logger = LogFactory.getLog(getClass());
protected PropertyTypeConverter converter;
protected ControlDAO controlDAO;
private final PropertyClassCallbackDAO propertyClassDaoCallback;
private final PropertyDateValueCallbackDAO propertyDateValueCallback;
private final PropertyStringValueCallbackDAO propertyStringValueCallback;
private final PropertyDoubleValueCallbackDAO propertyDoubleValueCallback;
private final PropertySerializableValueCallbackDAO propertySerializableValueCallback;
private final PropertyValueCallbackDAO propertyValueCallback;
private final PropertyCallbackDAO propertyCallback;
/**
* Cache for the property class:<br/>
* KEY: ID<br/>
* VALUE: Java class<br/>
* VALUE KEY: Java class name<br/>
*/
private EntityLookupCache<Long, Class<?>, String> propertyClassCache;
/**
* Cache for the property date value:<br/>
* KEY: ID<br/>
* VALUE: The Date instance<br/>
* VALUE KEY: The date-only date (i.e. everything below day is zeroed)<br/>
*/
private EntityLookupCache<Long, Date, Date> propertyDateValueCache;
/**
* Cache for the property string value:<br/>
* KEY: ID<br/>
* VALUE: The full string<br/>
* VALUE KEY: Short string-crc pair ({@link CrcHelper#getStringCrcPair(String, int, boolean, boolean)})<br/>
*/
private EntityLookupCache<Long, String, Pair<String, Long>> propertyStringValueCache;
/**
* Cache for the property double value:<br/>
* KEY: ID<br/>
* VALUE: The Double instance<br/>
* VALUE KEY: The value itself<br/>
*/
private EntityLookupCache<Long, Double, Double> propertyDoubleValueCache;
/**
* Cache for the property Serializable value:<br/>
* KEY: ID<br/>
* VALUE: The Serializable instance<br/>
* VALUE KEY: none<br/>. The cache is not used for value-based lookups.
*/
private EntityLookupCache<Long, Serializable, Serializable> propertySerializableValueCache;
/**
* Cache for the property value:<br/>
* KEY: ID<br/>
* VALUE: The Serializable instance<br/>
* VALUE KEY: A value key based on the persisted type<br/>
*/
private EntityLookupCache<Long, Serializable, Serializable> propertyValueCache;
/**
* Cache for the property:<br/>
* KEY: ID<br/>
* VALUE: The Serializable instance<br/>
* VALUE KEY: A value key based on the persisted type<br/>
*/
private EntityLookupCache<Long, Serializable, Serializable> propertyCache;
/**
* Default constructor.
* <p>
* This sets up the DAO accessors to bypass any caching to handle the case where the caches are not
* supplied in the setters.
*/
public AbstractPropertyValueDAOImpl()
{
this.propertyClassDaoCallback = new PropertyClassCallbackDAO();
this.propertyDateValueCallback = new PropertyDateValueCallbackDAO();
this.propertyStringValueCallback = new PropertyStringValueCallbackDAO();
this.propertyDoubleValueCallback = new PropertyDoubleValueCallbackDAO();
this.propertySerializableValueCallback = new PropertySerializableValueCallbackDAO();
this.propertyValueCallback = new PropertyValueCallbackDAO();
this.propertyCallback = new PropertyCallbackDAO();
this.propertyClassCache = new EntityLookupCache<Long, Class<?>, String>(propertyClassDaoCallback);
this.propertyDateValueCache = new EntityLookupCache<Long, Date, Date>(propertyDateValueCallback);
this.propertyStringValueCache = new EntityLookupCache<Long, String, Pair<String, Long>>(propertyStringValueCallback);
this.propertyDoubleValueCache = new EntityLookupCache<Long, Double, Double>(propertyDoubleValueCallback);
this.propertySerializableValueCache = new EntityLookupCache<Long, Serializable, Serializable>(propertySerializableValueCallback);
this.propertyValueCache = new EntityLookupCache<Long, Serializable, Serializable>(propertyValueCallback);
this.propertyCache = new EntityLookupCache<Long, Serializable, Serializable>(propertyCallback);
}
/**
* @param converter the converter that translates between external and persisted values
*/
public void setConverter(PropertyTypeConverter converter)
{
this.converter = converter;
}
/**
* @param controlDAO the DAO that provides connection control
*/
public void setControlDAO(ControlDAO controlDAO)
{
this.controlDAO = controlDAO;
}
/**
* Set the cache to use for <b>alf_prop_class</b> lookups (optional).
*
* @param propertyClassCache the cache of IDs to property classes
*/
public void setPropertyClassCache(SimpleCache<Serializable, Object> propertyClassCache)
{
this.propertyClassCache = new EntityLookupCache<Long, Class<?>, String>(
propertyClassCache,
CACHE_REGION_PROPERTY_CLASS,
propertyClassDaoCallback);
}
/**
* Set the cache to use for <b>alf_prop_date_value</b> lookups (optional).
*
* @param propertyDateValueCache the cache of IDs to property values
*/
public void setPropertyDateValueCache(SimpleCache<Serializable, Object> propertyDateValueCache)
{
this.propertyDateValueCache = new EntityLookupCache<Long, Date, Date>(
propertyDateValueCache,
CACHE_REGION_PROPERTY_DATE_VALUE,
propertyDateValueCallback);
}
/**
* Set the cache to use for <b>alf_prop_string_value</b> lookups (optional).
*
* @param propertyStringValueCache the cache of IDs to property string values
*/
public void setPropertyStringValueCache(SimpleCache<Serializable, Object> propertyStringValueCache)
{
this.propertyStringValueCache = new EntityLookupCache<Long, String, Pair<String, Long>>(
propertyStringValueCache,
CACHE_REGION_PROPERTY_STRING_VALUE,
propertyStringValueCallback);
}
/**
* Set the cache to use for <b>alf_prop_double_value</b> lookups (optional).
*
* @param propertyDoubleValueCache the cache of IDs to property values
*/
public void setPropertyDoubleValueCache(SimpleCache<Serializable, Object> propertyDoubleValueCache)
{
this.propertyDoubleValueCache = new EntityLookupCache<Long, Double, Double>(
propertyDoubleValueCache,
CACHE_REGION_PROPERTY_DOUBLE_VALUE,
propertyDoubleValueCallback);
}
/**
* Set the cache to use for <b>alf_prop_serializable_value</b> lookups (optional).
*
* @param propertySerializableValueCache the cache of IDs to property values
*/
public void setPropertySerializableValueCache(SimpleCache<Serializable, Object> propertySerializableValueCache)
{
this.propertySerializableValueCache = new EntityLookupCache<Long, Serializable, Serializable>(
propertySerializableValueCache,
CACHE_REGION_PROPERTY_SERIALIZABLE_VALUE,
propertySerializableValueCallback);
}
/**
* Set the cache to use for <b>alf_prop_value</b> lookups (optional).
*
* @param propertyValueCache the cache of IDs to property values
*/
public void setPropertyValueCache(SimpleCache<Serializable, Object> propertyValueCache)
{
this.propertyValueCache = new EntityLookupCache<Long, Serializable, Serializable>(
propertyValueCache,
CACHE_REGION_PROPERTY_VALUE,
propertyValueCallback);
}
/**
* Set the cache to use for <b>alf_prop_root</b> lookups (optional).
*
* @param propertyValueCache the cache of IDs to property values
*/
public void setPropertyCache(SimpleCache<Serializable, Object> propertyCache)
{
this.propertyCache = new EntityLookupCache<Long, Serializable, Serializable>(
propertyCache,
CACHE_REGION_PROPERTY,
propertyCallback);
}
//================================
// 'alf_prop_class' accessors
//================================
public Pair<Long, Class<?>> getPropertyClassById(Long id)
{
if (id == null)
{
throw new IllegalArgumentException("Cannot look up entity by null ID.");
}
Pair<Long, Class<?>> entityPair = propertyClassCache.getByKey(id);
if (entityPair == null)
{
throw new DataIntegrityViolationException("No property class exists for ID " + id);
}
return entityPair;
}
public Pair<Long, Class<?>> getPropertyClass(Class<?> value)
{
if (value == null)
{
throw new IllegalArgumentException("Property class cannot be null");
}
Pair<Long, Class<?>> entityPair = propertyClassCache.getByValue(value);
return entityPair;
}
public Pair<Long, Class<?>> getOrCreatePropertyClass(Class<?> value)
{
if (value == null)
{
throw new IllegalArgumentException("Property class cannot be null");
}
Pair<Long, Class<?>> entityPair = propertyClassCache.getOrCreateByValue(value);
return entityPair;
}
/**
* Callback for <b>alf_prop_class</b> DAO.
*/
private class PropertyClassCallbackDAO extends EntityLookupCallbackDAOAdaptor<Long, Class<?>, String>
{
private final Pair<Long, Class<?>> convertEntityToPair(PropertyClassEntity entity)
{
if (entity == null)
{
return null;
}
else
{
return entity.getEntityPair();
}
}
public String getValueKey(Class<?> value)
{
return value.getName();
}
public Pair<Long, Class<?>> createValue(Class<?> value)
{
PropertyClassEntity entity = createClass(value);
return convertEntityToPair(entity);
}
public Pair<Long, Class<?>> findByKey(Long key)
{
PropertyClassEntity entity = findClassById(key);
return convertEntityToPair(entity);
}
public Pair<Long, Class<?>> findByValue(Class<?> value)
{
PropertyClassEntity entity = findClassByValue(value);
return convertEntityToPair(entity);
}
}
protected abstract PropertyClassEntity findClassById(Long id);
protected abstract PropertyClassEntity findClassByValue(Class<?> value);
protected abstract PropertyClassEntity createClass(Class<?> value);
//================================
// 'alf_prop_date_value' accessors
//================================
public Pair<Long, Date> getPropertyDateValueById(Long id)
{
if (id == null)
{
throw new IllegalArgumentException("Cannot look up entity by null ID.");
}
Pair<Long, Date> entityPair = propertyDateValueCache.getByKey(id);
if (entityPair == null)
{
throw new DataIntegrityViolationException("No property date value exists for ID " + id);
}
return entityPair;
}
public Pair<Long, Date> getPropertyDateValue(Date value)
{
if (value == null)
{
throw new IllegalArgumentException("Persisted date values cannot be null");
}
value = PropertyDateValueEntity.truncateDate(value);
Pair<Long, Date> entityPair = propertyDateValueCache.getByValue(value);
return entityPair;
}
public Pair<Long, Date> getOrCreatePropertyDateValue(Date value)
{
if (value == null)
{
throw new IllegalArgumentException("Persisted date values cannot be null");
}
value = PropertyDateValueEntity.truncateDate(value);
Pair<Long, Date> entityPair = propertyDateValueCache.getOrCreateByValue(value);
return (Pair<Long, Date>) entityPair;
}
/**
* Callback for <b>alf_prop_date_value</b> DAO.
*/
private class PropertyDateValueCallbackDAO extends EntityLookupCallbackDAOAdaptor<Long, Date, Date>
{
private final Pair<Long, Date> convertEntityToPair(PropertyDateValueEntity entity)
{
if (entity == null)
{
return null;
}
else
{
return entity.getEntityPair();
}
}
/**
* {@inheritDoc}
* <p/>
* The value will already have been truncated to be accurate to the last day
*/
public Date getValueKey(Date value)
{
return PropertyDateValueEntity.truncateDate(value);
}
public Pair<Long, Date> createValue(Date value)
{
PropertyDateValueEntity entity = createDateValue(value);
return convertEntityToPair(entity);
}
public Pair<Long, Date> findByKey(Long key)
{
PropertyDateValueEntity entity = findDateValueById(key);
return convertEntityToPair(entity);
}
public Pair<Long, Date> findByValue(Date value)
{
PropertyDateValueEntity entity = findDateValueByValue(value);
return convertEntityToPair(entity);
}
}
protected abstract PropertyDateValueEntity findDateValueById(Long id);
/**
* @param value a date, accurate to the day
*/
protected abstract PropertyDateValueEntity findDateValueByValue(Date value);
/**
* @param value a date, accurate to the day
*/
protected abstract PropertyDateValueEntity createDateValue(Date value);
//================================
// 'alf_prop_string_value' accessors
//================================
public Pair<String, Long> getPropertyStringCaseSensitiveSearchParameters(String value)
{
return CrcHelper.getStringCrcPair(value, 16, false, true);
}
public Pair<Long, String> getPropertyStringValueById(Long id)
{
if (id == null)
{
throw new IllegalArgumentException("Cannot look up entity by null ID.");
}
Pair<Long, String> entityPair = propertyStringValueCache.getByKey(id);
if (entityPair == null)
{
throw new DataIntegrityViolationException("No property string value exists for ID " + id);
}
return entityPair;
}
public Pair<Long, String> getPropertyStringValue(String value)
{
if (value == null)
{
throw new IllegalArgumentException("Persisted string values cannot be null");
}
Pair<Long, String> entityPair = propertyStringValueCache.getByValue(value);
return entityPair;
}
public Pair<Long, String> getOrCreatePropertyStringValue(String value)
{
if (value == null)
{
throw new IllegalArgumentException("Persisted string values cannot be null");
}
int maxStringLen = SchemaBootstrap.getMaxStringLength();
if (value.length() > maxStringLen)
{
throw new IllegalArgumentException(
"Persisted string values for 'alf_prop_string_value' cannot be longer than "
+ maxStringLen + " characters. Increase the string column sizes and set property " +
"'system.maximumStringLength' accordingly.");
}
Pair<Long, String> entityPair = propertyStringValueCache.getOrCreateByValue(value);
return entityPair;
}
/**
* Callback for <b>alf_prop_string_value</b> DAO.
*/
private class PropertyStringValueCallbackDAO extends EntityLookupCallbackDAOAdaptor<Long, String, Pair<String, Long>>
{
public Pair<String, Long> getValueKey(String value)
{
return getPropertyStringCaseSensitiveSearchParameters(value);
}
public Pair<Long, String> createValue(String value)
{
Long key = createStringValue(value);
return new Pair<Long, String>(key, value);
}
public Pair<Long, String> findByKey(Long key)
{
String value = findStringValueById(key);
if (value == null)
{
return null;
}
else
{
return new Pair<Long, String>(key, value);
}
}
public Pair<Long, String> findByValue(String value)
{
Long key = findStringValueByValue(value);
if (key == null)
{
return null;
}
else
{
return new Pair<Long, String>(key, value);
}
}
}
protected abstract String findStringValueById(Long id);
protected abstract Long findStringValueByValue(String value);
protected abstract Long createStringValue(String value);
//================================
// 'alf_prop_double_value' accessors
//================================
public Pair<Long, Double> getPropertyDoubleValueById(Long id)
{
if (id == null)
{
throw new IllegalArgumentException("Cannot look up entity by null ID.");
}
Pair<Long, Double> entityPair = propertyDoubleValueCache.getByKey(id);
if (entityPair == null)
{
throw new DataIntegrityViolationException("No property double value exists for ID " + id);
}
return entityPair;
}
public Pair<Long, Double> getPropertyDoubleValue(Double value)
{
if (value == null)
{
throw new IllegalArgumentException("Persisted double values cannot be null");
}
Pair<Long, Double> entityPair = propertyDoubleValueCache.getByValue(value);
return entityPair;
}
public Pair<Long, Double> getOrCreatePropertyDoubleValue(Double value)
{
if (value == null)
{
throw new IllegalArgumentException("Persisted double values cannot be null");
}
Pair<Long, Double> entityPair = propertyDoubleValueCache.getOrCreateByValue(value);
return (Pair<Long, Double>) entityPair;
}
/**
* Callback for <b>alf_prop_double_value</b> DAO.
*/
private class PropertyDoubleValueCallbackDAO extends EntityLookupCallbackDAOAdaptor<Long, Double, Double>
{
private final Pair<Long, Double> convertEntityToPair(PropertyDoubleValueEntity entity)
{
if (entity == null)
{
return null;
}
else
{
return entity.getEntityPair();
}
}
public Double getValueKey(Double value)
{
return value;
}
public Pair<Long, Double> createValue(Double value)
{
PropertyDoubleValueEntity entity = createDoubleValue(value);
return convertEntityToPair(entity);
}
public Pair<Long, Double> findByKey(Long key)
{
PropertyDoubleValueEntity entity = findDoubleValueById(key);
return convertEntityToPair(entity);
}
public Pair<Long, Double> findByValue(Double value)
{
PropertyDoubleValueEntity entity = findDoubleValueByValue(value);
return convertEntityToPair(entity);
}
}
protected abstract PropertyDoubleValueEntity findDoubleValueById(Long id);
protected abstract PropertyDoubleValueEntity findDoubleValueByValue(Double value);
protected abstract PropertyDoubleValueEntity createDoubleValue(Double value);
//================================
// 'alf_prop_serializable_value' accessors
//================================
public Pair<Long, Serializable> getPropertySerializableValueById(Long id)
{
if (id == null)
{
throw new IllegalArgumentException("Cannot look up entity by null ID.");
}
Pair<Long, Serializable> entityPair = propertySerializableValueCache.getByKey(id);
if (entityPair == null)
{
throw new DataIntegrityViolationException("No property serializable value exists for ID " + id);
}
return entityPair;
}
public Pair<Long, Serializable> createPropertySerializableValue(Serializable value)
{
if (value == null)
{
throw new IllegalArgumentException("Persisted serializable values cannot be null");
}
Pair<Long, Serializable> entityPair = propertySerializableValueCache.getOrCreateByValue(value);
return (Pair<Long, Serializable>) entityPair;
}
/**
* Callback for <b>alf_prop_serializable_value</b> DAO.
*/
private class PropertySerializableValueCallbackDAO extends EntityLookupCallbackDAOAdaptor<Long, Serializable, Serializable>
{
private final Pair<Long, Serializable> convertEntityToPair(PropertySerializableValueEntity entity)
{
if (entity == null)
{
return null;
}
else
{
return entity.getEntityPair();
}
}
public Pair<Long, Serializable> createValue(Serializable value)
{
PropertySerializableValueEntity entity = createSerializableValue(value);
return convertEntityToPair(entity);
}
public Pair<Long, Serializable> findByKey(Long key)
{
PropertySerializableValueEntity entity = findSerializableValueById(key);
return convertEntityToPair(entity);
}
}
protected abstract PropertySerializableValueEntity findSerializableValueById(Long id);
protected abstract PropertySerializableValueEntity createSerializableValue(Serializable value);
//================================
// 'alf_prop_value' accessors
//================================
public Pair<Long, Serializable> getPropertyValueById(Long id)
{
if (id == null)
{
throw new IllegalArgumentException("Cannot look up entity by null ID.");
}
Pair<Long, Serializable> entityPair = propertyValueCache.getByKey(id);
if (entityPair == null)
{
throw new DataIntegrityViolationException("No property value exists for ID " + id);
}
return entityPair;
}
public Pair<Long, Serializable> getPropertyValue(Serializable value)
{
Pair<Long, Serializable> entityPair = propertyValueCache.getByValue(value);
return entityPair;
}
public Pair<Long, Serializable> getOrCreatePropertyValue(Serializable value)
{
Pair<Long, Serializable> entityPair = propertyValueCache.getOrCreateByValue(value);
return (Pair<Long, Serializable>) entityPair;
}
/**
* Callback for <b>alf_prop_value</b> DAO.
*/
private class PropertyValueCallbackDAO extends EntityLookupCallbackDAOAdaptor<Long, Serializable, Serializable>
{
@SuppressWarnings("unchecked")
private final Serializable convertToValue(PropertyValueEntity entity)
{
if (entity == null)
{
return null;
}
Long actualTypeId = entity.getActualTypeId();
final Class<Serializable> actualType = (Class<Serializable>) getPropertyClassById(actualTypeId).getSecond();
final Serializable actualValue = entity.getValue(actualType, converter);
// Done
return actualValue;
}
private final Pair<Long, Serializable> convertEntityToPair(PropertyValueEntity entity)
{
if (entity == null)
{
return null;
}
Long entityId = entity.getId();
Serializable actualValue = convertToValue(entity);
// Done
return new Pair<Long, Serializable>(entityId, actualValue);
}
public Serializable getValueKey(Serializable value)
{
PersistedType persistedType = PropertyValueEntity.getPersistedTypeEnum(value, converter);
// We don't return keys for pure Serializable instances
if (persistedType == PersistedType.SERIALIZABLE)
{
// It will be Serialized, so no search key
return null;
}
else if (value instanceof String)
{
return CrcHelper.getStringCrcPair((String)value, 128, true, true);
}
else
{
// We've dodged Serializable and String; everything else is OK as a key.
return value;
}
}
public Pair<Long, Serializable> createValue(Serializable value)
{
PropertyValueEntity entity = createPropertyValue(value);
// Done
return new Pair<Long, Serializable>(entity.getId(), value);
}
public Pair<Long, Serializable> findByKey(Long key)
{
PropertyValueEntity entity = findPropertyValueById(key);
return convertEntityToPair(entity);
}
public Pair<Long, Serializable> findByValue(Serializable value)
{
PropertyValueEntity entity = findPropertyValueByValue(value);
return convertEntityToPair(entity);
}
/**
* No-op. This is implemented as we just want to update the cache.
* @return Returns 0 always
*/
@Override
public int updateValue(Long key, Serializable value)
{
return 0;
}
}
protected abstract PropertyValueEntity findPropertyValueById(Long id);
protected abstract PropertyValueEntity findPropertyValueByValue(Serializable value);
protected abstract PropertyValueEntity createPropertyValue(Serializable value);
//================================
// 'alf_prop_root' accessors
//================================
public Serializable getPropertyById(Long id)
{
if (id == null)
{
throw new IllegalArgumentException("Cannot look up entity by null ID.");
}
Pair<Long, Serializable> entityPair = propertyCache.getByKey(id);
if (entityPair == null)
{
throw new DataIntegrityViolationException("No property value exists for ID " + id);
}
return entityPair.getSecond();
}
public void getPropertiesByIds(List<Long> ids, PropertyFinderCallback callback)
{
findPropertiesByIds(ids, callback);
}
/**
* {@inheritDoc}
* @see #createPropertyImpl(Serializable, int, int)
*/
public Long createProperty(Serializable value)
{
Pair<Long, Serializable> entityPair = propertyCache.getOrCreateByValue(value);
return entityPair.getFirst();
}
public void updateProperty(Long rootPropId, Serializable value)
{
propertyCache.updateValue(rootPropId, value);
}
public void deleteProperty(Long id)
{
propertyCache.deleteByKey(id);
}
/**
* Callback for <b>alf_prop_root</b> DAO.
*/
private class PropertyCallbackDAO extends EntityLookupCallbackDAOAdaptor<Long, Serializable, Serializable>
{
public Pair<Long, Serializable> createValue(Serializable value)
{
// We will need a new root
Long rootPropId = createPropertyRoot();
createPropertyImpl(rootPropId, 0L, 0L, null, value);
// Done
if (logger.isDebugEnabled())
{
logger.debug(
"Created property: \n" +
" ID: " + rootPropId + "\n" +
" Value: " + value);
}
return new Pair<Long, Serializable>(rootPropId, value);
}
public Pair<Long, Serializable> findByKey(Long key)
{
List<PropertyIdSearchRow> rows = findPropertyById(key);
if (rows.size() == 0)
{
// No results
return null;
}
Serializable value = convertPropertyIdSearchRows(rows);
return new Pair<Long, Serializable>(key, value);
}
/**
* Updates a property. The <b>alf_prop_root</b> entity is updated
* to ensure concurrent modification is detected.
*
* @return Returns 1 always
*/
@Override
public int updateValue(Long key, Serializable value)
{
// Remove all entries for the root
PropertyRootEntity entity = getPropertyRoot(key);
if (entity == null)
{
throw new DataIntegrityViolationException("No property root exists for ID " + key);
}
// Remove all links using the root
deletePropertyLinks(key);
// Create the new properties and update the cache
createPropertyImpl(key, 0L, 0L, null, value);
// Update the property root to detect concurrent modification
updatePropertyRoot(entity);
// Done
if (logger.isDebugEnabled())
{
logger.debug(
"Updated property: \n" +
" ID: " + key + "\n" +
" Value: " + value);
}
return 1;
}
@Override
public int deleteByKey(Long key)
{
deletePropertyRoot(key);
// Done
if (logger.isDebugEnabled())
{
logger.debug(
"Deleted property: \n" +
" ID: " + key);
}
return 1;
}
}
/**
* @param propIndex a unique index within the context of the current property root
*/
@SuppressWarnings("unchecked")
private long createPropertyImpl(
Long rootPropId,
long propIndex,
long containedIn,
Long keyPropId,
Serializable value)
{
// Keep track of the index for this property. It gets used later when making the link entry.
long thisPropIndex = propIndex;
Long valuePropId = null;
if (value == null)
{
// The key and the value are the same
valuePropId = getOrCreatePropertyValue(value).getFirst();
}
else if (value instanceof Map<?, ?>)
{
Map<Serializable, Serializable> map = (Map<Serializable, Serializable>) value;
// Check if the it has a default constructor
Serializable emptyInstance = constructEmptyContainer(value.getClass());
if (emptyInstance == null)
{
// No default constructor, so we just throw the whole thing in as a single property
valuePropId = getOrCreatePropertyValue(value).getFirst();
}
else
{
// Persist the empty map
valuePropId = getOrCreatePropertyValue(emptyInstance).getFirst();
// Persist the individual entries
for (Map.Entry<Serializable, Serializable> entry : map.entrySet())
{
// Recurse for each value
Serializable mapKey = entry.getKey();
Serializable mapValue = entry.getValue();
// Get the IDs for these
Long mapKeyId = getOrCreatePropertyValue(mapKey).getFirst();
propIndex = createPropertyImpl(
rootPropId,
propIndex + 1L,
thisPropIndex,
mapKeyId,
mapValue);
}
}
}
else if (value instanceof Collection<?>)
{
Collection<Serializable> collection = (Collection<Serializable>) value;
// Check if the it has a default constructor
Serializable emptyInstance = constructEmptyContainer(value.getClass());
if (emptyInstance == null)
{
// No default constructor, so we just throw the whole thing in as a single property
valuePropId = getOrCreatePropertyValue(value).getFirst();
}
else
{
// Persist the empty collection
valuePropId = getOrCreatePropertyValue(emptyInstance).getFirst();
// Persist the individual entries
for (Serializable collectionValue : collection)
{
// Recurse for each value
propIndex = createPropertyImpl(
rootPropId,
propIndex + 1L,
thisPropIndex,
null,
collectionValue);
}
}
}
else
{
// The key and the value are the same
valuePropId = getOrCreatePropertyValue(value).getFirst();
}
// Create a link entry
if (keyPropId == null)
{
// If the key matches the value then it is the root
keyPropId = valuePropId;
}
createPropertyLink(rootPropId, thisPropIndex, containedIn, keyPropId, valuePropId);
// Done
return propIndex;
}
private static final Serializable EMPTY_HASHMAP = new HashMap<Serializable, Serializable>();
private static final Serializable EMPTY_LIST = new ArrayList<Serializable>();
private static final Serializable EMPTY_SET = new HashSet<Serializable>();
/**
* Returns a reconstructable instance
*
* @return Returns an empty instance of the given container (map or collection), or
* <tt>null</tt> if it is not possible to do
*/
protected Serializable constructEmptyContainer(Class<?> clazz)
{
try
{
return (Serializable) clazz.getConstructor().newInstance();
}
catch (Throwable e)
{
// Can't be constructed, so we just choose a well-known implementation.
// There are so many variations on maps and collections (Unmodifiable, Immutable, etc)
// that to not choose an alternative would leave the database full of BLOBs
}
if (Map.class.isAssignableFrom(clazz))
{
return EMPTY_HASHMAP;
}
else if (List.class.isAssignableFrom(clazz))
{
return EMPTY_LIST;
}
else if (Set.class.isAssignableFrom(clazz))
{
return EMPTY_SET;
}
else
{
logger.warn("Unable to find suitable container type with default constructor: " + clazz);
return null;
}
}
protected abstract List<PropertyIdSearchRow> findPropertyById(Long id);
protected abstract void findPropertiesByIds(List<Long> ids, PropertyFinderCallback callback);
protected abstract Long createPropertyRoot();
protected abstract PropertyRootEntity getPropertyRoot(Long id);
protected abstract PropertyRootEntity updatePropertyRoot(PropertyRootEntity entity);
protected abstract void deletePropertyRoot(Long id);
/**
* Create an entry for the map or collection link.
*
* @param rootPropId the root (entry-point) property ID
* @param propIndex the property number within the root property
* @param containedIn the property that contains the current value
* @param keyPropId the map key entity ID or collection position count
* @param valuePropId the ID of the entity storing the value (may be another map or collection)
*/
protected abstract void createPropertyLink(
Long rootPropId,
Long propIndex,
Long containedIn,
Long keyPropId,
Long valuePropId);
/**
* Remove all property links for a given property root.
*
* @param rootPropId the root (entry-point) property ID
*/
protected abstract int deletePropertyLinks(Long rootPropId);
//================================
// 'alf_prop_unique_ctx' accessors
//================================
public Pair<Long, Long> createPropertyUniqueContext(
Serializable value1, Serializable value2, Serializable value3,
Serializable propertyValue1)
{
/*
* Use savepoints so that the PropertyUniqueConstraintViolation can be caught and handled in-transactioin
*/
// Translate the properties. Null values are acceptable
Long id1 = getOrCreatePropertyValue(value1).getFirst();
Long id2 = getOrCreatePropertyValue(value2).getFirst();
Long id3 = getOrCreatePropertyValue(value3).getFirst();
Long property1Id = null;
if (propertyValue1 != null)
{
property1Id = createProperty(propertyValue1);
}
Savepoint savepoint = controlDAO.createSavepoint("createPropertyUniqueContext");
try
{
PropertyUniqueContextEntity entity = createPropertyUniqueContext(id1, id2, id3, property1Id);
controlDAO.releaseSavepoint(savepoint);
if (logger.isDebugEnabled())
{
logger.debug(
"Created unique property context: \n" +
" Values: " + value1 + "-" + value2 + "-" + value3 + "\n" +
" Result: " + entity);
}
return new Pair<Long, Long>(entity.getId(), property1Id);
}
catch (Throwable e)
{
controlDAO.rollbackToSavepoint(savepoint);
throw new PropertyUniqueConstraintViolation(value1, value2, value3, e);
}
}
public Pair<Long, Long> getPropertyUniqueContext(Serializable value1, Serializable value2, Serializable value3)
{
// Translate the properties. Null values are quite acceptable
Pair<Long, Serializable> pair1 = getPropertyValue(value1);
Pair<Long, Serializable> pair2 = getPropertyValue(value2);
Pair<Long, Serializable> pair3 = getPropertyValue(value3);
if (pair1 == null || pair2 == null || pair3 == null)
{
// None of the values exist so no unique context values can exist
return null;
}
Long id1 = pair1.getFirst();
Long id2 = pair2.getFirst();
Long id3 = pair3.getFirst();
PropertyUniqueContextEntity entity = getPropertyUniqueContextByValues(id1, id2, id3);
// Done
if (logger.isDebugEnabled())
{
logger.debug(
"Searched for unique property context: \n" +
" Values: " + value1 + "-" + value2 + "-" + value3 + "\n" +
" Result: " + entity);
}
return entity == null ? null : new Pair<Long, Long>(entity.getId(), entity.getPropertyId());
}
public void getPropertyUniqueContext(PropertyUniqueContextCallback callback, Serializable... values)
{
if (values.length < 1 || values.length > 3)
{
throw new IllegalArgumentException("Get of unique property sets must have 1, 2 or 3 values");
}
Long[] valueIds = new Long[values.length];
for (int i = 0; i < values.length; i++)
{
Pair<Long, Serializable> valuePair = getPropertyValue(values[i]);
if (valuePair == null)
{
// No such value, so no need to get
return;
}
valueIds[i] = valuePair.getFirst();
}
getPropertyUniqueContextByValues(callback, valueIds);
// Done
if (logger.isDebugEnabled())
{
logger.debug(
"Searched for unique property context: \n" +
" Values: " + values);
}
}
public void updatePropertyUniqueContext(Long id, Serializable value1, Serializable value2, Serializable value3)
{
/*
* Use savepoints so that the PropertyUniqueConstraintViolation can be caught and handled in-transactioin
*/
// Translate the properties. Null values are acceptable
Long id1 = getOrCreatePropertyValue(value1).getFirst();
Long id2 = getOrCreatePropertyValue(value2).getFirst();
Long id3 = getOrCreatePropertyValue(value3).getFirst();
Savepoint savepoint = controlDAO.createSavepoint("updatePropertyUniqueContext");
try
{
PropertyUniqueContextEntity entity = getPropertyUniqueContextById(id);
if (entity == null)
{
throw new DataIntegrityViolationException("No unique property context exists for id: " + id);
}
entity.setValue1PropId(id1);
entity.setValue2PropId(id2);
entity.setValue3PropId(id3);
updatePropertyUniqueContext(entity);
controlDAO.releaseSavepoint(savepoint);
// Done
if (logger.isDebugEnabled())
{
logger.debug(
"Updated unique property context: \n" +
" ID: " + id + "\n" +
" Values: " + value1 + "-" + value2 + "-" + value3);
}
return;
}
catch (Throwable e)
{
controlDAO.rollbackToSavepoint(savepoint);
throw new PropertyUniqueConstraintViolation(value1, value2, value3, e);
}
}
public void updatePropertyUniqueContext(Long id, Serializable propertyValue)
{
PropertyUniqueContextEntity entity = getPropertyUniqueContextById(id);
if (entity == null)
{
throw new DataIntegrityViolationException("No unique property context exists for id: " + id);
}
Long propertyIdToDelete = entity.getPropertyId();
Long propertyId = null;
if (propertyValue != null)
{
propertyId = createProperty(propertyValue);
}
// Create a new property
entity.setPropertyId(propertyId);
updatePropertyUniqueContext(entity);
// Clean up the previous property, if present
if (propertyIdToDelete != null)
{
deleteProperty(propertyIdToDelete);
}
// Done
if (logger.isDebugEnabled())
{
logger.debug(
"Updated unique property context: \n" +
" ID: " + id + "\n" +
" Property: " + propertyId);
}
}
public int deletePropertyUniqueContext(Serializable... values)
{
if (values.length < 1 || values.length > 3)
{
throw new IllegalArgumentException("Deletion of unique property sets must have 1, 2 or 3 values");
}
Long[] valueIds = new Long[values.length];
for (int i = 0; i < values.length; i++)
{
Pair<Long, Serializable> valuePair = getPropertyValue(values[i]);
if (valuePair == null)
{
// No such value, so no need to delete
return 0;
}
valueIds[i] = valuePair.getFirst();
}
int deleted = deletePropertyUniqueContexts(valueIds);
// Done
if (logger.isDebugEnabled())
{
logger.debug(
"Deleted " + deleted + " unique property contexts: \n" +
" Values: " + values + "\n" +
" IDs: " + valueIds);
}
return deleted;
}
protected abstract PropertyUniqueContextEntity createPropertyUniqueContext(Long valueId1, Long valueId2, Long valueId3, Long propertyId);
protected abstract PropertyUniqueContextEntity getPropertyUniqueContextById(Long id);
protected abstract PropertyUniqueContextEntity getPropertyUniqueContextByValues(Long valueId1, Long valueId2, Long valueId3);
protected abstract void getPropertyUniqueContextByValues(PropertyUniqueContextCallback callback, Long... valueIds);
protected abstract PropertyUniqueContextEntity updatePropertyUniqueContext(PropertyUniqueContextEntity entity);
protected abstract int deletePropertyUniqueContexts(Long ... valueIds);
//================================
// Utility methods
//================================
@SuppressWarnings("unchecked")
public Serializable convertPropertyIdSearchRows(List<PropertyIdSearchRow> rows)
{
// Shortcut if there are no results
if (rows.size() == 0)
{
return null;
}
/*
* The results all share the same root property. Pass through the results and construct all
* instances, storing them ordered by prop_index.
*/
Map<Long, Serializable> valuesByPropIndex = new HashMap<Long, Serializable>(7);
TreeMap<Long, PropertyLinkEntity> linkEntitiesByPropIndex = new TreeMap<Long, PropertyLinkEntity>();
Long rootPropId = null; // Keep this to ensure the root_prop_id is common
for (PropertyIdSearchRow row : rows)
{
// Check that we are handling a single root property
if (rootPropId == null)
{
rootPropId = row.getLinkEntity().getRootPropId();
}
else if (!rootPropId.equals(row.getLinkEntity().getRootPropId()))
{
throw new IllegalArgumentException(
"The root_prop_id for the property search rows must not change: \n" +
" Rows: " + rows);
}
PropertyLinkEntity linkEntity = row.getLinkEntity();
Long propIndex = linkEntity.getPropIndex();
Long valuePropId = linkEntity.getValuePropId();
PropertyValueEntity valueEntity = row.getValueEntity();
// Get the value
Serializable value;
if (valueEntity != null)
{
value = propertyValueCallback.convertToValue(valueEntity);
}
else
{
// Go N+1 if the value entity was not retrieved
value = getPropertyValueById(valuePropId);
}
// Keep it for later
valuesByPropIndex.put(propIndex, value);
linkEntitiesByPropIndex.put(propIndex, linkEntity);
}
Serializable result = null;
// Iterate again, adding values to the collections and looking for the root property
for (Map.Entry<Long, PropertyLinkEntity> entry : linkEntitiesByPropIndex.entrySet())
{
PropertyLinkEntity linkEntity = entry.getValue();
Long propIndex = linkEntity.getPropIndex();
Long containedIn = linkEntity.getContainedIn();
Long keyPropId = linkEntity.getKeyPropId();
Serializable value = valuesByPropIndex.get(propIndex);
// Check if this is the root property
if (propIndex.equals(containedIn))
{
if (result != null)
{
logger.error("Found inconsistent property root data: " + linkEntity);
continue;
}
// This property is contained in itself i.e. it's the root
result = value;
}
else
{
// Add the value to the container to which it belongs.
// The ordering is irrelevant for some containers; but where it is important,
// ordering given by the prop_index will ensure that values are added back
// in the order in which the container originally iterated over them
Serializable container = valuesByPropIndex.get(containedIn);
if (container == null)
{
logger.error("Found container ID that doesn't have a value: " + linkEntity);
}
else if (container instanceof Map<?, ?>)
{
Map<Serializable, Serializable> map = (Map<Serializable, Serializable>) container;
Serializable mapKey = getPropertyValueById(keyPropId).getSecond();
map.put(mapKey, value);
}
else if (container instanceof Collection<?>)
{
Collection<Serializable> collection = (Collection<Serializable>) container;
collection.add(value);
}
else
{
logger.error("Found container ID that is not a map or collection: " + linkEntity);
}
}
}
// This will have put the values into the correct containers
return result;
}
}