Esempio n. 1
0
        private byte[] ParseFixed(TypeSchema schema, string jsonObject)
        {
            var fixedSchema = (FixedSchema)schema;
            var result      = ConvertToBytes(jsonObject);

            if (result.Length != fixedSchema.Size)
            {
                throw new SerializationException(
                          string.Format(CultureInfo.InvariantCulture, "'{0}' size does not match the size of fixed schema node.", jsonObject));
            }

            return(result);
        }
Esempio n. 2
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="ArraySchema" /> class.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="runtimeType">Type of the runtime.</param>
        /// <param name="attributes">The attributes.</param>
        internal ArraySchema(
            TypeSchema item,
            Type runtimeType,
            Dictionary <string, string> attributes)
            : base(runtimeType, attributes)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            this.itemSchema = item;
        }
        private void AddRecordFields(
            IEnumerable <MemberSerializationInfo> members,
            Dictionary <string, NamedSchema> schemas,
            uint currentDepth,
            RecordSchema record)
        {
            int index = 0;

            foreach (MemberSerializationInfo info in members)
            {
                var property = info.MemberInfo as PropertyInfo;
                var field    = info.MemberInfo as FieldInfo;

                Type memberType;
                if (property != null)
                {
                    memberType = property.PropertyType;
                }
                else if (field != null)
                {
                    memberType = field.FieldType;
                }
                else
                {
                    throw new SerializationException(
                              string.Format(
                                  CultureInfo.InvariantCulture,
                                  "Type member '{0}' is not supported.",
                                  info.MemberInfo.GetType().Name));
                }

                TypeSchema fieldSchema = this.TryBuildUnionSchema(memberType, info.MemberInfo, schemas, currentDepth)
                                         ?? this.TryBuildFixedSchema(memberType, info.MemberInfo, record)
                                         ?? this.CreateSchema(info.Nullable, memberType, schemas, currentDepth + 1, info.DefaultValue?.GetType());



                var aliases = info
                              .Aliases
                              .ToList();
                var recordField = new RecordField(
                    new NamedEntityAttributes(new SchemaName(info.Name), aliases, info.Doc),
                    fieldSchema,
                    SortOrder.Ascending,
                    info.HasDefaultValue,
                    info.DefaultValue,
                    info.MemberInfo,
                    index++);
                record.AddField(recordField);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Parses a JSON string according to given schema and returns the corresponding object.
        /// </summary>
        /// <param name="schema">The schema.</param>
        /// <param name="json">The JSON object.</param>
        /// <returns>The object.</returns>
        internal object Parse(TypeSchema schema, string json)
        {
            if (this.parsersWithoutSchema.ContainsKey(schema.GetType()))
            {
                return(this.parsersWithoutSchema[schema.GetType()](json));
            }

            if (this.parsersWithSchema.ContainsKey(schema.GetType()))
            {
                return(this.parsersWithSchema[schema.GetType()](schema, json));
            }

            throw new SerializationException(
                      string.Format(CultureInfo.InvariantCulture, "Unknown schema type '{0}'.", schema.GetType()));
        }
Esempio n. 5
0
        private AvroEnum ParseEnum(TypeSchema schema, string jsonObject)
        {
            var enumSchema = (EnumSchema)schema;

            if (!enumSchema.Symbols.Contains(jsonObject))
            {
                throw new SerializationException(
                          string.Format(CultureInfo.InvariantCulture, "'{0}' is not a valid enum value.", jsonObject));
            }

            return(new AvroEnum(schema)
            {
                Value = jsonObject
            });
        }
        /// <summary>
        /// Creates the avro schema for the specified type.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="schemas">The schemas seen so far.</param>
        /// <param name="currentDepth">The current depth.</param>
        /// <returns>
        /// New instance of schema.
        /// </returns>
        /// <exception cref="System.Runtime.Serialization.SerializationException">Thrown when maximum depth of object graph is reached.</exception>
        private TypeSchema CreateNotNullableSchema(Type type, Dictionary <string, NamedSchema> schemas, uint currentDepth)
        {
            TypeSchema schema = TryBuildPrimitiveTypeSchema(type);

            if (schema != null)
            {
                return(schema);
            }

            if ((type.IsInterface() || type.IsAbstract()) ||
                this.HasApplicableKnownType(type))
            {
                return(this.BuildKnownTypeSchema(type, schemas, currentDepth));
            }

            return(this.BuildComplexTypeSchema(type, schemas, currentDepth));
        }
Esempio n. 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MapSchema" /> class.
        /// </summary>
        /// <param name="keySchema">The key schema.</param>
        /// <param name="valueSchema">The value schema.</param>
        /// <param name="runtimeType">Type of the runtime.</param>
        /// <param name="attributes">The attributes.</param>
        internal MapSchema(
            TypeSchema keySchema,
            TypeSchema valueSchema,
            Type runtimeType,
            Dictionary <string, string> attributes)
            : base(runtimeType, attributes)
        {
            if (keySchema == null)
            {
                throw new ArgumentNullException("keySchema");
            }
            if (valueSchema == null)
            {
                throw new ArgumentNullException("valueSchema");
            }

            this.valueSchema = valueSchema;
            this.keySchema   = keySchema;
        }
Esempio n. 8
0
        private AvroRecord ParseRecord(TypeSchema schema, string jsonObject)
        {
            var recordSchema = (RecordSchema)schema;
            var result       = new AvroRecord(recordSchema);
            var data         = JsonConvert.DeserializeObject <Dictionary <string, JToken> >(jsonObject);

            foreach (var datum in data)
            {
                var matchedRecord = recordSchema.Fields.FirstOrDefault(field => field.Name == datum.Key);
                if (matchedRecord == null)
                {
                    throw new SerializationException(
                              string.Format(CultureInfo.InvariantCulture,
                                            "Could not set default value because JSON object contains fields that do not exist in the schema."));
                }
                result[matchedRecord.Name] = this.Parse(matchedRecord.TypeSchema, datum.Value.ToString());
            }

            return(result);
        }
Esempio n. 9
0
        /// <summary>
        /// Parses the record field.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <param name="parent">The parent schema.</param>
        /// <param name="namedSchemas">The named schemas.</param>
        /// <param name="position">The position.</param>
        /// <returns>
        /// Schema internal representation.
        /// </returns>
        /// <exception cref="System.Runtime.Serialization.SerializationException">Thrown when <paramref name="field"/> is not valid or when sort order is not valid.</exception>
        private RecordField ParseRecordField(JObject field, NamedSchema parent, Dictionary <string, NamedSchema> namedSchemas, int position)
        {
            var name      = field.RequiredProperty <string>(Token.Name);
            var doc       = field.OptionalProperty <string>(Token.Doc);
            var order     = field.OptionalProperty <string>(Token.Order);
            var aliases   = this.GetAliases(field, parent.FullName);
            var fieldType = field[Token.Type];

            if (fieldType == null)
            {
                throw new SerializationException(
                          string.Format(CultureInfo.InvariantCulture, "Record field schema '{0}' has no type.", field));
            }

            TypeSchema type            = this.Parse(fieldType, parent, namedSchemas);
            object     defaultValue    = null;
            bool       hasDefaultValue = field[Token.Default] != null;

            if (hasDefaultValue)
            {
                var objectParser = new JsonObjectParser();
                defaultValue = objectParser.Parse(type, field[Token.Default].ToString());
            }

            var orderValue = SortOrder.Ascending;

            if (!string.IsNullOrEmpty(order))
            {
                if (!SortValue.ContainsKey(order.ToUpperInvariant()))
                {
                    throw new SerializationException(
                              string.Format(CultureInfo.InvariantCulture, "Invalid sort order of the field '{0}'.", order));
                }
                orderValue = SortValue[order.ToUpperInvariant()];
            }

            var fieldName  = new SchemaName(name);
            var attributes = new NamedEntityAttributes(fieldName, aliases, doc);

            return(new RecordField(attributes, type, orderValue, hasDefaultValue, defaultValue, null, position));
        }
Esempio n. 10
0
        /// <summary>
        /// Creates a <see cref="RecordField" /> instance.
        /// </summary>
        /// <param name="fieldName">The field name.</param>
        /// <param name="fieldType">The field type.</param>
        /// <returns>An instance of the <see cref="RecordField" />.</returns>
        internal static RecordField CreateField(string fieldName, TypeSchema fieldType)
        {
            if (String.IsNullOrEmpty(fieldName))
            {
                throw new ArgumentException("Field name is not allowed to be null or empty.");
            }

            if (fieldType == null)
            {
                throw new ArgumentNullException("fieldType");
            }

            return(new RecordField(
                       new NamedEntityAttributes(new SchemaName(fieldName), new List <string>(), String.Empty),
                       fieldType,
                       SortOrder.Ascending,
                       false,
                       null,
                       null,
                       -1));
        }
Esempio n. 11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RecordField" /> class.
        /// </summary>
        /// <param name="namedEntityAttributes">The named entity attributes.</param>
        /// <param name="typeSchema">The type schema.</param>
        /// <param name="order">The order.</param>
        /// <param name="hasDefaultValue">Whether the field has a default value or not.</param>
        /// <param name="defaultValue">The default value.</param>
        /// <param name="info">The info.</param>
        /// <param name="position">The position of the field in the schema.</param>
        /// <param name="attributes">The attributes.</param>
        internal RecordField(
            NamedEntityAttributes namedEntityAttributes,
            TypeSchema typeSchema,
            SortOrder order,
            bool hasDefaultValue,
            object defaultValue,
            MemberInfo info,
            int position,
            Dictionary <string, string> attributes)
            : base(attributes)
        {
            this.namedEntityAttributes = namedEntityAttributes;
            this.typeSchema            = typeSchema;
            this.order           = order;
            this.hasDefaultValue = hasDefaultValue;
            this.defaultValue    = defaultValue;
            this.info            = info;
            this.position        = position;

            this.ShouldBeSkipped = false;
            this.UseDefaultValue = false;
        }
Esempio n. 12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SurrogateSchema" /> class.
        /// </summary>
        /// <param name="originalType">Type of the original.</param>
        /// <param name="surrogateType">Type of the surrogate.</param>
        /// <param name="attributes">The attributes.</param>
        /// <param name="surrogateSchema">The surrogate schema.</param>
        internal SurrogateSchema(
            Type originalType,
            Type surrogateType,
            IDictionary <string, string> attributes,
            TypeSchema surrogateSchema)
            : base(originalType, attributes)
        {
            if (originalType == null)
            {
                throw new ArgumentNullException("originalType");
            }
            if (surrogateType == null)
            {
                throw new ArgumentNullException("surrogateType");
            }
            if (surrogateSchema == null)
            {
                throw new ArgumentNullException("surrogateSchema");
            }

            this.surrogateType   = surrogateType;
            this.surrogateSchema = surrogateSchema;
        }
Esempio n. 13
0
 internal SurrogateSchema(Type originalType, Type surrogateType, TypeSchema surrogateSchema)
     : this(originalType, surrogateType, new Dictionary <string, string>(), surrogateSchema)
 {
 }
 /// <summary>
 ///  If reader's is a union, but writer's is not the first schema in the reader's union
 ///  that matches the writer's schema is recursively resolved against it. If none match, an error is signalled.
 /// </summary>
 /// <param name="w">The writer schema.</param>
 /// <param name="r">The reader schema.</param>
 /// <returns>True if match.</returns>
 private TypeSchema BuildCore(TypeSchema w, UnionSchema r)
 {
     return(r.Schemas.Select(rs => this.BuildDynamic(w, rs)).SingleOrDefault(s => s != null));
 }
Esempio n. 15
0
 internal MapSchema(TypeSchema keySchema, TypeSchema valueSchema, Type runtimeType)
     : this(keySchema, valueSchema, runtimeType, new Dictionary <string, string>())
 {
 }
 internal TypeSchema Build(TypeSchema w, TypeSchema r)
 {
     this.visited.Clear();
     return(this.BuildDynamic(w, r));
 }
 /// <summary>
 /// Implements double dispatch.
 /// </summary>
 /// <param name="w">The writer schema.</param>
 /// <param name="r">The reader schema.</param>
 /// <returns>True if match.</returns>
 private TypeSchema BuildDynamic(TypeSchema w, TypeSchema r)
 {
     return(this.BuildCore((dynamic)w, (dynamic)r));
 }
Esempio n. 18
0
 /// <summary>
 /// Creates a <see cref="ArraySchema" /> instance.
 /// </summary>
 /// <param name="itemSchema">The schema of the items.</param>
 /// <returns>An instance of the <see cref="ArraySchema" />.</returns>
 internal static ArraySchema CreateArray(TypeSchema itemSchema)
 {
     return(new ArraySchema(itemSchema, typeof(Array)));
 }
Esempio n. 19
0
        private object ParseUnion(TypeSchema schema, string jsonObject)
        {
            var unionSchema = (UnionSchema)schema;

            return(this.Parse(unionSchema.Schemas[0], jsonObject));
        }
Esempio n. 20
0
 /// <summary>
 /// Creates a <see cref="MapSchema" /> instance.
 /// </summary>
 /// <param name="valueSchema">The schema of the values.</param>
 /// <returns>An instance of the <see cref="MapSchema" />.</returns>
 internal static MapSchema CreateMap(TypeSchema valueSchema)
 {
     return(new MapSchema(new StringSchema(), valueSchema, typeof(Dictionary <,>)));
 }
Esempio n. 21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ArraySchema"/> class.
 /// </summary>
 /// <param name="item">The item.</param>
 /// <param name="runtimeType">Type of the runtime.</param>
 internal ArraySchema(
     TypeSchema item,
     Type runtimeType)
     : this(item, runtimeType, new Dictionary <string, string>())
 {
 }
Esempio n. 22
0
 internal NullableSchema(
     Type nullableType,
     TypeSchema valueSchema)
     : this(nullableType, new Dictionary <string, string>(), valueSchema)
 {
 }