Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2877_HiveImprovements/HeuristicLab.Persistence/3.3/Core/Deserializer.cs @ 16749

Last change on this file since 16749 was 15583, checked in by swagner, 7 years ago

#2640: Updated year of copyrights in license headers

File size: 9.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using HeuristicLab.Persistence.Auxiliary;
25using HeuristicLab.Persistence.Core.Tokens;
26using HeuristicLab.Persistence.Interfaces;
27
28namespace HeuristicLab.Persistence.Core {
29
30  /// <summary>
31  /// Core hub for deserialization. Reads the serialization token stream,
32  /// instantiates objects and fills in values.
33  /// </summary>
34  public class Deserializer {
35
36    /// <summary>
37    /// Helps in delivering the class instance and acts as proxy while
38    /// the object cannot yet be instantiate.
39    /// </summary>
40    private class Midwife {
41
42      public int? Id { get; private set; }
43      public bool MetaMode { get; set; }
44      public object Obj { get; private set; }
45
46      private List<Tag> metaInfo;
47      private List<Tag> customValues;
48      private Type type;
49      private ICompositeSerializer compositeSerializer;
50
51      public Midwife(object value) {
52        this.Obj = value;
53      }
54
55      public Midwife(Type type, ICompositeSerializer compositeSerializer, int? id) {
56        this.type = type;
57        this.compositeSerializer = compositeSerializer;
58        this.Id = id;
59        MetaMode = false;
60        metaInfo = new List<Tag>();
61        customValues = new List<Tag>();
62      }
63
64      public void CreateInstance() {
65        if (Obj != null)
66          throw new PersistenceException("object already instantiated");
67        Obj = compositeSerializer.CreateInstance(type, metaInfo);
68      }
69
70      public void AddValue(string name, object value) {
71        if (MetaMode) {
72          metaInfo.Add(new Tag(name, value));
73        } else {
74          customValues.Add(new Tag(name, value));
75        }
76      }
77
78      public void Populate() {
79        compositeSerializer.Populate(Obj, customValues, type);
80      }
81    }
82
83    private readonly Dictionary<int, object> id2obj;
84    private readonly Dictionary<Type, object> serializerMapping;
85    private readonly Stack<Midwife> parentStack;
86    private readonly Dictionary<int, Type> typeIds;
87    private Dictionary<Type, object> serializerInstances;
88
89    /// <summary>
90    /// Instantiates a new deserializer with the given type cache,
91    /// that contains information about the serializers to use
92    /// for every type and their type ids.
93    /// </summary>
94    /// <param name="typeCache">The type cache.</param>
95    public Deserializer(
96      IEnumerable<TypeMapping> typeCache) {
97      id2obj = new Dictionary<int, object>();
98      parentStack = new Stack<Midwife>();
99      typeIds = new Dictionary<int, Type>();
100      serializerMapping = new Dictionary<Type, object>();
101      serializerInstances = new Dictionary<Type, object>();
102      foreach (var typeMapping in typeCache) {
103        AddTypeInfo(typeMapping);
104      }
105    }
106
107    /// <summary>
108    /// Adds additionaly type information.
109    /// </summary>
110    /// <param name="typeMapping">The new type mapping.</param>
111    public void AddTypeInfo(TypeMapping typeMapping) {
112      if (typeIds.ContainsKey(typeMapping.Id))
113        return;
114      try {
115        Type type = TypeLoader.Load(typeMapping.TypeName);
116        typeIds.Add(typeMapping.Id, type);
117        Type serializerType = TypeLoader.Load(typeMapping.Serializer);
118        object serializer;
119        if (serializerInstances.ContainsKey(serializerType)) {
120          serializer = serializerInstances[serializerType];
121        } else {
122          serializer = Activator.CreateInstance(serializerType, true);
123          serializerInstances.Add(serializerType, serializer);
124        }
125        serializerMapping.Add(type, serializer);
126      } catch (PersistenceException) {
127        throw;
128      } catch (Exception e) {
129        throw new PersistenceException(string.Format(
130          "Could not add type info for {0} ({1})",
131          typeMapping.TypeName, typeMapping.Serializer), e);
132      }
133    }
134
135    /// <summary>
136    /// Process the token stream and deserialize an instantate a new object graph.
137    /// </summary>
138    /// <param name="tokens">The tokens.</param>
139    /// <returns>A fresh object filled with fresh data.</returns>
140    public object Deserialize(IEnumerable<ISerializationToken> tokens) {
141      foreach (ISerializationToken token in tokens) {
142        Type t = token.GetType();
143        if (t == typeof(BeginToken)) {
144          CompositeStartHandler((BeginToken)token);
145        } else if (t == typeof(EndToken)) {
146          CompositeEndHandler((EndToken)token);
147        } else if (t == typeof(PrimitiveToken)) {
148          PrimitiveHandler((PrimitiveToken)token);
149        } else if (t == typeof(ReferenceToken)) {
150          ReferenceHandler((ReferenceToken)token);
151        } else if (t == typeof(NullReferenceToken)) {
152          NullHandler((NullReferenceToken)token);
153        } else if (t == typeof(MetaInfoBeginToken)) {
154          MetaInfoBegin((MetaInfoBeginToken)token);
155        } else if (t == typeof(MetaInfoEndToken)) {
156          MetaInfoEnd((MetaInfoEndToken)token);
157        } else if (t == typeof(TypeToken)) {
158          Type((TypeToken)token);
159        } else {
160          throw new PersistenceException("invalid token type");
161        }
162      }
163      return parentStack.Pop().Obj;
164    }
165
166    private void InstantiateParent() {
167      if (parentStack.Count == 0)
168        return;
169      Midwife m = parentStack.Peek();
170      if (!m.MetaMode && m.Obj == null)
171        CreateInstance(m);
172    }
173
174    private void Type(TypeToken token) {
175      AddTypeInfo(new TypeMapping(token.Id, token.TypeName, token.Serializer));
176    }
177
178    private void CompositeStartHandler(BeginToken token) {
179      InstantiateParent();
180      Type type = typeIds[(int)token.TypeId];
181      try {
182        parentStack.Push(new Midwife(type, (ICompositeSerializer)serializerMapping[type], token.Id));
183      } catch (Exception e) {
184        if (e is InvalidCastException || e is KeyNotFoundException) {
185          throw new PersistenceException(String.Format(
186            "Invalid composite serializer configuration for type \"{0}\".",
187            type.AssemblyQualifiedName), e);
188        } else {
189          throw new PersistenceException(String.Format(
190            "Unexpected exception while trying to compose object of type \"{0}\".",
191            type.AssemblyQualifiedName), e);
192        }
193      }
194    }
195
196    private void CompositeEndHandler(EndToken token) {
197      Type type = typeIds[(int)token.TypeId];
198      Midwife midwife = parentStack.Pop();
199      if (midwife.Obj == null)
200        CreateInstance(midwife);
201      midwife.Populate();
202      SetValue(token.Name, midwife.Obj);
203    }
204
205    private void PrimitiveHandler(PrimitiveToken token) {
206      Type type = typeIds[(int)token.TypeId];
207      try {
208        object value = ((IPrimitiveSerializer)serializerMapping[type]).Parse(token.SerialData);
209        if (token.Id != null)
210          id2obj[(int)token.Id] = value;
211        SetValue(token.Name, value);
212      } catch (Exception e) {
213        if (e is InvalidCastException || e is KeyNotFoundException) {
214          throw new PersistenceException(String.Format(
215            "Invalid primitive serializer configuration for type \"{0}\".",
216            type.AssemblyQualifiedName), e);
217        } else {
218          throw new PersistenceException(String.Format(
219            "Unexpected exception while trying to parse object of type \"{0}\".",
220            type.AssemblyQualifiedName), e);
221        }
222      }
223    }
224
225    private void ReferenceHandler(ReferenceToken token) {
226      object referredObject = id2obj[token.Id];
227      SetValue(token.Name, referredObject);
228    }
229
230    private void NullHandler(NullReferenceToken token) {
231      SetValue(token.Name, null);
232    }
233
234    private void MetaInfoBegin(MetaInfoBeginToken token) {
235      parentStack.Peek().MetaMode = true;
236    }
237
238    private void MetaInfoEnd(MetaInfoEndToken token) {
239      Midwife m = parentStack.Peek();
240      m.MetaMode = false;
241      CreateInstance(m);
242    }
243
244    private void CreateInstance(Midwife m) {
245      m.CreateInstance();
246      if (m.Id != null)
247        id2obj.Add((int)m.Id, m.Obj);
248    }
249
250    private void SetValue(string name, object value) {
251      if (parentStack.Count == 0) {
252        parentStack.Push(new Midwife(value));
253      } else {
254        Midwife m = parentStack.Peek();
255        if (m.MetaMode == false && m.Obj == null) {
256          CreateInstance(m);
257        }
258        m.AddValue(name, value);
259      }
260    }
261  }
262}
Note: See TracBrowser for help on using the repository browser.