Example #1
0
        public void InvokeInParallel(IServiceContext serviceContext, bool inheritThreadLocals, params Runnable[] runnables)
        {
            CountDownLatch          latch           = new CountDownLatch(runnables.Length);
            ParamHolder <Exception> throwableHolder = new ParamHolder <Exception>();
            IForkState forkState = inheritThreadLocals ? ThreadLocalCleanupController.CreateForkState() : null;

            Thread[] threads = new Thread[runnables.Length];
            for (int a = runnables.Length; a-- > 0;)
            {
                Runnable catchingRunnable = new CatchingRunnable(forkState, runnables[a], latch, throwableHolder, ThreadLocalCleanupController);

                Thread thread = new Thread(delegate()
                {
                    catchingRunnable.Run();
                });
                thread.IsBackground = true;
                threads[a]          = thread;
            }
            foreach (Thread thread in threads)
            {
                thread.Start();
            }
            latch.Await(TimeSpan.FromMilliseconds(Timeout));
            if (throwableHolder.Value != null)
            {
                throw RuntimeExceptionUtil.Mask(throwableHolder.Value, "Error occured while invoking runnables");
            }
        }
Example #2
0
        public Object ProcessServiceResult(Object result, IList <IObjRef> objRefs, IList <Object> entities, Type expectedType, Object[] serviceRequestArgs,
                                           Attribute annotation)
        {
            IPagingResponse pagingResponse = (IPagingResponse)result;

            QueryResultType queryResultType = QueryResultType.REFERENCES;

            if (annotation is FindAttribute)
            {
                queryResultType = ((FindAttribute)annotation).ResultType;
            }
            switch (queryResultType)
            {
            case QueryResultType.BOTH:
                pagingResponse.RefResult = objRefs;
                pagingResponse.Result    = entities;
                break;

            case QueryResultType.ENTITIES:
                pagingResponse.RefResult = null;
                pagingResponse.Result    = entities;
                break;

            case QueryResultType.REFERENCES:
                pagingResponse.RefResult = objRefs;
                pagingResponse.Result    = null;
                break;

            default:
                throw RuntimeExceptionUtil.CreateEnumNotSupportedException(queryResultType);
            }
            return(pagingResponse);
        }
Example #3
0
 protected void ValidateDocument(XDocument doc)
 {
     try
     {
         validator.Validate(doc);
     }
     catch (Exception e)
     {
         throw RuntimeExceptionUtil.Mask(e, "Error during xml document validation");
     }
 }
Example #4
0
 protected void CallMethod(Object entity, String message)
 {
     try
     {
         Method.Invoke(entity, EMPTY_ARGS);
     }
     catch (Exception e)
     {
         Type entityType = EntityMetaDataProvider.GetMetaData(entity.GetType()).EntityType;
         throw RuntimeExceptionUtil.Mask(e, "Error occured while handling " + message + " method of entity type " + entityType.FullName);
     }
 }
Example #5
0
        public virtual void IfZCmp(CompareOperator compareOperator, Label label)
        {
            switch (compareOperator)
            {
            case CompareOperator.EQ:
                gen.Emit(OpCodes.Brfalse, label);
                break;

            case CompareOperator.NE:
                gen.Emit(OpCodes.Brtrue, label);
                break;

            default:
                throw RuntimeExceptionUtil.CreateEnumNotSupportedException(compareOperator);
            }
        }
Example #6
0
 public override Object GetValue(Object obj)
 {
     if (Getter == null)
     {
         return(null);
     }
     try
     {
         return(Getter.Invoke(obj, EMPTY_ARGS));
     }
     catch (Exception e)
     {
         throw RuntimeExceptionUtil.Mask(e, "Error occured while calling '" + Getter + "' on object '" + obj + "' of type '" + obj.GetType().ToString()
                                         + "'");
     }
 }
Example #7
0
 public override Object GetValue(Object obj)
 {
     try
     {
         return(getDelegate(obj));
     }
     catch (Exception e)
     {
         if (getDelegate == null)
         {
             throw new NotSupportedException();
         }
         throw RuntimeExceptionUtil.Mask(e, "Error occured while calling '" + Getter + "' on object '" + obj + "' of type '" + obj.GetType().ToString()
                                         + "'");
     }
 }
Example #8
0
        public virtual void IfCmp(Type type, CompareOperator compareOperator, Label label)
        {
            switch (compareOperator)
            {
            case CompareOperator.EQ:
                gen.Emit(OpCodes.Beq, label);
                break;

            case CompareOperator.NE:
                gen.Emit(OpCodes.Bne_Un, label);
                break;

            default:
                throw RuntimeExceptionUtil.CreateEnumNotSupportedException(compareOperator);
            }
        }
