public void MapModifiedFlagsToMapFromEntity(ISessionImplementor session, IDictionary <string, object> data, object newObj, object oldObj) { var propertyData = CommonCollectionMapperData.CollectionReferencingPropertyData; if (propertyData.UsingModifiedFlag) { if (isNotPersistentCollection(newObj) || isNotPersistentCollection(oldObj)) { //Compare POCOs data[propertyData.ModifiedFlagPropertyName] = !Toolz.ObjectsEqual(newObj, oldObj); } else { var newObjAsPersistentCollection = (IPersistentCollection)newObj; if (isFromNullToEmptyOrFromEmptyToNull(newObjAsPersistentCollection, oldObj)) { data[propertyData.ModifiedFlagPropertyName] = true; } else { var changes = MapCollectionChanges(session, propertyData.Name, newObjAsPersistentCollection, oldObj, null); data[propertyData.ModifiedFlagPropertyName] = changes.Any(); } } } }
public AuditEntitiesConfiguration(IDictionary <String, String> properties, String revisionInfoEntityName) { this.RevisionInfoEntityName = revisionInfoEntityName; auditTablePrefix = Toolz.GetProperty(properties, "NHibernate.envers.audit_table_prefix", "NHibernate.envers.auditTablePrefix", ""); auditTableSuffix = Toolz.GetProperty(properties, "NHibernate.envers.audit_table_suffix", "NHibernate.envers.auditTableSuffix", "_AUD"); OriginalIdPropName = "originalId"; RevisionFieldName = Toolz.GetProperty(properties, "NHibernate.envers.revision_field_name", "NHibernate.envers.revisionFieldName", "REV"); RevisionTypePropName = Toolz.GetProperty(properties, "NHibernate.envers.revision_type_field_name", "NHibernate.envers.revisionTypeFieldName", "REVTYPE"); RevisionTypePropType = "byte"; customAuditTablesNames = new Dictionary <String, String>(); RevisionNumberPath = OriginalIdPropName + "." + RevisionFieldName + ".id"; revisionPropBasePath = OriginalIdPropName + "." + RevisionFieldName + "."; }
public void MapModifiedFlagsToMapFromEntity(ISessionImplementor session, IDictionary <string, object> data, object newObj, object oldObj) { if (_propertyData.UsingModifiedFlag) { data[_propertyData.ModifiedFlagPropertyName] = !Toolz.ObjectsEqual(newObj, oldObj); } }
private String GetMappedBy(Mapping.Collection collectionValue) { PersistentClass referencedClass = ((OneToMany)collectionValue.Element).AssociatedClass; // If there's an @AuditMappedBy specified, returning it directly. String auditMappedBy = propertyAuditingData.AuditMappedBy; if (auditMappedBy != null) { return(auditMappedBy); } IEnumerator <Property> assocClassProps = referencedClass.PropertyIterator.GetEnumerator(); while (assocClassProps.MoveNext()) { Property property = assocClassProps.Current; if (Toolz.IteratorsContentEqual(property.Value.ColumnIterator.GetEnumerator(), collectionValue.Key.ColumnIterator.GetEnumerator())) { return(property.Name); } } throw new MappingException("Unable to read the mapped by attribute for " + propertyName + " in " + referencingEntityName + "!"); }
public ISet <Tuple <string, System.Type> > FindEntityTypes(long revision) { ArgumentsTools.CheckPositive(revision, "revision"); if (!_verCfg.GlobalCfg.IsTrackEntitiesChangedInRevisionEnabled) { throw new AuditException(@"This query is designed for Envers default mechanism of tracking entities modified in a given revision." + " Extend DefaultTrackingModifiedEntitiesRevisionEntity, utilize ModifiedEntityNamesAttribute or set " + "'nhibernate.envers.track_entities_changed_in_revision' parameter to true."); } var session = _auditReaderImplementor.Session; var sessionImplementor = _auditReaderImplementor.SessionImplementor; var revisions = new HashSet <long> { revision }; var query = _verCfg.RevisionInfoQueryCreator.RevisionsQuery(session, revisions); var revisionInfo = query.UniqueResult(); if (revisionInfo != null) { // If revision exists var entityNames = _verCfg.ModifiedEntityNamesReader.ModifiedEntityTypes(revisionInfo); if (entityNames != null) { // Generate result that contains entity names and corresponding CLR classes. var result = new HashSet <Tuple <string, System.Type> >(); foreach (var entityName in entityNames) { result.Add(new Tuple <string, System.Type>(entityName, Toolz.ResolveEntityClass(sessionImplementor, entityName))); } return(result); } } return(new HashSet <Tuple <string, System.Type> >()); }
private void addCollectionChangeWorkUnit(AuditProcess auditProcess, ISessionImplementor session, string fromEntityName, RelationDescription relDesc, object value) { // relDesc.getToEntityName() doesn't always return the entity name of the value - in case // of subclasses, this will be root class, no the actual class. So it can't be used here. string toEntityName; object id; if (value is INHibernateProxy newValueAsProxy) { toEntityName = session.BestGuessEntityName(value); id = newValueAsProxy.HibernateLazyInitializer.Identifier; // We've got to initialize the object from the proxy to later read its state. value = Toolz.GetTargetFromProxy(session, newValueAsProxy); } else { toEntityName = session.GuessEntityName(value); var idMapper = VerCfg.EntCfg[toEntityName].IdMapper; id = idMapper.MapToIdFromEntity(value); } var toPropertyNames = VerCfg.EntCfg.ToPropertyNames(fromEntityName, relDesc.FromPropertyName, toEntityName); var toPropertyName = toPropertyNames.First(); auditProcess.AddWorkUnit(new CollectionChangeWorkUnit(session, toEntityName, toPropertyName, VerCfg, id, value)); }
public GlobalConfiguration(IDictionary <string, string> properties) { String generateRevisionsForCollectionsStr = Toolz.GetProperty(properties, "NHibernate.Envers.revision_on_collection_change", "NHibernate.Envers.revisionOnCollectionChange", "true"); generateRevisionsForCollections = Boolean.Parse(generateRevisionsForCollectionsStr); String ignoreOptimisticLockingPropertyStr = Toolz.GetProperty(properties, "NHibernate.Envers.do_not_audit_optimistic_locking_field", "NHibernate.Envers.doNotAuditOptimisticLockingField", "true"); doNotAuditOptimisticLockingField = Boolean.Parse(ignoreOptimisticLockingPropertyStr); String storeDataDeletedEntityStr = Toolz.GetProperty(properties, "NHibernate.Envers.store_data_at_delete", "NHibernate.Envers.storeDataAtDelete", "false"); storeDataAtDelete = Boolean.Parse(storeDataDeletedEntityStr); defaultSchemaName = Toolz.GetProperty(properties, "NHibernate.Envers.default_schema", ""); defaultCatalogName = Toolz.GetProperty(properties, "NHibernate.Envers.default_catalog", ""); //TODO Simon - see if we need to parametrize this, HSQLDialect (HSQLDB) not implemented for NHibernate correlatedSubqueryOperator = "org.hibernate.dialect.HSQLDialect".Equals( Toolz.GetProperty(properties, "hibernate.dialect", "")) ? "in" : "="; }
static void Main(string[] args) { Console.WriteLine(DateTime.Now); Toolz.SetTimeout(() => { Console.WriteLine(DateTime.Now); return(""); }, 10); }
/// <summary> /// Creates an entity instance based on an entry from the versions table. /// </summary> /// <param name="entityName">Name of the entity, which instances should be read.</param> /// <param name="versionsEntity">An entry in the versions table, from which data should be mapped.</param> /// <param name="revision">Revision at which this entity was read.</param> /// <returns>An entity instance, with versioned properties set as in the versionsEntity map, and proxies created for collections.</returns> public object CreateInstanceFromVersionsEntity(string entityName, IDictionary versionsEntity, long revision) { const string typeKey = "$type$"; if (versionsEntity == null) { return(null); } if (versionsEntity.Contains(typeKey)) { entityName = verCfg.EntCfg.GetEntityNameForVersionsEntityName((string)versionsEntity[typeKey]); } // First mapping the primary key var idMapper = verCfg.EntCfg[entityName].IdMapper; var originalId = (IDictionary)versionsEntity[verCfg.AuditEntCfg.OriginalIdPropName]; var primaryKey = idMapper.MapToIdFromMap(originalId); object ret; // Checking if the entity is in cache if (versionsReader.FirstLevelCache.TryGetValue(entityName, revision, primaryKey, out ret)) { return(ret); } // If it is not in the cache, creating a new entity instance try { var cls = Toolz.ResolveEntityClass(versionsReader.SessionImplementor, entityName); ret = verCfg.EntCfg[entityName].Factory(cls); } catch (Exception e) { throw new AuditException("Cannot create instance of type " + entityName, e); } // Putting the newly created entity instance into the first level cache, in case a one-to-one bidirectional // relation is present (which is eagerly loaded). versionsReader.FirstLevelCache.Add(entityName, revision, primaryKey, ret); verCfg.EntCfg[entityName].PropertyMapper.MapToEntityFromMap(verCfg, ret, versionsEntity, primaryKey, versionsReader, revision); idMapper.MapToEntityFromMap(ret, originalId); verCfg.GlobalCfg.PostInstantiationListener.PostInstantiate(ret); // Put entity on entityName cache after mapping it from the map representation versionsReader.FirstLevelCache.AddEntityName(primaryKey, revision, ret, entityName); return(ret); }
/// <summary> /// Notifies <see cref="IRevisionInfoGenerator"/> about changes made in the current revision. Provides information /// about modified entity class, entity name and its id, as well as <see cref="RevisionType"/> and revision log entity. /// </summary> /// <param name="currentRevisionData">Revision log entity.</param> /// <param name="vwu">Performed work unit.</param> public void EntityChanged(object currentRevisionData, IAuditWorkUnit vwu) { var entityId = vwu.EntityId; if (entityId is PersistentCollectionChangeWorkUnit.PersistentCollectionChangeWorkUnitId idAsPersistentColl) { entityId = idAsPersistentColl.OwnerId; } var entClass = Toolz.ResolveEntityClass(_sessionImplementor, vwu.EntityName); _revisionInfoGenerator.EntityChanged(entClass, vwu.EntityName, entityId, vwu.RevisionType, currentRevisionData); }
protected EntityInfo GetEntityInfo(AuditConfiguration verCfg, string entityName) { var entCfg = verCfg.EntCfg[entityName]; var isRelationAudited = true; if (entCfg == null) { // a relation marked as RelationTargetAuditMode.NOT_AUDITED entCfg = verCfg.EntCfg.GetNotVersionEntityConfiguration(entityName); isRelationAudited = false; } var entityClass = Toolz.ResolveDotnetType(entCfg.EntityClassName); return(new EntityInfo(entityClass, entityName, isRelationAudited)); }
public AuditedPropertiesReader(ModificationStore defaultStore, IPersistentPropertiesSource persistentPropertiesSource, IAuditedPropertiesHolder auditedPropertiesHolder, GlobalConfiguration globalCfg, String propertyNamePrefix) { this._defaultStore = defaultStore; this._persistentPropertiesSource = persistentPropertiesSource; this._auditedPropertiesHolder = auditedPropertiesHolder; this._globalCfg = globalCfg; this._propertyNamePrefix = propertyNamePrefix; _propertyAccessedPersistentProperties = Toolz.NewHashSet <String>(); _fieldAccessedPersistentProperties = Toolz.NewHashSet <String>(); }
public bool MapToMapFromEntity(ISessionImplementor session, IDictionary <String, Object> data, Object newObj, Object oldObj) { //Simon 27/06/2010 - era new LinkedHashMap IDictionary <String, Object> newData = new Dictionary <String, Object>(); data.Add(propertyData.Name, newData); // If this property is originally non-insertable, but made insertable because it is in a many-to-one "fake" // bi-directional relation, we always store the "old", unchaged data, to prevent storing changes made // to this field. It is the responsibility of the collection to properly update it if it really changed. delegat.MapToMapFromEntity(newData, nonInsertableFake ? oldObj : newObj); //noinspection SimplifiableConditionalExpression return(nonInsertableFake ? false : !Toolz.EntitiesEqual(session, newObj, oldObj)); }
/** * Creates an entity instance based on an entry from the versions table. * @param entityName Name of the entity, which instances should be read * @param versionsEntity An entry in the versions table, from which data should be mapped. * @param revision Revision at which this entity was read. * @return An entity instance, with versioned properties set as in the versionsEntity map, and proxies * created for collections. */ public Object CreateInstanceFromVersionsEntity(String entityName, IDictionary <string, object> versionsEntity, long revision) { if (versionsEntity == null) { return(null); } // The $type$ property holds the name of the (versions) entity String name = verCfg.EntCfg.GetEntityNameForVersionsEntityName(((String)versionsEntity["$type$"])); if (name != null) { entityName = name; } // First mapping the primary key IIdMapper idMapper = verCfg.EntCfg[entityName].GetIdMapper(); IDictionary <string, object> originalId = DictionaryWrapper <string, object> .Wrap((IDictionary)versionsEntity[verCfg.AuditEntCfg.OriginalIdPropName]); Object primaryKey = idMapper.MapToIdFromMap(originalId); // Checking if the entity is in cache if (versionsReader.FirstLevelCache.Contains(entityName, revision, primaryKey)) { return(versionsReader.FirstLevelCache[entityName, revision, primaryKey]); } // If it is not in the cache, creating a new entity instance Object ret; try { //System.Type cls = ReflectionTools.loadClass(entityName); //ret = ReflectHelper.GetDefaultConstructor(cls).newInstance(); ret = Activator.CreateInstance(Toolz.ResolveDotnetType(entityName)); } catch (Exception e) { throw new AuditException(e); } // Putting the newly created entity instance into the first level cache, in case a one-to-one bidirectional // relation is present (which is eagerly loaded). versionsReader.FirstLevelCache.Add(entityName, revision, primaryKey, ret); verCfg.EntCfg[entityName].PropertyMapper.MapToEntityFromMap(verCfg, ret, versionsEntity, primaryKey, versionsReader, revision); idMapper.MapToEntityFromMap(ret, originalId); return(ret); }
private void generateBidirectionalCollectionChangeWorkUnits(AuditProcess auditProcess, IEntityPersister entityPersister, string entityName, IList <object> newState, IList <object> oldState, ISessionImplementor session) { // Checking if this is enabled in configuration ... if (!VerCfg.GlobalCfg.GenerateRevisionsForCollections) { return; } // Checks every property of the entity, if it is an "owned" to-one relation to another entity. // If the value of that property changed, and the relation is bi-directional, a new revision // for the related entity is generated. var propertyNames = entityPersister.PropertyNames; for (var i = 0; i < propertyNames.GetLength(0); i++) { var propertyName = propertyNames[i]; var relDesc = VerCfg.EntCfg.GetRelationDescription(entityName, propertyName); if (relDesc != null && relDesc.Bidirectional && relDesc.RelationType == RelationType.ToOne && relDesc.Insertable) { // Checking for changes var oldValue = oldState?[i]; var newValue = newState?[i]; if (!Toolz.EntitiesEqual(session, oldValue, newValue)) { // We have to generate changes both in the old collection (size decreses) and new collection // (size increases). if (newValue != null) { addCollectionChangeWorkUnit(auditProcess, session, entityName, relDesc, newValue); } if (oldValue != null) { addCollectionChangeWorkUnit(auditProcess, session, entityName, relDesc, oldValue); } } } } }
public void MapToEntityFromMap(AuditConfiguration verCfg, object obj, IDictionary data, object primaryKey, IAuditReaderImplementor versionsReader, long revision) { if (data == null || obj == null) { return; } if (_propertyData.BeanName == null) { // If properties are not encapsulated in a component but placed directly in a class // (e.g. by applying <properties> tag). _delegate.MapToEntityFromMap(verCfg, obj, data, primaryKey, versionsReader, revision); return; } var setter = ReflectionTools.GetSetter(obj.GetType(), _propertyData); // If all properties are null and single, then the component has to be null also. var allNullAndSingle = true; foreach (var property in _delegate.Properties) { if (data[property.Key.Name] != null || !(property.Value is SinglePropertyMapper)) { allNullAndSingle = false; break; } } if (allNullAndSingle) { // single property, but default value need not be null, so we'll set it to null anyway setter.Set(obj, null); } else { var componentType = Toolz.ResolveDotnetType(_componentClassName); var subObj = ReflectionTools.CreateInstanceByDefaultConstructor(componentType); _delegate.MapToEntityFromMap(verCfg, subObj, data, primaryKey, versionsReader, revision); setter.Set(obj, subObj); } }
public void MapToEntityFromMap(AuditConfiguration verCfg, Object obj, IDictionary <String, Object> data, Object primaryKey, IAuditReaderImplementor versionsReader, long revision) { if (data == null || obj == null) { return; } //ORIG: Setter setter = ReflectionTools.getSetter(obj.getClass(), propertyData); PropertyInfo propInfo = obj.GetType().GetProperty(propertyData.Name); // If all properties are null and single, then the component has to be null also. bool allNullAndSingle = true; foreach (KeyValuePair <PropertyData, IPropertyMapper> property in _delegate.Properties) { if (data[property.Key.Name] != null || !(property.Value is SinglePropertyMapper)) { allNullAndSingle = false; break; } } // And we don't have to set anything on the object - the default value is null if (!allNullAndSingle) { try { //ORIG: Object subObj = ReflectHelper.getDefaultConstructor( // Thread.currentThread().getContextClassLoader().loadClass(componentClassName)).newInstance(); //setter.set(obj, subObj, null); object subObj = Activator.CreateInstance(Toolz.ResolveDotnetType(componentClassName)); propInfo.SetValue(obj, subObj, null); _delegate.MapToEntityFromMap(verCfg, subObj, data, primaryKey, versionsReader, revision); } catch (Exception e) { throw new AuditException(e); } } }
public void DoBeforeTransactionCompletion() { if (workUnits.Count == 0 && undoQueue.Count == 0) { return; } var castedSession = (ISession)session; if (castedSession.FlushMode == FlushMode.Manual) { using (var tempSession = Toolz.CreateChildSession(castedSession)) { executeInSession(tempSession); tempSession.Flush(); } } else { executeInSession(castedSession); // Explicity flushing the session, as the auto-flush may have already happened. castedSession.Flush(); } }
public void MapToEntityFromMap(AuditConfiguration verCfg, Object obj, IDictionary <String, Object> data, Object primaryKey, IAuditReaderImplementor versionsReader, long revision) { if (obj == null) { return; } Object entityId = delegat.MapToIdFromMap(DictionaryWrapper <String, Object> .Wrap((IDictionary)data[propertyData.Name])); Object value; if (entityId == null) { value = null; } else { if (versionsReader.FirstLevelCache.Contains(referencedEntityName, revision, entityId)) { value = versionsReader.FirstLevelCache[referencedEntityName, revision, entityId]; } else { //java: Class<?> entityClass = ReflectionTools.loadClass(referencedEntityName); value = versionsReader.SessionImplementor.Factory.GetEntityPersister(referencedEntityName).CreateProxy( entityId, new ToOneDelegateSessionImplementor(versionsReader, Toolz.ResolveDotnetType(referencedEntityName), entityId, revision, verCfg)); } } PropertyInfo propInfo = obj.GetType().GetProperty(propertyData.Name); propInfo.SetValue(obj, value, null); }
public MiddleEmbeddableComponentMapper(MultiPropertyMapper theDelegate, string componentClassName) { _delegate = theDelegate; _componentClass = Toolz.ResolveDotnetType(componentClassName); }
public FirstLevelCache() { cache = Toolz.NewDictionary <Triple <String, long, Object>, Object>(); }
public ClassAuditingData() { Properties = Toolz.NewDictionary <String, PropertyAuditingData>(); SecondaryTableDictionary = Toolz.NewDictionary <String, String>(); }
private void GenerateBidirectionalCollectionChangeWorkUnits(AuditSync verSync, IEntityPersister entityPersister, String entityName, Object[] newState, Object[] oldState, ISessionImplementor session) { // Checking if this is enabled in configuration ... if (!verCfg.GlobalCfg.isGenerateRevisionsForCollections()) { return; } // Checks every property of the entity, if it is an "owned" to-one relation to another entity. // If the value of that property changed, and the relation is bi-directional, a new revision // for the related entity is generated. String[] propertyNames = entityPersister.PropertyNames; for (int i = 0; i < propertyNames.GetLength(0); i++) { String propertyName = propertyNames[i]; RelationDescription relDesc = verCfg.EntCfg.GetRelationDescription(entityName, propertyName); if (relDesc != null && relDesc.Bidirectional && relDesc.RelationType == RelationType.TO_ONE && relDesc.Insertable) { // Checking for changes Object oldValue = oldState == null ? null : oldState[i]; Object newValue = newState == null ? null : newState[i]; if (!Toolz.EntitiesEqual(session, oldValue, newValue)) { // We have to generate changes both in the old collection (size decreses) and new collection // (size increases). //<TODO Simon: doua if-uri cu cod duplicat, refact. if (newValue != null) { // relDesc.getToEntityName() doesn't always return the entity name of the value - in case // of subclasses, this will be root class, no the actual class. So it can't be used here. String toEntityName; // Java: Serializable id object id; if (newValue is INHibernateProxy) { INHibernateProxy hibernateProxy = (INHibernateProxy)newValue; toEntityName = session.BestGuessEntityName(newValue); id = hibernateProxy.HibernateLazyInitializer.Identifier; // We've got to initialize the object from the proxy to later read its state. newValue = NHibernate.Envers.Tools.Toolz.GetTargetFromProxy(session.Factory, hibernateProxy); } else { toEntityName = session.GuessEntityName(newValue); IIdMapper idMapper = verCfg.EntCfg[toEntityName].GetIdMapper(); id = idMapper.MapToIdFromEntity(newValue); } verSync.AddWorkUnit(new CollectionChangeWorkUnit(session, toEntityName, verCfg, id, newValue)); } if (oldValue != null) { String toEntityName; object id; if (oldValue is INHibernateProxy) { INHibernateProxy hibernateProxy = (INHibernateProxy)oldValue; toEntityName = session.BestGuessEntityName(oldValue); id = hibernateProxy.HibernateLazyInitializer.Identifier; // We've got to initialize the object as we'll read it's state anyway. oldValue = Toolz.GetTargetFromProxy(session.Factory, hibernateProxy); } else { toEntityName = session.GuessEntityName(oldValue); IIdMapper idMapper = verCfg.EntCfg[toEntityName].GetIdMapper(); id = idMapper.MapToIdFromEntity(oldValue); } verSync.AddWorkUnit(new CollectionChangeWorkUnit(session, toEntityName, verCfg, id, oldValue)); } } } } }
protected override IEnumerable GetOldCollectionContent(object oldCollection) { return(oldCollection == null ? null : Toolz.ListToIndexElementPairList((IList)oldCollection)); }
private bool checkModified(ISessionImplementor session, object newObj, object oldObj) { return(!_nonInsertableFake && !Toolz.EntitiesEqual(session, newObj, oldObj)); }
public override IAuditWorkUnit Merge(AddWorkUnit second) { return(Toolz.ArraysEqual(second.State, state) ? null : new ModWorkUnit(SessionImplementor, EntityName, VerCfg, EntityId, entityPersister, second.State, state)); }
protected override IEnumerable GetNewCollectionContent(IPersistentCollection newCollection) { return(newCollection == null ? null : Toolz.ListToIndexElementPairList((IList)newCollection)); }