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;
14 import net.mograsim.logic.model.model.LogicModelModifiable;
15 import net.mograsim.logic.model.model.components.ModelComponent;
16 import net.mograsim.logic.model.model.components.submodels.SubmodelComponent;
17 import net.mograsim.logic.model.util.JsonHandler;
19 public class IndirectModelComponentCreator
21 private static final Map<String, String> standardComponentIDs = new HashMap<>();
22 private static final Map<String, String> standardComponentIDsUnmodifiable = Collections.unmodifiableMap(standardComponentIDs);
24 private static final Map<String, ComponentSupplier> componentSuppliers = new HashMap<>();
25 private static final Map<String, ResourceLoader> resourceLoaders = new HashMap<>();
26 private static final Map<String, SubmodelComponentParams> componentCache = new HashMap<>();
28 private static final ResourceLoader defaultResourceLoader;
31 defaultResourceLoader = ClassLoaderBasedResourceLoader.create(IndirectModelComponentCreator.class.getClassLoader());
32 loadStandardComponentIDs(IndirectModelComponentCreator.class.getResourceAsStream("standardComponentIDMapping.json"));
35 public static void loadStandardComponentIDs(InputStream standardComponentIdMappingStream)
37 try (InputStream s = standardComponentIdMappingStream)
40 throw new IOException("Resource not found");
41 Map<String, String> tmp = JsonHandler.readJson(s, Map.class);
42 // don't use putAll to apply sanity checks
43 tmp.forEach((st, id) ->
47 addStandardComponentID(st, id);
49 catch (IllegalArgumentException e)
51 System.err.println("Component ID mapping contained illegal entry: " + e.getMessage());
57 System.err.println("Failed to initialize standard snippet ID mapping: " + e.getMessage());
61 public static void addStandardComponentID(String standardComponentID, String associatedComponentID)
63 if (!checkIDIsValidResolvedID(associatedComponentID))
64 throw new IllegalArgumentException("Unrecognized component ID format: " + associatedComponentID);
65 standardComponentIDs.put(standardComponentID, associatedComponentID);
68 public static Map<String, String> getStandardComponentIDs()
70 return standardComponentIDsUnmodifiable;
73 public static void setComponentSupplier(String id, ComponentSupplier componentSupplier)
75 componentSuppliers.put(id, componentSupplier);
78 public static ModelComponent createComponent(LogicModelModifiable model, String id)
80 return createComponent(model, id, (String) null);
83 public static ModelComponent createComponent(LogicModelModifiable model, String id, String name)
85 return createComponent(model, id, JsonNull.INSTANCE, name);
88 public static ModelComponent createComponent(LogicModelModifiable model, String id, JsonElement params)
90 return createComponent(model, id, params, null);
93 public static ModelComponent createComponent(LogicModelModifiable model, String id, JsonElement params, String name)
96 throw new NullPointerException("Component ID is null");
97 if (componentCache.containsKey(id))
98 return loadComponentFromJsonObject(model, id, name, componentCache.get(id));
99 String resolvedID = resolveID(id);
100 if (resolvedID == null)
101 throw new IllegalArgumentException("Unknown standard ID or illegal resolved ID: " + id);
102 String[] parts = resolvedID.split(":");
103 String firstPart = parts[0];
104 if (firstPart.equals("jsonfile"))
106 SubmodelComponentParams jsonContents;
109 // don't use parts[1], because the path could contain ':'
110 jsonContents = JsonHandler.readJson(resolvedID.substring("jsonfile:".length()), SubmodelComponentParams.class);
112 catch (IOException e)
114 throw new UncheckedIOException("Error loading JSON file", e);
116 return loadComponentFromJsonObject(model, id, name, jsonContents);
118 ResourceLoader loader;
121 if (firstPart.equals("resloader"))
123 String loaderID = parts[1];
124 loader = resourceLoaders.get(loaderID);
126 tryLoadResourceLoader(loaderID);
127 loader = resourceLoaders.get(loaderID);
129 throw new IllegalArgumentException(
130 "Unknown resource loader: " + loaderID + " (but class was found. Probably the static initializer is missing)");
131 resTypeID = parts[2];
135 loader = defaultResourceLoader;
136 resTypeID = parts[0];
139 if (resTypeID.equals("jsonres"))
141 SubmodelComponentParams jsonContents;
144 @SuppressWarnings("resource") // jsonStream is closed in JsonHandler
145 InputStream jsonStream = Objects.requireNonNull(loader.loadResource(resID), "Error loading JSON resource: Not found");
146 jsonContents = JsonHandler.readJson(jsonStream, SubmodelComponentParams.class);
148 catch (IOException e)
150 throw new UncheckedIOException("Error loading JSON resource", e);
152 return loadComponentFromJsonObject(model, id, name, jsonContents);
153 } else if (resTypeID.equals("class"))
155 ComponentSupplier componentSupplier = componentSuppliers.get(resID);
156 if (componentSupplier == null)
159 loader.loadClass(resID);
161 catch (@SuppressWarnings("unused") ClassNotFoundException e)
163 throw new IllegalArgumentException("Unknown component supplier: " + resID);
165 componentSupplier = componentSuppliers.get(resID);
166 if (componentSupplier == null)
167 throw new IllegalArgumentException(
168 "Unknown component supplier: " + resID + " (but class was found. Probably the static initializer is missing)");
169 return componentSupplier.create(model, params, name);
171 throw new IllegalStateException("Unknown resource type ID: " + resTypeID);
174 public static String resolveID(String id)
176 if (checkIDIsValidResolvedID(id))
178 return standardComponentIDs.get(id);
181 private static boolean checkIDIsValidResolvedID(String id)
183 return id.matches("jsonfile:(.+)|(resloader:([^:]+):)?(jsonres|class):[^:]+");
186 private static SubmodelComponent loadComponentFromJsonObject(LogicModelModifiable model, String id, String name,
187 SubmodelComponentParams jsonContents)
189 componentCache.putIfAbsent(id, jsonContents);
190 return SubmodelComponentSerializer.deserialize(model, jsonContents, name, id, null);
193 public static void registerResourceLoader(ResourceLoader resourceLoader)
195 registerResourceLoader(resourceLoader, resourceLoader.getClass());
198 public static void registerResourceLoader(ResourceLoader resourceLoader, Class<?> reference)
200 resourceLoaders.put(reference.getName(), Objects.requireNonNull(resourceLoader));
203 public static void registerResourceLoader(ResourceLoader resourceLoader, String reference)
205 resourceLoaders.put(reference, Objects.requireNonNull(resourceLoader));
208 private static void tryLoadResourceLoader(String loaderClassName)
210 ReflectionHelper.tryInvokeStaticInitializer(loaderClassName, "Error loading resoruce loader %s: %s\n");
213 public static interface ComponentSupplier
215 public ModelComponent create(LogicModelModifiable model, JsonElement params, String name);