public IList <T> GetObjects <T>() { CheckNotDisposed(); IdentityHashSet <T> result = new IdentityHashSet <T>(); IList <T> parentResult = parent != null?parent.GetObjects <T>() : null; if (parentResult != null) { foreach (T parentItem in parentResult) { result.Add(parentItem); } } readLock.Lock(); try { HandleObjects(delegate(Object obj) { if (typeof(T).IsAssignableFrom(obj.GetType())) { result.Add((T)obj); } }); return(ListUtil.ToList(result)); } finally { readLock.Unlock(); } }
protected ICacheWalkerResult WalkIntern(IObjRef[] objRefs, IdentityHashSet <ICache> allCachesSet) { IdentityHashMap <ICache, List <ICache> > cacheToChildCaches = new IdentityHashMap <ICache, List <ICache> >(); IdentityHashMap <ICache, ICache> cacheToProxyCache = new IdentityHashMap <ICache, ICache>(); ICache currentCommittedRootCache = CommittedRootCache.CurrentCache; if (!CacheProvider.IsNewInstanceOnCall) { allCachesSet.Add(FirstLevelCache.CurrentCache); } ICache[] allChildCaches = allCachesSet.ToArray(); allCachesSet.Add(currentCommittedRootCache); foreach (ICache childCache in allChildCaches) { ICache child = childCache; ICache parent = ((ChildCache)child).Parent; while (parent != null) { ICache currentParent = parent.CurrentCache; if (!allCachesSet.Add(currentParent)) { // skip this cache. we handled it already break; } CheckParentCache(parent, currentParent, child, cacheToChildCaches, cacheToProxyCache); parent = ((IRootCache)currentParent).Parent; child = currentParent; } CheckParentCache(CommittedRootCache, currentCommittedRootCache, child, cacheToChildCaches, cacheToProxyCache); } if (objRefs != allEntityRefs) { objRefs = new CHashSet <IObjRef>(objRefs).ToArray(); Array.Sort(objRefs, ObjRef.comparator); } CacheWalkerResult rootEntry = BuildWalkedEntry(currentCommittedRootCache, objRefs, cacheToChildCaches, cacheToProxyCache); if (objRefs == allEntityRefs) { HashMap <IObjRef, int?> allObjRefs = new HashMap <IObjRef, int?>(); CollectAllObjRefs(rootEntry, allObjRefs); objRefs = allObjRefs.Count > 0 ? ListUtil.ToArray(allObjRefs.KeyList()) : ObjRef.EMPTY_ARRAY; Array.Sort(objRefs, ObjRef.comparator); for (int a = objRefs.Length; a-- > 0;) { allObjRefs.Put(objRefs[a], a); } ReallocateObjRefsAndCacheValues(rootEntry, objRefs, allObjRefs); } return(rootEntry); }
protected void WaitEventToResume(IBackgroundWorkerParamDelegate <IProcessResumeItem> resumeDelegate, IBackgroundWorkerParamDelegate <Exception> errorDelegate) { IRootCache rootCache = RootCache; IList <IWritableCache> selectedFirstLevelCaches = FirstLevelCacheManager.SelectFirstLevelCaches(); ISet <Object> collisionSet = new IdentityHashSet <Object>(); collisionSet.Add(rootCache); for (int a = selectedFirstLevelCaches.Count; a-- > 0;) { collisionSet.Add(selectedFirstLevelCaches[a]); } // Without the current rootcache we can not handle the event now. We have to block till the rootCache and all childCaches get valid EventDispatcher.WaitEventToResume(collisionSet, -1, resumeDelegate, errorDelegate); }
public virtual void DisplayCurrentSortStates() { GridViewColumnCollection columns = GridViewDataControl.Columns; ISet <GridViewBoundColumnBase> unmatchedColumns = new IdentityHashSet <GridViewBoundColumnBase>(); foreach (GridViewBoundColumnBase column in columns) { unmatchedColumns.Add(column); } foreach (AmbethSortDescriptor sortDescriptor in SortDescriptorList) { foreach (GridViewBoundColumnBase column in columns) { if (column.GetDataMemberName() == sortDescriptor.Member) { column.SortingState = SortDescriptorConverter.GetTelerikSortingState(sortDescriptor); unmatchedColumns.Remove(column); break; } } } foreach (GridViewBoundColumnBase unmatchedColumn in unmatchedColumns) { unmatchedColumn.SortingState = SortingState.None; } }
public virtual void RemoveArgument(ExtractionObject argToRemove, bool removeParent) { ICollection <ExtractionObject> thisEvent = new IdentityHashSet <ExtractionObject>(); thisEvent.Add(argToRemove); RemoveArguments(thisEvent, removeParent); }
protected void BuildCollisionSetIntern(CacheDependencyNode node, IdentityHashSet <Object> collisionSet) { collisionSet.Add(node.rootCache); List <CacheDependencyNode> childNodes = node.childNodes; for (int a = childNodes.Count; a-- > 0;) { BuildCollisionSetIntern(childNodes[a], collisionSet); } collisionSet.AddAll(node.directChildCaches); }
protected void HandleObjects(HandleObjectsDelegate handleObjectsDelegate) { IdentityHashSet <Object> alreadyHandledSet = new IdentityHashSet <Object>(); foreach (Entry <Type, Object> entry in typeToServiceDict) { Object obj = entry.Value; if (alreadyHandledSet.Add(obj)) { handleObjectsDelegate.Invoke(obj); } } foreach (Entry <String, Object> entry in nameToServiceDict) { Object obj = entry.Value; if (alreadyHandledSet.Add(obj)) { handleObjectsDelegate.Invoke(obj); } } }
public void Register(V listener) { ParamChecker.AssertParamNotNull(listener, message); Lock writeLock = this.writeLock; writeLock.Lock(); try { ParamChecker.AssertTrue(set.Add(listener), message); } finally { writeLock.Unlock(); } }
/** * Create a disjoint set for the element passed in. This method should be * called for all elements before any of the other API methods are called * (i.e. construct a disjoint set for each element first and then union them * together as appropriate). * * @param element * the element for which a new disjoint set should be * constructed. */ public void makeSet(E element) { if (!elementToSet.ContainsKey(element)) { // Note: It is necessary to use an identity based hash set // whose equal and hashCode method are based on the Sets // identity and not its elements as we are adding // this set to a set but changing its values as unions // occur. ISet <E> set = new IdentityHashSet <E>(); set.Add(element); elementToSet.Put(element, set); disjointSets.Add(set); } }
protected void FilterWrongRelationMappings(IISet <RelationMember> relationMembers) { // filter all relations which can not be a relation because of explicit embedded property mapping IdentityHashSet <RelationMember> toRemove = new IdentityHashSet <RelationMember>(); foreach (RelationMember relationMember in relationMembers) { String[] memberPath = EmbeddedMember.Split(relationMember.Name); foreach (RelationMember otherRelationMember in relationMembers) { if (Object.ReferenceEquals(relationMember, otherRelationMember) || toRemove.Contains(otherRelationMember)) { continue; } if (!(otherRelationMember is IEmbeddedMember)) { // only embedded members can help identifying other wrong relation members continue; } String[] otherMemberPath = ((IEmbeddedMember)otherRelationMember).GetMemberPathToken(); if (memberPath.Length > otherMemberPath.Length) { continue; } bool match = true; for (int a = 0, size = memberPath.Length; a < size; a++) { if (!memberPath[a].Equals(otherMemberPath[a])) { match = false; break; } } if (match) { toRemove.Add(relationMember); break; } } } relationMembers.RemoveAll(toRemove); }
public IBusyToken AcquireBusyToken() { BusyToken token = new BusyToken(this); bool changed; lock (pendingTokens) { pendingTokens.Add(token); changed = (pendingTokens.Count == 1); } GuiThreadHelper.InvokeInGui(delegate() { PropertyChanged(this, busyCountPCE); // Busy flag might evaluate to true if (changed) { PropertyChanged(this, isBusyPCE); } }); return(token); }
public IList <T> GetImplementingObjects <T>() { IdentityHashSet <T> set = new IdentityHashSet <T>(); Lock readLock = this.readLock; readLock.Lock(); try { HandleObjects(delegate(Object obj) { if (typeof(T).IsAssignableFrom(obj.GetType())) { set.Add((T)obj); } }); return(ListUtil.ToList(set)); } finally { readLock.Unlock(); } }
public ICacheWalkerResult WalkEntities <T>(params T[] entities) { IList <IObjRef> objRefs = new List <IObjRef>(entities.Length); objRefs = ObjRefHelper.ExtractObjRefList(entities, null, objRefs); IdentityHashSet <ICache> allCachesSet = new IdentityHashSet <ICache>(); foreach (Object entity in entities) { if (entity is IValueHolderContainer) { ICache targetCache = ((IValueHolderContainer)entity).__TargetCache; if (targetCache != null) { allCachesSet.Add(targetCache); } } } return(WalkIntern(ListUtil.ToArray(objRefs), allCachesSet)); }
public void WaitEventToResume(Object eventTargetToResume, long maxWaitTime, IBackgroundWorkerParamDelegate <IProcessResumeItem> resumeDelegate, IBackgroundWorkerParamDelegate <Exception> errorDelegate) { try { IdentityHashSet <Object> pendingSet = new IdentityHashSet <Object>(); if (eventTargetToResume is IEnumerable) { pendingSet.AddAll((IEnumerable)eventTargetToResume); } else { pendingSet.Add(eventTargetToResume); } WaitForResumeItem pauseItem = null; listenersWriteLock.Lock(); try { IList <Object> remainingPausedEventTargets = EvaluatePausedEventTargetsOfForeignThreads(); IdentityLinkedSet <Object> remainingPausedEventTargetsSet = new IdentityLinkedSet <Object>(remainingPausedEventTargets); remainingPausedEventTargetsSet.RetainAll(pendingSet); if (remainingPausedEventTargetsSet.Count > 0) { // We should wait now but we have to check if we are in the UI thread, which must never wait if (GuiThreadHelper.IsInGuiThread()) { // This is the trick: We "requeue" the current action in the UI pipeline to prohibit blocking GuiThreadHelper.InvokeInGuiLate(delegate() { WaitEventToResume(eventTargetToResume, maxWaitTime, resumeDelegate, errorDelegate); }); return; } pauseItem = new WaitForResumeItem(pendingSet); waitForResumeSet.Add(pauseItem); } } finally { listenersWriteLock.Unlock(); } if (pauseItem == null) { resumeDelegate.Invoke(null); return; } CountDownLatch latch = pauseItem.Latch; if (maxWaitTime < 0) { latch.Await(); } else if (maxWaitTime > 0) { latch.Await(TimeSpan.FromMilliseconds(maxWaitTime)); } else { throw new System.Exception("Thread should wait but does not want to"); } resumeDelegate.Invoke(pauseItem); } catch (Exception e) { if (Log.ErrorEnabled) { Log.Error(e); } if (errorDelegate != null) { errorDelegate.Invoke(e); } throw; } }
/* * Non-recursive version of object descend. this consumes more memory than recursive in-depth * traversal but prevents stack overflows on long chains of objects * or complex graphs (a max. recursion depth on my machine was ~5000 objects linked in a chain * so not too much). */ private static long MeasureObjectSize(object root) { // Objects seen so far. IdentityHashSet <object> seen = new IdentityHashSet <object>(); // Class cache with reference Field and precalculated shallow size. IDictionary <Type, ClassCache> classCache = new JCG.Dictionary <Type, ClassCache>(IdentityEqualityComparer <Type> .Default); // Stack of objects pending traversal. Recursion caused stack overflows. Stack <object> stack = new Stack <object>(); stack.Push(root); long totalSize = 0; while (stack.Count > 0) { object ob = stack.Pop(); if (ob is null || seen.Contains(ob)) { continue; } seen.Add(ob); Type obClazz = ob.GetType(); // LUCENENET specific - .NET cannot return a null type for an object, so no need to assert it if (obClazz.Equals(typeof(string))) { // LUCENENET specific - we can get a closer estimate of a string // by using simple math. Reference: http://stackoverflow.com/a/8171099. // This fixes the TestSanity test. totalSize += (2 * (((string)ob).Length + 1)); } if (obClazz.IsArray) { /* * Consider an array, possibly of primitive types. Push any of its references to * the processing stack and accumulate this array's shallow size. */ long size = NUM_BYTES_ARRAY_HEADER; Array array = (Array)ob; int len = array.Length; if (len > 0) { Type componentClazz = obClazz.GetElementType(); if (componentClazz.IsPrimitive) { size += (long)len * primitiveSizes[componentClazz]; } else { size += (long)NUM_BYTES_OBJECT_REF * len; // Push refs for traversal later. for (int i = len; --i >= 0;) { object o = array.GetValue(i); if (o != null && !seen.Contains(o)) { stack.Push(o); } } } } totalSize += AlignObjectSize(size); } else { /* * Consider an object. Push any references it has to the processing stack * and accumulate this object's shallow size. */ try { if (!classCache.TryGetValue(obClazz, out ClassCache cachedInfo) || cachedInfo is null) { classCache[obClazz] = cachedInfo = CreateCacheEntry(obClazz); } foreach (FieldInfo f in cachedInfo.ReferenceFields) { // Fast path to eliminate redundancies. object o = f.GetValue(ob); if (o != null && !seen.Contains(o)) { stack.Push(o); } } totalSize += cachedInfo.AlignedShallowInstanceSize; } catch (Exception e) when(e.IsIllegalAccessException()) { // this should never happen as we enabled setAccessible(). throw RuntimeException.Create("Reflective field access failed?", e); } } } // Help the GC (?). seen.Clear(); stack.Clear(); classCache.Clear(); return(totalSize); }
static TestRandomChains() { try { brokenConstructors[typeof(LimitTokenCountFilter).GetConstructor(new Type[] { typeof(TokenStream), typeof(int) })] = ALWAYS; brokenConstructors[typeof(LimitTokenCountFilter).GetConstructor(new Type[] { typeof(TokenStream), typeof(int), typeof(bool) })] = new PredicateAnonymousInnerClassHelper2(); brokenConstructors[typeof(LimitTokenPositionFilter).GetConstructor(new Type[] { typeof(TokenStream), typeof(int) })] = ALWAYS; brokenConstructors[typeof(LimitTokenPositionFilter).GetConstructor(new Type[] { typeof(TokenStream), typeof(int), typeof(bool) })] = new PredicateAnonymousInnerClassHelper3(); foreach (Type c in Arrays.AsList( // TODO: can we promote some of these to be only // offsets offenders? // doesn't actual reset itself: typeof(CachingTokenFilter), // Not broken, simulates brokenness: typeof(CrankyTokenFilter), // Not broken: we forcefully add this, so we shouldn't // also randomly pick it: typeof(ValidatingTokenFilter))) { foreach (ConstructorInfo ctor in c.GetConstructors()) { brokenConstructors[ctor] = ALWAYS; } } } catch (Exception e) { throw new Exception(e.Message, e); } try { foreach (Type c in Arrays.AsList( typeof(ReversePathHierarchyTokenizer), typeof(PathHierarchyTokenizer), // TODO: it seems to mess up offsets!? typeof(WikipediaTokenizer), // TODO: doesn't handle graph inputs typeof(CJKBigramFilter), // TODO: doesn't handle graph inputs (or even look at positionIncrement) typeof(HyphenatedWordsFilter), // TODO: LUCENE-4983 typeof(CommonGramsFilter), // TODO: doesn't handle graph inputs typeof(CommonGramsQueryFilter), // TODO: probably doesnt handle graph inputs, too afraid to try typeof(WordDelimiterFilter))) { foreach (ConstructorInfo ctor in c.GetConstructors()) { brokenOffsetsConstructors[ctor] = ALWAYS; } } } catch (Exception e) { throw new Exception(e.Message, e); } allowedTokenizerArgs = new IdentityHashSet <Type>(); // Collections.NewSetFromMap(new IdentityHashMap<Type, bool?>()); allowedTokenizerArgs.addAll(argProducers.Keys); allowedTokenizerArgs.Add(typeof(TextReader)); allowedTokenizerArgs.Add(typeof(AttributeSource.AttributeFactory)); allowedTokenizerArgs.Add(typeof(AttributeSource)); allowedTokenFilterArgs = new IdentityHashSet <Type>(); //Collections.newSetFromMap(new IdentityHashMap<Type, bool?>()); allowedTokenFilterArgs.addAll(argProducers.Keys); allowedTokenFilterArgs.Add(typeof(TokenStream)); // TODO: fix this one, thats broken: allowedTokenFilterArgs.Add(typeof(CommonGramsFilter)); allowedCharFilterArgs = new IdentityHashSet <Type>(); //Collections.newSetFromMap(new IdentityHashMap<Type, bool?>()); allowedCharFilterArgs.addAll(argProducers.Keys); allowedCharFilterArgs.Add(typeof(TextReader)); }
/* * Non-recursive version of object descend. this consumes more memory than recursive in-depth * traversal but prevents stack overflows on long chains of objects * or complex graphs (a max. recursion depth on my machine was ~5000 objects linked in a chain * so not too much). */ private static long MeasureObjectSize(object root) { // Objects seen so far. IdentityHashSet <object> seen = new IdentityHashSet <object>(); // Class cache with reference Field and precalculated shallow size. HashMap <Type, ClassCache> classCache = new HashMap <Type, ClassCache>(); // Stack of objects pending traversal. Recursion caused stack overflows. Stack <object> stack = new Stack <object>(); stack.Push(root); long totalSize = 0; while (stack.Count > 0) { object ob = stack.Pop(); if (ob == null || seen.Contains(ob)) { continue; } seen.Add(ob); Type obClazz = ob.GetType(); if (obClazz.IsArray) { /* * Consider an array, possibly of primitive types. Push any of its references to * the processing stack and accumulate this array's shallow size. */ long size = NUM_BYTES_ARRAY_HEADER; Array array = (Array)ob; int len = array.Length; if (len > 0) { Type componentClazz = obClazz.GetElementType(); if (componentClazz.IsPrimitive) { size += (long)len * PrimitiveSizes[componentClazz]; } else { size += (long)NUM_BYTES_OBJECT_REF * len; // Push refs for traversal later. for (int i = len; --i >= 0;) { object o = array.GetValue(i); if (o != null && !seen.Contains(o)) { stack.Push(o); } } } } totalSize += AlignObjectSize(size); } else { /* * Consider an object. Push any references it has to the processing stack * and accumulate this object's shallow size. */ try { ClassCache cachedInfo = classCache[obClazz]; if (cachedInfo == null) { classCache[obClazz] = cachedInfo = CreateCacheEntry(obClazz); } foreach (FieldInfo f in cachedInfo.ReferenceFields) { // Fast path to eliminate redundancies. object o = f.GetValue(ob); if (o != null && !seen.Contains(o)) { stack.Push(o); } } totalSize += cachedInfo.AlignedShallowInstanceSize; } catch (Exception e) { // this should never happen as we enabled setAccessible(). throw new Exception("Reflective field access failed?", e); } } } // Help the GC (?). seen.Clear(); stack.Clear(); classCache.Clear(); return(totalSize); }
public Type GetEnhancedType(Type typeToEnhance, String newTypeNamePrefix, IEnhancementHint hint) { Type extendedType = GetEnhancedTypeIntern(typeToEnhance, hint); if (extendedType != null) { return(extendedType); } lock (writeLock) { // Concurrent thread may have been faster extendedType = GetEnhancedTypeIntern(typeToEnhance, hint); if (extendedType != null) { return(extendedType); } if (Log.InfoEnabled) { Log.Info("Enhancing " + typeToEnhance + " with hint: " + hint); } ValueType valueType = DictionaryExtension.ValueOrDefault(typeToExtendedType, typeToEnhance); if (valueType == null) { valueType = new ValueType(); typeToExtendedType.Add(typeToEnhance, valueType); } else { valueType.AddChangeCount(); newTypeNamePrefix += "_O" + valueType.ChangeCount; } List <IBytecodeBehavior> pendingBehaviors = new List <IBytecodeBehavior>(); IBytecodeBehavior[] extensions = bytecodeBehaviorExtensions.GetExtensions(); pendingBehaviors.AddRange(extensions); Type enhancedType; if (pendingBehaviors.Count > 0) { enhancedType = EnhanceTypeIntern(typeToEnhance, newTypeNamePrefix, pendingBehaviors, hint); } else { enhancedType = typeToEnhance; } WeakReference entityTypeR = typeToExtendedType.GetWeakReferenceEntry(typeToEnhance); if (entityTypeR == null) { throw new Exception("Must never happen"); } hardRefToTypes.Add(enhancedType); hardRefToTypes.Add(typeToEnhance); if (TraceDir != null) { LogBytecodeOutput(enhancedType.FullName, BytecodeClassLoader.ToPrintableBytecode(enhancedType)); } else if (Log.DebugEnabled) { // note that this intentionally will only be logged to the console if the traceDir is NOT specified already Log.Debug(BytecodeClassLoader.ToPrintableBytecode(enhancedType)); } try { CheckEnhancedTypeConsistency(enhancedType); } catch (Exception e) { if (Log.ErrorEnabled) { Log.Error(BytecodeClassLoader.ToPrintableBytecode(enhancedType), e); } BytecodeClassLoader.Save(); throw; } WeakReference enhancedEntityTypeR = new WeakReference(enhancedType); valueType.Put(hint, enhancedEntityTypeR); extendedTypeToType.Add(enhancedType, entityTypeR); if (Log.InfoEnabled) { Log.Info("Enhancement finished successfully with type: " + enhancedType); } return(enhancedType); } }
protected CacheWalkerResult BuildWalkedEntry(ICache cache, IObjRef[] objRefs, IdentityHashMap <ICache, List <ICache> > cacheToChildCaches, IdentityHashMap <ICache, ICache> cacheToProxyCache) { List <ICache> childCaches = cacheToChildCaches.Get(cache); CacheWalkerResult[] childCacheEntries; if (childCaches == null) { childCacheEntries = null; } else { childCacheEntries = new CacheWalkerResult[childCaches.Count]; for (int a = childCaches.Count; a-- > 0;) { childCacheEntries[a] = BuildWalkedEntry(childCaches[a], objRefs, cacheToChildCaches, cacheToProxyCache); } } ICache proxyCache = cacheToProxyCache.Get(cache); bool transactional = false, threadLocal = false; if (proxyCache != null) { threadLocal = true; if (TransactionState != null && TransactionState.IsTransactionActive) { transactional = true; } } IList <Object> cacheValues; if (objRefs != allEntityRefs) { if (cache is ChildCache) { cacheValues = cache.GetObjects(objRefs, CacheDirective.FailEarly | CacheDirective.ReturnMisses); } else { cacheValues = cache.GetObjects(objRefs, CacheDirective.FailEarly | CacheDirective.CacheValueResult | CacheDirective.ReturnMisses); } } else { IdentityHashSet <Object> fCacheValues = new IdentityHashSet <Object>(); cache.GetContent(new HandleContentDelegate(delegate(Type entityType, sbyte idIndex, Object id, Object value) { fCacheValues.Add(value); })); cacheValues = fCacheValues.ToList(); // generate ad-hoc objRefs objRefs = cacheValues.Count > 0 ? ListUtil.ToArray(ObjRefHelper.ExtractObjRefList(cacheValues, null)) : ObjRef.EMPTY_ARRAY; } Object childEntries = childCacheEntries; if (childCacheEntries != null && childCacheEntries.Length == 1) { childEntries = childCacheEntries[0]; } CacheWalkerResult parentEntry = new CacheWalkerResult(cache, transactional, threadLocal, objRefs, ListUtil.ToArray(cacheValues), childEntries); if (childCacheEntries != null) { for (int a = childCacheEntries.Length; a-- > 0;) { childCacheEntries[a].ParentEntry = parentEntry; } } if (objRefs != allEntityRefs) { parentEntry.UpdatePendingChanges(); } return(parentEntry); }
public void AddMembers(EntityMetaData metaData, IEntityConfig entityConfig) { Type realType = entityConfig.RealType; ISet <String> memberNamesToIgnore = new HashSet <String>(); ISet <String> explicitBasicMemberNames = new HashSet <String>(); IList <IMemberConfig> embeddedMembers = new List <IMemberConfig>(); IMap <String, IMemberConfig> nameToMemberConfig = new HashMap <String, IMemberConfig>(); IMap <String, IRelationConfig> nameToRelationConfig = new HashMap <String, IRelationConfig>(); IdentityLinkedMap <String, Member> nameToMemberMap = new IdentityLinkedMap <String, Member>(); FillNameCollections(entityConfig, memberNamesToIgnore, explicitBasicMemberNames, embeddedMembers, nameToMemberConfig, nameToRelationConfig); IdentityLinkedSet <PrimitiveMember> alternateIdMembers = new IdentityLinkedSet <PrimitiveMember>(); IdentityLinkedSet <PrimitiveMember> primitiveMembers = new IdentityLinkedSet <PrimitiveMember>(); IdentityLinkedSet <RelationMember> relationMembers = new IdentityLinkedSet <RelationMember>(); IdentityLinkedSet <Member> notMergeRelevant = new IdentityLinkedSet <Member>(); IdentityLinkedSet <Member> containedInAlternateIdMember = new IdentityLinkedSet <Member>(); IPropertyInfo[] properties = PropertyInfoProvider.GetProperties(realType); IdentityLinkedMap <String, Member> explicitlyConfiguredMemberNameToMember = new IdentityLinkedMap <String, Member>(); HashMap <String, IOrmConfig> nameToConfigMap = new HashMap <String, IOrmConfig>(); // Resolve members for all explicit configurations - both simple and composite ones, each with embedded // functionality (dot-member-path) foreach (IMemberConfig memberConfig in entityConfig.GetMemberConfigIterable()) { PutNameToConfigMap(memberConfig, nameToConfigMap); if (memberConfig.Ignore) { continue; } HandleMemberConfig(metaData, realType, memberConfig, explicitlyConfiguredMemberNameToMember, nameToMemberMap); } foreach (IRelationConfig relationConfig in entityConfig.GetRelationConfigIterable()) { PutNameToConfigMap(relationConfig, nameToConfigMap); HandleRelationConfig(realType, relationConfig, explicitlyConfiguredMemberNameToMember); } PutNameToConfigMap(entityConfig.IdMemberConfig, nameToConfigMap); PutNameToConfigMap(entityConfig.VersionMemberConfig, nameToConfigMap); PutNameToConfigMap(entityConfig.CreatedByMemberConfig, nameToConfigMap); PutNameToConfigMap(entityConfig.CreatedOnMemberConfig, nameToConfigMap); PutNameToConfigMap(entityConfig.UpdatedByMemberConfig, nameToConfigMap); PutNameToConfigMap(entityConfig.UpdatedOnMemberConfig, nameToConfigMap); metaData.IdMember = HandleMemberConfig(metaData, realType, entityConfig.IdMemberConfig, explicitlyConfiguredMemberNameToMember, nameToMemberMap); metaData.VersionMember = HandleMemberConfig(metaData, realType, entityConfig.VersionMemberConfig, explicitlyConfiguredMemberNameToMember, nameToMemberMap); metaData.CreatedByMember = HandleMemberConfig(metaData, realType, entityConfig.CreatedByMemberConfig, explicitlyConfiguredMemberNameToMember, nameToMemberMap); metaData.CreatedOnMember = HandleMemberConfig(metaData, realType, entityConfig.CreatedOnMemberConfig, explicitlyConfiguredMemberNameToMember, nameToMemberMap); metaData.UpdatedByMember = HandleMemberConfig(metaData, realType, entityConfig.UpdatedByMemberConfig, explicitlyConfiguredMemberNameToMember, nameToMemberMap); metaData.UpdatedOnMember = HandleMemberConfig(metaData, realType, entityConfig.UpdatedOnMemberConfig, explicitlyConfiguredMemberNameToMember, nameToMemberMap); IdentityHashSet <Member> idMembers = new IdentityHashSet <Member>(); Member idMember = metaData.IdMember; if (idMember is CompositeIdMember) { idMembers.AddAll(((CompositeIdMember)idMember).Members); } else { idMembers.Add(idMember); } // Handle all explicitly configured members foreach (Entry <String, Member> entry in explicitlyConfiguredMemberNameToMember) { String memberName = entry.Key; IOrmConfig ormConfig = nameToConfigMap.Get(memberName); Member member = entry.Value; if (idMembers.Contains(member)) { continue; } if (ormConfig.ExplicitlyNotMergeRelevant) { notMergeRelevant.Add(member); } if (ormConfig is IRelationConfig) { if (!relationMembers.Add((RelationMember)member)) { throw new Exception("Member has been registered as relation multiple times: " + member.Name); } continue; } if (!(ormConfig is IMemberConfig)) { continue; } if (((IMemberConfig)ormConfig).AlternateId) { if (!alternateIdMembers.Add((PrimitiveMember)member)) { throw new Exception("Member has been registered as alternate id multiple times: " + member.Name); } if (member is CompositeIdMember) { Member[] containedMembers = ((CompositeIdMember)member).Members; containedInAlternateIdMember.AddAll(containedMembers); } } if (!(member is CompositeIdMember) && metaData.VersionMember != member) { // Alternate Ids are normally primitives, too. But Composite Alternate Ids not - only their composite // items are primitives primitiveMembers.Add((PrimitiveMember)member); } } IdentityHashSet <String> explicitTypeInfoItems = IdentityHashSet <String> .Create(explicitlyConfiguredMemberNameToMember.Count); foreach (Entry <String, Member> entry in explicitlyConfiguredMemberNameToMember) { Member member = entry.Value; explicitTypeInfoItems.Add(member.Name); if (member is IEmbeddedMember) { explicitTypeInfoItems.Add(((IEmbeddedMember)member).GetMemberPath()[0].Name); } } // Go through the available members to look for potential auto-mapping (simple, no embedded) for (int i = 0; i < properties.Length; i++) { IPropertyInfo property = properties[i]; String memberName = property.Name; if (memberNamesToIgnore.Contains(memberName)) { continue; } if (explicitTypeInfoItems.Contains(memberName)) { // already configured, no auto mapping needed for this member continue; } MethodPropertyInfo mProperty = (MethodPropertyInfo)property; Type elementType = TypeInfoItemUtil.GetElementTypeUsingReflection(mProperty.Getter.ReturnType, null); if ((nameToMemberMap.Get(property.Name) is RelationMember) || RelationProvider.IsEntityType(elementType)) { RelationMember member = GetRelationMember(metaData.EntityType, property, nameToMemberMap); relationMembers.Add(member); continue; } PrimitiveMember member2 = GetPrimitiveMember(metaData.EntityType, property, nameToMemberMap); if (metaData.IdMember == null && memberName.Equals(EntityMetaData.DEFAULT_NAME_ID)) { metaData.IdMember = member2; continue; } if (idMembers.Contains(member2) && !alternateIdMembers.Contains(member2) && !containedInAlternateIdMember.Contains(member2)) { continue; } if (member2.Equals(metaData.IdMember) || member2.Equals(metaData.VersionMember) || member2.Equals(metaData.CreatedByMember) || member2.Equals(metaData.CreatedOnMember) || member2.Equals(metaData.UpdatedByMember) || member2.Equals(metaData.UpdatedOnMember)) { continue; } if (metaData.VersionMember == null && memberName.Equals(EntityMetaData.DEFAULT_NAME_VERSION)) { metaData.VersionMember = member2; continue; } if (metaData.CreatedByMember == null && memberName.Equals(EntityMetaData.DEFAULT_NAME_CREATED_BY)) { metaData.CreatedByMember = member2; } else if (metaData.CreatedOnMember == null && memberName.Equals(EntityMetaData.DEFAULT_NAME_CREATED_ON)) { metaData.CreatedOnMember = member2; } else if (metaData.UpdatedByMember == null && memberName.Equals(EntityMetaData.DEFAULT_NAME_UPDATED_BY)) { metaData.UpdatedByMember = member2; } else if (metaData.UpdatedOnMember == null && memberName.Equals(EntityMetaData.DEFAULT_NAME_UPDATED_ON)) { metaData.UpdatedOnMember = member2; } primitiveMembers.Add(member2); } foreach (PrimitiveMember member in primitiveMembers) { String memberName = member.Name; if (explicitBasicMemberNames.Contains(memberName)) { // Even if the name would match, this member was explicitly configured as "basic" continue; } if (metaData.CreatedByMember == null && memberName.Equals(EntityMetaData.DEFAULT_NAME_CREATED_BY)) { metaData.CreatedByMember = member; } else if (metaData.CreatedOnMember == null && memberName.Equals(EntityMetaData.DEFAULT_NAME_CREATED_ON)) { metaData.CreatedOnMember = member; } else if (metaData.UpdatedByMember == null && memberName.Equals(EntityMetaData.DEFAULT_NAME_UPDATED_BY)) { metaData.UpdatedByMember = member; } else if (metaData.UpdatedOnMember == null && memberName.Equals(EntityMetaData.DEFAULT_NAME_UPDATED_ON)) { metaData.UpdatedOnMember = member; } } FilterWrongRelationMappings(relationMembers); // Order of setter calls is important PrimitiveMember[] primitives = primitiveMembers.ToArray(); PrimitiveMember[] alternateIds = alternateIdMembers.ToArray(); RelationMember[] relations = relationMembers.ToArray(); Array.Sort(primitives); Array.Sort(alternateIds); Array.Sort(relations); metaData.PrimitiveMembers = primitives; metaData.AlternateIdMembers = alternateIds; metaData.RelationMembers = relations; foreach (Member member in notMergeRelevant) { metaData.SetMergeRelevant(member, false); } if (metaData.IdMember == null) { throw new Exception("No ID member could be resolved for entity of type " + metaData.RealType); } }
public virtual void AfterPropertiesSet(IBeanContextFactory beanContextFactory) { ParamChecker.AssertNotNull(RevertChangesHelper, "RevertChangesHelper"); ParamChecker.AssertNotNull(SharedData, "SharedData"); ParamChecker.AssertNotNull(SharedDataHandOnExtendable, "SharedDataHandOnExtendable"); //TODO: inject Uri as bean #if SILVERLIGHT Uri uri = HtmlPage.Document.DocumentUri; #else Uri uri = null; if (uri == null) { throw new NotSupportedException("This code has to be compatible with .NET first"); } #endif ISet <String> allBeanNames = new HashSet <String>(); if (BeansToConsume != null) { allBeanNames.UnionWith(BeansToConsume.Keys); } IDictionary <String, IModelContainer> data = null; if (Token != null) { data = SharedData.Read(Token); } if (data == null) { // Clear token to suppress handsOn in afterStarted() Token = null; data = new Dictionary <String, IModelContainer>(); } IModelMultiContainer <Uri> uriList = (IModelMultiContainer <Uri>)DictionaryExtension.ValueOrDefault(data, SourceUriBeanName); if (uriList != null) { //Url-list is avaliable uriList.Values.Add(uri); } allBeanNames.UnionWith(data.Keys); if (!allBeanNames.Contains(SourceUriBeanName)) { //Url-list is not avaliable beanContextFactory.RegisterBean <ModelMultiContainer <Uri> >(SourceUriBeanName).PropertyValue("Value", uri); } IdentityHashSet <Object> allProvidedBusinessObjects = new IdentityHashSet <Object>(); foreach (String nameInOwnContext in allBeanNames) { //Proecess the input IModelContainer dataContainer = DictionaryExtension.ValueOrDefault(data, nameInOwnContext); if (dataContainer != null) { if (dataContainer is IModelMultiContainer) { IEnumerable businessObjects = ((IModelMultiContainer)dataContainer).ValuesData; if (businessObjects != null) { allProvidedBusinessObjects.AddAll(businessObjects.Cast <object>()); } } else if (dataContainer is IModelSingleContainer) { Object businessObject = ((IModelSingleContainer)dataContainer).ValueData; if (businessObject != null) { allProvidedBusinessObjects.Add(businessObject); } } //By copying only the data, listeners are unregistered //beanContextFactory.registerBean(name, dataContainer.GetType()).propertyValue("Data", dataContainer.Data); beanContextFactory.RegisterExternalBean(nameInOwnContext, dataContainer); continue; } if (!BeansToConsume.ContainsKey(nameInOwnContext)) { continue; } //Process default-beans String aliasToDefaultBean = BeansToConsume[nameInOwnContext]; if (aliasToDefaultBean == null) { //Mandatory parameter was not present in data throw new Exception("The new Screen has not all mandatory information: \"" + nameInOwnContext + "\" is missing."); } if (!nameInOwnContext.Equals(aliasToDefaultBean)) { beanContextFactory.RegisterAlias(nameInOwnContext, aliasToDefaultBean); } } if (allProvidedBusinessObjects.Count > 0) { IRevertChangesSavepoint savepoint = RevertChangesHelper.CreateSavepoint(allProvidedBusinessObjects); beanContextFactory.RegisterExternalBean(savepoint).Autowireable <IRevertChangesSavepoint>(); } }
protected virtual void RevertChangesIntern(IRevertChangesSavepoint savepoint, IList <Object> objectsToRevert, bool globally, RevertChangesFinishedCallback revertChangesFinishedCallback) { // Store the RevertChangesFinishedCallback from this thread on the stack and set the property null (for following calls): if (objectsToRevert == null || objectsToRevert.Count == 0) { if (revertChangesFinishedCallback != null) { revertChangesFinishedCallback.Invoke(true); } return; } if (globally) { GuiThreadHelper.InvokeOutOfGui(delegate() { bool success = false; try { DataChangeEvent dataChange = new DataChangeEvent(); dataChange.IsLocalSource = true; dataChange.Inserts = new List <IDataChangeEntry>(0); dataChange.Updates = new List <IDataChangeEntry>(); dataChange.Deletes = new List <IDataChangeEntry>(); for (int a = objectsToRevert.Count; a-- > 0;) { Object objectToRevert = objectsToRevert[a]; IEntityMetaData metaData = ((IEntityMetaDataHolder)objectToRevert).Get__EntityMetaData(); Object id = metaData.IdMember.GetValue(objectToRevert, false); if (id == null) { dataChange.Deletes.Add(new DirectDataChangeEntry(objectToRevert)); continue; } dataChange.Updates.Add(new DataChangeEntry(metaData.EntityType, ObjRef.PRIMARY_KEY_INDEX, id, null)); } EventDispatcher.DispatchEvent(dataChange, DateTime.Now, -1); success = true; } finally { if (revertChangesFinishedCallback != null) { revertChangesFinishedCallback.Invoke(success); } } }); } else { // Commented the following part from Ambeth 0.130 and use the part from Ambeth 0.129 due to a deadlock in the merge process: //GuiThreadHelper.InvokeOutOfGui(delegate() //{ // bool success1 = false; // try // { // IList<IDataChangeEntry> directObjectDeletes = new List<IDataChangeEntry>(); // IList<Object> initializedObjects = MergeController.ScanForInitializedObjects(objectsToRevert, true, null); // IList<IObjRef> orisToRevert = new List<IObjRef>(); // ISet<Object> persistedObjectsToRevert = new IdentityHashSet<Object>(); // for (int a = initializedObjects.Count; a-- > 0; ) // { // Object objectToRevert = initializedObjects[a]; // IEntityMetaData metaData = EntityMetaDataProvider.GetMetaData(objectToRevert.GetType()); // Object id = metaData.IdMember.GetValue(objectToRevert, false); // if (id == null) // { // directObjectDeletes.Add(new DirectDataChangeEntry(objectToRevert)); // continue; // } // persistedObjectsToRevert.Add(objectToRevert); // orisToRevert.Add(new ObjRef(metaData.EntityType, ObjRef.PRIMARY_KEY_INDEX, id, null)); // } // IList<Object> hardRefsToRootCacheValues = RootCache.GetObjects(orisToRevert, CacheDirective.CacheValueResult | CacheDirective.ReturnMisses); // for (int a = orisToRevert.Count; a-- > 0; ) // { // if (hardRefsToRootCacheValues[a] == null) // { // // Object could not be loaded/retrieved any more. So the ori refers to an invalid object // // We can not revert invalid objects and currently ignore them. They will raise exceptions if they will // // be tried to persist in a merge process any time in the future // orisToRevert.RemoveAt(a); // } // } // // We do nothing with the hardRef-list from the RootCache. It is only necessary to keep track of the instance reference on the stack // // To prohibit GC any potential WeakReferences in the meantime.... // GuiThreadHelper.InvokeInGuiAndWait(delegate() // { // IProcessResumeItem processResumeItem = WaitEventToResume(); // try // { // bool oldCacheModificationValue = CacheModification.IsActive; // CacheModification.IsActive = true; // bool oldFailEarlyModeActive = AbstractCache<Object>.FailEarlyModeActive; // AbstractCache<Object>.FailEarlyModeActive = true; // try // { // IList<IWritableCache> firstLevelCaches = FirstLevelCacheManager.SelectFirstLevelCaches(); // IList<Object> hardRefsToRootCacheValuesHere = hardRefsToRootCacheValues; // foreach (IWritableCache firstLevelCache in firstLevelCaches) // { // IList<Object> persistedObjectsInThisCache = firstLevelCache.GetObjects(orisToRevert, CacheDirective.FailEarly); // for (int a = persistedObjectsInThisCache.Count; a-- > 0; ) // { // Object persistedObjectInThisCache = persistedObjectsInThisCache[a]; // if (!persistedObjectsToRevert.Contains(persistedObjectInThisCache)) // { // continue; // } // RootCache.ApplyValues(persistedObjectInThisCache, (ICacheIntern)firstLevelCache); // } // } // for (int a = objectsToRevert.Count; a-- > 0; ) // { // Object objectToRevert = objectsToRevert[a]; // if (objectToRevert is IDataObject) // { // // Objects which are specified to be reverted loose their delete flag // ((IDataObject)objectToRevert).ToBeDeleted = false; // } // } // } // finally // { // AbstractCache<Object>.FailEarlyModeActive = oldFailEarlyModeActive; // CacheModification.IsActive = oldCacheModificationValue; // } // } // finally // { // if (processResumeItem != null) // { // processResumeItem.ResumeProcessingFinished(); // processResumeItem = null; // } // } // }); // if (directObjectDeletes.Count > 0) // { // DataChangeEvent dataChange = DataChangeEvent.Create(0, 0, 0); // dataChange.Deletes = directObjectDeletes; // EventDispatcher.DispatchEvent(dataChange, DateTime.Now, -1); // } // success1 = true; // } // finally // { // if (revertChangesFinishedCallback != null) // { // revertChangesFinishedCallback.Invoke(success1); // } // } //}); // Here comes the part from Ambeth 0.129: GuiThreadHelper.InvokeOutOfGui(delegate() { bool success1 = false; bool?success2 = null; bool?success3 = null; try { IList <IDataChangeEntry> directObjectDeletes = new List <IDataChangeEntry>(); List <IObjRef> objRefs = new List <IObjRef>(); List <ValueHolderRef> valueHolderKeys = new List <ValueHolderRef>(); IList <Object> initializedObjects = MergeController.ScanForInitializedObjects(objectsToRevert, true, null, objRefs, valueHolderKeys); IList <IObjRef> orisToRevert = new List <IObjRef>(); ISet <Object> persistedObjectsToRevert = new IdentityHashSet <Object>(); for (int a = initializedObjects.Count; a-- > 0;) { Object objectToRevert = initializedObjects[a]; IEntityMetaData metaData = ((IEntityMetaDataHolder)objectToRevert).Get__EntityMetaData(); Object id = metaData.IdMember.GetValue(objectToRevert, false); if (id == null) { directObjectDeletes.Add(new DirectDataChangeEntry(objectToRevert)); continue; } persistedObjectsToRevert.Add(objectToRevert); orisToRevert.Add(new ObjRef(metaData.EntityType, ObjRef.PRIMARY_KEY_INDEX, id, null)); } IList <Object> hardRefsToRootCacheValues = RootCache.GetObjects(orisToRevert, CacheDirective.CacheValueResult | CacheDirective.ReturnMisses); for (int a = orisToRevert.Count; a-- > 0;) { if (hardRefsToRootCacheValues[a] == null) { // Object could not be loaded/retrieved any more. So the ori refers to an invalid object // We can not revert invalid objects and currently ignore them. They will raise exceptions if they will // be tried to persist in a merge process any time in the future orisToRevert.RemoveAt(a); } } // We do nothing with the hardRef-list from the RootCache. It is only necessary to keep track of the instance reference on the stack // To prohibit GC any potential WeakReferences in the meantime.... success2 = false; GuiThreadHelper.InvokeInGui(delegate(Object state) { WaitEventToResume(delegate(IProcessResumeItem processResumeItem) { try { bool oldCacheModificationValue = CacheModification.Active; CacheModification.Active = true; bool oldFailEarlyModeActive = AbstractCache.FailInCacheHierarchyModeActive; AbstractCache.FailInCacheHierarchyModeActive = true; try { IList <IWritableCache> firstLevelCaches = FirstLevelCacheManager.SelectFirstLevelCaches(); IList <Object> hardRefsToRootCacheValuesHere = hardRefsToRootCacheValues; foreach (IWritableCache firstLevelCache in firstLevelCaches) { IList <Object> persistedObjectsInThisCache = firstLevelCache.GetObjects(orisToRevert, CacheDirective.FailEarly); for (int a = persistedObjectsInThisCache.Count; a-- > 0;) { Object persistedObjectInThisCache = persistedObjectsInThisCache[a]; if (!persistedObjectsToRevert.Contains(persistedObjectInThisCache)) { continue; } RootCache.ApplyValues(persistedObjectInThisCache, (ICacheIntern)firstLevelCache, null); } } for (int a = objectsToRevert.Count; a-- > 0;) { Object objectToRevert = objectsToRevert[a]; if (objectToRevert is IDataObject) { // Objects which are specified to be reverted loose their flags ((IDataObject)objectToRevert).ToBeDeleted = false; } } if (directObjectDeletes.Count == 0) { success2 = true; return; } } finally { AbstractCache.FailInCacheHierarchyModeActive = oldFailEarlyModeActive; CacheModification.Active = oldCacheModificationValue; } } finally { if (processResumeItem != null) { processResumeItem.ResumeProcessingFinished(); } } success3 = false; GuiThreadHelper.InvokeOutOfGui(delegate() { try { DataChangeEvent dataChange = DataChangeEvent.Create(0, 0, 0); dataChange.Deletes = directObjectDeletes; EventDispatcher.DispatchEvent(dataChange, DateTime.Now, -1); success3 = true; } finally { if (revertChangesFinishedCallback != null) { revertChangesFinishedCallback.Invoke(success3.Value); } } }); success2 = true; }, delegate(Exception e) { if (revertChangesFinishedCallback != null && success3 == null) { revertChangesFinishedCallback.Invoke(success2.Value); } }); }, null); success1 = true; } finally { if (revertChangesFinishedCallback != null && success2 == null && success3 == null) { revertChangesFinishedCallback.Invoke(success1); } } }); } }