1 package net.mograsim.logic.model.serializing;
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;
9 import java.util.Objects;
11 import com.google.gson.JsonElement;
12 import com.google.gson.JsonNull;
13 import com.google.gson.JsonObject;
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;
21 public class IndirectModelComponentCreator
23 public static final Version CURRENT_STD_ID_MAPPING_VERSION = Version.parseSemver("0.1.0");
25 private static final Map<String, String> standardComponentIDs = new HashMap<>();
26 private static final Map<String, String> standardComponentIDsUnmodifiable = Collections.unmodifiableMap(standardComponentIDs);
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<>();
32 private static final ResourceLoader defaultResourceLoader;
35 defaultResourceLoader = ClassLoaderBasedResourceLoader.create(IndirectModelComponentCreator.class.getClassLoader());
36 loadStandardComponentIDs(IndirectModelComponentCreator.class.getResourceAsStream("standardComponentIDMapping.json"));
39 public static void loadStandardComponentIDs(InputStream standardComponentIdMappingStream)
41 try (InputStream s = standardComponentIdMappingStream)
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) ->
51 addStandardComponentID(st, id);
53 catch (IllegalArgumentException e)
55 System.err.println("Component ID mapping contained illegal entry: " + e.getMessage());
61 System.err.println("Failed to initialize standard snippet ID mapping: " + e.getMessage());
65 public static void addStandardComponentID(String standardComponentID, String associatedComponentID)
67 if (!checkIDIsValidResolvedID(associatedComponentID))
68 throw new IllegalArgumentException("Unrecognized component ID format: " + associatedComponentID);
69 standardComponentIDs.put(standardComponentID, associatedComponentID);
72 public static Map<String, String> getStandardComponentIDs()
74 return standardComponentIDsUnmodifiable;
77 public static void setComponentSupplier(String id, ComponentSupplier componentSupplier)
79 componentSuppliers.put(id, componentSupplier);
82 public static ModelComponent createComponent(LogicModelModifiable model, String id)
84 return createComponent(model, id, (String) null);
87 public static ModelComponent createComponent(LogicModelModifiable model, String id, String name)
89 return createComponent(model, id, JsonNull.INSTANCE, name);
92 public static ModelComponent createComponent(LogicModelModifiable model, String id, JsonElement params)
94 return createComponent(model, id, params, null);
97 public static ModelComponent createComponent(LogicModelModifiable model, String id, JsonElement params, String name)
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"))
110 JsonObject jsonContents;
113 // don't use parts[1], because the path could contain ':'
114 jsonContents = JsonHandler.readJson(resolvedID.substring("jsonfile:".length()), JsonObject.class);
116 catch (IOException e)
118 throw new UncheckedIOException("Error loading JSON file", e);
120 return loadComponentFromJsonObject(model, id, name, jsonContents);
122 ResourceLoader loader;
125 if (firstPart.equals("resloader"))
127 String loaderID = parts[1];
128 loader = resourceLoaders.get(loaderID);
130 tryLoadResourceLoader(loaderID);
131 loader = resourceLoaders.get(loaderID);
133 throw new IllegalArgumentException(
134 "Unknown resource loader: " + loaderID + " (but class was found. Probably the static initializer is missing)");
135 resTypeID = parts[2];
139 loader = defaultResourceLoader;
140 resTypeID = parts[0];
143 if (resTypeID.equals("jsonres"))
145 JsonObject jsonContents;
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);
152 catch (IOException e)
154 throw new UncheckedIOException("Error loading JSON resource", e);
156 return loadComponentFromJsonObject(model, id, name, jsonContents);
157 } else if (resTypeID.equals("class"))
159 ComponentSupplier componentSupplier = componentSuppliers.get(resID);
160 if (componentSupplier == null)
163 loader.loadClass(resID);
165 catch (@SuppressWarnings("unused") ClassNotFoundException e)
167 throw new IllegalArgumentException("Unknown component supplier: " + resID);
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);
175 throw new IllegalStateException("Unknown resource type ID: " + resTypeID);
178 public static String resolveID(String id)
180 if (checkIDIsValidResolvedID(id))
182 return standardComponentIDs.get(id);
185 private static boolean checkIDIsValidResolvedID(String id)
187 return id.matches("jsonfile:(.+)|(resloader:([^:]+):)?(jsonres|class):[^:]+");
190 private static SubmodelComponent loadComponentFromJsonObject(LogicModelModifiable model, String id, String name,
191 JsonObject jsonContents)
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),
202 public static void registerResourceLoader(ResourceLoader resourceLoader)
204 registerResourceLoader(resourceLoader, resourceLoader.getClass());
207 public static void registerResourceLoader(ResourceLoader resourceLoader, Class<?> reference)
209 resourceLoaders.put(reference.getName(), Objects.requireNonNull(resourceLoader));
212 public static void registerResourceLoader(ResourceLoader resourceLoader, String reference)
214 resourceLoaders.put(reference, Objects.requireNonNull(resourceLoader));
217 private static void tryLoadResourceLoader(String loaderClassName)
219 ReflectionHelper.tryInvokeStaticInitializer(loaderClassName, "Error loading resoruce loader %s: %s\n");
222 public static interface ComponentSupplier
224 public ModelComponent create(LogicModelModifiable model, JsonElement params, String name);