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.ViewModelModifiable;
16 import net.mograsim.logic.model.model.components.GUIComponent;
17 import net.mograsim.logic.model.model.components.submodels.SubmodelComponent;
18 import net.mograsim.logic.model.snippets.CodeSnippetSupplier;
19 import net.mograsim.logic.model.util.JsonHandler;
21 public class IndirectGUIComponentCreator
23 private static final Map<String, String> standardComponentIDs = new HashMap<>();
24 private static final Map<String, String> standardComponentIDsUnmodifiable = Collections.unmodifiableMap(standardComponentIDs);
26 private static final Map<String, ComponentSupplier> componentSuppliers = new HashMap<>();
27 private static final Map<String, ResourceLoader> resourceLoaders = new HashMap<>();
28 private static final Map<String, JsonObject> componentCache = new HashMap<>();
30 private static final ResourceLoader defaultResourceLoader;
33 defaultResourceLoader = ClassLoaderBasedResourceLoader.create(IndirectGUIComponentCreator.class.getClassLoader());
34 loadStandardComponentIDs(IndirectGUIComponentCreator.class.getResourceAsStream("standardComponentIDMapping.json"));
37 public static void loadStandardComponentIDs(InputStream standardComponentIdMappingStream)
39 try (InputStream s = standardComponentIdMappingStream)
42 throw new IOException("Resource not found");
43 Map<String, String> tmp = JsonHandler.readJson(s, Map.class);
44 // don't use putAll to apply sanity checks
45 tmp.forEach((st, id) ->
49 addStandardComponentID(st, id);
51 catch (IllegalArgumentException e)
53 System.err.println("Component ID mapping contained illegal entry: " + e.getMessage());
59 System.err.println("Failed to initialize standard snippet ID mapping: " + e.getMessage());
63 public static void addStandardComponentID(String standardComponentID, String associatedComponentID)
65 if (!checkIDIsValidResolvedID(associatedComponentID))
66 throw new IllegalArgumentException("Unrecognized component ID format: " + associatedComponentID);
67 standardComponentIDs.put(standardComponentID, associatedComponentID);
70 public static Map<String, String> getStandardComponentIDs()
72 return standardComponentIDsUnmodifiable;
75 public static void setComponentSupplier(String className, ComponentSupplier componentSupplier)
77 componentSuppliers.put(className, componentSupplier);
80 public static GUIComponent createComponent(ViewModelModifiable model, String id)
82 return createComponent(model, id, (String) null);
85 public static GUIComponent createComponent(ViewModelModifiable model, String id, String name)
87 return createComponent(model, id, JsonNull.INSTANCE, name);
90 public static GUIComponent createComponent(ViewModelModifiable model, String id, JsonElement params)
92 return createComponent(model, id, params, null);
95 public static GUIComponent createComponent(ViewModelModifiable model, String id, JsonElement params, String name)
98 throw new NullPointerException("Component ID is null");
99 if (componentCache.containsKey(id))
100 return loadComponentFromJsonObject(model, id, name, componentCache.get(id));
101 String resolvedID = resolveID(id);
102 if (resolvedID == null)
103 throw new IllegalArgumentException("Unknown standard ID or illegal resolved ID: " + id);
104 String[] parts = resolvedID.split(":");
105 String firstPart = parts[0];
106 if (firstPart.equals("jsonfile"))
108 JsonObject jsonContents;
111 // don't use parts[1], because the path could contain ':'
112 jsonContents = JsonHandler.readJson(resolvedID.substring("jsonfile:".length()), JsonObject.class);
114 catch (IOException e)
116 throw new UncheckedIOException("Error loading JSON file", e);
118 return loadComponentFromJsonObject(model, id, name, jsonContents);
120 ResourceLoader loader;
123 if (firstPart.equals("resloader"))
125 String loaderID = parts[1];
126 loader = resourceLoaders.get(loaderID);
128 tryLoadResourceLoader(loaderID);
129 loader = resourceLoaders.get(loaderID);
131 throw new IllegalArgumentException(
132 "Unknown resource loader: " + loaderID + " (but class was found. Probably the static initializer is missing)");
133 resTypeID = parts[2];
137 loader = defaultResourceLoader;
138 resTypeID = parts[0];
141 if (resTypeID.equals("jsonres"))
143 JsonObject jsonContents;
146 @SuppressWarnings("resource") // jsonStream is closed in JsonHandler
147 InputStream jsonStream = Objects.requireNonNull(loader.loadResource(resID), "Error loading JSON resource: Not found");
148 jsonContents = JsonHandler.readJson(jsonStream, JsonObject.class);
150 catch (IOException e)
152 throw new UncheckedIOException("Error loading JSON resource", e);
154 return loadComponentFromJsonObject(model, id, name, jsonContents);
155 } else if (resTypeID.equals("class"))
157 ComponentSupplier componentSupplier = componentSuppliers.get(resID);
158 if (componentSupplier == null)
161 loader.loadClass(resID);
163 catch (@SuppressWarnings("unused") ClassNotFoundException e)
165 throw new IllegalArgumentException("Unknown component supplier: " + resID);
167 componentSupplier = componentSuppliers.get(resID);
168 if (componentSupplier == null)
169 throw new IllegalArgumentException(
170 "Unknown component supplier: " + resID + " (but class was found. Probably the static initializer is missing)");
171 return componentSupplier.create(model, params, name);
173 throw new IllegalStateException("Unknown resource type ID: " + resTypeID);
176 public static String resolveID(String id)
178 if (checkIDIsValidResolvedID(id))
180 return standardComponentIDs.get(id);
183 private static boolean checkIDIsValidResolvedID(String id)
185 return id.matches("jsonfile:(.+)|(resloader:([^:]+):)?(jsonres|class):[^:]+");
188 private static SubmodelComponent loadComponentFromJsonObject(ViewModelModifiable model, String id, String name, JsonObject jsonContents)
190 componentCache.putIfAbsent(id, jsonContents);
191 SerializablePojo jsonContentsAsSerializablePojo = JsonHandler.parser.fromJson(jsonContents, SerializablePojo.class);
192 if (jsonContentsAsSerializablePojo.version == null)
193 return LegacySubmodelComponentSerializer.deserialize(model,
194 JsonHandler.parser.fromJson(jsonContents, LegacySubmodelComponentParams.class), name, id, null);
195 return SubmodelComponentSerializer.deserialize(model, JsonHandler.parser.fromJson(jsonContents, SubmodelComponentParams.class),
199 public static void registerResourceLoader(ResourceLoader resourceLoader)
201 registerResourceLoader(resourceLoader, resourceLoader.getClass());
204 public static void registerResourceLoader(ResourceLoader resourceLoader, Class<?> reference)
206 resourceLoaders.put(reference.getName(), Objects.requireNonNull(resourceLoader));
209 public static void registerResourceLoader(ResourceLoader resourceLoader, String reference)
211 resourceLoaders.put(reference, Objects.requireNonNull(resourceLoader));
214 private static void tryLoadResourceLoader(String loaderClassName)
216 CodeSnippetSupplier.tryInvokeStaticInitializer(loaderClassName, "Error loading resoruce loader %s: %s\n");
219 public static interface ComponentSupplier
221 public GUIComponent create(ViewModelModifiable model, JsonElement params, String name);