Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/JCGenerator.cs @ 17379

Last change on this file since 17379 was 17379, checked in by dpiringe, 4 years ago

#3026:

  • removed classes:
    • CheckedItemListConverter: unnecessary
    • ItemCollectionConverter: unnecessary
    • PrimitiveConverter: not possible to implement because it needs to Extract/Inject from/into objects (but interfaces pretends IItem)
    • StorableConverter: unnecessary
    • ConfigurableConverter: unnecessary
  • removed graphviz code in Heuristiclab.ConfigStarter/Program.cs
  • updated Constants
  • some simple code refactors in BaseConverter
  • in JsonItem:
    • renamed Parameters -> Children
    • removed Properties: Operators, Type, Reference, IsConfigurable, IsParameterizedItem
    • removed unnecessary/old code
  • implemented a new way to get data from an object, which is a matrix, in ValueTypeMatrixConverter method: CopyMatrixData
    • converts the object into an array -> rows: from array.Length, cols: when the length is > 0 pick length of first array of index 0 (it is saved as an array of arrays)
  • created a binding flag const in ValueRangeConverter to prevent duplicates in code
File size: 3.3 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using HeuristicLab.Common;
5using HeuristicLab.Core;
6using HeuristicLab.Data;
7using HeuristicLab.Optimization;
8using Newtonsoft.Json;
9using Newtonsoft.Json.Linq;
10using HEAL.Attic;
11
12namespace HeuristicLab.JsonInterface {
13  /// <summary>
14  /// Static class to generate json interface templates.
15  /// </summary>
16  public static class JCGenerator {
17    private struct GenData {
18      public JObject Template { get; set; }
19      public JArray JsonItems { get; set; }
20    }
21   
22    public static string GenerateTemplate(IAlgorithm algorithm) {
23      // data container
24      GenData genData = new GenData() {
25        Template = JObject.Parse(Constants.Template),
26        JsonItems = new JArray()
27      };
28
29      ProtoBufSerializer serializer = new ProtoBufSerializer();
30      serializer.Serialize(algorithm, @"C:\Workspace\template.hl");
31      genData.Template[Constants.Metadata][Constants.HLFileLocation] = @"C:\Workspace\template.hl";
32
33      // extract JsonItem, save the name in the metadata section of the
34      // template and save it an JArray incl. all parameters of the JsonItem,
35      // which have parameters aswell
36      AddInstantiableIItem(Constants.Algorithm, algorithm, genData);
37      //IsConvertable(algorithm, true);
38      if (algorithm.Problem != null) // only when an problem exists
39        AddInstantiableIItem(Constants.Problem, algorithm.Problem, genData);
40
41      // save the JArray with JsonItems (= IParameterizedItems)
42      genData.Template[Constants.Parameters] = genData.JsonItems;
43      // serialize template and return string
44      return CustomJsonWriter.Serialize(genData.Template);
45    }
46   
47    #region Helper
48    private static bool IsConvertable(object obj, bool throwException = false) {
49      bool tmp = ConvertableAttribute.IsConvertable(obj);
50      if (throwException && tmp)
51        throw new NotSupportedException($"Type {obj.GetType().GetPrettyName(false)} is not convertable!");
52      return tmp;
53    }
54
55    private static void AddInstantiableIItem(string metaDataTagName, IItem item, GenData genData) {
56      JsonItem jsonItem = JsonItemConverter.Extract(item);
57      genData.Template[Constants.Metadata][metaDataTagName] = item.ItemName;
58      PopulateJsonItems(jsonItem, genData);
59    }
60
61    // serializes ParameterizedItems and saves them in list "JsonItems".
62    private static void PopulateJsonItems(JsonItem item, GenData genData) {
63      IEnumerable<JsonItem> tmpParameter = item.Children;
64      item.Children = null;
65
66      if (item.Value != null || item.Range != null) {
67        genData.JsonItems.Add(Serialize(item));
68      }
69
70      if (tmpParameter != null) {
71        foreach (var p in tmpParameter) {
72          PopulateJsonItems(p, genData);
73        }
74      }
75    }
76
77    private static JObject Serialize(JsonItem item) =>
78      JObject.FromObject(item, Settings());
79
80    /// <summary>
81    /// Settings for the json serialization.
82    /// </summary>
83    /// <returns>A configured JsonSerializer.</returns>
84    private static JsonSerializer Settings() => new JsonSerializer() {
85      TypeNameHandling = TypeNameHandling.None,
86      NullValueHandling = NullValueHandling.Ignore,
87      ReferenceLoopHandling = ReferenceLoopHandling.Serialize
88    };
89    #endregion
90  }
91}
Note: See TracBrowser for help on using the repository browser.