Return-Path: X-Original-To: apmail-ignite-commits-archive@minotaur.apache.org Delivered-To: apmail-ignite-commits-archive@minotaur.apache.org Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by minotaur.apache.org (Postfix) with SMTP id C12E418813 for ; Sat, 5 Sep 2015 02:31:45 +0000 (UTC) Received: (qmail 83248 invoked by uid 500); 5 Sep 2015 02:31:45 -0000 Delivered-To: apmail-ignite-commits-archive@ignite.apache.org Received: (qmail 83093 invoked by uid 500); 5 Sep 2015 02:31:45 -0000 Mailing-List: contact commits-help@ignite.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@ignite.apache.org Delivered-To: mailing list commits@ignite.apache.org Received: (qmail 82515 invoked by uid 99); 5 Sep 2015 02:31:45 -0000 Received: from git1-us-west.apache.org (HELO git1-us-west.apache.org) (140.211.11.23) by apache.org (qpsmtpd/0.29) with ESMTP; Sat, 05 Sep 2015 02:31:45 +0000 Received: by git1-us-west.apache.org (ASF Mail Server at git1-us-west.apache.org, from userid 33) id 0EDE8E0544; Sat, 5 Sep 2015 02:31:45 +0000 (UTC) Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit From: akuznetsov@apache.org To: commits@ignite.apache.org Date: Sat, 05 Sep 2015 02:32:03 -0000 Message-Id: <441e4cc2bcc849cc8dc2a0c09a90e662@git.apache.org> In-Reply-To: References: X-Mailer: ASF-Git Admin Mailer Subject: [20/45] ignite git commit: IGNITE-1348: Moved GridGain's .Net module to Ignite. http://git-wip-us.apache.org/repos/asf/ignite/blob/5cec202c/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Portable/PortableWriterImpl.cs ---------------------------------------------------------------------- diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Portable/PortableWriterImpl.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Portable/PortableWriterImpl.cs new file mode 100644 index 0000000..c44a0a4 --- /dev/null +++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Portable/PortableWriterImpl.cs @@ -0,0 +1,1305 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace Apache.Ignite.Core.Impl.Portable +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; + using System.IO; + using Apache.Ignite.Core.Impl.Portable.IO; + using Apache.Ignite.Core.Impl.Portable.Metadata; + using Apache.Ignite.Core.Portable; + + /// + /// Portable writer implementation. + /// + internal class PortableWriterImpl : IPortableWriter, IPortableRawWriter + { + /** Marshaller. */ + private readonly PortableMarshaller _marsh; + + /** Stream. */ + private readonly IPortableStream _stream; + + /** Builder (used only during build). */ + private PortableBuilderImpl _builder; + + /** Handles. */ + private PortableHandleDictionary _hnds; + + /** Metadatas collected during this write session. */ + private IDictionary _metas; + + /** Current type ID. */ + private int _curTypeId; + + /** Current name converter */ + private IPortableNameMapper _curConverter; + + /** Current mapper. */ + private IPortableIdMapper _curMapper; + + /** Current metadata handler. */ + private IPortableMetadataHandler _curMetaHnd; + + /** Current raw flag. */ + private bool _curRaw; + + /** Current raw position. */ + private long _curRawPos; + + /** Ignore handles flag. */ + private bool _detach; + + /** Object started ignore mode. */ + private bool _detachMode; + + /// + /// Gets the marshaller. + /// + internal PortableMarshaller Marshaller + { + get { return _marsh; } + } + + /// + /// Write named boolean value. + /// + /// Field name. + /// Boolean value. + public void WriteBoolean(string fieldName, bool val) + { + WriteSimpleField(fieldName, PortableUtils.TypeBool, val, PortableSystemHandlers.WriteHndBoolTyped, 1); + } + + /// + /// Write boolean value. + /// + /// Boolean value. + public void WriteBoolean(bool val) + { + _stream.WriteBool(val); + } + + /// + /// Write named boolean array. + /// + /// Field name. + /// Boolean array. + public void WriteBooleanArray(string fieldName, bool[] val) + { + WriteSimpleNullableField(fieldName, PortableUtils.TypeArrayBool, val, + PortableSystemHandlers.WriteHndBoolArrayTyped, val != null ? val.Length + 4 : 0); + } + + /// + /// Write boolean array. + /// + /// Boolean array. + public void WriteBooleanArray(bool[] val) + { + WriteSimpleNullableRawField(val, PortableSystemHandlers.WriteHndBoolArrayTyped); + } + + /// + /// Write named byte value. + /// + /// Field name. + /// Byte value. + public void WriteByte(string fieldName, byte val) + { + WriteSimpleField(fieldName, PortableUtils.TypeByte, val, PortableSystemHandlers.WriteHndByteTyped, 1); + } + + /// + /// Write byte value. + /// + /// Byte value. + public void WriteByte(byte val) + { + _stream.WriteByte(val); + } + + /// + /// Write named byte array. + /// + /// Field name. + /// Byte array. + public void WriteByteArray(string fieldName, byte[] val) + { + WriteSimpleNullableField(fieldName, PortableUtils.TypeArrayByte, val, + PortableSystemHandlers.WriteHndByteArrayTyped, val != null ? val.Length + 4 : 0); + } + + /// + /// Write byte array. + /// + /// Byte array. + public void WriteByteArray(byte[] val) + { + WriteSimpleNullableRawField(val, PortableSystemHandlers.WriteHndByteArrayTyped); + } + + /// + /// Write named short value. + /// + /// Field name. + /// Short value. + public void WriteShort(string fieldName, short val) + { + WriteSimpleField(fieldName, PortableUtils.TypeShort, val, PortableSystemHandlers.WriteHndShortTyped, 2); + } + + /// + /// Write short value. + /// + /// Short value. + public void WriteShort(short val) + { + _stream.WriteShort(val); + } + + /// + /// Write named short array. + /// + /// Field name. + /// Short array. + public void WriteShortArray(string fieldName, short[] val) + { + WriteSimpleNullableField(fieldName, PortableUtils.TypeArrayShort, val, + PortableSystemHandlers.WriteHndShortArrayTyped, val != null ? 2 * val.Length + 4 : 0); + } + + /// + /// Write short array. + /// + /// Short array. + public void WriteShortArray(short[] val) + { + WriteSimpleNullableRawField(val, PortableSystemHandlers.WriteHndShortArrayTyped); + } + + /// + /// Write named char value. + /// + /// Field name. + /// Char value. + public void WriteChar(string fieldName, char val) + { + WriteSimpleField(fieldName, PortableUtils.TypeChar, val, PortableSystemHandlers.WriteHndCharTyped, 2); + } + + /// + /// Write char value. + /// + /// Char value. + public void WriteChar(char val) + { + _stream.WriteChar(val); + } + + /// + /// Write named char array. + /// + /// Field name. + /// Char array. + public void WriteCharArray(string fieldName, char[] val) + { + WriteSimpleNullableField(fieldName, PortableUtils.TypeArrayChar, val, + PortableSystemHandlers.WriteHndCharArrayTyped, val != null ? 2 * val.Length + 4 : 0); + } + + /// + /// Write char array. + /// + /// Char array. + public void WriteCharArray(char[] val) + { + WriteSimpleNullableRawField(val, PortableSystemHandlers.WriteHndCharArrayTyped); + } + + /// + /// Write named int value. + /// + /// Field name. + /// Int value. + public void WriteInt(string fieldName, int val) + { + WriteSimpleField(fieldName, PortableUtils.TypeInt, val, PortableSystemHandlers.WriteHndIntTyped, 4); + } + + /// + /// Write int value. + /// + /// Int value. + public void WriteInt(int val) + { + _stream.WriteInt(val); + } + + /// + /// Write named int array. + /// + /// Field name. + /// Int array. + public void WriteIntArray(string fieldName, int[] val) + { + WriteSimpleNullableField(fieldName, PortableUtils.TypeArrayInt, val, + PortableSystemHandlers.WriteHndIntArrayTyped, val != null ? 4 * val.Length + 4 : 0); + } + + /// + /// Write int array. + /// + /// Int array. + public void WriteIntArray(int[] val) + { + WriteSimpleNullableRawField(val, PortableSystemHandlers.WriteHndIntArrayTyped); + } + + /// + /// Write named long value. + /// + /// Field name. + /// Long value. + public void WriteLong(string fieldName, long val) + { + WriteSimpleField(fieldName, PortableUtils.TypeLong, val, PortableSystemHandlers.WriteHndLongTyped, 8); + } + + /// + /// Write long value. + /// + /// Long value. + public void WriteLong(long val) + { + _stream.WriteLong(val); + } + + /// + /// Write named long array. + /// + /// Field name. + /// Long array. + public void WriteLongArray(string fieldName, long[] val) + { + WriteSimpleNullableField(fieldName, PortableUtils.TypeArrayLong, val, + PortableSystemHandlers.WriteHndLongArrayTyped, val != null ? 8 * val.Length + 4 : 0); + } + + /// + /// Write long array. + /// + /// Long array. + public void WriteLongArray(long[] val) + { + WriteSimpleNullableRawField(val, PortableSystemHandlers.WriteHndLongArrayTyped); + } + + /// + /// Write named float value. + /// + /// Field name. + /// Float value. + public void WriteFloat(string fieldName, float val) + { + WriteSimpleField(fieldName, PortableUtils.TypeFloat, val, PortableSystemHandlers.WriteHndFloatTyped, 4); + } + + /// + /// Write float value. + /// + /// Float value. + public void WriteFloat(float val) + { + _stream.WriteFloat(val); + } + + /// + /// Write named float array. + /// + /// Field name. + /// Float array. + public void WriteFloatArray(string fieldName, float[] val) + { + WriteSimpleNullableField(fieldName, PortableUtils.TypeArrayFloat, val, + PortableSystemHandlers.WriteHndFloatArrayTyped, val != null ? 4 * val.Length + 4 : 0); + } + + /// + /// Write float array. + /// + /// Float array. + public void WriteFloatArray(float[] val) + { + WriteSimpleNullableRawField(val, PortableSystemHandlers.WriteHndFloatArrayTyped); + } + + /// + /// Write named double value. + /// + /// Field name. + /// Double value. + public void WriteDouble(string fieldName, double val) + { + WriteSimpleField(fieldName, PortableUtils.TypeDouble, val, PortableSystemHandlers.WriteHndDoubleTyped, 8); + } + + /// + /// Write double value. + /// + /// Double value. + public void WriteDouble(double val) + { + _stream.WriteDouble(val); + } + + /// + /// Write named double array. + /// + /// Field name. + /// Double array. + public void WriteDoubleArray(string fieldName, double[] val) + { + WriteSimpleNullableField(fieldName, PortableUtils.TypeArrayDouble, val, + PortableSystemHandlers.WriteHndDoubleArrayTyped, val != null ? 8 * val.Length + 4 : 0); + } + + /// + /// Write double array. + /// + /// Double array. + public void WriteDoubleArray(double[] val) + { + WriteSimpleNullableRawField(val, PortableSystemHandlers.WriteHndDoubleArrayTyped); + } + + /// + /// Write named decimal value. + /// + /// Field name. + /// Decimal value. + public void WriteDecimal(string fieldName, decimal val) + { + WriteSimpleNullableField(fieldName, PortableUtils.TypeDecimal, val, PortableSystemHandlers.WriteHndDecimalTyped); + } + + /// + /// Write decimal value. + /// + /// Decimal value. + public void WriteDecimal(decimal val) + { + WriteSimpleNullableRawField(val, PortableSystemHandlers.WriteHndDecimalTyped); + } + + /// + /// Write named decimal array. + /// + /// Field name. + /// Decimal array. + public void WriteDecimalArray(string fieldName, decimal[] val) + { + WriteSimpleNullableField(fieldName, PortableUtils.TypeArrayDecimal, val, + PortableSystemHandlers.WriteHndDecimalArrayTyped); + } + + /// + /// Write decimal array. + /// + /// Decimal array. + public void WriteDecimalArray(decimal[] val) + { + WriteSimpleNullableRawField(val, PortableSystemHandlers.WriteHndDecimalArrayTyped); + } + + /// + /// Write named date value. + /// + /// Field name. + /// Date value. + public void WriteDate(string fieldName, DateTime? val) + { + WriteSimpleNullableField(fieldName, PortableUtils.TypeDate, val, PortableSystemHandlers.WriteHndDateTyped, + val.HasValue ? 12 : 0); + } + + /// + /// Write date value. + /// + /// Date value. + public void WriteDate(DateTime? val) + { + WriteSimpleNullableRawField(val, PortableSystemHandlers.WriteHndDateTyped); + } + + /// + /// Write named date array. + /// + /// Field name. + /// Date array. + public void WriteDateArray(string fieldName, DateTime?[] val) + { + WriteSimpleNullableField(fieldName, PortableUtils.TypeArrayDate, val, + PortableSystemHandlers.WriteHndDateArrayTyped); + } + + /// + /// Write date array. + /// + /// Date array. + public void WriteDateArray(DateTime?[] val) + { + WriteSimpleNullableRawField(val, PortableSystemHandlers.WriteHndDateArrayTyped); + } + + /// + /// Write named string value. + /// + /// Field name. + /// String value. + public void WriteString(string fieldName, string val) + { + WriteSimpleNullableField(fieldName, PortableUtils.TypeString, val, PortableSystemHandlers.WriteHndStringTyped); + } + + /// + /// Write string value. + /// + /// String value. + public void WriteString(string val) + { + WriteSimpleNullableRawField(val, PortableSystemHandlers.WriteHndStringTyped); + } + + /// + /// Write named string array. + /// + /// Field name. + /// String array. + public void WriteStringArray(string fieldName, string[] val) + { + WriteSimpleNullableField(fieldName, PortableUtils.TypeArrayString, val, + PortableSystemHandlers.WriteHndStringArrayTyped); + } + + /// + /// Write string array. + /// + /// String array. + public void WriteStringArray(string[] val) + { + WriteSimpleNullableRawField(val, PortableSystemHandlers.WriteHndStringArrayTyped); + } + + /// + /// Write named GUID value. + /// + /// Field name. + /// GUID value. + public void WriteGuid(string fieldName, Guid? val) + { + WriteSimpleNullableField(fieldName, PortableUtils.TypeGuid, val, PortableSystemHandlers.WriteHndGuidTyped, + val.HasValue ? 16 : 0); + } + + /// + /// Write GUID value. + /// + /// GUID value. + public void WriteGuid(Guid? val) + { + WriteSimpleNullableRawField(val, PortableSystemHandlers.WriteHndGuidTyped); + } + + /// + /// Write named GUID array. + /// + /// Field name. + /// GUID array. + public void WriteGuidArray(string fieldName, Guid?[] val) + { + WriteSimpleNullableField(fieldName, PortableUtils.TypeArrayGuid, val, + PortableSystemHandlers.WriteHndGuidArrayTyped); + } + + /// + /// Write GUID array. + /// + /// GUID array. + public void WriteGuidArray(Guid?[] val) + { + WriteSimpleNullableRawField(val, PortableSystemHandlers.WriteHndGuidArrayTyped); + } + + /// + /// Write named enum value. + /// + /// + /// Field name. + /// Enum value. + public void WriteEnum(string fieldName, T val) + { + WriteField(fieldName, PortableUtils.TypeEnum, val, PortableSystemHandlers.WriteHndEnum); + } + + /// + /// Write enum value. + /// + /// + /// Enum value. + public void WriteEnum(T val) + { + Write(val, PortableSystemHandlers.WriteHndEnum); + } + + /// + /// Write named enum array. + /// + /// + /// Field name. + /// Enum array. + public void WriteEnumArray(string fieldName, T[] val) + { + WriteField(fieldName, PortableUtils.TypeArrayEnum, val, PortableSystemHandlers.WriteHndEnumArray); + } + + /// + /// Write enum array. + /// + /// + /// Enum array. + public void WriteEnumArray(T[] val) + { + Write(val, PortableSystemHandlers.WriteHndEnumArray); + } + + /// + /// Write named object value. + /// + /// + /// Field name. + /// Object value. + public void WriteObject(string fieldName, T val) + { + WriteField(fieldName, PortableUtils.TypeObject, val, null); + } + + /// + /// Write object value. + /// + /// + /// Object value. + public void WriteObject(T val) + { + Write(val); + } + + /// + /// Write named object array. + /// + /// + /// Field name. + /// Object array. + public void WriteObjectArray(string fieldName, T[] val) + { + WriteField(fieldName, PortableUtils.TypeArray, val, PortableSystemHandlers.WriteHndArray); + } + + /// + /// Write object array. + /// + /// + /// Object array. + public void WriteObjectArray(T[] val) + { + Write(val, PortableSystemHandlers.WriteHndArray); + } + + /// + /// Write named collection. + /// + /// Field name. + /// Collection. + public void WriteCollection(string fieldName, ICollection val) + { + WriteField(fieldName, PortableUtils.TypeCollection, val, null); + } + + /// + /// Write collection. + /// + /// Collection. + public void WriteCollection(ICollection val) + { + Write(val); + } + + /// + /// Write named generic collection. + /// + /// + /// Field name. + /// Collection. + public void WriteGenericCollection(string fieldName, ICollection val) + { + WriteField(fieldName, PortableUtils.TypeCollection, val, null); + } + + /// + /// Write generic collection. + /// + /// + /// Collection. + public void WriteGenericCollection(ICollection val) + { + Write(val); + } + + /// + /// Write named dictionary. + /// + /// Field name. + /// Dictionary. + public void WriteDictionary(string fieldName, IDictionary val) + { + WriteField(fieldName, PortableUtils.TypeDictionary, val, null); + } + + /// + /// Write dictionary. + /// + /// Dictionary. + public void WriteDictionary(IDictionary val) + { + Write(val); + } + + /// + /// Write named generic dictionary. + /// + /// Field name. + /// Dictionary. + public void WriteGenericDictionary(string fieldName, IDictionary val) + { + WriteField(fieldName, PortableUtils.TypeDictionary, val, null); + } + + /// + /// Write generic dictionary. + /// + /// Dictionary. + public void WriteGenericDictionary(IDictionary val) + { + Write(val); + } + + /// + /// Get raw writer. + /// + /// + /// Raw writer. + /// + public IPortableRawWriter RawWriter() + { + if (!_curRaw) + { + _curRaw = true; + _curRawPos = _stream.Position; + } + + return this; + } + + /// + /// Set new builder. + /// + /// Builder. + /// Previous builder. + internal PortableBuilderImpl Builder(PortableBuilderImpl builder) + { + PortableBuilderImpl ret = _builder; + + _builder = builder; + + return ret; + } + + /// + /// Constructor. + /// + /// Marshaller. + /// Stream. + internal PortableWriterImpl(PortableMarshaller marsh, IPortableStream stream) + { + _marsh = marsh; + _stream = stream; + } + + /// + /// Write object. + /// + /// Object. + internal void Write(T obj) + { + Write(obj, null); + } + + /// + /// Write object. + /// + /// Object. + /// Optional write handler. + [SuppressMessage("ReSharper", "FunctionComplexityOverflow")] + internal void Write(T obj, object handler) + { + // Apply detach mode if needed. + PortableHandleDictionary oldHnds = null; + + bool resetDetach = false; + + if (_detach) + { + _detach = false; + _detachMode = true; + resetDetach = true; + + oldHnds = _hnds; + + _hnds = null; + } + + try + { + // Write null. + if (obj == null) + { + _stream.WriteByte(PortableUtils.HdrNull); + + return; + } + + if (_builder != null) + { + // Special case for portable object during build. + PortableUserObject portObj = obj as PortableUserObject; + + if (portObj != null) + { + if (!WriteHandle(_stream.Position, portObj)) + _builder.ProcessPortable(_stream, portObj); + + return; + } + + // Special case for builder during build. + PortableBuilderImpl portBuilder = obj as PortableBuilderImpl; + + if (portBuilder != null) + { + if (!WriteHandle(_stream.Position, portBuilder)) + _builder.ProcessBuilder(_stream, portBuilder); + + return; + } + } + + // Try writting as well-known type. + if (InvokeHandler(handler, handler as PortableSystemWriteDelegate, obj)) + return; + + Type type = obj.GetType(); + + IPortableTypeDescriptor desc = _marsh.Descriptor(type); + + object typedHandler; + PortableSystemWriteDelegate untypedHandler; + + if (desc == null) + { + typedHandler = null; + untypedHandler = PortableSystemHandlers.WriteHandler(type); + } + else + { + typedHandler = desc.TypedHandler; + untypedHandler = desc.UntypedHandler; + } + + if (InvokeHandler(typedHandler, untypedHandler, obj)) + return; + + if (desc == null) + { + if (!type.IsSerializable) + // If neither handler, nor descriptor exist, and not serializable, this is an exception. + throw new PortableException("Unsupported object type [type=" + type + + ", object=" + obj + ']'); + + Write(new SerializableObjectHolder(obj)); + + return; + } + + int pos = _stream.Position; + + // Dealing with handles. + if (!(desc.Serializer is IPortableSystemTypeSerializer) && WriteHandle(pos, obj)) + return; + + // Write header. + _stream.WriteByte(PortableUtils.HdrFull); + + _stream.WriteBool(desc.UserType); + _stream.WriteInt(desc.TypeId); + _stream.WriteInt(obj.GetHashCode()); + + // Skip length as it is not known in the first place. + _stream.Seek(8, SeekOrigin.Current); + + // Preserve old frame. + int oldTypeId = _curTypeId; + IPortableNameMapper oldConverter = _curConverter; + IPortableIdMapper oldMapper = _curMapper; + IPortableMetadataHandler oldMetaHnd = _curMetaHnd; + bool oldRaw = _curRaw; + long oldRawPos = _curRawPos; + + // Push new frame. + _curTypeId = desc.TypeId; + _curConverter = desc.NameConverter; + _curMapper = desc.Mapper; + _curMetaHnd = desc.MetadataEnabled ? _marsh.MetadataHandler(desc) : null; + _curRaw = false; + _curRawPos = 0; + + // Write object fields. + desc.Serializer.WritePortable(obj, this); + + // Calculate and write length. + int retPos = _stream.Position; + + _stream.Seek(pos + 10, SeekOrigin.Begin); + + int len = retPos - pos; + + _stream.WriteInt(len); + + if (_curRawPos != 0) + // When set, it is difference between object head and raw position. + _stream.WriteInt((int)(_curRawPos - pos)); + else + // When no set, it is equal to object length. + _stream.WriteInt(len); + + _stream.Seek(retPos, SeekOrigin.Begin); + + // 13. Collect metadata. + if (_curMetaHnd != null) + { + IDictionary meta = _curMetaHnd.OnObjectWriteFinished(); + + if (meta != null) + SaveMetadata(_curTypeId, desc.TypeName, desc.AffinityKeyFieldName, meta); + } + + // Restore old frame. + _curTypeId = oldTypeId; + _curConverter = oldConverter; + _curMapper = oldMapper; + _curMetaHnd = oldMetaHnd; + _curRaw = oldRaw; + _curRawPos = oldRawPos; + } + finally + { + // Restore handles if needed. + if (resetDetach) + { + // Add newly recorded handles without overriding already existing ones. + if (_hnds != null) + { + if (oldHnds == null) + oldHnds = _hnds; + else + oldHnds.Merge(_hnds); + } + + _hnds = oldHnds; + + _detachMode = false; + } + } + } + + /// + /// Add handle to handles map. + /// + /// Position in stream. + /// Object. + /// true if object was written as handle. + private bool WriteHandle(long pos, object obj) + { + if (_hnds == null) + { + // Cache absolute handle position. + _hnds = new PortableHandleDictionary(obj, pos); + + return false; + } + + long hndPos; + + if (!_hnds.TryGetValue(obj, out hndPos)) + { + // Cache absolute handle position. + _hnds.Add(obj, pos); + + return false; + } + + _stream.WriteByte(PortableUtils.HdrHnd); + + // Handle is written as difference between position before header and handle position. + _stream.WriteInt((int)(pos - hndPos)); + + return true; + } + + /// + /// Try invoking predefined handler on object. + /// + /// Handler + /// Not typed handler. + /// Object. + /// True if handler was called. + private bool InvokeHandler(object typedHandler, PortableSystemWriteDelegate untypedHandler, T obj) + { + var typedHandler0 = typedHandler as PortableSystemTypedWriteDelegate; + + if (typedHandler0 != null) + { + typedHandler0.Invoke(_stream, obj); + + return true; + } + + if (untypedHandler != null) + { + untypedHandler.Invoke(this, obj); + + return true; + } + + return false; + } + + /// + /// Write simple field with known length. + /// + /// Field ID. + /// Value. + /// Handler. + /// Length. + private void WriteSimpleField(int fieldId, T val, PortableSystemTypedWriteDelegate handler, int len) + { + CheckNotRaw(); + + _stream.WriteInt(fieldId); + _stream.WriteInt(1 + len); // Additional byte for field type. + + handler(_stream, val); + } + + /// + /// Write simple nullable field with unknown length. + /// + /// Field ID. + /// Value. + /// Handler. + private void WriteSimpleNullableField(int fieldId, T val, PortableSystemTypedWriteDelegate handler) + { + CheckNotRaw(); + + _stream.WriteInt(fieldId); + + if (val == null) + { + _stream.WriteInt(1); + + _stream.WriteByte(PortableUtils.HdrNull); + } + else + { + int pos = _stream.Position; + + _stream.Seek(4, SeekOrigin.Current); + + handler(_stream, val); + + WriteFieldLength(_stream, pos); + } + } + + /// + /// Write simple nullable field with known length. + /// + /// Field ID. + /// Value. + /// Handler. + /// Length. + private void WriteSimpleNullableField(int fieldId, T val, PortableSystemTypedWriteDelegate handler, int len) + { + CheckNotRaw(); + + _stream.WriteInt(fieldId); + + if (val == null) + { + _stream.WriteInt(1); + + _stream.WriteByte(PortableUtils.HdrNull); + } + else + { + _stream.WriteInt(1 + len); + + handler(_stream, val); + } + } + + /// + /// Write field. + /// + /// Field ID. + /// Value. + /// Handler. + private void WriteField(int fieldId, object val, PortableSystemWriteDelegate handler) + { + CheckNotRaw(); + + _stream.WriteInt(fieldId); + + int pos = _stream.Position; + + _stream.Seek(4, SeekOrigin.Current); + + Write(val, handler); + + WriteFieldLength(_stream, pos); + } + + /// + /// Enable detach mode for the next object. + /// + internal void DetachNext() + { + if (!_detachMode) + _detach = true; + } + + /// + /// Stream. + /// + internal IPortableStream Stream + { + get { return _stream; } + } + + /// + /// Gets collected metadatas. + /// + /// Collected metadatas (if any). + internal IDictionary Metadata() + { + return _metas; + } + + /// + /// Check whether the given object is portable, i.e. it can be + /// serialized with portable marshaller. + /// + /// Object. + /// True if portable. + internal bool IsPortable(object obj) + { + if (obj != null) + { + Type type = obj.GetType(); + + // We assume object as portable only in case it has descriptor. + // Collections, Enums and non-primitive arrays do not have descriptors + // and this is fine here because we cannot know whether their members + // are portable. + return _marsh.Descriptor(type) != null; + } + + return true; + } + + /// + /// Write simple field with known length. + /// + /// Field name. + /// Type ID. + /// Value. + /// Handler. + /// Length. + private void WriteSimpleField(string fieldName, byte typeId, T val, + PortableSystemTypedWriteDelegate handler, int len) + { + int fieldId = PortableUtils.FieldId(_curTypeId, fieldName, _curConverter, _curMapper); + + WriteSimpleField(fieldId, val, handler, len); + + if (_curMetaHnd != null) + _curMetaHnd.OnFieldWrite(fieldId, fieldName, typeId); + } + + /// + /// Write simple nullable field with unknown length. + /// + /// Field name. + /// Type ID. + /// Value. + /// Handler. + private void WriteSimpleNullableField(string fieldName, byte typeId, T val, + PortableSystemTypedWriteDelegate handler) + { + int fieldId = PortableUtils.FieldId(_curTypeId, fieldName, _curConverter, _curMapper); + + WriteSimpleNullableField(fieldId, val, handler); + + if (_curMetaHnd != null) + _curMetaHnd.OnFieldWrite(fieldId, fieldName, typeId); + } + + /// + /// Write simple nullable field with known length. + /// + /// Field name. + /// Type ID. + /// Value. + /// Handler. + /// Length. + private void WriteSimpleNullableField(string fieldName, byte typeId, T val, + PortableSystemTypedWriteDelegate handler, int len) + { + int fieldId = PortableUtils.FieldId(_curTypeId, fieldName, _curConverter, _curMapper); + + WriteSimpleNullableField(fieldId, val, handler, len); + + if (_curMetaHnd != null) + _curMetaHnd.OnFieldWrite(fieldId, fieldName, typeId); + } + + /// + /// Write nullable raw field. + /// + /// Value. + /// Handler. + private void WriteSimpleNullableRawField(T val, PortableSystemTypedWriteDelegate handler) + { + if (val == null) + _stream.WriteByte(PortableUtils.HdrNull); + else + handler(_stream, val); + } + + /// + /// Write field. + /// + /// Field name. + /// Type ID. + /// Value. + /// Handler. + private void WriteField(string fieldName, byte typeId, object val, + PortableSystemWriteDelegate handler) + { + int fieldId = PortableUtils.FieldId(_curTypeId, fieldName, _curConverter, _curMapper); + + WriteField(fieldId, val, handler); + + if (_curMetaHnd != null) + _curMetaHnd.OnFieldWrite(fieldId, fieldName, typeId); + } + + /// + /// Write field length. + /// + /// Stream. + /// Position where length should reside + private static void WriteFieldLength(IPortableStream stream, int pos) + { + int retPos = stream.Position; + + stream.Seek(pos, SeekOrigin.Begin); + + stream.WriteInt(retPos - pos - 4); + + stream.Seek(retPos, SeekOrigin.Begin); + } + + /// + /// Ensure that we are not in raw mode. + /// + private void CheckNotRaw() + { + if (_curRaw) + throw new PortableException("Cannot write named fields after raw data is written."); + } + + /// + /// Saves metadata for this session. + /// + /// Type ID. + /// Type name. + /// Affinity key field name. + /// Fields metadata. + internal void SaveMetadata(int typeId, string typeName, string affKeyFieldName, IDictionary fields) + { + if (_metas == null) + { + PortableMetadataImpl meta = + new PortableMetadataImpl(typeId, typeName, fields, affKeyFieldName); + + _metas = new Dictionary(1); + + _metas[typeId] = meta; + } + else + { + IPortableMetadata meta; + + if (_metas.TryGetValue(typeId, out meta)) + { + IDictionary existingFields = ((PortableMetadataImpl)meta).FieldsMap(); + + foreach (KeyValuePair field in fields) + { + if (!existingFields.ContainsKey(field.Key)) + existingFields[field.Key] = field.Value; + } + } + else + _metas[typeId] = new PortableMetadataImpl(typeId, typeName, fields, affKeyFieldName); + } + } + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/5cec202c/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Portable/PortablesImpl.cs ---------------------------------------------------------------------- diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Portable/PortablesImpl.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Portable/PortablesImpl.cs new file mode 100644 index 0000000..066f46b --- /dev/null +++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Portable/PortablesImpl.cs @@ -0,0 +1,205 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace Apache.Ignite.Core.Impl.Portable +{ + using System; + using System.Collections.Generic; + using System.IO; + using Apache.Ignite.Core.Common; + using Apache.Ignite.Core.Impl.Common; + using Apache.Ignite.Core.Impl.Portable.IO; + using Apache.Ignite.Core.Portable; + + /// + /// Portables implementation. + /// + internal class PortablesImpl : IPortables + { + /** Owning grid. */ + private readonly PortableMarshaller _marsh; + + /// + /// Constructor. + /// + /// Marshaller. + internal PortablesImpl(PortableMarshaller marsh) + { + _marsh = marsh; + } + + /** */ + public T ToPortable(object obj) + { + if (obj is IPortableObject) + return (T)obj; + + IPortableStream stream = new PortableHeapStream(1024); + + // Serialize. + PortableWriterImpl writer = _marsh.StartMarshal(stream); + + try + { + writer.Write(obj); + } + finally + { + // Save metadata. + _marsh.FinishMarshal(writer); + } + + // Deserialize. + stream.Seek(0, SeekOrigin.Begin); + + return _marsh.Unmarshal(stream, PortableMode.ForcePortable); + } + + /** */ + public IPortableBuilder Builder(Type type) + { + IgniteArgumentCheck.NotNull(type, "type"); + + IPortableTypeDescriptor desc = _marsh.Descriptor(type); + + if (desc == null) + throw new IgniteException("Type is not portable (add it to PortableConfiguration): " + + type.FullName); + + return Builder0(null, PortableFromDescriptor(desc), desc); + } + + /** */ + public IPortableBuilder Builder(string typeName) + { + IgniteArgumentCheck.NotNullOrEmpty(typeName, "typeName"); + + IPortableTypeDescriptor desc = _marsh.Descriptor(typeName); + + return Builder0(null, PortableFromDescriptor(desc), desc); + } + + /** */ + public IPortableBuilder Builder(IPortableObject obj) + { + IgniteArgumentCheck.NotNull(obj, "obj"); + + PortableUserObject obj0 = obj as PortableUserObject; + + if (obj0 == null) + throw new ArgumentException("Unsupported object type: " + obj.GetType()); + + IPortableTypeDescriptor desc = _marsh.Descriptor(true, obj0.TypeId()); + + return Builder0(null, obj0, desc); + } + + /** */ + public int GetTypeId(string typeName) + { + IgniteArgumentCheck.NotNullOrEmpty(typeName, "typeName"); + + return Marshaller.Descriptor(typeName).TypeId; + } + + /** */ + public ICollection GetMetadata() + { + return Marshaller.Ignite.ClusterGroup.Metadata(); + } + + /** */ + public IPortableMetadata GetMetadata(int typeId) + { + return Marshaller.Metadata(typeId); + } + + /** */ + public IPortableMetadata GetMetadata(string typeName) + { + IgniteArgumentCheck.NotNullOrEmpty(typeName, "typeName"); + + return GetMetadata(GetTypeId(typeName)); + } + + /** */ + public IPortableMetadata GetMetadata(Type type) + { + IgniteArgumentCheck.NotNull(type, "type"); + + var desc = Marshaller.Descriptor(type); + + return desc == null ? null : Marshaller.Metadata(desc.TypeId); + } + + /// + /// Create child builder. + /// + /// Parent builder. + /// Portable object. + /// + internal PortableBuilderImpl ChildBuilder(PortableBuilderImpl parent, PortableUserObject obj) + { + IPortableTypeDescriptor desc = _marsh.Descriptor(true, obj.TypeId()); + + return Builder0(null, obj, desc); + } + + /// + /// Marshaller. + /// + internal PortableMarshaller Marshaller + { + get + { + return _marsh; + } + } + + /// + /// Create empty portable object from descriptor. + /// + /// Descriptor. + /// Empty portable object. + private PortableUserObject PortableFromDescriptor(IPortableTypeDescriptor desc) + { + PortableHeapStream stream = new PortableHeapStream(18); + + stream.WriteByte(PortableUtils.HdrFull); + stream.WriteBool(true); + stream.WriteInt(desc.TypeId); + stream.WriteInt(0); // Hash. + stream.WriteInt(PortableUtils.FullHdrLen); // Length. + stream.WriteInt(PortableUtils.FullHdrLen); // Raw data offset. + + return new PortableUserObject(_marsh, stream.InternalArray, 0, desc.TypeId, 0); + } + + /// + /// Internal builder creation routine. + /// + /// Parent builder. + /// Portable object. + /// Type descriptor. + /// Builder. + private PortableBuilderImpl Builder0(PortableBuilderImpl parent, PortableUserObject obj, + IPortableTypeDescriptor desc) + { + return new PortableBuilderImpl(this, parent, obj, desc); + } + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/5cec202c/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Portable/SerializableObjectHolder.cs ---------------------------------------------------------------------- diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Portable/SerializableObjectHolder.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Portable/SerializableObjectHolder.cs new file mode 100644 index 0000000..a3a9fe7 --- /dev/null +++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Portable/SerializableObjectHolder.cs @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace Apache.Ignite.Core.Impl.Portable +{ + using Apache.Ignite.Core.Portable; + + /// + /// Wraps Serializable item in a portable. + /// + internal class SerializableObjectHolder : IPortableWriteAware + { + /** */ + private readonly object _item; + + /// + /// Initializes a new instance of the class. + /// + /// The item to wrap. + public SerializableObjectHolder(object item) + { + _item = item; + } + + /// + /// Gets the item to wrap. + /// + public object Item + { + get { return _item; } + } + + /** */ + public void WritePortable(IPortableWriter writer) + { + var writer0 = (PortableWriterImpl)writer.RawWriter(); + + writer0.DetachNext(); + + PortableUtils.WriteSerializable(writer0, Item); + } + + /// + /// Initializes a new instance of the class. + /// + /// The reader. + public SerializableObjectHolder(IPortableReader reader) + { + _item = PortableUtils.ReadSerializable((PortableReaderImpl)reader.RawReader()); + } + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/ignite/blob/5cec202c/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Portable/TypeResolver.cs ---------------------------------------------------------------------- diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Portable/TypeResolver.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Portable/TypeResolver.cs new file mode 100644 index 0000000..0785f4a --- /dev/null +++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Portable/TypeResolver.cs @@ -0,0 +1,227 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace Apache.Ignite.Core.Impl.Portable +{ + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.Diagnostics.CodeAnalysis; + using System.Linq; + using System.Reflection; + using System.Text.RegularExpressions; + + /// + /// Resolves types by name. + /// + internal class TypeResolver + { + /** Regex to parse generic types from portable configuration. Allows nested generics in type arguments. */ + private static readonly Regex GenericTypeRegex = + new Regex(@"([^`,\[\]]*)(?:`[0-9]+)?(?:\[((?:(?
\[)|(?<-br>\])|[^\[\]]*)+)\])?", RegexOptions.Compiled); + + /** Assemblies loaded in ReflectionOnly mode. */ + private readonly Dictionary _reflectionOnlyAssemblies = new Dictionary(); + + /// + /// Resolve type by name. + /// + /// Name of the type. + /// Optional, name of the assembly. + /// + /// Resolved type. + /// + public Type ResolveType(string typeName, string assemblyName = null) + { + Debug.Assert(!string.IsNullOrEmpty(typeName)); + + return ResolveType(assemblyName, typeName, AppDomain.CurrentDomain.GetAssemblies()) + ?? ResolveTypeInReferencedAssemblies(assemblyName, typeName); + } + + /// + /// Resolve type by name in specified assembly set. + /// + /// Name of the assembly. + /// Name of the type. + /// Assemblies to look in. + /// + /// Resolved type. + /// + private static Type ResolveType(string assemblyName, string typeName, ICollection assemblies) + { + return ResolveGenericType(assemblyName, typeName, assemblies) ?? + ResolveNonGenericType(assemblyName, typeName, assemblies); + } + + /// + /// Resolves non-generic type by searching provided assemblies. + /// + /// Name of the assembly. + /// Name of the type. + /// The assemblies. + /// Resolved type, or null. + private static Type ResolveNonGenericType(string assemblyName, string typeName, ICollection assemblies) + { + if (!string.IsNullOrEmpty(assemblyName)) + assemblies = assemblies + .Where(x => x.FullName == assemblyName || x.GetName().Name == assemblyName).ToArray(); + + if (!assemblies.Any()) + return null; + + // Trim assembly qualification + var commaIdx = typeName.IndexOf(','); + + if (commaIdx > 0) + typeName = typeName.Substring(0, commaIdx); + + return assemblies.Select(a => a.GetType(typeName, false, false)).FirstOrDefault(type => type != null); + } + + /// + /// Resolves the name of the generic type by resolving each generic arg separately + /// and substituting it's fully qualified name. + /// (Assembly.GetType finds generic types only when arguments are fully qualified). + /// + /// Name of the assembly. + /// Name of the type. + /// Assemblies + /// Fully qualified generic type name, or null if argument(s) could not be resolved. + private static Type ResolveGenericType(string assemblyName, string typeName, ICollection assemblies) + { + var match = GenericTypeRegex.Match(typeName); + + if (!match.Success || !match.Groups[2].Success) + return null; + + // Try to construct generic type; each generic arg can also be a generic type. + var genericArgs = GenericTypeRegex.Matches(match.Groups[2].Value) + .OfType().Select(m => m.Value).Where(v => !string.IsNullOrWhiteSpace(v)) + .Select(v => ResolveType(null, TrimBrackets(v), assemblies)).ToArray(); + + if (genericArgs.Any(x => x == null)) + return null; + + var genericType = ResolveNonGenericType(assemblyName, + string.Format("{0}`{1}", match.Groups[1].Value, genericArgs.Length), assemblies); + + if (genericType == null) + return null; + + return genericType.MakeGenericType(genericArgs); + } + + /// + /// Trims the brackets from generic type arg. + /// + private static string TrimBrackets(string s) + { + return s.StartsWith("[") && s.EndsWith("]") ? s.Substring(1, s.Length - 2) : s; + } + + /// + /// Resolve type by name in non-loaded referenced assemblies. + /// + /// Name of the assembly. + /// Name of the type. + /// + /// Resolved type. + /// + private Type ResolveTypeInReferencedAssemblies(string assemblyName, string typeName) + { + ResolveEventHandler resolver = (sender, args) => GetReflectionOnlyAssembly(args.Name); + + AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += resolver; + + try + { + var result = ResolveType(assemblyName, typeName, GetNotLoadedReferencedAssemblies().ToArray()); + + if (result == null) + return null; + + // result is from ReflectionOnly assembly, load it properly into current domain + var asm = AppDomain.CurrentDomain.Load(result.Assembly.GetName()); + + return asm.GetType(result.FullName); + } + finally + { + AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= resolver; + } + } + + /// + /// Gets the reflection only assembly. + /// + [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] + private Assembly GetReflectionOnlyAssembly(string fullName) + { + Assembly result; + + if (!_reflectionOnlyAssemblies.TryGetValue(fullName, out result)) + { + try + { + result = Assembly.ReflectionOnlyLoad(fullName); + } + catch (Exception) + { + // Some assemblies may fail to load + result = null; + } + + _reflectionOnlyAssemblies[fullName] = result; + } + + return result; + } + + /// + /// Recursively gets all referenced assemblies for current app domain, excluding those that are loaded. + /// + private IEnumerable GetNotLoadedReferencedAssemblies() + { + var roots = new Stack(AppDomain.CurrentDomain.GetAssemblies()); + + var visited = new HashSet(); + + var loaded = new HashSet(roots.Select(x => x.FullName)); + + while (roots.Any()) + { + var asm = roots.Pop(); + + if (visited.Contains(asm.FullName)) + continue; + + if (!loaded.Contains(asm.FullName)) + yield return asm; + + visited.Add(asm.FullName); + + foreach (var refAsm in asm.GetReferencedAssemblies() + .Where(x => !visited.Contains(x.FullName)) + .Where(x => !loaded.Contains(x.FullName)) + .Select(x => GetReflectionOnlyAssembly(x.FullName)) + .Where(x => x != null)) + roots.Push(refAsm); + } + } + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/ignite/blob/5cec202c/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Resource/IResourceInjector.cs ---------------------------------------------------------------------- diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Resource/IResourceInjector.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Resource/IResourceInjector.cs new file mode 100644 index 0000000..b751680 --- /dev/null +++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Resource/IResourceInjector.cs @@ -0,0 +1,27 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace Apache.Ignite.Core.Impl.Resource +{ + /// + /// Resource injector interface. + /// + internal interface IResourceInjector + { + void Inject(object target, object val); + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/5cec202c/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Resource/ResourceFieldInjector.cs ---------------------------------------------------------------------- diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Resource/ResourceFieldInjector.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Resource/ResourceFieldInjector.cs new file mode 100644 index 0000000..d48db1f --- /dev/null +++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Resource/ResourceFieldInjector.cs @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace Apache.Ignite.Core.Impl.Resource +{ + using System; + using System.Reflection; + using Apache.Ignite.Core.Impl.Common; + + /// + /// Field resource injector. + /// + internal class ResourceFieldInjector : IResourceInjector + { + /** */ + private readonly Action _inject; + + /// + /// Constructor. + /// + /// Field. + public ResourceFieldInjector(FieldInfo field) + { + _inject = DelegateConverter.CompileFieldSetter(field); + } + + /** */ + public void Inject(object target, object val) + { + _inject(target, val); + } + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/5cec202c/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Resource/ResourceMethodInjector.cs ---------------------------------------------------------------------- diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Resource/ResourceMethodInjector.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Resource/ResourceMethodInjector.cs new file mode 100644 index 0000000..9a7d9d3 --- /dev/null +++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Resource/ResourceMethodInjector.cs @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace Apache.Ignite.Core.Impl.Resource +{ + using System; + using System.Reflection; + using Apache.Ignite.Core.Impl.Common; + + /// + /// Method resource injector. + /// + internal class ResourceMethodInjector : IResourceInjector + { + /** */ + private readonly Action _inject; + + /// + /// Constructor. + /// + /// Method. + public ResourceMethodInjector(MethodInfo mthd) + { + _inject = DelegateConverter.CompileFunc>(mthd.DeclaringType, mthd, + new[] {mthd.GetParameters()[0].ParameterType}, new[] {true, false}); + } + + /** */ + public void Inject(object target, object val) + { + _inject(target, val); + } + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/5cec202c/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Resource/ResourceProcessor.cs ---------------------------------------------------------------------- diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Resource/ResourceProcessor.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Resource/ResourceProcessor.cs new file mode 100644 index 0000000..0a41d8c --- /dev/null +++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Resource/ResourceProcessor.cs @@ -0,0 +1,105 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace Apache.Ignite.Core.Impl.Resource +{ + using System; + using System.Collections.Generic; + using System.Diagnostics; + using Apache.Ignite.Core.Cache.Store; + + /// + /// Resource processor. + /// + internal class ResourceProcessor + { + /** Mutex. */ + private static readonly object Mux = new object(); + + /** Cached descriptors. */ + private static volatile IDictionary _descs = + new Dictionary(); + + /// + /// Get descriptor for the given type. + /// + /// Type. + /// + public static ResourceTypeDescriptor Descriptor(Type type) + { + IDictionary descs0 = _descs; + + ResourceTypeDescriptor desc; + + if (!descs0.TryGetValue(type, out desc)) + { + lock (Mux) + { + if (!_descs.TryGetValue(type, out desc)) + { + // Create descriptor from scratch. + desc = new ResourceTypeDescriptor(type); + + descs0 = new Dictionary(_descs); + + descs0[type] = desc; + + _descs = descs0; + } + } + } + + return desc; + } + + /// + /// Inject resources to the given target. + /// + /// Target object. + /// Grid. + public static void Inject(object target, Ignite grid) + { + Inject(target, grid.Proxy); + } + + /// + /// Inject resources to the given target. + /// + /// Target object. + /// Grid. + public static void Inject(object target, IgniteProxy grid) + { + if (target != null) { + var desc = Descriptor(target.GetType()); + + desc.InjectIgnite(target, grid); + } + } + + /// + /// Inject cache store session. + /// + /// Store. + /// Store session. + public static void InjectStoreSession(ICacheStore store, ICacheStoreSession ses) + { + Debug.Assert(store != null); + + Descriptor(store.GetType()).InjectStoreSession(store, ses); + } + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/5cec202c/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Resource/ResourcePropertyInjector.cs ---------------------------------------------------------------------- diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Resource/ResourcePropertyInjector.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Resource/ResourcePropertyInjector.cs new file mode 100644 index 0000000..05e2c2d --- /dev/null +++ b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Resource/ResourcePropertyInjector.cs @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace Apache.Ignite.Core.Impl.Resource +{ + using System; + using System.Reflection; + using Apache.Ignite.Core.Impl.Common; + + /// + /// Property resource injector. + /// + internal class ResourcePropertyInjector : IResourceInjector + { + /** */ + private readonly Action _inject; + + /// + /// Constructor. + /// + /// Property. + public ResourcePropertyInjector(PropertyInfo prop) + { + _inject = DelegateConverter.CompilePropertySetter(prop); + } + + /** */ + public void Inject(object target, object val) + { + _inject(target, val); + } + } +}