Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Core/DeSerializer.cs @ 4068

Last change on this file since 4068 was 4068, checked in by swagner, 14 years ago

Sorted usings and removed unused usings in entire solution (#1094)

File size: 9.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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
88    /// <summary>
89    /// Instantiates a new deserializer with the given type cache,
90    /// that contains information about the serializers to use
91    /// for every type and their type ids.
92    /// </summary>
93    /// <param name="typeCache">The type cache.</param>
94    public Deserializer(
95      IEnumerable<TypeMapping> typeCache) {
96      id2obj = new Dictionary<int, object>();
97      parentStack = new Stack<Midwife>();
98      typeIds = new Dictionary<int, Type>();
99      serializerMapping = new Dictionary<Type, object>();
100      foreach (var typeMapping in typeCache) {
101        AddTypeInfo(typeMapping);
102      }
103    }
104
105    private Dictionary<Type, object> serializerInstances = new Dictionary<Type, object>();
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        serializerMapping.Add(type, serializer);
124      }
125      catch (PersistenceException) {
126        throw;
127      }
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      }
184      catch (Exception e) {
185        if (e is InvalidCastException || e is KeyNotFoundException) {
186          throw new PersistenceException(String.Format(
187            "Invalid composite serializer configuration for type \"{0}\".",
188            type.AssemblyQualifiedName), e);
189        } else {
190          throw new PersistenceException(String.Format(
191            "Unexpected exception while trying to compose object of type \"{0}\".",
192            type.AssemblyQualifiedName), e);
193        }
194      }
195    }
196
197    private void CompositeEndHandler(EndToken token) {
198      Type type = typeIds[(int)token.TypeId];
199      Midwife midwife = parentStack.Pop();
200      if (midwife.Obj == null)
201        CreateInstance(midwife);
202      midwife.Populate();
203      SetValue(token.Name, midwife.Obj);
204    }
205
206    private void PrimitiveHandler(PrimitiveToken token) {
207      Type type = typeIds[(int)token.TypeId];
208      try {
209        object value = ((IPrimitiveSerializer)serializerMapping[type]).Parse(token.SerialData);
210        if (token.Id != null)
211          id2obj[(int)token.Id] = value;
212        SetValue(token.Name, value);
213      }
214      catch (Exception e) {
215        if (e is InvalidCastException || e is KeyNotFoundException) {
216          throw new PersistenceException(String.Format(
217            "Invalid primitive serializer configuration for type \"{0}\".",
218            type.AssemblyQualifiedName), e);
219        } else {
220          throw new PersistenceException(String.Format(
221            "Unexpected exception while trying to parse object of type \"{0}\".",
222            type.AssemblyQualifiedName), e);
223        }
224      }
225    }
226
227    private void ReferenceHandler(ReferenceToken token) {
228      object referredObject = id2obj[token.Id];
229      SetValue(token.Name, referredObject);
230    }
231
232    private void NullHandler(NullReferenceToken token) {
233      SetValue(token.Name, null);
234    }
235
236    private void MetaInfoBegin(MetaInfoBeginToken token) {
237      parentStack.Peek().MetaMode = true;
238    }
239
240    private void MetaInfoEnd(MetaInfoEndToken token) {
241      Midwife m = parentStack.Peek();
242      m.MetaMode = false;
243      CreateInstance(m);
244    }
245
246    private void CreateInstance(Midwife m) {
247      m.CreateInstance();
248      if (m.Id != null)
249        id2obj.Add((int)m.Id, m.Obj);
250    }
251
252    private void SetValue(string name, object value) {
253      if (parentStack.Count == 0) {
254        parentStack.Push(new Midwife(value));
255      } else {
256        Midwife m = parentStack.Peek();
257        if (m.MetaMode == false && m.Obj == null) {
258          CreateInstance(m);
259        }
260        m.AddValue(name, value);
261      }
262    }
263  }
264}
Note: See TracBrowser for help on using the repository browser.