Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceSpeedUp/HeuristicLab.Persistence/3.3/Default/Xml/XmlGenerator.cs

Last change on this file was 6737, checked in by epitzer, 13 years ago

#1530 Split type and serializer tokens and include special handling for CachedTypeSerializer (this should also fix #1527)

File size: 17.9 KB
RevLine 
[3742]1#region License Information
[6737]2/* HeuristicLab
3 * Copyright (C) 2002-2011 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/>.
[3742]19 */
20#endregion
21
[4068]22using System;
[3742]23using System.Collections.Generic;
[4068]24using System.IO;
25using System.IO.Compression;
26using System.Linq;
[1454]27using System.Text;
[4068]28using HeuristicLab.Persistence.Core;
29using HeuristicLab.Persistence.Core.Tokens;
[1454]30using HeuristicLab.Persistence.Interfaces;
[4068]31using HeuristicLab.Tracing;
[1466]32using ICSharpCode.SharpZipLib.Zip;
[1454]33
[1615]34namespace HeuristicLab.Persistence.Default.Xml {
[1454]35
[3004]36
37  /// <summary>
38  /// Main entry point of persistence to XML. Use the static methods to serialize
39  /// to a file or to a stream.
40  /// </summary>
[1564]41  public class XmlGenerator : GeneratorBase<string> {
[1566]42
[3935]43    protected int depth;
44    protected int Depth {
[1570]45      get {
46        return depth;
47      }
48      set {
49        depth = value;
50        prefix = new string(' ', depth * 2);
51      }
52    }
[1454]53
[3935]54    protected string prefix;
[1570]55
56
[3016]57    /// <summary>
58    /// Initializes a new instance of the <see cref="XmlGenerator"/> class.
59    /// </summary>
[1454]60    public XmlGenerator() {
[1570]61      Depth = 0;
[1454]62    }
63
[3935]64    protected enum NodeType { Start, End, Inline } ;
[1454]65
[3937]66    protected static void AddXmlTagContent(StringBuilder sb, string name, Dictionary<string, string> attributes) {
[1566]67      sb.Append(name);
[1454]68      foreach (var attribute in attributes) {
69        if (attribute.Value != null && !string.IsNullOrEmpty(attribute.Value.ToString())) {
[1570]70          sb.Append(' ');
[1454]71          sb.Append(attribute.Key);
72          sb.Append("=\"");
73          sb.Append(attribute.Value);
74          sb.Append('"');
75        }
76      }
[1570]77    }
78
[3937]79    protected static int AttributeLength(Dictionary<string, string> attributes) {
80      return attributes
81        .Where(kvp => !string.IsNullOrEmpty(kvp.Key) && !string.IsNullOrEmpty(kvp.Value))
82        .Select(kvp => kvp.Key.Length + kvp.Value.Length + 4).Sum();
83    }
84
85    protected static void AddXmlStartTag(StringBuilder sb, string name, Dictionary<string, string> attributes) {
[1570]86      sb.Append('<');
87      AddXmlTagContent(sb, name, attributes);
88      sb.Append('>');
89    }
90
[3937]91    protected static void AddXmlInlineTag(StringBuilder sb, string name, Dictionary<string, string> attributes) {
[1570]92      sb.Append('<');
93      AddXmlTagContent(sb, name, attributes);
94      sb.Append("/>");
95    }
96
[3935]97    protected static void AddXmlEndTag(StringBuilder sb, string name) {
[1570]98      sb.Append("</");
99      sb.Append(name);
[1454]100      sb.Append(">");
[1570]101    }
102
[3937]103    protected string CreateNodeStart(string name, Dictionary<string, string> attributes) {
[6737]104      StringBuilder sb = new StringBuilder(prefix.Length + name.Length + 4
[3937]105        + AttributeLength(attributes));
[1570]106      sb.Append(prefix);
107      Depth += 1;
108      AddXmlStartTag(sb, name, attributes);
109      sb.Append("\r\n");
[1566]110      return sb.ToString();
[1454]111    }
112
[3937]113    private static Dictionary<string, string> emptyDict = new Dictionary<string, string>();
[3935]114    protected string CreateNodeStart(string name) {
[3937]115      return CreateNodeStart(name, emptyDict);
[1454]116    }
117
[3935]118    protected string CreateNodeEnd(string name) {
[1570]119      Depth -= 1;
[3937]120      StringBuilder sb = new StringBuilder(prefix.Length + name.Length + 5);
[1570]121      sb.Append(prefix);
122      AddXmlEndTag(sb, name);
123      sb.Append("\r\n");
124      return sb.ToString();
125    }
126
[3937]127    protected string CreateNode(string name, Dictionary<string, string> attributes) {
[6737]128      StringBuilder sb = new StringBuilder(prefix.Length + name.Length + 5
[3937]129        + AttributeLength(attributes));
[1570]130      sb.Append(prefix);
131      AddXmlInlineTag(sb, name, attributes);
132      sb.Append("\r\n");
133      return sb.ToString();
134    }
135
[3937]136    protected string CreateNode(string name, Dictionary<string, string> attributes, string content) {
[3944]137      StringBuilder sb = new StringBuilder(
[6737]138        prefix.Length + name.Length + AttributeLength(attributes) + 2
[3944]139        + content.Length + name.Length + 5);
[1570]140      sb.Append(prefix);
141      AddXmlStartTag(sb, name, attributes);
142      sb.Append(content);
143      sb.Append("</").Append(name).Append(">\r\n");
144      return sb.ToString();
145    }
146
[3036]147    /// <summary>
148    /// Formats the specified begin token.
149    /// </summary>
150    /// <param name="beginToken">The begin token.</param>
151    /// <returns>The token in serialized form.</returns>
[1566]152    protected override string Format(BeginToken beginToken) {
[6737]153      var dict = new Dictionary<string, string> {
154          {"name", beginToken.Name},
155          {"typeId", beginToken.TypeId.ToString()},
[3937]156          {"id", beginToken.Id.ToString()}};
[3005]157      AddTypeInfo(beginToken.TypeId, dict);
158      return CreateNodeStart(XmlStringConstants.COMPOSITE, dict);
[1454]159    }
160
[3937]161    protected void AddTypeInfo(int typeId, Dictionary<string, string> dict) {
[3005]162      if (lastTypeToken != null) {
163        if (typeId == lastTypeToken.Id) {
164          dict.Add("typeName", lastTypeToken.TypeName);
165          lastTypeToken = null;
166        } else {
167          FlushTypeToken();
168        }
169      }
[6737]170      if (lastSerializerToken != null) {
171        if (typeId == lastSerializerToken.Id) {
172          dict.Add("serializer", lastSerializerToken.Serializer);
173          lastSerializerToken = null;
174        } else {
175          FlushSerializerToken();
176        }
177      }
[3005]178    }
179
[3036]180    /// <summary>
181    /// Formats the specified end token.
182    /// </summary>
183    /// <param name="endToken">The end token.</param>
184    /// <returns>The token in serialized form.</returns>
[1566]185    protected override string Format(EndToken endToken) {
[1612]186      return CreateNodeEnd(XmlStringConstants.COMPOSITE);
[1454]187    }
188
[3036]189    /// <summary>
190    /// Formats the specified data token.
191    /// </summary>
192    /// <param name="dataToken">The data token.</param>
193    /// <returns>The token in serialized form.</returns>
[1566]194    protected override string Format(PrimitiveToken dataToken) {
[6737]195      var dict = new Dictionary<string, string> {
196            {"typeId", dataToken.TypeId.ToString()},
197            {"name", dataToken.Name},
[3937]198            {"id", dataToken.Id.ToString()}};
[3005]199      AddTypeInfo(dataToken.TypeId, dict);
200      return CreateNode(XmlStringConstants.PRIMITIVE, dict,
[1570]201        ((XmlString)dataToken.SerialData).Data);
[1454]202    }
203
[3036]204    /// <summary>
205    /// Formats the specified ref token.
206    /// </summary>
207    /// <param name="refToken">The ref token.</param>
208    /// <returns>The token in serialized form.</returns>
[1566]209    protected override string Format(ReferenceToken refToken) {
[1612]210      return CreateNode(XmlStringConstants.REFERENCE,
[6737]211        new Dictionary<string, string> {
212          {"ref", refToken.Id.ToString()},
[1570]213          {"name", refToken.Name}});
[1454]214    }
215
[3036]216    /// <summary>
217    /// Formats the specified null ref token.
218    /// </summary>
219    /// <param name="nullRefToken">The null ref token.</param>
220    /// <returns>The token in serialized form.</returns>
[1566]221    protected override string Format(NullReferenceToken nullRefToken) {
[1612]222      return CreateNode(XmlStringConstants.NULL,
[6737]223        new Dictionary<string, string>{
[1570]224          {"name", nullRefToken.Name}});
[1454]225    }
226
[3036]227    /// <summary>
228    /// Formats the specified meta info begin token.
229    /// </summary>
230    /// <param name="metaInfoBeginToken">The meta info begin token.</param>
231    /// <returns>The token in serialized form.</returns>
[1553]232    protected override string Format(MetaInfoBeginToken metaInfoBeginToken) {
[1612]233      return CreateNodeStart(XmlStringConstants.METAINFO);
[1553]234    }
235
[3036]236    /// <summary>
237    /// Formats the specified meta info end token.
238    /// </summary>
239    /// <param name="metaInfoEndToken">The meta info end token.</param>
240    /// <returns>The token in serialized form.</returns>
[1553]241    protected override string Format(MetaInfoEndToken metaInfoEndToken) {
[1612]242      return CreateNodeEnd(XmlStringConstants.METAINFO);
[1553]243    }
244
[3935]245    protected TypeToken lastTypeToken;
[6737]246    protected SerializerToken lastSerializerToken;
[3036]247    /// <summary>
248    /// Formats the specified token.
249    /// </summary>
250    /// <param name="token">The token.</param>
251    /// <returns>The token in serialized form.</returns>
[3005]252    protected override string Format(TypeToken token) {
253      lastTypeToken = token;
254      return "";
255    }
256
[6737]257    protected override string Format(SerializerToken token) {
258      lastSerializerToken = token;
259      return "";
260    }
261
[3935]262    protected string FlushTypeToken() {
[3005]263      if (lastTypeToken == null)
264        return "";
265      try {
266        return CreateNode(XmlStringConstants.TYPE,
[6737]267          new Dictionary<string, string> {
268          {"id", lastTypeToken.Id.ToString()},
269          {"typeName", lastTypeToken.TypeName }});
[6211]270      } finally {
[3005]271        lastTypeToken = null;
272      }
273    }
274
[6737]275    protected string FlushSerializerToken() {
276      if (lastSerializerToken == null)
277        return "";
278      try {
279        return CreateNode(XmlStringConstants.SERIALIZER,
280          new Dictionary<string, string> {
281          {"id", lastSerializerToken.Id.ToString()},
282          {"serializer", lastSerializerToken.Serializer }});
283      } finally {
284        lastTypeToken = null;
285      }
286    }
287
[3028]288    /// <summary>
289    /// Formats the specified type cache.
290    /// </summary>
291    /// <param name="typeCache">The type cache.</param>
292    /// <returns>An enumerable of formatted type cache tags.</returns>
[6737]293    public IEnumerable<string> Format(TypeCache typeCache) {
[1612]294      yield return CreateNodeStart(XmlStringConstants.TYPECACHE);
[6737]295      foreach (var type in typeCache.Types) {
296        int id = typeCache.GetOrCreateId(type);
297        var dict = new Dictionary<string, string> {
298          {"id", id.ToString()},
299          {"typeName", type.AssemblyQualifiedName},
300        };
301        Type serializer = typeCache.GetSerializer(id);
302        if (serializer != null)
303          dict.Add("serializer", serializer.AssemblyQualifiedName);
304        yield return CreateNode(XmlStringConstants.TYPE, dict);
305      }
[1612]306      yield return CreateNodeEnd(XmlStringConstants.TYPECACHE);
[1454]307    }
308
[3004]309    /// <summary>
310    /// Serialize an object into a file.
[3016]311    /// The XML configuration is obtained from the <c>ConfigurationService</c>.
[3004]312    /// The file is actually a ZIP file.
313    /// Compression level is set to 5 and needed assemblies are not included.
[3036]314    /// </summary>
315    /// <param name="o">The object.</param>
316    /// <param name="filename">The filename.</param>
[1566]317    public static void Serialize(object o, string filename) {
[3004]318      Serialize(o, filename, ConfigurationService.Instance.GetConfiguration(new XmlFormat()), false, 5);
[1454]319    }
320
[3004]321    /// <summary>
322    /// Serialize an object into a file.
[3016]323    /// The XML configuration is obtained from the <c>ConfigurationService</c>.
[3004]324    /// Needed assemblies are not included.
325    /// </summary>
[3028]326    /// <param name="o">The object.</param>
327    /// <param name="filename">The filename.</param>
[3004]328    /// <param name="compression">ZIP file compression level</param>
[1892]329    public static void Serialize(object o, string filename, int compression) {
330      Serialize(o, filename, ConfigurationService.Instance.GetConfiguration(new XmlFormat()), false, compression);
331    }
332
[3028]333    /// <summary>
334    /// Serializes the specified object into a file.
335    /// Needed assemblies are not included, ZIP compression level is set to 5.
336    /// </summary>
337    /// <param name="obj">The object.</param>
338    /// <param name="filename">The filename.</param>
339    /// <param name="config">The configuration.</param>
[1466]340    public static void Serialize(object obj, string filename, Configuration config) {
[1892]341      Serialize(obj, filename, config, false, 5);
[1797]342    }
343
[3028]344    /// <summary>
345    /// Serializes the specified object into a file.
346    /// </summary>
347    /// <param name="obj">The object.</param>
348    /// <param name="filename">The filename.</param>
349    /// <param name="config">The configuration.</param>
350    /// <param name="includeAssemblies">if set to <c>true</c> include needed assemblies.</param>
351    /// <param name="compression">The ZIP compression level.</param>
[3944]352    public static void Serialize(object obj, string filename, Configuration config, bool includeAssemblies, int compression) {
[1625]353      try {
[1892]354        string tempfile = Path.GetTempFileName();
355        DateTime start = DateTime.Now;
[2037]356        using (FileStream stream = File.Create(tempfile)) {
[3005]357          Serializer serializer = new Serializer(obj, config);
358          serializer.InterleaveTypeInformation = false;
359          XmlGenerator generator = new XmlGenerator();
360          using (ZipOutputStream zipStream = new ZipOutputStream(stream)) {
361            zipStream.IsStreamOwner = false;
362            zipStream.SetLevel(compression);
363            zipStream.PutNextEntry(new ZipEntry("data.xml") { DateTime = DateTime.MinValue });
364            StreamWriter writer = new StreamWriter(zipStream);
[6211]365            foreach (ISerializationToken token in new AsyncBuffer<ISerializationToken>(serializer)) {
366              writer.Write(generator.Format(token));
[3005]367            }
368            writer.Flush();
369            zipStream.PutNextEntry(new ZipEntry("typecache.xml") { DateTime = DateTime.MinValue });
[6211]370            foreach (string line in new AsyncBuffer<string>(generator.Format(serializer.TypeCache))) {
[3005]371              writer.Write(line);
372            }
373            writer.Flush();
374            if (includeAssemblies) {
[6737]375              foreach (string name in serializer.GetRequiredFiles()) {
[3005]376                Uri uri = new Uri(name);
377                if (!uri.IsFile) {
378                  Logger.Warn("cannot read non-local files");
379                  continue;
380                }
381                zipStream.PutNextEntry(new ZipEntry(Path.GetFileName(uri.PathAndQuery)));
382                FileStream reader = File.OpenRead(uri.PathAndQuery);
383                byte[] buffer = new byte[1024 * 1024];
384                while (true) {
385                  int bytesRead = reader.Read(buffer, 0, 1024 * 1024);
386                  if (bytesRead == 0)
387                    break;
388                  zipStream.Write(buffer, 0, bytesRead);
389                }
390                writer.Flush();
391              }
392            }
393          }
[2037]394        }
[1892]395        Logger.Info(String.Format("serialization took {0} seconds with compression level {1}",
396          (DateTime.Now - start).TotalSeconds, compression));
[1733]397        File.Copy(tempfile, filename, true);
398        File.Delete(tempfile);
[6211]399      } catch (Exception) {
[1733]400        Logger.Warn("Exception caught, no data has been written.");
401        throw;
402      }
403    }
404
[3028]405    /// <summary>
406    /// Serializes the specified object into a stream using the <see cref="XmlFormat"/>
407    /// obtained from the <see cref="ConfigurationService"/>.
408    /// </summary>
409    /// <param name="obj">The object.</param>
410    /// <param name="stream">The stream.</param>
[3005]411    public static void Serialize(object obj, Stream stream) {
412      Serialize(obj, stream, ConfigurationService.Instance.GetConfiguration(new XmlFormat()));
413    }
[1797]414
[3005]415
[3028]416    /// <summary>
417    /// Serializes the specified object into a stream.
418    /// </summary>
419    /// <param name="obj">The object.</param>
420    /// <param name="stream">The stream.</param>
421    /// <param name="config">The configuration.</param>
[1733]422    public static void Serialize(object obj, Stream stream, Configuration config) {
[1797]423      Serialize(obj, stream, config, false);
424    }
[3005]425
[3028]426    /// <summary>
427    /// Serializes the specified object into a stream.
428    /// </summary>
429    /// <param name="obj">The object.</param>
430    /// <param name="stream">The stream.</param>
431    /// <param name="config">The configuration.</param>
432    /// <param name="includeAssemblies">if set to <c>true</c> include need assemblies.</param>
[3944]433    public static void Serialize(object obj, Stream stream, Configuration config, bool includeAssemblies) {
[1733]434      try {
[5403]435        Serializer serializer = new Serializer(obj, config);
436        Serialize(stream, serializer);
437      } catch (PersistenceException) {
438        throw;
439      } catch (Exception e) {
440        throw new PersistenceException("Unexpected exception during Serialization.", e);
[4068]441      }
[5403]442    }
443
444    /// <summary>
445    /// Serializes the specified object into a stream.
446    /// </summary>
447    /// <param name="obj">The object.</param>
448    /// <param name="stream">The stream.</param>
449    /// <param name="config">The configuration.</param>
450    /// <param name="includeAssemblies">if set to <c>true</c> include need assemblies.</param>
451    /// <param name="types">The list of all serialized types.</param>
452    public static void Serialize(object obj, Stream stream, Configuration config, bool includeAssemblies, out IEnumerable<Type> types) {
453      try {
454        Serializer serializer = new Serializer(obj, config);
455        Serialize(stream, serializer);
456        types = serializer.SerializedTypes;
457      } catch (PersistenceException) {
[1625]458        throw;
[5403]459      } catch (Exception e) {
[1625]460        throw new PersistenceException("Unexpected exception during Serialization.", e);
[3005]461      }
[1454]462    }
[5403]463
464    private static void Serialize(Stream stream, Serializer serializer) {
465      using (StreamWriter writer = new StreamWriter(new GZipStream(stream, CompressionMode.Compress))) {
466        serializer.InterleaveTypeInformation = true;
467        XmlGenerator generator = new XmlGenerator();
[6211]468        foreach (ISerializationToken token in new AsyncBuffer<ISerializationToken>(serializer)) {
[5403]469          string line = generator.Format(token);
470          writer.Write(line);
471        }
472        writer.Flush();
473      }
474    }
[1454]475  }
476}
Note: See TracBrowser for help on using the repository browser.