Ejemplo n.º 1
0
        protected IdentityHashSet <Object> BuildCollisionSet(CacheDependencyNode node)
        {
            IdentityHashSet <Object> collisionSet = new IdentityHashSet <Object>();

            BuildCollisionSetIntern(node, collisionSet);
            return(collisionSet);
        }
Ejemplo n.º 2
0
        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();
            }
        }
Ejemplo n.º 3
0
        protected void Initialize()
        {
            HashMap <Type, IISet <Type> >     typeRelatedByTypes = new HashMap <Type, IISet <Type> >();
            IdentityHashSet <IEntityMetaData> extensions         = new IdentityHashSet <IEntityMetaData>(GetExtensions().Values());

            foreach (IEntityMetaData metaData in extensions)
            {
                if (Object.ReferenceEquals(metaData, alreadyHandled))
                {
                    continue;
                }
                foreach (RelationMember relationMember in metaData.RelationMembers)
                {
                    AddTypeRelatedByTypes(typeRelatedByTypes, metaData.EntityType, relationMember.ElementType);
                }
            }
            foreach (IEntityMetaData metaData in extensions)
            {
                if (Object.ReferenceEquals(metaData, alreadyHandled))
                {
                    continue;
                }
                Type         entityType     = metaData.EntityType;
                IISet <Type> relatedByTypes = typeRelatedByTypes.Get(entityType);
                if (relatedByTypes == null)
                {
                    relatedByTypes = new CHashSet <Type>();
                }
                ((EntityMetaData)metaData).TypesRelatingToThis = relatedByTypes.ToArray();
                RefreshMembers(metaData);
            }
        }
        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);
        }
Ejemplo n.º 6
0
        public override void Execute(Object parameter, INextCommandDelegate commandFinishedCallback)
        {
            if (RevertChangesSavepoint == null)
            {
                base.Execute(parameter, commandFinishedCallback);
                return;
            }
            if (parameter == null)
            {
                if (commandFinishedCallback != null)
                {
                    commandFinishedCallback.Invoke(true);
                }
                return;
            }
            IList <Object> businessObjects = ExtractBusinessObjects(parameter);

            RevertChangesFinishedCallback revertChangesFinishedCallback = null;

            if (commandFinishedCallback != null)
            {
                revertChangesFinishedCallback = new RevertChangesFinishedCallback(delegate(bool success)
                {
                    commandFinishedCallback.Invoke(success);
                });
            }

            IdentityHashSet <Object> mentionedBusinessObjects = new IdentityHashSet <Object>(businessObjects);
            IdentityHashSet <Object> savepointBusinessObjects = new IdentityHashSet <Object>(RevertChangesSavepoint.GetSavedBusinessObjects());

            mentionedBusinessObjects.RemoveAll(savepointBusinessObjects);

            RevertChangesSavepoint.RevertChanges();
            RevertChangesHelper.RevertChanges(mentionedBusinessObjects, revertChangesFinishedCallback);
        }
Ejemplo n.º 7
0
        public IList <Object> ScanForInitializedObjects(Object obj, bool isDeepMerge, IMap <Type, IList <Object> > typeToObjectsToMerge, IList <IObjRef> objRefs,
                                                        IList <ValueHolderRef> valueHolderKeys)
        {
            IList <Object> objects = new List <Object>();
            ISet <Object>  alreadyHandledObjectsSet = new IdentityHashSet <Object>();

            ScanForInitializedObjectsIntern(obj, isDeepMerge, objects, typeToObjectsToMerge, alreadyHandledObjectsSet, objRefs, valueHolderKeys);
            return(objects);
        }
Ejemplo n.º 8
0
        public DefaultExtendableContainer(String message)
        {
            this.type    = typeof(V);
            this.message = message;
            set          = new IdentityHashSet <V>();
            ReadWriteLock rwLock = new ReadWriteLock();

            readLock  = rwLock.ReadLock;
            writeLock = rwLock.WriteLock;
        }
Ejemplo n.º 9
0
        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);
        }
