Free cookie consent management tool by TermsFeed Policy Generator

source: tags/3.3.0/HeuristicLab.Persistence/3.3/Core/DeSerializer.cs

Last change on this file was 3743, checked in by gkronber, 14 years ago

Fixed GPL license headers #893

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.Collections.Generic;
23using System;
24using HeuristicLab.Persistence.Interfaces;
25using HeuristicLab.Persistence.Core.Tokens;
26using HeuristicLab.Persistence.Auxiliary;
27using HeuristicLab.Tracing;
28using System.Reflection;
29
30namespace HeuristicLab.Persistence.Core {
31
32  /// <summary>
33  /// Core hub for deserialization. Reads the serialization token stream,
34  /// instantiates objects and fills in values.
35  /// </summary>
36  public class Deserializer {
37
38    /// <summary>
39    /// Helps in delivering the class instance and acts as proxy while
40    /// the object cannot yet be instantiate.
41    /// </summary>
42    private class Midwife {
43
44      public int? Id { get; private set; }
45      public bool MetaMode { get; set; }
46      public object Obj { get; private set; }
47
48      private List<Tag> metaInfo;
49      private List<Tag> customValues;
50      private Type type;
51      private ICompositeSerializer compositeSerializer;
52
53      public Midwife(object value) {
54        this.Obj = value;
55      }
56
57      public Midwife(Type type, ICompositeSerializer compositeSerializer, int? id) {
58        this.type = type;
59        this.compositeSerializer = compositeSerializer;
60        this.Id = id;
61        MetaMode = false;
62        metaInfo = new List<Tag>();
63        customValues = new List<Tag>();
64      }
65
66      public void CreateInstance() {
67        if (Obj != null)
68          throw new PersistenceException("object already instantiated");
69        Obj = compositeSerializer.CreateInstance(type, metaInfo);
70      }
71
72      public void AddValue(string name, object value) {
73        if (MetaMode) {
74          metaInfo.Add(new Tag(name, value));
75        } else {
76          customValues.Add(new Tag(name, value));
77        }
78      }
79
80      public void Populate() {
81        compositeSerializer.Populate(Obj, customValues, type);
82      }
83    }
84   
85    private readonly Dictionary<int, object> id2obj;
86    private readonly Dictionary<Type, object> serializerMapping;
87    private readonly Stack<Midwife> parentStack;
88    private readonly Dictionary<int, Type> typeIds;
89
90    /// <summary>
91    /// Instantiates a new deserializer with the given type cache,
92    /// that contains information about the serializers to use
93    /// for every type and their type ids.
94    /// </summary>
95    /// <param name="typeCache">The type cache.</param>
96    public Deserializer(
97      IEnumerable<TypeMapping> typeCache) {
98      id2obj = new Dictionary<int, object>();
99      parentStack = new Stack<Midwife>();
100      typeIds = new Dictionary<int, Type>();
101      serializerMapping = new Dictionary<Type, object>();
102      foreach (var typeMapping in typeCache) {
103        AddTypeInfo(typeMapping);
104      }
105    }
106
107    private Dictionary<Type, object> serializerInstances = new Dictionary<Type, object>();
108
109    /// <summary>
110    /// Adds additionaly type information.
111    /// </summary>
112    /// <param name="typeMapping">The new type mapping.</param>
113    public void AddTypeInfo(TypeMapping typeMapping) {
114      if (typeIds.ContainsKey(typeMapping.Id))
115        return;
116      try {
117        Type type = TypeLoader.Load(typeMapping.TypeName);
118        typeIds.Add(typeMapping.Id, type);
119        Type serializerType = TypeLoader.Load(typeMapping.Serializer);
120        object serializer;
121        if (serializerInstances.ContainsKey(serializerType))
122          serializer = serializerInstances[serializerType];
123        else
124          serializer = Activator.CreateInstance(serializerType, true);
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.