The final restructured version for automatic build using maven tycho
[Mograsim.git] / plugins / net.mograsim.logic.model / src / net / mograsim / logic / model / serializing / IndirectModelComponentCreator.java
1 package net.mograsim.logic.model.serializing;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.io.UncheckedIOException;
6 import java.util.Collections;
7 import java.util.HashMap;
8 import java.util.Map;
9 import java.util.Objects;
10
11 import com.google.gson.JsonElement;
12 import com.google.gson.JsonNull;
13 import com.google.gson.JsonObject;
14
15 import net.mograsim.logic.model.model.LogicModelModifiable;
16 import net.mograsim.logic.model.model.components.ModelComponent;
17 import net.mograsim.logic.model.model.components.submodels.SubmodelComponent;
18 import net.mograsim.logic.model.util.JsonHandler;
19 import net.mograsim.logic.model.util.Version;
20
21 public class IndirectModelComponentCreator
22 {
23         public static final Version CURRENT_STD_ID_MAPPING_VERSION = Version.parseSemver("0.1.0");
24
25         private static final Map<String, String> standardComponentIDs = new HashMap<>();
26         private static final Map<String, String> standardComponentIDsUnmodifiable = Collections.unmodifiableMap(standardComponentIDs);
27
28         private static final Map<String, ComponentSupplier> componentSuppliers = new HashMap<>();
29         private static final Map<String, ResourceLoader> resourceLoaders = new HashMap<>();
30         private static final Map<String, JsonObject> componentCache = new HashMap<>();
31
32         private static final ResourceLoader defaultResourceLoader;
33         static
34         {
35                 defaultResourceLoader = ClassLoaderBasedResourceLoader.create(IndirectModelComponentCreator.class.getClassLoader());
36                 loadStandardComponentIDs(IndirectModelComponentCreator.class.getResourceAsStream("standardComponentIDMapping.json"));
37         }
38
39         public static void loadStandardComponentIDs(InputStream standardComponentIdMappingStream)
40         {
41                 try (InputStream s = standardComponentIdMappingStream)
42                 {
43                         if (s == null)
44                                 throw new IOException("Resource not found");
45                         Map<String, String> tmp = JsonHandler.readJson(s, StandardComponentIdMappingContainer.class).getMap();
46                         // don't use putAll to apply sanity checks
47                         tmp.forEach((st, id) ->
48                         {
49                                 try
50                                 {
51                                         addStandardComponentID(st, id);
52                                 }
53                                 catch (IllegalArgumentException e)
54                                 {
55                                         System.err.println("Component ID mapping contained illegal entry: " + e.getMessage());
56                                 }
57                         });
58                 }
59                 catch (IOException e)
60                 {
61                         System.err.println("Failed to initialize standard snippet ID mapping: " + e.getMessage());
62                 }
63         }
64
65         public static void addStandardComponentID(String standardComponentID, String associatedComponentID)
66         {
67                 if (!checkIDIsValidResolvedID(associatedComponentID))
68                         throw new IllegalArgumentException("Unrecognized component ID format: " + associatedComponentID);
69                 standardComponentIDs.put(standardComponentID, associatedComponentID);
70         }
71
72         public static Map<String, String> getStandardComponentIDs()
73         {
74                 return standardComponentIDsUnmodifiable;
75         }
76
77         public static void setComponentSupplier(String id, ComponentSupplier componentSupplier)
78         {
79                 componentSuppliers.put(id, componentSupplier);
80         }
81
82         public static ModelComponent createComponent(LogicModelModifiable model, String id)
83         {
84                 return createComponent(model, id, (String) null);
85         }
86
87         public static ModelComponent createComponent(LogicModelModifiable model, String id, String name)
88         {
89                 return createComponent(model, id, JsonNull.INSTANCE, name);
90         }
91
92         public static ModelComponent createComponent(LogicModelModifiable model, String id, JsonElement params)
93         {
94                 return createComponent(model, id, params, null);
95         }
96
97         public static ModelComponent createComponent(LogicModelModifiable model, String id, JsonElement params, String name)
98         {
99                 if (id == null)
100                         throw new NullPointerException("Component ID is null");
101                 if (componentCache.containsKey(id))
102                         return loadComponentFromJsonObject(model, id, name, componentCache.get(id));
103                 String resolvedID = resolveID(id);
104                 if (resolvedID == null)
105                         throw new IllegalArgumentException("Unknown standard ID or illegal resolved ID: " + id);
106                 String[] parts = resolvedID.split(":");
107                 String firstPart = parts[0];
108                 if (firstPart.equals("jsonfile"))
109                 {
110                         JsonObject jsonContents;
111                         try
112                         {
113                                 // don't use parts[1], because the path could contain ':'
114                                 jsonContents = JsonHandler.readJson(resolvedID.substring("jsonfile:".length()), JsonObject.class);
115                         }
116                         catch (IOException e)
117                         {
118                                 throw new UncheckedIOException("Error loading JSON file", e);
119                         }
120                         return loadComponentFromJsonObject(model, id, name, jsonContents);
121                 }
122                 ResourceLoader loader;
123                 String resTypeID;
124                 String resID;
125                 if (firstPart.equals("resloader"))
126                 {
127                         String loaderID = parts[1];
128                         loader = resourceLoaders.get(loaderID);
129                         if (loader == null)
130                                 tryLoadResourceLoader(loaderID);
131                         loader = resourceLoaders.get(loaderID);
132                         if (loader == null)
133                                 throw new IllegalArgumentException(
134                                                 "Unknown resource loader: " + loaderID + " (but class was found. Probably the static initializer is missing)");
135                         resTypeID = parts[2];
136                         resID = parts[3];
137                 } else
138                 {
139                         loader = defaultResourceLoader;
140                         resTypeID = parts[0];
141                         resID = parts[1];
142                 }
143                 if (resTypeID.equals("jsonres"))
144                 {
145                         JsonObject jsonContents;
146                         try
147                         {
148                                 @SuppressWarnings("resource") // jsonStream is closed in JsonHandler
149                                 InputStream jsonStream = Objects.requireNonNull(loader.loadResource(resID), "Error loading JSON resource: Not found");
150                                 jsonContents = JsonHandler.readJson(jsonStream, JsonObject.class);
151                         }
152                         catch (IOException e)
153                         {
154                                 throw new UncheckedIOException("Error loading JSON resource", e);
155                         }
156                         return loadComponentFromJsonObject(model, id, name, jsonContents);
157                 } else if (resTypeID.equals("class"))
158                 {
159                         ComponentSupplier componentSupplier = componentSuppliers.get(resID);
160                         if (componentSupplier == null)
161                                 try
162                                 {
163                                         loader.loadClass(resID);
164                                 }
165                                 catch (@SuppressWarnings("unused") ClassNotFoundException e)
166                                 {
167                                         throw new IllegalArgumentException("Unknown component supplier: " + resID);
168                                 }
169                         componentSupplier = componentSuppliers.get(resID);
170                         if (componentSupplier == null)
171                                 throw new IllegalArgumentException(
172                                                 "Unknown component supplier: " + resID + " (but class was found. Probably the static initializer is missing)");
173                         return componentSupplier.create(model, params, name);
174                 } else
175                         throw new IllegalStateException("Unknown resource type ID: " + resTypeID);
176         }
177
178         public static String resolveID(String id)
179         {
180                 if (checkIDIsValidResolvedID(id))
181                         return id;
182                 return standardComponentIDs.get(id);
183         }
184
185         private static boolean checkIDIsValidResolvedID(String id)
186         {
187                 return id.matches("jsonfile:(.+)|(resloader:([^:]+):)?(jsonres|class):[^:]+");
188         }
189
190         private static SubmodelComponent loadComponentFromJsonObject(LogicModelModifiable model, String id, String name,
191                         JsonObject jsonContents)
192         {
193                 componentCache.putIfAbsent(id, jsonContents);
194                 SerializablePojo jsonContentsAsSerializablePojo = JsonHandler.parser.fromJson(jsonContents, SerializablePojo.class);
195                 if (jsonContentsAsSerializablePojo.version == null)
196                         return LegacySubmodelComponentSerializer.deserialize(model,
197                                         JsonHandler.parser.fromJson(jsonContents, LegacySubmodelComponentParams.class), name, id, null);
198                 return SubmodelComponentSerializer.deserialize(model, JsonHandler.parser.fromJson(jsonContents, SubmodelComponentParams.class),
199                                 name, id, null);
200         }
201
202         public static void registerResourceLoader(ResourceLoader resourceLoader)
203         {
204                 registerResourceLoader(resourceLoader, resourceLoader.getClass());
205         }
206
207         public static void registerResourceLoader(ResourceLoader resourceLoader, Class<?> reference)
208         {
209                 resourceLoaders.put(reference.getName(), Objects.requireNonNull(resourceLoader));
210         }
211
212         public static void registerResourceLoader(ResourceLoader resourceLoader, String reference)
213         {
214                 resourceLoaders.put(reference, Objects.requireNonNull(resourceLoader));
215         }
216
217         private static void tryLoadResourceLoader(String loaderClassName)
218         {
219                 ReflectionHelper.tryInvokeStaticInitializer(loaderClassName, "Error loading resoruce loader %s: %s\n");
220         }
221
222         public static interface ComponentSupplier
223         {
224                 public ModelComponent create(LogicModelModifiable model, JsonElement params, String name);
225         }
226 }