Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2520_PersistenceReintegration/HeuristicLab.Persistence/3.3/Default/Xml/EasyXmlGenerator.cs @ 16462

Last change on this file since 16462 was 16462, checked in by jkarder, 5 years ago

#2520: worked on reintegration of new persistence

  • added nuget references to HEAL.Fossil
  • added StorableType attributes to many classes
  • changed signature of StorableConstructors
  • removed some classes in old persistence
  • removed some unnecessary usings
File size: 7.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2019 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 System.IO;
25using HEAL.Fossil;
26using HeuristicLab.Persistence.Auxiliary;
27using HeuristicLab.Persistence.Core;
28using HeuristicLab.Persistence.Core.Tokens;
29using HeuristicLab.Persistence.Interfaces;
30using HeuristicLab.Tracing;
31
32namespace HeuristicLab.Persistence.Default.Xml {
33
34
35  /// <summary>
36  /// Main entry point of persistence to XML. Use the static methods to serialize
37  /// to a file or to a stream.
38  /// </summary>
39  public class ReadableXmlGenerator : XmlGenerator {
40
41    protected Dictionary<int, string> typeCache = new Dictionary<int, string>();
42
43    /// <summary>
44    /// Formats the specified begin token.
45    /// </summary>
46    /// <param name="beginToken">The begin token.</param>
47    /// <returns>The token in serialized form.</returns>
48    protected override string Format(BeginToken beginToken) {
49      var dict = new Dictionary<string, string> {
50          {"name", beginToken.Name},
51          {"id", beginToken.Id.ToString()}};
52      return CreateNodeStart(typeCache[beginToken.TypeId], dict);
53    }
54
55    /// <summary>
56    /// Formats the specified end token.
57    /// </summary>
58    /// <param name="endToken">The end token.</param>
59    /// <returns>The token in serialized form.</returns>
60    protected override string Format(EndToken endToken) {
61      return CreateNodeEnd(typeCache[endToken.TypeId]);
62    }
63
64    /// <summary>
65    /// Formats the specified data token.
66    /// </summary>
67    /// <param name="dataToken">The data token.</param>
68    /// <returns>The token in serialized form.</returns>
69    protected override string Format(PrimitiveToken dataToken) {
70      var dict = new Dictionary<string, string> {
71            {"name", dataToken.Name},
72            {"id", dataToken.Id.ToString()}};
73      return CreateNode(typeCache[dataToken.TypeId], dict,
74        ((XmlString)dataToken.SerialData).Data);
75    }
76
77    /// <summary>
78    /// Formats the specified ref token.
79    /// </summary>
80    /// <param name="refToken">The ref token.</param>
81    /// <returns>The token in serialized form.</returns>
82    protected override string Format(ReferenceToken refToken) {
83      return CreateNode(refToken.Id.ToString(),
84        new Dictionary<string, string> {
85          {"name", refToken.Name}});
86    }
87
88    /// <summary>
89    /// Formats the specified null ref token.
90    /// </summary>
91    /// <param name="nullRefToken">The null ref token.</param>
92    /// <returns>The token in serialized form.</returns>
93    protected override string Format(NullReferenceToken nullRefToken) {
94      return CreateNode(XmlStringConstants.NULL,
95        new Dictionary<string, string>{
96          {"name", nullRefToken.Name}});
97    }
98
99    /// <summary>
100    /// Formats the specified meta info begin token.
101    /// </summary>
102    /// <param name="metaInfoBeginToken">The meta info begin token.</param>
103    /// <returns>The token in serialized form.</returns>
104    protected override string Format(MetaInfoBeginToken metaInfoBeginToken) {
105      return CreateNodeStart(XmlStringConstants.METAINFO);
106    }
107
108    /// <summary>
109    /// Formats the specified meta info end token.
110    /// </summary>
111    /// <param name="metaInfoEndToken">The meta info end token.</param>
112    /// <returns>The token in serialized form.</returns>
113    protected override string Format(MetaInfoEndToken metaInfoEndToken) {
114      return CreateNodeEnd(XmlStringConstants.METAINFO);
115    }
116
117    /// <summary>
118    /// Formats the specified token.
119    /// </summary>
120    /// <param name="token">The token.</param>
121    /// <returns>The token in serialized form.</returns>
122    protected override string Format(TypeToken token) {
123      typeCache[token.Id] = TypeNameParser.Parse(token.TypeName).GetTypeNameInCode(false);
124      return "";
125    }
126
127    /// <summary>
128    /// Serialize an object into a file.
129    /// The XML configuration is obtained from the <c>ConfigurationService</c>.
130    /// The file is actually a ZIP file.
131    /// Compression level is set to 5 and needed assemblies are not included.
132    /// </summary>
133    /// <param name="o">The object.</param>
134    /// <param name="filename">The filename.</param>
135    public new static void Serialize(object o, string filename) {
136      Serialize(o, filename, ConfigurationService.Instance.GetConfiguration(new XmlFormat()));
137    }
138
139    /// <summary>
140    /// Serializes the specified object into a file.
141    /// Needed assemblies are not included, ZIP compression level is set to 5.
142    /// </summary>
143    /// <param name="obj">The object.</param>
144    /// <param name="filename">The filename.</param>
145    /// <param name="config">The configuration.</param>
146    public new static void Serialize(object obj, string filename, Configuration config) {
147      try {
148        string tempfile = Path.GetTempFileName();
149        DateTime start = DateTime.Now;
150        using (FileStream stream = File.Create(tempfile)) {
151          Serialize(obj, stream, config);
152        }
153        Logger.Info(String.Format("easy serialization took {0} seconds",
154          (DateTime.Now - start).TotalSeconds));
155        File.Copy(tempfile, filename, true);
156        File.Delete(tempfile);
157      }
158      catch (Exception) {
159        Logger.Warn("Exception caught, no data has been written.");
160        throw;
161      }
162    }
163
164    /// <summary>
165    /// Serializes the specified object into a stream using the <see cref="XmlFormat"/>
166    /// obtained from the <see cref="ConfigurationService"/>.
167    /// </summary>
168    /// <param name="obj">The object.</param>
169    /// <param name="stream">The stream.</param>
170    public static void Serialize(object obj, Stream stream) {
171      Serialize(obj, stream, ConfigurationService.Instance.GetConfiguration(new XmlFormat()));
172    }
173
174
175    /// <summary>
176    /// Serializes the specified object into a stream.
177    /// </summary>
178    /// <param name="obj">The object.</param>
179    /// <param name="stream">The stream.</param>
180    /// <param name="config">The configuration.</param>
181    public static void Serialize(object obj, Stream stream, Configuration config) {
182      try {
183        using (StreamWriter writer = new StreamWriter(stream)) {
184          Core.Serializer serializer = new Core.Serializer(obj, config);
185          serializer.InterleaveTypeInformation = true;
186          ReadableXmlGenerator generator = new ReadableXmlGenerator();
187          foreach (ISerializationToken token in serializer) {
188            string line = generator.Format(token);
189            writer.Write(line);
190          }
191          writer.Flush();
192        }
193      }
194      catch (PersistenceException) {
195        throw;
196      }
197      catch (Exception e) {
198        throw new PersistenceException("Unexpected exception during Serialization.", e);
199      }
200    }
201  }
202}
Note: See TracBrowser for help on using the repository browser.