Ejemplo n.º 10
0
        protected void CheckEnhancedTypeConsistency(Type type)
        {
            IdentityHashSet <MethodInfo> allMethods = new IdentityHashSet <MethodInfo>();

            foreach (Type interf in type.GetInterfaces())
            {
                allMethods.AddAll(interf.GetMethods());
            }
            Type currType = type;

            while (currType != typeof(Object) && currType != null)
            {
                allMethods.AddAll(currType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly));
                currType = currType.BaseType;
            }
            if (allMethods.Count == 0)
            {
                throw new Exception("Type invalid (not a single method): " + type);
            }
            if (type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly).Length == 0)
            {
                throw new Exception("Type invalid (not a single constructor): " + type);
            }
            if (!type.IsAbstract)
            {
                foreach (MethodInfo method in allMethods)
                {
                    MethodInfo method2 = ReflectUtil.GetDeclaredMethod(true, type, method.ReturnType, method.Name, TypeUtil.GetParameterTypesToTypes(method.GetParameters()));
                    if (method2 == null || method2.IsAbstract)
                    {
                        throw new Exception("Type is not abstract but has at least one abstract method: " + method);
                    }
                }
            }
            Type[] interfaces = type.GetInterfaces();
            foreach (Type interf in interfaces)
            {
                MethodInfo[] interfaceMethods = ReflectUtil.GetDeclaredMethods(interf);
                foreach (MethodInfo interfaceMethod in interfaceMethods)
                {
                    try
                    {
                        if (type.GetMethod(interfaceMethod.Name, TypeUtil.GetParameterTypesToTypes(interfaceMethod.GetParameters())) == null)
                        {
                            throw new Exception("Type is not abstract but has at least one abstract method: " + interfaceMethod);
                        }
                    }
                    catch (Exception e)
                    {
                        throw new Exception("Type is not abstract but has at least one abstract method: " + interfaceMethod, e);
                    }
                }
            }
        }
Ejemplo n.º 11
0
        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);
        }
Ejemplo n.º 12
0
        protected virtual IList <Object> ExtractBusinessObjects(Object parameter, bool extractAlsoUnchanged = false)
        {
            if (parameter == null)
            {
                return(EMPTY_BO_ARRAY);
            }
            List <Object>            targetObjects     = new List <Object>();
            IdentityHashSet <Object> alreadyScannedSet = new IdentityHashSet <Object>();

            ExtractBusinessObjectsIntern(parameter, targetObjects, alreadyScannedSet, extractAlsoUnchanged);
            return(targetObjects);
        }
Ejemplo n.º 13
0
        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);
        }
