Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Persistence/3.3/Core/Deserializer.cs @ 12011

Last change on this file since 12011 was 12009, checked in by ascheibe, 10 years ago

#2212 updated copyright year

File size: 9.2 KB
RevLine 
[3743]1#region License Information
2/* HeuristicLab
[12009]3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[3743]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
[4068]22using System;
[3743]23using System.Collections.Generic;
[4068]24using HeuristicLab.Persistence.Auxiliary;
25using HeuristicLab.Persistence.Core.Tokens;
[1454]26using HeuristicLab.Persistence.Interfaces;
27
[1574]28namespace HeuristicLab.Persistence.Core {
[1454]29
[3004]30  /// <summary>
31  /// Core hub for deserialization. Reads the serialization token stream,
32  /// instantiates objects and fills in values.
33  /// </summary>
[1574]34  public class Deserializer {
[1454]35
[3004]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 {
[1566]41
[1567]42      public int? Id { get; private set; }
43      public bool MetaMode { get; set; }
44      public object Obj { get; private set; }
[1454]45
[1567]46      private List<Tag> metaInfo;
47      private List<Tag> customValues;
48      private Type type;
[1823]49      private ICompositeSerializer compositeSerializer;
[1553]50
[1567]51      public Midwife(object value) {
52        this.Obj = value;
53      }
[1566]54
[1823]55      public Midwife(Type type, ICompositeSerializer compositeSerializer, int? id) {
[1567]56        this.type = type;
[1823]57        this.compositeSerializer = compositeSerializer;
[1567]58        this.Id = id;
59        MetaMode = false;
60        metaInfo = new List<Tag>();
61        customValues = new List<Tag>();
62      }
[1454]63
[1567]64      public void CreateInstance() {
65        if (Obj != null)
[1625]66          throw new PersistenceException("object already instantiated");
[1823]67        Obj = compositeSerializer.CreateInstance(type, metaInfo);
[1567]68      }
[1454]69
[1567]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        }
[1553]76      }
[1454]77
[1567]78      public void Populate() {
[1823]79        compositeSerializer.Populate(Obj, customValues, type);
[1567]80      }
[1553]81    }
[4068]82
[1454]83    private readonly Dictionary<int, object> id2obj;
[1553]84    private readonly Dictionary<Type, object> serializerMapping;
[1566]85    private readonly Stack<Midwife> parentStack;
[1553]86    private readonly Dictionary<int, Type> typeIds;
[4175]87    private Dictionary<Type, object> serializerInstances;
[1454]88
[3004]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.
[3016]93    /// </summary>
94    /// <param name="typeCache">The type cache.</param>
[1542]95    public Deserializer(
[1553]96      IEnumerable<TypeMapping> typeCache) {
[1454]97      id2obj = new Dictionary<int, object>();
[1553]98      parentStack = new Stack<Midwife>();
[1454]99      typeIds = new Dictionary<int, Type>();
[3005]100      serializerMapping = new Dictionary<Type, object>();
[4175]101      serializerInstances = new Dictionary<Type, object>();
[3005]102      foreach (var typeMapping in typeCache) {
103        AddTypeInfo(typeMapping);
104      }
[1454]105    }
106
[3016]107    /// <summary>
108    /// Adds additionaly type information.
109    /// </summary>
110    /// <param name="typeMapping">The new type mapping.</param>
[3005]111    public void AddTypeInfo(TypeMapping typeMapping) {
112      if (typeIds.ContainsKey(typeMapping.Id))
113        return;
[1625]114      try {
[3005]115        Type type = TypeLoader.Load(typeMapping.TypeName);
116        typeIds.Add(typeMapping.Id, type);
117        Type serializerType = TypeLoader.Load(typeMapping.Serializer);
118        object serializer;
[4175]119        if (serializerInstances.ContainsKey(serializerType)) {
[3005]120          serializer = serializerInstances[serializerType];
[4175]121        } else {
[3005]122          serializer = Activator.CreateInstance(serializerType, true);
[4175]123          serializerInstances.Add(serializerType, serializer);
124        }
[3005]125        serializerMapping.Add(type, serializer);
[4175]126      } catch (PersistenceException) {
[1779]127        throw;
[4175]128      } catch (Exception e) {
[3005]129        throw new PersistenceException(string.Format(
130          "Could not add type info for {0} ({1})",
131          typeMapping.TypeName, typeMapping.Serializer), e);
[1703]132      }
[1454]133    }
134
[3004]135    /// <summary>
136    /// Process the token stream and deserialize an instantate a new object graph.
[3016]137    /// </summary>
138    /// <param name="tokens">The tokens.</param>
139    /// <returns>A fresh object filled with fresh data.</returns>
[1566]140    public object Deserialize(IEnumerable<ISerializationToken> tokens) {
[1454]141      foreach (ISerializationToken token in tokens) {
142        Type t = token.GetType();
[1566]143        if (t == typeof(BeginToken)) {
[1454]144          CompositeStartHandler((BeginToken)token);
[1566]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);
[1454]151        } else if (t == typeof(NullReferenceToken)) {
152          NullHandler((NullReferenceToken)token);
[1553]153        } else if (t == typeof(MetaInfoBeginToken)) {
154          MetaInfoBegin((MetaInfoBeginToken)token);
155        } else if (t == typeof(MetaInfoEndToken)) {
156          MetaInfoEnd((MetaInfoEndToken)token);
[3005]157        } else if (t == typeof(TypeToken)) {
158          Type((TypeToken)token);
[1454]159        } else {
[1625]160          throw new PersistenceException("invalid token type");
[1454]161        }
162      }
163      return parentStack.Pop().Obj;
164    }
165
[2873]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
[3005]174    private void Type(TypeToken token) {
175      AddTypeInfo(new TypeMapping(token.Id, token.TypeName, token.Serializer));
176    }
177
[1553]178    private void CompositeStartHandler(BeginToken token) {
[2873]179      InstantiateParent();
[1454]180      Type type = typeIds[(int)token.TypeId];
[1859]181      try {
182        parentStack.Push(new Midwife(type, (ICompositeSerializer)serializerMapping[type], token.Id));
[4175]183      } catch (Exception e) {
[1859]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      }
[1454]194    }
195
[1553]196    private void CompositeEndHandler(EndToken token) {
[1454]197      Type type = typeIds[(int)token.TypeId];
[1553]198      Midwife midwife = parentStack.Pop();
[1574]199      if (midwife.Obj == null)
200        CreateInstance(midwife);
[1553]201      midwife.Populate();
202      SetValue(token.Name, midwife.Obj);
[1454]203    }
204
[1553]205    private void PrimitiveHandler(PrimitiveToken token) {
[1454]206      Type type = typeIds[(int)token.TypeId];
[1859]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);
[4175]212      } catch (Exception e) {
[1859]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      }
[1454]223    }
224
[1553]225    private void ReferenceHandler(ReferenceToken token) {
[1454]226      object referredObject = id2obj[token.Id];
[1553]227      SetValue(token.Name, referredObject);
[1454]228    }
229
[1553]230    private void NullHandler(NullReferenceToken token) {
[1454]231      SetValue(token.Name, null);
[1553]232    }
[1454]233
[1553]234    private void MetaInfoBegin(MetaInfoBeginToken token) {
235      parentStack.Peek().MetaMode = true;
236    }
237
238    private void MetaInfoEnd(MetaInfoEndToken token) {
[1566]239      Midwife m = parentStack.Peek();
[1553]240      m.MetaMode = false;
241      CreateInstance(m);
242    }
243
244    private void CreateInstance(Midwife m) {
245      m.CreateInstance();
246      if (m.Id != null)
[1566]247        id2obj.Add((int)m.Id, m.Obj);
[1553]248    }
249
[1454]250    private void SetValue(string name, object value) {
[1566]251      if (parentStack.Count == 0) {
[1553]252        parentStack.Push(new Midwife(value));
253      } else {
254        Midwife m = parentStack.Peek();
[2873]255        if (m.MetaMode == false && m.Obj == null) {
[1553]256          CreateInstance(m);
[2873]257        }
[1566]258        m.AddValue(name, value);
[1454]259      }
260    }
261  }
262}
Note: See TracBrowser for help on using the repository browser.