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;
20 public class IndirectModelComponentCreator
22 private static final Map<String, String> standardComponentIDs = new HashMap<>();
23 private static final Map<String, String> standardComponentIDsUnmodifiable = Collections.unmodifiableMap(standardComponentIDs);
25 private static final Map<String, ComponentSupplier> componentSuppliers = new HashMap<>();
26 private static final Map<String, ResourceLoader> resourceLoaders = new HashMap<>();
27 private static final Map<String, JsonObject> componentCache = new HashMap<>();
29 private static final ResourceLoader defaultResourceLoader;
32 defaultResourceLoader = ClassLoaderBasedResourceLoader.create(IndirectModelComponentCreator.class.getClassLoader());
33 loadStandardComponentIDs(IndirectModelComponentCreator.class.getResourceAsStream("standardComponentIDMapping.json"));
36 public static void loadStandardComponentIDs(InputStream standardComponentIdMappingStream)
38 try (InputStream s = standardComponentIdMappingStream)
41 throw new IOException("Resource not found");
42 Map<String, String> tmp = JsonHandler.readJson(s, Map.class);
43 // don't use putAll to apply sanity checks
44 tmp.forEach((st, id) ->
48 addStandardComponentID(st, id);
50 catch (IllegalArgumentException e)
52 System.err.println("Component ID mapping contained illegal entry: " + e.getMessage());
58 System.err.println("Failed to initialize standard snippet ID mapping: " + e.getMessage());
62 public static void addStandardComponentID(String standardComponentID, String associatedComponentID)
64 if (!checkIDIsValidResolvedID(associatedComponentID))
65 throw new IllegalArgumentException("Unrecognized component ID format: " + associatedComponentID);
66 standardComponentIDs.put(standardComponentID, associatedComponentID);
69 public static Map<String, String> getStandardComponentIDs()
71 return standardComponentIDsUnmodifiable;
74 public static void setComponentSupplier(String id, ComponentSupplier componentSupplier)
76 componentSuppliers.put(id, componentSupplier);
79 public static ModelComponent createComponent(LogicModelModifiable model, String id)
81 return createComponent(model, id, (String) null);
84 public static ModelComponent createComponent(LogicModelModifiable model, String id, String name)
86 return createComponent(model, id, JsonNull.INSTANCE, name);
89 public static ModelComponent createComponent(LogicModelModifiable model, String id, JsonElement params)
91 return createComponent(model, id, params, null);
94 public static ModelComponent createComponent(LogicModelModifiable model, String id, JsonElement params, String name)
97 throw new NullPointerException("Component ID is null");
98 if (componentCache.containsKey(id))
99 return loadComponentFromJsonObject(model, id, name, componentCache.get(id));
100 String resolvedID = resolveID(id);
101 if (resolvedID == null)
102 throw new IllegalArgumentException("Unknown standard ID or illegal resolved ID: " + id);
103 String[] parts = resolvedID.split(":");
104 String firstPart = parts[0];
105 if (firstPart.equals("jsonfile"))
107 JsonObject jsonContents;
110 // don't use parts[1], because the path could contain ':'
111 jsonContents = JsonHandler.readJson(resolvedID.substring("jsonfile:".length()), JsonObject.class);
113 catch (IOException e)
115 throw new UncheckedIOException("Error loading JSON file", e);
117 return loadComponentFromJsonObject(model, id, name, jsonContents);
119 ResourceLoader loader;
122 if (firstPart.equals("resloader"))
124 String loaderID = parts[1];
125 loader = resourceLoaders.get(loaderID);
127 tryLoadResourceLoader(loaderID);
128 loader = resourceLoaders.get(loaderID);
130 throw new IllegalArgumentException(
131 "Unknown resource loader: " + loaderID + " (but class was found. Probably the static initializer is missing)");
132 resTypeID = parts[2];
136 loader = defaultResourceLoader;
137 resTypeID = parts[0];
140 if (resTypeID.equals("jsonres"))
142 JsonObject jsonContents;
145 @SuppressWarnings("resource") // jsonStream is closed in JsonHandler
146 InputStream jsonStream = Objects.requireNonNull(loader.loadResource(resID), "Error loading JSON resource: Not found");
147 jsonContents = JsonHandler.readJson(jsonStream, JsonObject.class);
149 catch (IOException e)
151 throw new UncheckedIOException("Error loading JSON resource", e);
153 return loadComponentFromJsonObject(model, id, name, jsonContents);
154 } else if (resTypeID.equals("class"))
156 ComponentSupplier componentSupplier = componentSuppliers.get(resID);
157 if (componentSupplier == null)
160 loader.loadClass(resID);
162 catch (@SuppressWarnings("unused") ClassNotFoundException e)
164 throw new IllegalArgumentException("Unknown component supplier: " + resID);
166 componentSupplier = componentSuppliers.get(resID);
167 if (componentSupplier == null)
168 throw new IllegalArgumentException(
169 "Unknown component supplier: " + resID + " (but class was found. Probably the static initializer is missing)");
170 return componentSupplier.create(model, params, name);
172 throw new IllegalStateException("Unknown resource type ID: " + resTypeID);
175 public static String resolveID(String id)
177 if (checkIDIsValidResolvedID(id))
179 return standardComponentIDs.get(id);
182 private static boolean checkIDIsValidResolvedID(String id)
184 return id.matches("jsonfile:(.+)|(resloader:([^:]+):)?(jsonres|class):[^:]+");
187 private static SubmodelComponent loadComponentFromJsonObject(LogicModelModifiable model, String id, String name, JsonObject jsonContents)
189 componentCache.putIfAbsent(id, jsonContents);
190 SerializablePojo jsonContentsAsSerializablePojo = JsonHandler.parser.fromJson(jsonContents, SerializablePojo.class);
191 if (jsonContentsAsSerializablePojo.version == null)
192 return LegacySubmodelComponentSerializer.deserialize(model,
193 JsonHandler.parser.fromJson(jsonContents, LegacySubmodelComponentParams.class), name, id, null);
194 return SubmodelComponentSerializer.deserialize(model, JsonHandler.parser.fromJson(jsonContents, SubmodelComponentParams.class),
198 public static void registerResourceLoader(ResourceLoader resourceLoader)
200 registerResourceLoader(resourceLoader, resourceLoader.getClass());
203 public static void registerResourceLoader(ResourceLoader resourceLoader, Class<?> reference)
205 resourceLoaders.put(reference.getName(), Objects.requireNonNull(resourceLoader));
208 public static void registerResourceLoader(ResourceLoader resourceLoader, String reference)
210 resourceLoaders.put(reference, Objects.requireNonNull(resourceLoader));
213 private static void tryLoadResourceLoader(String loaderClassName)
215 ReflectionHelper.tryInvokeStaticInitializer(loaderClassName, "Error loading resoruce loader %s: %s\n");
218 public static interface ComponentSupplier
220 public ModelComponent create(LogicModelModifiable model, JsonElement params, String name);