Ejemplo n.º 14
0
 /**
  * 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);
     }
 }
Ejemplo n.º 15
0
        protected void DataChanged(IDataChange dataChange, Object eventTarget, IList <Object> pausedEventTargets, DateTime dispatchTime, long sequenceId)
        {
            CacheDependencyNode rootNode = BuildCacheDependency();

            if (pausedEventTargets != null && pausedEventTargets.Count > 0)
            {
                IdentityHashSet <Object> collisionSet = BuildCollisionSet(rootNode);
                if (collisionSet.ContainsAny(pausedEventTargets))
                {
                    // 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, delegate(IProcessResumeItem processResumeItem)
                    {
                        DataChangedIntern(dataChange, pausedEventTargets, processResumeItem, rootNode);
                    }, null);
                    return;
                }
            }
            DataChangedIntern(dataChange, pausedEventTargets, null, rootNode);
        }
Ejemplo n.º 16
0
        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);
        }
Ejemplo n.º 17
0
        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);
                }
            }
        }
Ejemplo n.º 18
0
        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();
            }
        }
Ejemplo n.º 19
0
        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));
        }
Ejemplo n.º 20
0
        public IdentityLinkedSet <Member> GetPrioMembers(ILinkedMap <Type, PrefetchPath[]> entityTypeToPrefetchPath,
                                                         List <PrefetchCommand> pendingPrefetchCommands, MergePrefetchPathsCache mergePrefetchPathsCache)
        {
            IdentityLinkedSet <Member> key1 = new IdentityLinkedSet <Member>();
            PrioMembersKey             key  = new PrioMembersKey(entityTypeToPrefetchPath, key1);

            for (int a = 0, size = pendingPrefetchCommands.Count; a < size; a++)
            {
                PrefetchCommand prefetchCommand = pendingPrefetchCommands[a];
                key1.Add(prefetchCommand.valueHolder.Member);
            }
            IdentityLinkedSet <Member> prioMembersMap = activeMembersToPrioMembersMap.Get(key);

            if (prioMembersMap != null)
            {
                return(prioMembersMap);
            }
            prioMembersMap = new IdentityLinkedSet <Member>(0.5f);
            Tuple2KeyHashMap <Type, PrefetchPath[], bool?> alreadyVisited = null;
            IdentityHashSet <Type> touchedTypesInPriority = null;

            if (mergePrefetchPathsCache == null)
            {
                mergePrefetchPathsCache = new MergePrefetchPathsCache(entityMetaDataProvider);
            }
            bool prio2Mode = true;

            foreach (PrefetchCommand prefetchCommand in pendingPrefetchCommands)
            {
                DirectValueHolderRef valueHolder   = prefetchCommand.valueHolder;
                PrefetchPath[]       prefetchPaths = prefetchCommand.prefetchPaths;
                RelationMember       member        = valueHolder.Member;

                Type targetEntityType = member.ElementType;
                // Merge the root prefetch path with the relative prefetch path
                prefetchPaths = mergePrefetchPathsCache.MergePrefetchPaths(targetEntityType, prefetchPaths, entityTypeToPrefetchPath);

                IEntityMetaData metaData = valueHolder.Vhc.Get__EntityMetaData();

                if (targetEntityType.Equals(metaData.EntityType))
                {
                    // prio1 overrides prio2
                    if (prio2Mode)
                    {
                        prio2Mode      = false;
                        alreadyVisited = null;
                        prioMembersMap.Clear();
                        if (touchedTypesInPriority != null)
                        {
                            touchedTypesInPriority.Clear();
                        }
                    }
                    prioMembersMap.Add(member);
                    if (touchedTypesInPriority == null)
                    {
                        touchedTypesInPriority = new IdentityHashSet <Type>();
                    }
                    touchedTypesInPriority.Add(member.EntityType);
                    touchedTypesInPriority.Add(targetEntityType);
                    continue;
                }
                if (prefetchPaths == null || !prio2Mode)
                {
                    continue;
                }
                if (alreadyVisited == null)
                {
                    alreadyVisited = new Tuple2KeyHashMap <Type, PrefetchPath[], bool?>();
                }
                if (IsPrio2Member(metaData, entityMetaDataProvider.GetMetaData(targetEntityType), prefetchPaths, entityTypeToPrefetchPath, alreadyVisited,
                                  mergePrefetchPathsCache))
                {
                    prioMembersMap.Add(member);
                    if (touchedTypesInPriority == null)
                    {
                        touchedTypesInPriority = new IdentityHashSet <Type>();
                    }
                    touchedTypesInPriority.Add(member.EntityType);
                    touchedTypesInPriority.Add(targetEntityType);
                }
            }
            if (prioMembersMap.Count > 0)
            {
                // check for out-of-order members which have nothing to do (and will never ever have in a transitive manner) with the priorized members
                foreach (PrefetchCommand prefetchCommand in pendingPrefetchCommands)
                {
                    DirectValueHolderRef valueHolder = prefetchCommand.valueHolder;
                    RelationMember       member      = valueHolder.Member;

                    if (prioMembersMap.Contains(member))
                    {
                        // already priorized
                        continue;
                    }
                    if (touchedTypesInPriority.Contains(member.EntityType) || touchedTypesInPriority.Contains(member.ElementType))
                    {
                        continue;
                    }
                    prioMembersMap.Add(member);
                }
            }
            Object writeLock = activeMembersToPrioMembersMap.GetWriteLock();

            lock (writeLock)
            {
                IdentityLinkedSet <Member> existingPrioMembersMap = activeMembersToPrioMembersMap.Get(key);
                if (existingPrioMembersMap != null)
                {
                    return(existingPrioMembersMap);
                }
                activeMembersToPrioMembersMap.Put(key, prioMembersMap);
                return(prioMembersMap);
            }
        }
Ejemplo n.º 21
0
        /*
         * 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);
        }
Ejemplo n.º 22
0
 public IteratorAnonymousClass(IdentityHashSet <KType> outerInstance)
 {
     this.outerInstance = outerInstance;
     pos         = -1;
     nextElement = FetchNext();
 }
Ejemplo n.º 23
0
        public ICUDResult CreateCUDResult(MergeHandle mergeHandle)
        {
            ILinkedMap <Type, ICUDResultExtension> typeToCudResultExtension = extensions.GetExtensions();

            foreach (Entry <Type, ICUDResultExtension> entry in typeToCudResultExtension)
            {
                entry.Value.Extend(mergeHandle);
            }

            IdentityLinkedMap <Object, IList <IUpdateItem> > objToModDict = mergeHandle.objToModDict;
            IdentityHashSet <Object> objToDeleteSet = mergeHandle.objToDeleteSet;

            HashMap <Type, IPrimitiveUpdateItem[]> entityTypeToFullPuis = new HashMap <Type, IPrimitiveUpdateItem[]>();
            HashMap <Type, IRelationUpdateItem[]>  entityTypeToFullRuis = new HashMap <Type, IRelationUpdateItem[]>();

            List <IChangeContainer> allChanges   = new List <IChangeContainer>(objToModDict.Count);
            List <Object>           originalRefs = new List <Object>(objToModDict.Count);

            foreach (Object objToDelete in objToDeleteSet)
            {
                IObjRef         ori             = OriHelper.GetCreateObjRef(objToDelete, mergeHandle);
                DeleteContainer deleteContainer = new DeleteContainer();
                deleteContainer.Reference = ori;
                allChanges.Add(deleteContainer);
                originalRefs.Add(objToDelete);
            }
            IEntityMetaDataProvider entityMetaDataProvider = this.EntityMetaDataProvider;

            foreach (Entry <Object, IList <IUpdateItem> > entry in objToModDict)
            {
                Object obj = entry.Key;
                IList <IUpdateItem> modItems = entry.Value;

                IEntityMetaData metaData = entityMetaDataProvider.GetMetaData(obj.GetType());

                IPrimitiveUpdateItem[] fullPuis = GetEnsureFullPUIs(metaData, entityTypeToFullPuis);
                IRelationUpdateItem[]  fullRuis = GetEnsureFullRUIs(metaData, entityTypeToFullRuis);

                int puiCount = 0, ruiCount = 0;
                for (int a = modItems.Count; a-- > 0;)
                {
                    IUpdateItem modItem = modItems[a];

                    Member member = metaData.GetMemberByName(modItem.MemberName);

                    if (modItem is IRelationUpdateItem)
                    {
                        fullRuis[metaData.GetIndexByRelation(member)] = (IRelationUpdateItem)modItem;
                        ruiCount++;
                    }
                    else
                    {
                        fullPuis[metaData.GetIndexByPrimitive(member)] = (IPrimitiveUpdateItem)modItem;
                        puiCount++;
                    }
                }

                IRelationUpdateItem[]  ruis = CompactRUIs(fullRuis, ruiCount);
                IPrimitiveUpdateItem[] puis = CompactPUIs(fullPuis, puiCount);
                IObjRef ori = OriHelper.GetCreateObjRef(obj, mergeHandle);
                originalRefs.Add(obj);

                if (ori is IDirectObjRef)
                {
                    CreateContainer createContainer = new CreateContainer();

                    ((IDirectObjRef)ori).CreateContainerIndex = allChanges.Count;

                    createContainer.Reference  = ori;
                    createContainer.Primitives = puis;
                    createContainer.Relations  = ruis;

                    allChanges.Add(createContainer);
                }
                else
                {
                    UpdateContainer updateContainer = new UpdateContainer();
                    updateContainer.Reference  = ori;
                    updateContainer.Primitives = puis;
                    updateContainer.Relations  = ruis;
                    allChanges.Add(updateContainer);
                }
            }
            return(new CUDResult(allChanges, originalRefs));
        }
Ejemplo n.º 24
0
        public override int GetHashCode()
        {
            IdentityHashSet<ICoreMap> calledSet = HashCodeCalled.Value;
            bool createdCalledSet = (calledSet == null);
            if (createdCalledSet)
            {
                calledSet = new IdentityHashSet<ICoreMap>();
                HashCodeCalled.Value = calledSet;
            }

            if (calledSet.Contains(this))
            {
                return 0;
            }

            calledSet.Add(this);

            int keysCode = 0;
            int valuesCode = 0;
            for (int i = 0; i < psize; i++)
            {
                keysCode += (i < keys.Length && values[i] != null ? keys[i].GetHashCode() : 0);
                valuesCode += (i < values.Length && values[i] != null ? values[i].GetHashCode() : 0);
            }

            if (createdCalledSet)
            {
                HashCodeCalled.Value = null;
            }
            else
            {
                // Remove the object after processing is complete so that if
                // there are multiple instances of this CoreMap in the overall
                // object graph, they each have their hash code calculated.
                // TODO: can we cache this for later?
                calledSet.Remove(this);
            }
            return keysCode*37 + valuesCode;
        }
Ejemplo n.º 25
0
        public override string ToString()
        {
            IdentityHashSet<ICoreMap> calledSet = ToStringCalled.Value;
            if (calledSet == null)
            {
                calledSet = new IdentityHashSet<ICoreMap>();
            }

            if (calledSet.Contains(this))
            {
                return "[...]";
            }

            calledSet.Add(this);

            var s = new StringBuilder("[");
            for (int i = 0; i < psize; i++)
            {
                s.Append(keys[i].Name);
                s.Append('=');
                s.Append(values[i]);
                if (i < psize - 1)
                {
                    s.Append(' ');
                }
            }
            s.Append(']');

            bool createdCalledSet = calledSet == null || calledSet.IsEmpty();
            if (createdCalledSet)
            {
                ToStringCalled.Dispose(); /*remove();*/
            }
            else
            {
                // Remove the object from the already called set so that
                // potential later calls in this object graph have something
                // more description than [...]
                calledSet.Remove(this);
            }
            return s.ToString();
        }