Example #9
0
 public override void SetValue(Object obj, Object value)
 {
     try
     {
         setDelegate(obj, value);
     }
     catch (Exception e)
     {
         if (setDelegate == null)
         {
             throw new NotSupportedException();
         }
         throw RuntimeExceptionUtil.Mask(e, "Error occured while calling '" + Setter + "' on object '" + obj + "' of type '" + obj.GetType().ToString()
                                         + "' with argument '" + value + "'");
     }
 }
Example #10
0
        protected void LogBytecodeOutput(String typeName, String bytecodeOutput)
        {
#if SILVERLIGHT
            DirectoryInfo outputFileDir = new DirectoryInfo(TraceDir + Path.DirectorySeparatorChar + GetType().FullName);
            outputFileDir.Create();
            String formattedName = outputFileDir.FullName + Path.DirectorySeparatorChar + typeName + ".txt";
            try
            {
                using (FileStream outputFile = new FileStream(formattedName, FileMode.Create, FileAccess.Write, FileShare.Read))
#else
            // the following code allows to write to directories with a length > 260 chars
            char sep             = System.IO.Path.DirectorySeparatorChar;
            String dirName       = LongPath.CreateDir(TraceDir + sep + GetType().FullName);
            String formattedName = dirName + sep + typeName + ".txt";
            try
            {
                // Create a file with generic write access
                SafeFileHandle fileHandle = LongPath.CreateFile(formattedName, FileAccess.ReadWrite, FileShare.ReadWrite, FileMode.OpenOrCreate);
                try
                {
                    using (FileStream outputFile = new FileStream(fileHandle, FileAccess.Write))
#endif
                {
                    System.IO.StreamWriter fw = new System.IO.StreamWriter(outputFile);
                    try
                    {
                        fw.Write(bytecodeOutput);
                    }
                    finally
                    {
                        fw.Close();
                    }
                }
#if SILVERLIGHT
#else
            }
            finally
            {
                fileHandle.Close();
            }
#endif
            }
            catch (Exception e)
            {
                throw RuntimeExceptionUtil.Mask(e, "Error occurred while trying to write to '" + formattedName + "'");
            }
        }
Example #11
0
 public override void SetValue(Object obj, Object value)
 {
     if (Setter == null)
     {
         throw new NotSupportedException("No setter configured for property " + Name);
     }
     Object[] args = { value };
     try
     {
         Setter.Invoke(obj, args);
     }
     catch (Exception e)
     {
         throw RuntimeExceptionUtil.Mask(e, "Error occured while calling '" + Setter + "' on object '" + obj + "' of type '" + obj.GetType().ToString()
                                         + "' with argument '" + value + "'");
     }
 }
Example #12
0
 public ValueHolderContainerEntry(Type targetType, RelationMember[] members, IBytecodeEnhancer bytecodeEnhancer,
                                  IPropertyInfoProvider propertyInfoProvider, IMemberTypeProvider memberTypeProvider)
 {
     entries = new ValueHolderEntry[members.Length];
     try
     {
         for (int relationIndex = members.Length; relationIndex-- > 0;)
         {
             RelationMember   member  = members[relationIndex];
             ValueHolderEntry vhEntry = new ValueHolderEntry(targetType, member, bytecodeEnhancer, propertyInfoProvider, memberTypeProvider);
             entries[relationIndex] = vhEntry;
         }
     }
     catch (Exception e)
     {
         throw RuntimeExceptionUtil.Mask(e, "Error occured while processing type '" + targetType.FullName + "'");
     }
 }
Example #13
0
        protected Object ReadFromStreamLogBeforeException(Stream se, Encoding encoding)
        {
            StringBuilder sb = new StringBuilder();

            try
            {
                StreamReader streamReader = new ExtendedStreamReader(se, sb);;
                return(ReadFromReader(streamReader));
            }
            catch (XmlTypeNotFoundException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw RuntimeExceptionUtil.Mask(e, sb.ToString());
            }
        }
Example #14
0
 protected Object CreateEntityIntern(IEntityMetaData metaData, bool doEmptyInit)
 {
     try
     {
         if (metaData.EnhancedType == null)
         {
             EntityMetaDataRefresher.RefreshMembers(metaData);
         }
         EntityFactoryConstructor constructor = GetConstructorEntry(metaData.EnhancedType);
         Object entity = constructor.CreateEntity();
         PostProcessEntity(entity, metaData);
         return(entity);
     }
     catch (Exception e)
     {
         if (BytecodePrinter != null)
         {
             throw RuntimeExceptionUtil.Mask(e, BytecodePrinter.ToPrintableBytecode(metaData.EnhancedType));
         }
         throw;
     }
 }
Example #15
0
        protected ConstructorInfo GetEmbeddedParamConstructor(Type embeddedType, Type parentObjectType)
        {
            ConstructorInfo constructor = typeToEmbbeddedParamConstructorMap.Get(embeddedType);

            if (constructor == null)
            {
                try
                {
                    constructor = embeddedType.GetConstructor(new Type[] { parentObjectType });
                }
                catch (Exception e)
                {
                    if (BytecodePrinter != null)
                    {
                        throw RuntimeExceptionUtil.Mask(e, BytecodePrinter.ToPrintableBytecode(embeddedType));
                    }
                    throw;
                }
                typeToEmbbeddedParamConstructorMap.Put(embeddedType, constructor);
            }
            return(constructor);
        }
Example #16
0
        protected Object ReadFromStreamLogAfterException(Stream se, Encoding encoding)
        {
            long         position     = se.Position;
            StreamReader streamReader = null;

            try
            {
                streamReader = new StreamReader(se, encoding);
                return(ReadFromReader(streamReader));
            }
            catch (XmlTypeNotFoundException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                long newPosition = se.Position;
                se.Seek(position, SeekOrigin.Begin);
                byte[] buffer = new byte[newPosition - position];
                se.Read(buffer, 0, buffer.Length);
                String xmlContent = new String(encoding.GetChars(buffer));
                throw RuntimeExceptionUtil.Mask(e, xmlContent);
            }
        }
Example #17
0
 public void PostProcessCreatedType(Type newType)
 {
     foreach (Entry <String, IValueResolveDelegate> entry in initializeStaticFields)
     {
         FieldInfo[] fields = ReflectUtil.GetDeclaredFieldInHierarchy(newType, entry.Key);
         if (fields.Length == 0)
         {
             throw new Exception("Field not found: '" + newType.FullName + "." + entry.Key);
         }
         Object value = entry.Value.Invoke(entry.Key, newType);
         foreach (FieldInfo field in fields)
         {
             try
             {
                 field.SetValue(null, value);
             }
             catch (Exception e)
             {
                 throw RuntimeExceptionUtil.Mask(e, "Error occured while setting field: " + field);
             }
         }
     }
     initializeStaticFields.Clear();
 }
Example #18
0
        public void HandleCollectionChange(INotifyPropertyChangedSource obj, Object sender, NotifyCollectionChangedEventArgs evnt)
        {
            IEntityMetaData metaData = ((IEntityMetaDataHolder)obj).Get__EntityMetaData();

            Object bases = null;
            bool   parentChildProperty = false;

            RelationMember[] relationMembers = metaData.RelationMembers;
            for (int relationIndex = relationMembers.Length; relationIndex-- > 0;)
            {
                Object valueDirect = ((IValueHolderContainer)obj).Get__ValueDirect(relationIndex);
                if (!Object.ReferenceEquals(valueDirect, sender))
                {
                    continue;
                }
                if (relationMembers[relationIndex].GetAnnotation(typeof(ParentChild)) != null)
                {
                    bases = obj;
                    parentChildProperty = true;
                }
                else
                {
                    bases = sender;
                }
                break;
            }
            if (bases == null)
            {
                foreach (PrimitiveMember primitiveMember in metaData.PrimitiveMembers)
                {
                    Object valueDirect = primitiveMember.GetValue(obj);
                    if (!Object.ReferenceEquals(valueDirect, sender))
                    {
                        continue;
                    }
                    bases = obj;
                    parentChildProperty = true;
                    break;
                }
            }
            if (bases == null)
            {
                throw new Exception("Must never happen");
            }
            ICacheModification cacheModification = this.CacheModification;
            bool oldCacheModification            = cacheModification.Active;
            bool cacheModificationUsed           = false;

            try
            {
                switch (evnt.Action)
                {
                case NotifyCollectionChangedAction.Add:
                case NotifyCollectionChangedAction.Remove:
                case NotifyCollectionChangedAction.Replace:
                    if (evnt.OldItems != null)
                    {
                        foreach (Object oldItem in evnt.OldItems)
                        {
                            HandleRemovedItem(obj, oldItem, parentChildProperty);
                        }
                    }
                    if (evnt.NewItems != null)
                    {
                        foreach (Object newItem in evnt.NewItems)
                        {
                            HandleAddedItem(obj, newItem, parentChildProperty);
                        }
                    }
                    break;

#if !SILVERLIGHT
                case NotifyCollectionChangedAction.Move:
                    // Nothing to do in that case
                    break;
#endif
                case NotifyCollectionChangedAction.Reset:
                    throw new NotSupportedException("Reset is not allowed in a managed collection");

                default:
                    throw RuntimeExceptionUtil.CreateEnumNotSupportedException(evnt.Action);
                }
                IList <ICollectionChangeExtension> extensions = collectionChangeExtensions.GetExtensions(obj.GetType());
                for (int a = 0, size = extensions.Count; a < size; a++)
                {
                    extensions[a].CollectionChanged(obj, evnt);
                }
            }
            finally
            {
                if (!oldCacheModification)
                {
                    SetToBeUpdated(obj, true);
                }
                if (cacheModificationUsed)
                {
                    cacheModification.Active = oldCacheModification;
                }
            }
        }
Example #19
0
        protected EntityConfig ReadEntityConfig(XElement entityTag, IMap <String, ILinkConfig> nameToLinkMap)
        {
            String entityTypeName = XmlConfigUtil.GetRequiredAttribute(entityTag, XmlConstants.CLASS);

            try
            {
                Type         entityType   = XmlConfigUtil.GetTypeForName(entityTypeName);
                Type         realType     = ProxyHelper.GetRealType(entityType);
                EntityConfig entityConfig = new EntityConfig(entityType, realType);

                bool localEntity = !entityTag.Name.Equals(XmlConstants.EXTERNAL_ENTITY);
                entityConfig.Local = localEntity;

                IMap <String, IList <XElement> > attributeMap = null;

                IMap <String, IList <XElement> > entityDefs = XmlConfigUtil.ChildrenToElementMap(entityTag);
                if (entityDefs.ContainsKey(XmlConstants.TABLE.LocalName))
                {
                    String specifiedTableName = XmlConfigUtil.GetRequiredAttribute(entityDefs.Get(XmlConstants.TABLE.LocalName)[0], XmlConstants.NAME);
                    entityConfig.TableName = specifiedTableName;
                }
                if (entityDefs.ContainsKey(XmlConstants.PERMISSION_GROUP.LocalName))
                {
                    String permissionGroupName = XmlConfigUtil.GetRequiredAttribute(entityDefs.Get(XmlConstants.PERMISSION_GROUP.LocalName)[0], XmlConstants.NAME);
                    entityConfig.PermissionGroupName = permissionGroupName;
                }
                if (entityDefs.ContainsKey(XmlConstants.SEQ.LocalName))
                {
                    String sequenceName = XmlConfigUtil.GetRequiredAttribute(entityDefs.Get(XmlConstants.SEQ.LocalName)[0], XmlConstants.NAME);
                    entityConfig.SequenceName = sequenceName;
                }
                if (attributeMap.ContainsKey(XmlConstants.DESCRIMINATOR.LocalName))
                {
                    String descriminatorName = XmlConfigUtil.GetRequiredAttribute(entityDefs.Get(XmlConstants.DESCRIMINATOR.LocalName)[0], XmlConstants.NAME);
                    entityConfig.DescriminatorName = descriminatorName;
                }

                if (entityDefs.ContainsKey(XmlConstants.ATTR.LocalName))
                {
                    attributeMap = XmlConfigUtil.ToElementMap(entityDefs.Get(XmlConstants.ATTR.LocalName)[0].Elements());
                }
                bool versionRequired = true;
                if (attributeMap != null)
                {
                    IMap <String, MemberConfig> allIdMemberConfigs = new HashMap <String, MemberConfig>();
                    if (attributeMap.ContainsKey(XmlConstants.ID.LocalName))
                    {
                        MemberConfig idMemberConfig = ReadUniqueMemberConfig(XmlConstants.ID.LocalName, attributeMap);
                        entityConfig.IdMemberConfig = idMemberConfig;
                        allIdMemberConfigs.Put(idMemberConfig.Name, idMemberConfig);
                    }
                    else if (attributeMap.ContainsKey(XmlConstants.ID_COMP.LocalName))
                    {
                        XElement      memberElement  = attributeMap.Get(XmlConstants.ID_COMP.LocalName)[0];
                        IMemberConfig idMemberConfig = ReadCompositeMemberConfig(memberElement, allIdMemberConfigs);
                        entityConfig.IdMemberConfig = idMemberConfig;
                    }
                    else if (!localEntity)
                    {
                        throw new ArgumentException("ID member name has to be set on external entities");
                    }

                    if (attributeMap.ContainsKey(XmlConstants.ALT_ID.LocalName))
                    {
                        IList <XElement> altIds = attributeMap.Get(XmlConstants.ALT_ID.LocalName);
                        for (int j = altIds.Count; j-- > 0;)
                        {
                            XElement     memberElement = altIds[j];
                            MemberConfig memberConfig  = ReadMemberConfig(memberElement);
                            memberConfig.AlternateId = true;
                            entityConfig.AddMemberConfig(memberConfig);
                            allIdMemberConfigs.Put(memberConfig.Name, memberConfig);
                        }
                    }

                    if (attributeMap.ContainsKey(XmlConstants.ALT_ID_COMP.LocalName))
                    {
                        IList <XElement> altIdsComp = attributeMap.Get(XmlConstants.ALT_ID_COMP.LocalName);
                        for (int j = altIdsComp.Count; j-- > 0;)
                        {
                            XElement memberElement             = altIdsComp[j];
                            CompositeMemberConfig memberConfig = ReadCompositeMemberConfig(memberElement, allIdMemberConfigs);
                            memberConfig.AlternateId = true;
                            entityConfig.AddMemberConfig(memberConfig);
                        }
                    }

                    if (attributeMap.ContainsKey(XmlConstants.VERSION.LocalName))
                    {
                        MemberConfig versionMemberConfig = ReadUniqueMemberConfig(XmlConstants.VERSION.LocalName, attributeMap);
                        entityConfig.VersionMemberConfig = versionMemberConfig;
                    }
                    else if (attributeMap.ContainsKey(XmlConstants.NO_VERSION.LocalName))
                    {
                        versionRequired = false;
                    }
                    else if (!localEntity)
                    {
                        throw new ArgumentException("Version member name has to be set on external entities");
                    }
                    if (attributeMap.ContainsKey(XmlConstants.CREATED_BY.LocalName))
                    {
                        MemberConfig createdByMemberConfig = ReadUniqueMemberConfig(XmlConstants.CREATED_BY.LocalName, attributeMap);
                        entityConfig.CreatedByMemberConfig = createdByMemberConfig;
                    }
                    if (attributeMap.ContainsKey(XmlConstants.CREATED_ON.LocalName))
                    {
                        MemberConfig createdOnMemberConfig = ReadUniqueMemberConfig(XmlConstants.CREATED_ON.LocalName, attributeMap);
                        entityConfig.CreatedOnMemberConfig = createdOnMemberConfig;
                    }
                    if (attributeMap.ContainsKey(XmlConstants.UPDATED_BY.LocalName))
                    {
                        MemberConfig updatedByMemberConfig = ReadUniqueMemberConfig(XmlConstants.UPDATED_BY.LocalName, attributeMap);
                        entityConfig.UpdatedByMemberConfig = updatedByMemberConfig;
                    }
                    if (attributeMap.ContainsKey(XmlConstants.UPDATED_ON.LocalName))
                    {
                        MemberConfig updatedOnMemberConfig = ReadUniqueMemberConfig(XmlConstants.UPDATED_ON.LocalName, attributeMap);
                        entityConfig.UpdatedOnMemberConfig = updatedOnMemberConfig;
                    }

                    if (attributeMap.ContainsKey(XmlConstants.BASIC.LocalName))
                    {
                        IList <XElement> basicAttrs = attributeMap.Get(XmlConstants.BASIC.LocalName);
                        for (int j = basicAttrs.Count; j-- > 0;)
                        {
                            XElement     memberElement = basicAttrs[j];
                            MemberConfig memberConfig  = ReadMemberConfig(memberElement);
                            entityConfig.AddMemberConfig(memberConfig);
                        }
                    }

                    if (attributeMap.ContainsKey(XmlConstants.IGNORE.LocalName))
                    {
                        IList <XElement> ignoreAttrs = attributeMap.Get(XmlConstants.IGNORE.LocalName);
                        for (int j = ignoreAttrs.Count; j-- > 0;)
                        {
                            XElement     ignoreElement = ignoreAttrs[j];
                            MemberConfig memberConfig  = ReadMemberConfig(ignoreElement);
                            memberConfig.Ignore = true;
                            entityConfig.AddMemberConfig(memberConfig);
                        }
                    }

                    if (attributeMap.ContainsKey(XmlConstants.RELATION.LocalName))
                    {
                        IList <XElement> relationAttrs = attributeMap.Get(XmlConstants.RELATION.LocalName);
                        for (int j = relationAttrs.Count; j-- > 0;)
                        {
                            XElement        relationElement = relationAttrs[j];
                            IRelationConfig relationConfig  = ReadRelationConfig(relationElement, nameToLinkMap);
                            entityConfig.AddRelationConfig(relationConfig);
                        }
                    }
                }
                entityConfig.VersionRequired = versionRequired;

                return(entityConfig);
            }
            catch (Exception e)
            {
                throw RuntimeExceptionUtil.Mask(e, "Error occured while processing mapping for entity: " + entityTypeName);
            }
        }
        public override Object ConvertValueToType(Type expectedType, Object value, Object additionalInformation)
        {
            if (expectedType == null)
            {
                return(value);
            }
            if (value == null)
            {
                if (expectedType.IsValueType)
                {
                    return(Activator.CreateInstance(expectedType));
                }
                return(null);
            }
            if (expectedType.IsAssignableFrom(value.GetType()))
            {
                return(value);
            }
            Object sourceValue = value;

            while (true)
            {
                Type sourceClass = sourceValue.GetType();
                IDedicatedConverter dedicatedConverter = converters.GetExtension(sourceClass, expectedType);
                if (dedicatedConverter == null)
                {
                    break;
                }
                Object targetValue;
                try
                {
                    targetValue = dedicatedConverter.ConvertValueToType(expectedType, sourceClass, sourceValue, additionalInformation);
                }
                catch (Exception e)
                {
                    throw RuntimeExceptionUtil.Mask(e, "Error occured while converting value: " + sourceValue);
                }
                if (targetValue == null)
                {
                    if (expectedType.IsValueType)
                    {
                        throw new Exception("It is not allowed that an instance of " + typeof(IDedicatedConverter).FullName + " returns null like "
                                            + dedicatedConverter + " did for conversion from '" + sourceClass.FullName + "' to '" + expectedType + "'");
                    }
                    return(null);
                }
                if (expectedType.IsAssignableFrom(targetValue.GetType()))
                {
                    return(targetValue);
                }
                if (targetValue.GetType().Equals(sourceValue.GetType()))
                {
                    throw new Exception("It is not allowed that an instance of " + typeof(IDedicatedConverter).FullName
                                        + " returns a value of the same type (" + targetValue.GetType().FullName + ") after conversion like " + dedicatedConverter
                                        + " did");
                }
                sourceValue = targetValue;
            }
            if (expectedType.IsArray && sourceValue != null && sourceValue.GetType().IsArray)
            {
                // try to convert item by item of the array
                Array sourceArray           = (Array)sourceValue;
                int   size                  = sourceArray.GetLength(0);
                Type  expectedComponentType = expectedType.GetElementType();
                Array targetValue           = Array.CreateInstance(expectedComponentType, size);
                for (int a = sourceArray.GetLength(0); a-- > 0;)
                {
                    Object sourceItem = sourceArray.GetValue(a);
                    Object targetItem = ConvertValueToType(expectedComponentType, sourceItem);
                    targetValue.SetValue(targetItem, a);
                }
                return(targetValue);
            }
            return(DefaultConversionHelper.ConvertValueToType(expectedType, sourceValue, additionalInformation));
        }
Example #21
0
        protected Type EnhanceTypeIntern(Type originalType, String newTypeNamePrefix, IList <IBytecodeBehavior> pendingBehaviors,
                                         IEnhancementHint hint)
        {
            if (pendingBehaviors.Count == 0)
            {
                return(originalType);
            }
            WeakReference originalTypeR = typeToExtendedType.GetWeakReferenceEntry(originalType);

            if (originalTypeR == null)
            {
                throw new Exception("Must never happen");
            }
            String lastTypeHandleName = newTypeNamePrefix;

            newTypeNamePrefix = newTypeNamePrefix.Replace('.', '/');
            StringBuilder sw = new StringBuilder();

            try
            {
                Type currentType = originalType;
                if (currentType.IsInterface)
                {
                    currentType = typeof(Object);
                }
                for (int a = 0, size = pendingBehaviors.Count; a < size; a++)
                {
                    Type newCurrentType = pendingBehaviors[a].GetTypeToExtendFrom(originalType, currentType, hint);
                    if (newCurrentType != null)
                    {
                        currentType = newCurrentType;
                    }
                }
                int iterationCount = 0;

                List <BytecodeBehaviorState> pendingStatesToPostProcess = new List <BytecodeBehaviorState>();
                Type currentContent = currentType; //BytecodeClassLoader.ReadTypeAsBinary(currentType);
                while (pendingBehaviors.Count > 0)
                {
                    iterationCount++;

                    NewType newTypeHandle = NewType.GetObjectType(newTypeNamePrefix + "$A" + iterationCount);
                    lastTypeHandleName = newTypeHandle.ClassName;

                    IBytecodeBehavior[] currentPendingBehaviors = ListUtil.ToArray(pendingBehaviors);
                    pendingBehaviors.Clear();

                    if (currentPendingBehaviors.Length > 0 && Log.DebugEnabled)
                    {
                        Log.Debug("Applying behaviors on " + newTypeHandle.ClassName + ": " + Arrays.ToString(currentPendingBehaviors));
                    }
                    BytecodeEnhancer This            = this;
                    Type             fCurrentContent = currentContent;

                    BytecodeBehaviorState acquiredState = null;
                    Type newContent = BytecodeBehaviorState.SetState(originalType, currentType, newTypeHandle, BeanContext, hint,
                                                                     delegate()
                    {
                        acquiredState = (BytecodeBehaviorState)BytecodeBehaviorState.State;
                        return(This.ExecutePendingBehaviors(fCurrentContent, sw, currentPendingBehaviors, pendingBehaviors));
                    });
                    if (newContent == null)
                    {
                        if (pendingBehaviors.Count > 0)
                        {
                            // "fix" the iterationCount to have a consistent class name hierarchy
                            iterationCount--;
                            continue;
                        }
                        return(currentType);
                    }
                    Type newType = newContent;// BytecodeClassLoader.LoadClass(newTypeHandle.InternalName, newContent);
                    extendedTypeToType.Add(newType, originalTypeR);
                    pendingStatesToPostProcess.Add(acquiredState);
                    currentContent = newContent;
                    currentType    = newType;
                }
                for (int a = 0, size = pendingStatesToPostProcess.Count; a < size; a++)
                {
                    pendingStatesToPostProcess[a].PostProcessCreatedType(currentType);
                }
                return(currentType);
            }
            catch (Exception e)
            {
                BytecodeClassLoader.Save();
                String classByteCode = sw.ToString();
                if (classByteCode.Length > 0)
                {
                    if (TraceDir != null)
                    {
                        LogBytecodeOutput(lastTypeHandleName, classByteCode);
                    }
                    else
                    {
                        throw RuntimeExceptionUtil.Mask(e, "Bytecode:\n" + classByteCode);
                    }
                }
                throw;
            }
        }
Example #22
0
        protected PropertyInfoEntry GetPropertyEntry(Type type, SmartCopyMap <Type, PropertyInfoEntry> map, bool isOldIocMode, bool isIocMode)
        {
            ParamChecker.AssertParamNotNull(type, "type");
            PropertyInfoEntry propertyEntry = map.Get(type);

            if (propertyEntry != null)
            {
                return(propertyEntry);
            }
            Object writeLock = map.GetWriteLock();

            lock (writeLock)
            {
                propertyEntry = map.Get(type);
                if (propertyEntry != null)
                {
                    // Concurrent thread might have been faster
                    return(propertyEntry);
                }

                HashMap <String, HashMap <Type, HashMap <String, MethodInfo> > > sortedMethods = new HashMap <String, HashMap <Type, HashMap <String, MethodInfo> > >();
                MethodInfo[] methods = ReflectUtil.GetDeclaredMethodsInHierarchy(type);

                foreach (MethodInfo method in methods)
                {
                    if (method.DeclaringType.Equals(typeof(Object)))
                    {
                        continue;
                    }
                    if (method.IsStatic)
                    {
                        continue;
                    }
                    try
                    {
                        String propName = GetPropertyNameFor(method);
                        if (propName.Length == 0)
                        {
                            continue;
                        }
                        HashMap <Type, HashMap <String, MethodInfo> > sortedMethod = sortedMethods.Get(propName);
                        if (sortedMethod == null)
                        {
                            sortedMethod = HashMap <Type, HashMap <String, MethodInfo> > .Create(1);

                            sortedMethods.Put(propName, sortedMethod);
                        }

                        ParameterInfo[] parameterInfos = method.GetParameters();
                        Type            propertyType;
                        String          prefix;
                        if (parameterInfos.Length == 1)
                        {
                            propertyType = parameterInfos[0].ParameterType;
                            prefix       = "set";
                        }
                        else if (parameterInfos.Length == 0)
                        {
                            propertyType = method.ReturnType;
                            prefix       = "get";
                        }
                        else
                        {
                            throw new Exception("Method is not an accessor: " + method);
                        }

                        HashMap <String, MethodInfo> methodPerType = sortedMethod.Get(propertyType);
                        if (methodPerType == null)
                        {
                            methodPerType = HashMap <String, MethodInfo> .Create(2);

                            sortedMethod.Put(propertyType, methodPerType);
                        }

                        methodPerType.Put(prefix, method);
                    }
                    catch (Exception e)
                    {
                        throw RuntimeExceptionUtil.Mask(e, "Error occured while processing " + method);
                    }
                }

                HashMap <String, HashMap <String, MethodInfo> > filteredMethods = FilterOverriddenMethods(sortedMethods, type);

                HashMap <String, IPropertyInfo> propertyMap = new HashMap <String, IPropertyInfo>(0.5f);
                foreach (MapEntry <String, HashMap <String, MethodInfo> > propertyData in filteredMethods)
                {
                    String propertyName = propertyData.Key;

                    HashMap <String, MethodInfo> propertyMethods = propertyData.Value;
                    MethodInfo getter = propertyMethods.Get("get");
                    MethodInfo setter = propertyMethods.Get("set");

                    if (isIocMode)
                    {
                        if (setter == null ||
                            (!setter.IsPublic && !AnnotationUtil.IsAnnotationPresent <AutowiredAttribute>(setter, false) &&
                             !AnnotationUtil.IsAnnotationPresent <PropertyAttribute>(setter, false)))
                        {
                            continue;
                        }
                    }
                    MethodPropertyInfo propertyInfo = new MethodPropertyInfo(type, propertyName, getter, setter);
                    propertyMap.Put(propertyInfo.Name, propertyInfo);
                }

                Type[]      interfaces    = type.GetInterfaces();
                List <Type> typesToSearch = new List <Type>(interfaces);
                typesToSearch.Add(type);
                foreach (Type typeToSearch in typesToSearch)
                {
                    PropertyInfo[] properties = typeToSearch.GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public);
                    foreach (PropertyInfo property in properties)
                    {
                        if (property.GetGetMethod() != null && property.GetGetMethod().GetParameters().Length != 0)
                        {
                            continue;
                        }
                        if (property.GetSetMethod() != null && property.GetSetMethod().GetParameters().Length != 1)
                        {
                            continue;
                        }
                        MethodInfo getter = null;
                        MethodInfo setter = null;

                        MethodPropertyInfo propertyInfo = (MethodPropertyInfo)propertyMap.Get(property.Name);
                        if (propertyInfo != null)
                        {
                            getter = propertyInfo.Getter;
                            setter = propertyInfo.Setter;
                        }
                        if (getter == null)
                        {
                            getter = property.GetGetMethod();
                        }
                        if (setter == null)
                        {
                            setter = property.GetSetMethod();
                        }
                        if (isIocMode && setter == null)
                        {
                            continue;
                        }
                        propertyInfo = new MethodPropertyInfo(type, property.Name, getter, setter);
                        propertyInfo.PutAnnotations(property);
                        propertyMap.Put(propertyInfo.Name, propertyInfo);
                    }
                }

                FieldInfo[] fields = ReflectUtil.GetDeclaredFieldsInHierarchy(type);
                foreach (FieldInfo field in fields)
                {
                    if (field.IsStatic)
                    {
                        continue;
                    }
                    if (isOldIocMode)
                    {
                        if (!AnnotationUtil.IsAnnotationPresent <AutowiredAttribute>(field, false) && !AnnotationUtil.IsAnnotationPresent <PropertyAttribute>(field, false))
                        {
                            continue;
                        }
                    }
                    String        propertyName     = GetPropertyNameFor(field);
                    IPropertyInfo existingProperty = propertyMap.Get(propertyName);
                    if (existingProperty != null && existingProperty.IsWritable)
                    {
                        // Ignore field injection if the already resolved (method-)property is writable
                        continue;
                    }
                    IPropertyInfo propertyInfo = new FieldPropertyInfo(type, propertyName, field);
                    propertyMap.Put(propertyInfo.Name, propertyInfo);
                }
                propertyEntry = new PropertyInfoEntry(propertyMap);
                map.Put(type, propertyEntry);
                return(propertyEntry);
            }
        }