1 package net.mograsim.logic.ui.serializing;
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.lang.reflect.Constructor;
6 import java.lang.reflect.InvocationTargetException;
7 import java.util.HashMap;
10 import net.mograsim.logic.ui.model.ViewModelModifiable;
11 import net.mograsim.logic.ui.model.components.GUIComponent;
12 import net.mograsim.logic.ui.model.components.atomic.SimpleRectangularGUIGate;
13 import net.mograsim.logic.ui.model.components.submodels.SimpleRectangularSubmodelComponent;
14 import net.mograsim.logic.ui.model.wires.WireCrossPoint;
15 import net.mograsim.logic.ui.util.JsonHandler;
17 public class IndirectGUIComponentCreator
19 private final static Map<String, String> componentMapping;
23 Map<String, String> tmp;
24 try (InputStream s = IndirectGUIComponentCreator.class.getResourceAsStream("./mapping.json"))
26 tmp = JsonHandler.readJson(s, Map.class);
30 System.err.println("Failed to initialize component mapping; Components cannot be created from file.");
32 tmp = new HashMap<>();
34 componentMapping = tmp;
37 public static GUIComponent create(ViewModelModifiable model, String name, Map<String, Object> params)
41 String path = componentMapping.get(name);
42 if (path.startsWith("class:"))
44 path = path.substring(6);
45 return createComponentFromClass(model, path, params);
46 } else if (path.startsWith("file:"))
48 path = path.substring(5);
49 return SubmodelComponentDeserializer.create(model, path);
51 throw new IllegalArgumentException("Invalid submodel type! Type was neither prefixed by 'class:' nor by 'file:'");
53 catch (NullPointerException | InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException
54 | SecurityException | ClassNotFoundException | IllegalArgumentException e)
56 System.err.println("Failed to create requested component!");
58 return new SimpleRectangularSubmodelComponent(model, 1, "ERROR");
62 private static GUIComponent createComponentFromClass(ViewModelModifiable model, String classname, Map<String, Object> params)
63 throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, SecurityException,
64 ClassNotFoundException
66 Class<?> c = Class.forName(classname);
68 if (SimpleRectangularGUIGate.class.isAssignableFrom(c) || WireCrossPoint.class.equals(c))
70 Constructor<?> constructor = c.getConstructor(ViewModelModifiable.class, int.class);
71 comp = constructor.newInstance(model, ((Number) params.get(SimpleRectangularGUIGate.kLogicWidth)).intValue());
74 Constructor<?> constructor = c.getConstructor(ViewModelModifiable.class);
75 comp = constructor.newInstance(model);
77 return (GUIComponent) comp;