Ejemplo n.º 26
0
        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));
        }
Ejemplo n.º 27
0
        public virtual Object PostProcessBean(IBeanContextFactory beanContextFactory, IServiceContext beanContext, IBeanConfiguration beanConfiguration, Type beanType, Object targetBean, ISet <Type> requestedTypes)
        {
            if (!typeof(FrameworkElement).IsAssignableFrom(beanType))
            {
                // Handle only FrameworkElements
                return(targetBean);
            }
            if (beanType.IsAssignableFrom(typeof(UserControl)))
            {
                // Ignore all instances which are base types of UserControl
                return(targetBean);
            }

            ISet <Object> alreadyHandledBeans = factoryToAlreadyHandledNames[beanContextFactory];

            if (alreadyHandledBeans == null)
            {
                alreadyHandledBeans = new IdentityHashSet <Object>();
                factoryToAlreadyHandledNames[beanContextFactory] = alreadyHandledBeans;
            }
            if (alreadyHandledBeans.Contains(targetBean))
            {
                //Do not yet add the Bean to the list.
                return(targetBean);
            }

            FrameworkElement frameworkElement          = (FrameworkElement)targetBean;
            MethodInfo       initializeComponentMethod = beanType.GetMethod("InitializeComponent");

            if (initializeComponentMethod != null)
            {
                IServiceContext oldCurrentBeanContext = XamlBeanProvider.CurrentBeanContext;
                try
                {
                    XamlBeanProvider.CurrentBeanContext = beanContext;
                    initializeComponentMethod.Invoke(targetBean, null);
                }
                catch (Exception e)
                {
                    throw new Exception("InitializeComponent of \"" + frameworkElement.Name + "\" (" + beanType.FullName + ") failed.", e);
                }
                finally
                {
                    XamlBeanProvider.CurrentBeanContext = oldCurrentBeanContext;
                }
            }

            if (!typeof(UIElement).IsAssignableFrom(beanType))
            {
                return(targetBean);
            }

            ISet <Object> unnamedBeans = new IdentityHashSet <Object>();
            IDictionary <String, Object> namedBeans = new Dictionary <String, Object>();

            CollectChildBeans((UIElement)targetBean, unnamedBeans, namedBeans, alreadyHandledBeans);

            foreach (Object unnamedBean in unnamedBeans)
            {
                IBeanConfiguration nestedBeanConfiguration = beanContextFactory.RegisterWithLifecycle(unnamedBean);
                if (unnamedBean is ISelfRegisteringControlBean)
                {
                    ((ISelfRegisteringControlBean)unnamedBean).RegisterSelf(nestedBeanConfiguration, beanContext, beanContextFactory);
                }
            }
            foreach (KeyValuePair <String, Object> namedBean in namedBeans)
            {
                Object             currentNamedBean        = namedBean.Value;
                IBeanConfiguration nestedBeanConfiguration = beanContextFactory.RegisterWithLifecycle(namedBean.Key, currentNamedBean);
                if (currentNamedBean is ISelfRegisteringControlBean)
                {
                    ((ISelfRegisteringControlBean)currentNamedBean).RegisterSelf(nestedBeanConfiguration, beanContext, beanContextFactory);
                }
            }
            if (targetBean is ISelfRegisteringControlBean)
            {
                ((ISelfRegisteringControlBean)targetBean).RegisterSelf(beanConfiguration, beanContext, beanContextFactory);
            }
            return(targetBean);
        }
