GeoJsonObjectSerializerHelper.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. /* Copyright 2010-present MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Linq;
  18. using MongoDB.Bson;
  19. using MongoDB.Bson.IO;
  20. using MongoDB.Bson.Serialization;
  21. using MongoDB.Bson.Serialization.Serializers;
  22. namespace MongoDB.Driver.GeoJsonObjectModel.Serializers
  23. {
  24. /// <summary>
  25. /// Represents a serializer helper for GeoJsonObjects.
  26. /// </summary>
  27. /// <typeparam name="TCoordinates">The type of the coordinates.</typeparam>
  28. public class GeoJsonObjectSerializerHelper<TCoordinates> : SerializerHelper where TCoordinates : GeoJsonCoordinates
  29. {
  30. // private constants
  31. private static class Flags
  32. {
  33. public const long Type = 1;
  34. public const long CoordinateReferenceSystem = 2;
  35. public const long BoundingBox = 4;
  36. public const long ExtraMember = 8;
  37. }
  38. // private fields
  39. private readonly IBsonSerializer<GeoJsonBoundingBox<TCoordinates>> _boundingBoxSerializer = BsonSerializer.LookupSerializer<GeoJsonBoundingBox<TCoordinates>>();
  40. private readonly IBsonSerializer<GeoJsonCoordinateReferenceSystem> _coordinateReferenceSystemSerializer = BsonSerializer.LookupSerializer<GeoJsonCoordinateReferenceSystem>();
  41. private readonly string _type;
  42. // constructors
  43. /// <summary>
  44. /// Initializes a new instance of the <see cref="GeoJsonObjectSerializerHelper{TCoordinates}"/> class.
  45. /// </summary>
  46. /// <param name="type">The type.</param>
  47. /// <param name="derivedMembers">The derived members.</param>
  48. public GeoJsonObjectSerializerHelper(string type, params SerializerHelper.Member[] derivedMembers)
  49. : base(CreateCombinedMembers(derivedMembers))
  50. {
  51. _type = type;
  52. }
  53. // private static methods
  54. private static IEnumerable<SerializerHelper.Member> CreateBaseMembers()
  55. {
  56. return new[]
  57. {
  58. new SerializerHelper.Member("type", Flags.Type),
  59. new SerializerHelper.Member("bbox", Flags.BoundingBox, isOptional: true),
  60. new SerializerHelper.Member("crs", Flags.CoordinateReferenceSystem, isOptional: true),
  61. new SerializerHelper.Member("*", Flags.ExtraMember, isOptional: true)
  62. };
  63. }
  64. private static SerializerHelper.Member[] CreateCombinedMembers(IEnumerable<SerializerHelper.Member> derivedMembers)
  65. {
  66. var combinedMembers = CreateBaseMembers().Concat(derivedMembers).ToArray();
  67. ThrowIfDuplicateMemberFlags(combinedMembers);
  68. return combinedMembers;
  69. }
  70. private static void ThrowIfDuplicateMemberFlags(SerializerHelper.Member[] members)
  71. {
  72. var distinctFlags = new HashSet<long>(members.Select(m => m.Flag));
  73. if (distinctFlags.Count < members.Length)
  74. {
  75. throw new BsonInternalException("Duplicate GeoJsonObject member flags.");
  76. }
  77. }
  78. // public methods
  79. /// <summary>
  80. /// Deserializes a base member.
  81. /// </summary>
  82. /// <param name="context">The context.</param>
  83. /// <param name="elementName">The element name.</param>
  84. /// <param name="flag">The flag.</param>
  85. /// <param name="args">The arguments.</param>
  86. public void DeserializeBaseMember(BsonDeserializationContext context, string elementName, long flag, GeoJsonObjectArgs<TCoordinates> args)
  87. {
  88. switch (flag)
  89. {
  90. case Flags.Type: EnsureTypeIsValid(context); break;
  91. case Flags.CoordinateReferenceSystem: args.CoordinateReferenceSystem = DeserializeCoordinateReferenceSystem(context); break;
  92. case Flags.BoundingBox: args.BoundingBox = DeserializeBoundingBox(context); break;
  93. case Flags.ExtraMember: DeserializeExtraMember(context, elementName, args); break;
  94. default: throw new BsonInternalException();
  95. }
  96. }
  97. /// <summary>
  98. /// Serializes the members.
  99. /// </summary>
  100. /// <typeparam name="TValue">The type of the value.</typeparam>
  101. /// <param name="context">The context.</param>
  102. /// <param name="value">The value.</param>
  103. /// <param name="serializeDerivedMembers">The delegate to serialize the derived members.</param>
  104. public void SerializeMembers<TValue>(BsonSerializationContext context, TValue value, Action<BsonSerializationContext, TValue> serializeDerivedMembers)
  105. where TValue : GeoJsonObject<TCoordinates>
  106. {
  107. context.Writer.WriteStartDocument();
  108. SerializeType(context, value.Type);
  109. SerializeCoordinateReferenceSystem(context, value.CoordinateReferenceSystem);
  110. SerializeBoundingBox(context, value.BoundingBox);
  111. serializeDerivedMembers(context, value);
  112. SerializeExtraMembers(context, value.ExtraMembers);
  113. context.Writer.WriteEndDocument();
  114. }
  115. // private methods
  116. private GeoJsonBoundingBox<TCoordinates> DeserializeBoundingBox(BsonDeserializationContext context)
  117. {
  118. return _boundingBoxSerializer.Deserialize(context);
  119. }
  120. private GeoJsonCoordinateReferenceSystem DeserializeCoordinateReferenceSystem(BsonDeserializationContext context)
  121. {
  122. return _coordinateReferenceSystemSerializer.Deserialize(context);
  123. }
  124. private void DeserializeExtraMember(BsonDeserializationContext context, string elementName, GeoJsonObjectArgs<TCoordinates> args)
  125. {
  126. var value = BsonValueSerializer.Instance.Deserialize(context);
  127. if (args.ExtraMembers == null)
  128. {
  129. args.ExtraMembers = new BsonDocument();
  130. }
  131. args.ExtraMembers[elementName] = value;
  132. }
  133. private void EnsureTypeIsValid(BsonDeserializationContext context)
  134. {
  135. var type = context.Reader.ReadString();
  136. if (type != _type)
  137. {
  138. throw new FormatException(string.Format(
  139. "Invalid GeoJson type: '{0}'. Expected: '{1}'.", type, _type));
  140. }
  141. }
  142. private void SerializeBoundingBox(BsonSerializationContext context, GeoJsonBoundingBox<TCoordinates> boundingBox)
  143. {
  144. if (boundingBox != null)
  145. {
  146. context.Writer.WriteName("bbox");
  147. _boundingBoxSerializer.Serialize(context, boundingBox);
  148. }
  149. }
  150. private void SerializeCoordinateReferenceSystem(BsonSerializationContext context, GeoJsonCoordinateReferenceSystem coordinateReferenceSystem)
  151. {
  152. if (coordinateReferenceSystem != null)
  153. {
  154. context.Writer.WriteName("crs");
  155. _coordinateReferenceSystemSerializer.Serialize(context, coordinateReferenceSystem);
  156. }
  157. }
  158. private void SerializeExtraMembers(BsonSerializationContext context, BsonDocument value)
  159. {
  160. if (value != null)
  161. {
  162. foreach (var element in value)
  163. {
  164. context.Writer.WriteName(element.Name);
  165. BsonValueSerializer.Instance.Serialize(context, element.Value);
  166. }
  167. }
  168. }
  169. private void SerializeType(BsonSerializationContext context, GeoJsonObjectType type)
  170. {
  171. context.Writer.WriteString("type", type.ToString());
  172. }
  173. }
  174. }