Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/XmlGenerator.cs @ 1542

Last change on this file since 1542 was 1542, checked in by epitzer, 15 years ago

Numerous small changes, coding conventions, renames, mini refactoring (#548)

File size: 5.9 KB
Line 
1using System.Collections.Generic;
2using System;
3using System.Text;
4using HeuristicLab.Persistence.Interfaces;
5using HeuristicLab.Persistence.Core;
6using System.IO;
7using ICSharpCode.SharpZipLib.Zip;
8using HeuristicLab.Tracing;
9using log4net;
10using HeuristicLab.Persistence.Interfaces.Tokens;
11
12namespace HeuristicLab.Persistence.Default.Xml {
13
14  struct XmlStrings {
15    public const string PRIMITIVE = "PRIMITVE";
16    public const string COMPOSITE = "COMPOSITE";
17    public const string REFERENCE = "REFERENCE";
18    public const string NULL = "NULL";
19    public const string TYPECACHE = "TYPECACHE";
20    public const string TYPE = "TYPE";
21  }
22
23  public abstract class Generator<T> {
24    public T Format(ISerializationToken token) {
25      Type type = token.GetType();
26      if (type == typeof(BeginToken))
27        return Format((BeginToken)token);
28      if (type == typeof(EndToken))
29        return Format((EndToken)token);
30      if (type == typeof(PrimitiveToken))
31        return Format((PrimitiveToken)token);
32      if (type == typeof(ReferenceToken))
33        return Format((ReferenceToken)token);
34      if (type == typeof(NullReferenceToken))
35        return Format((NullReferenceToken)token);
36      throw new ApplicationException("Invalid token of type " + type.FullName);
37    }
38    protected abstract T Format(BeginToken beginToken);
39    protected abstract T Format(EndToken endToken);
40    protected abstract T Format(PrimitiveToken primitiveToken);
41    protected abstract T Format(ReferenceToken referenceToken);
42    protected abstract T Format(NullReferenceToken nullReferenceToken);
43  }
44
45  public class XmlGenerator : Generator<string> {
46   
47    private int depth;
48
49    public XmlGenerator() {
50      depth = 0;
51    }
52
53    private enum NodeType { Start, End, Inline } ;
54
55    private static string FormatNode(string name,
56        Dictionary<string, object> attributes,
57        NodeType type) {
58      return FormatNode(name, attributes, type, " ");
59    }
60
61    private static string FormatNode(string name,
62        Dictionary<string, object> attributes,
63        NodeType type, string space) {
64      StringBuilder sb = new StringBuilder();
65      sb.Append('<');
66      if (type == NodeType.End)
67        sb.Append('/');
68      sb.Append(name);     
69      foreach (var attribute in attributes) {
70        if (attribute.Value != null && !string.IsNullOrEmpty(attribute.Value.ToString())) {
71          sb.Append(space);
72          sb.Append(attribute.Key);
73          sb.Append("=\"");
74          sb.Append(attribute.Value);
75          sb.Append('"');
76        }
77      }
78      if (type == NodeType.Inline)
79        sb.Append('/');
80      sb.Append(">");
81      return sb.ToString();     
82    }
83
84    private string Prefix {
85      get { return new string(' ', depth * 2); }
86    }
87
88    protected override string Format(BeginToken beginToken) {           
89      var attributes = new Dictionary<string, object> {
90        {"name", beginToken.Name},
91        {"typeId", beginToken.TypeId},
92        {"id", beginToken.Id}};
93      string result = Prefix +
94                      FormatNode(XmlStrings.COMPOSITE, attributes, NodeType.Start) + "\r\n";
95      depth += 1;
96      return result;
97    }
98
99    protected override string Format(EndToken endToken) {     
100      depth -= 1;
101      return Prefix + "</" + XmlStrings.COMPOSITE + ">\r\n";
102    }
103
104    protected override string Format(PrimitiveToken dataToken) {     
105      var attributes =
106        new Dictionary<string, object> {
107            {"typeId", dataToken.TypeId},
108            {"name", dataToken.Name},
109            {"id", dataToken.Id}};
110      return Prefix +
111        FormatNode(XmlStrings.PRIMITIVE, attributes, NodeType.Start) +
112        dataToken.SerialData + "</" + XmlStrings.PRIMITIVE + ">\r\n";     
113    }
114
115    protected override string Format(ReferenceToken refToken) {     
116      var attributes = new Dictionary<string, object> {
117        {"ref", refToken.Id},
118        {"name", refToken.Name}};                                       
119      return Prefix + FormatNode(XmlStrings.REFERENCE, attributes, NodeType.Inline) + "\r\n"; 
120    }
121
122    protected override string Format(NullReferenceToken nullRefToken) {     
123      var attributes = new Dictionary<string, object>{
124        {"name", nullRefToken.Name}};     
125      return Prefix + FormatNode(XmlStrings.NULL, attributes, NodeType.Inline) + "\r\n";
126    }
127
128    public IEnumerable<string> Format(List<TypeMapping> typeCache) {
129      yield return "<" + XmlStrings.TYPECACHE + ">";
130      foreach (var mapping in typeCache)
131        yield return "  " + FormatNode(
132          XmlStrings.TYPE,
133          mapping.GetDict(),
134          NodeType.Inline,
135          "\r\n    ");
136      yield return "</" + XmlStrings.TYPECACHE + ">";
137    }
138
139    public static void Serialize(object o, string filename) {     
140      Serialize(o, filename, ConfigurationService.Instance.GetDefaultConfig(XmlFormat.Instance));
141    }
142
143    public static void Serialize(object obj, string filename, Configuration config) {
144      Serializer serializer = new Serializer(obj, config);
145      XmlGenerator generator = new XmlGenerator();
146      ZipOutputStream zipStream = new ZipOutputStream(File.Create(filename));
147      zipStream.SetLevel(9);     
148      zipStream.PutNextEntry(new ZipEntry("data.xml"));     
149      StreamWriter writer = new StreamWriter(zipStream);
150      ILog logger = Logger.GetDefaultLogger();     
151      foreach (ISerializationToken token in serializer) {
152        string line = generator.Format(token);
153        writer.Write(line);
154        logger.Debug(line);
155      }
156      writer.Flush();
157      zipStream.PutNextEntry(new ZipEntry("typecache.xml"));
158      writer = new StreamWriter(zipStream);
159      foreach (string line in generator.Format(serializer.TypeCache)) {
160        writer.WriteLine(line);
161        logger.Debug(line);
162      }
163      writer.Flush();           
164      zipStream.Close();     
165    }
166
167  }
168}
Note: See TracBrowser for help on using the repository browser.