Ejemplo n.º 28
0
        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);
            }
        }
Ejemplo n.º 29
0
 public WaitForResumeItem(IdentityHashSet <Object> pendingPauses)
 {
     this.pendingPauses = pendingPauses;
 }
Ejemplo n.º 30
0
        /*
         * 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);
        }
Ejemplo n.º 31
0
        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);
                        }
                    }
                });
            }
        }
Ejemplo n.º 32
0
        public virtual void DataChanged(IDataChange dataChange, DateTime dispatchTime, long sequenceId)
        {
            dataChange = dataChange.Derive(InterestedEntityTypes);
            if (dataChange.IsEmpty)
            {
                return;
            }
            ISet <Object> directObjectsToDelete = null;

            ISet <Type> requestedTypes = new HashSet <Type>();
            IDictionary <Type, IEntityMetaData> typeToMetaDataDict = new Dictionary <Type, IEntityMetaData>();

            GuiThreadHelper.InvokeInGuiAndWait(delegate()
            {
                IList <T> entities = Model.Objects;

                for (int i = entities.Count; i-- > 0;)
                {
                    Object entity = entities[i];

                    requestedTypes.Add(entity.GetType());
                }
            });

            IList <IDataChangeEntry> dataChangeEntries = dataChange.Inserts;

            for (int a = dataChangeEntries.Count; a-- > 0;)
            {
                requestedTypes.Add(dataChangeEntries[a].EntityType);
            }
            dataChangeEntries = dataChange.Updates;
            for (int a = dataChangeEntries.Count; a-- > 0;)
            {
                requestedTypes.Add(dataChangeEntries[a].EntityType);
            }
            dataChangeEntries = dataChange.Deletes;
            for (int a = dataChangeEntries.Count; a-- > 0;)
            {
                requestedTypes.Add(dataChangeEntries[a].EntityType);
            }

            IList <IEntityMetaData> metaDatas = EntityMetaDataProvider.GetMetaData(ListUtil.ToList(requestedTypes));

            foreach (IEntityMetaData metaData in metaDatas)
            {
                typeToMetaDataDict[metaData.EntityType] = metaData;
            }

            bool consistsOnlyOfDirectDeletes = false;

            if (dataChange.Deletes.Count > 0)
            {
                consistsOnlyOfDirectDeletes = true;
                foreach (IDataChangeEntry deleteEntry in dataChange.Deletes)
                {
                    if (deleteEntry is DirectDataChangeEntry)
                    {
                        if (directObjectsToDelete == null)
                        {
                            directObjectsToDelete = new IdentityHashSet <Object>();
                        }
                        directObjectsToDelete.Add(((DirectDataChangeEntry)deleteEntry).Entry);
                    }
                    else
                    {
                        consistsOnlyOfDirectDeletes = false;
                    }
                }
            }

            IList <T> interestingEntities = null;

            Object[]                contextInformation = GetContextInformation();
            IFilterDescriptor       filterDescriptor   = GetFilterDescriptor();
            IList <ISortDescriptor> sortDescriptors    = GetSortDescriptors();
            IPagingRequest          pagingRequest      = GetPagingRequest();

            IPagingResponse         pagingResponse  = null;
            List <IDataChangeEntry> modifiedEntries = new List <IDataChangeEntry>();

            modifiedEntries.AddRange(dataChange.All);

            if (!consistsOnlyOfDirectDeletes)
            {
                interestingEntities = CacheContext.ExecuteWithCache(CacheProvider.GetCurrentCache(), delegate()
                {
                    ConfigureCacheWithEagerLoads(Cache);
                    if (Refresher is IPagingRefresher <T> )
                    {
                        interestingEntities = new List <T>();
                        pagingResponse      = ((IPagingRefresher <T>)Refresher).Refresh(modifiedEntries, filterDescriptor, sortDescriptors, pagingRequest, contextInformation);
                        foreach (Object obj in pagingResponse.Result)
                        {
                            interestingEntities.Add((T)obj);
                        }
                        return(interestingEntities);
                    }
                    else
                    {
                        if (filterDescriptor != null || sortDescriptors != null)
                        {
                            contextInformation    = new Object[2];
                            contextInformation[0] = filterDescriptor;
                            contextInformation[1] = sortDescriptors;
                        }

                        return(((IRefresher <T>)Refresher).Refresh(modifiedEntries, contextInformation));
                    }
                });
            }
            GuiThreadHelper.InvokeInGuiAndWait(delegate()
            {
                IList <T> entities = Model.Objects;

                ISet <T> entitiesToAdd                           = null;
                ISet <T> entitiesToRemove                        = null;
                IDictionary <T, T> entitiesToReplace             = null;
                IDictionary <IObjRef, T> oldObjRefToOldEntityMap = null;
                bool mergeModel = false;

                if (interestingEntities != null && interestingEntities.Count > 0)
                {
                    entitiesToAdd           = new IdentityHashSet <T>(interestingEntities);
                    entitiesToRemove        = new IdentityHashSet <T>(entities);
                    entitiesToReplace       = new IdentityDictionary <T, T>();
                    oldObjRefToOldEntityMap = new Dictionary <IObjRef, T>();
                    mergeModel = true;
                }
                for (int i = entities.Count; i-- > 0;)
                {
                    T oldEntity = entities[i];
                    if (directObjectsToDelete != null && directObjectsToDelete.Contains(oldEntity))
                    {
                        if (entitiesToRemove != null)
                        {
                            entitiesToRemove.Remove(oldEntity);
                        }
                        Model.RemoveAt(i);
                        continue;
                    }
                    Type oldEntityType       = ProxyHelper.GetRealType(oldEntity.GetType());
                    PrimitiveMember idMember = typeToMetaDataDict[oldEntityType].IdMember;
                    Object oldEntityId       = idMember.GetValue(oldEntity, false);
                    if (oldEntityId == null)
                    {
                        if (entitiesToRemove != null)
                        {
                            entitiesToRemove.Remove(oldEntity);
                        }
                        // Unpersisted object. This object should not be removed
                        // only because of a background DCE
                        continue;
                    }
                    bool entryRemoved = false;
                    foreach (IDataChangeEntry deleteEntry in dataChange.Deletes)
                    {
                        if (deleteEntry is DirectDataChangeEntry)
                        {
                            continue;
                        }
                        Object id = deleteEntry.Id;
                        if (!EqualsItems(oldEntityType, oldEntityId, deleteEntry.EntityType, id))
                        {
                            continue;
                        }
                        if (entitiesToRemove != null)
                        {
                            entitiesToRemove.Remove(oldEntity);
                        }
                        Model.RemoveAt(i);
                        entryRemoved = true;
                        break;
                    }
                    if (entryRemoved)
                    {
                        continue;
                    }
                    if (mergeModel)
                    {
                        IObjRef oldObjRef   = new ObjRef(oldEntityType, ObjRef.PRIMARY_KEY_INDEX, oldEntityId, null);
                        T existingOldEntity = DictionaryExtension.ValueOrDefault(oldObjRefToOldEntityMap, oldObjRef);
                        if (existingOldEntity == null)
                        {
                            oldObjRefToOldEntityMap.Add(oldObjRef, oldEntity);
                        }
                        else if (!Object.ReferenceEquals(existingOldEntity, oldEntity))
                        {
                            // Force duplicate key exception
                            oldObjRefToOldEntityMap.Add(oldObjRef, oldEntity);
                        }
                    }
                }
                if (oldObjRefToOldEntityMap != null && oldObjRefToOldEntityMap.Count > 0)
                {
                    IDictionary <IObjRef, T> newObjRefToNewEntityMap = new Dictionary <IObjRef, T>();
                    for (int a = interestingEntities.Count; a-- > 0;)
                    {
                        T newEntity              = interestingEntities[a];
                        Type newEntityType       = ProxyHelper.GetRealType(newEntity.GetType());
                        PrimitiveMember idMember = typeToMetaDataDict[newEntityType].IdMember;
                        Object newEntityId       = idMember.GetValue(newEntity, false);

                        IObjRef newObjRef = new ObjRef(newEntityType, ObjRef.PRIMARY_KEY_INDEX, newEntityId, null);
                        newObjRefToNewEntityMap.Add(newObjRef, newEntity);
                    }
                    DictionaryExtension.Loop(oldObjRefToOldEntityMap, delegate(IObjRef objRef, T oldEntity)
                    {
                        T newEntity = DictionaryExtension.ValueOrDefault(newObjRefToNewEntityMap, objRef);
                        if (newEntity == null)
                        {
                            // Nothing to do if current oldEntity has no corresponding newEntity
                            return;
                        }
                        entitiesToAdd.Remove(newEntity);
                        if (!Object.ReferenceEquals(oldEntity, newEntity) &&
                            (dataChange.IsLocalSource || !(oldEntity is IDataObject) || !((IDataObject)oldEntity).ToBeUpdated))
                        {
                            entitiesToReplace[oldEntity] = newEntity;
                        }
                        entitiesToRemove.Remove(oldEntity);
                    });
                }

                if (mergeModel)
                {
                    for (int a = entities.Count; a-- > 0;)
                    {
                        T item = entities[a];
                        if (entitiesToRemove.Contains(item))
                        {
                            Model.RemoveAt(a);
                            continue;
                        }
                        T replacingItem = DictionaryExtension.ValueOrDefault(entitiesToReplace, item);
                        if (replacingItem != null)
                        {
                            Model.Replace(a, replacingItem);
                            continue;
                        }
                    }
                    IEnumerator <T> enumerator = entitiesToAdd.GetEnumerator();
                    while (enumerator.MoveNext())
                    {
                        T entityToAdd = enumerator.Current;
                        Model.Add(entityToAdd);
                    }

                    if (hasPagedViewModel)
                    {
                        UpdatePagingInformation(pagingResponse);
                    }
                    UpdateAfterDCE();
                }
            });
        }