|
| 1 | +package com.thecoderscorner.embedcontrol.core.util; |
| 2 | + |
| 3 | +import java.lang.reflect.Method; |
| 4 | +import java.lang.reflect.Parameter; |
| 5 | +import java.util.*; |
| 6 | +import java.util.concurrent.ConcurrentHashMap; |
| 7 | +import java.util.stream.Collectors; |
| 8 | + |
| 9 | +/** |
| 10 | + * BaseMenuConfig is a base class for configuring menu settings and properties. It holds both the core configuration |
| 11 | + * and also extra configuration added by plugins, it is assumed that the plugin based configuration does not have any |
| 12 | + * dependencies outside of those that are declared in its parameters. |
| 13 | + */ |
| 14 | +public class BaseMenuConfig { |
| 15 | + protected final Map<Class<?>, Object> componentMap = new ConcurrentHashMap<>(); |
| 16 | + protected final System.Logger logger = System.getLogger(getClass().getSimpleName()); |
| 17 | + protected final String environment; |
| 18 | + protected final Properties resolvedProperties; |
| 19 | + protected final String baseName; |
| 20 | + |
| 21 | + /** |
| 22 | + * this constructor ensures that the environment and properties are initialised. To configure the environment from |
| 23 | + * system properties set `env` to `null` and set system property `tc.env` to the environment name. |
| 24 | + * @param env the environment or null to evaluate from system properties. |
| 25 | + */ |
| 26 | + public BaseMenuConfig(String baseAppName, String env) { |
| 27 | + environment = (env != null) ? env : System.getProperty("tc.env", "dev"); |
| 28 | + logger.log(System.Logger.Level.INFO, "Starting app in environment " + environment); |
| 29 | + baseName = baseAppName != null ? baseAppName : "application"; |
| 30 | + resolvedProperties = resolveProperties(environment); |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * Resolves properties based on the specified environment. |
| 35 | + * |
| 36 | + * @param environment the environment for which properties need to be resolved |
| 37 | + * @return the resolved properties as a Properties object |
| 38 | + */ |
| 39 | + protected Properties resolveProperties(String environment) { |
| 40 | + Properties p = new Properties(); |
| 41 | + try(var envProps = getClass().getResourceAsStream(String.format("/%s_%s.properties", baseName, environment)); |
| 42 | + var globalProps = getClass().getResourceAsStream("/" + baseName + ".properties")) { |
| 43 | + if(globalProps != null) { |
| 44 | + logger.log(System.Logger.Level.INFO, "Reading global properties from " + globalProps); |
| 45 | + p.load(globalProps); |
| 46 | + } |
| 47 | + |
| 48 | + if(envProps != null) { |
| 49 | + logger.log(System.Logger.Level.INFO, "Reading env properties from " + envProps); |
| 50 | + p.load(envProps); |
| 51 | + } |
| 52 | + logger.log(System.Logger.Level.INFO, "App Properties read finished"); |
| 53 | + } catch (Exception ex) { |
| 54 | + logger.log(System.Logger.Level.ERROR, "Failed to read app property files", ex); |
| 55 | + } |
| 56 | + return p; |
| 57 | + } |
| 58 | + |
| 59 | + /** |
| 60 | + * Scans for components annotated with {@code TcComponent} in the current class and stores them in the component map. |
| 61 | + * If an annotated method fails to invoke, an error message will be logged. Further, you can add parameters that will |
| 62 | + * be resolved, but this code cannot resolve circular dependencies, it will scan as long as at one component is built |
| 63 | + * each time around the loop. |
| 64 | + */ |
| 65 | + protected void scanForComponents() { |
| 66 | + var toResolve = Arrays.stream(getClass().getDeclaredMethods()).filter(m -> m.isAnnotationPresent(TcComponent.class)) |
| 67 | + .collect(Collectors.toCollection(ArrayList::new)); |
| 68 | + while(!toResolve.isEmpty()) { |
| 69 | + var resolvedThisTurn = new ArrayList<Method>(); |
| 70 | + for (var m : toResolve) { |
| 71 | + m.setAccessible(true); |
| 72 | + try { |
| 73 | + if (m.getParameters().length == 0) { |
| 74 | + logger.log(System.Logger.Level.DEBUG, "Found " + m.getName() + " to fulfill " + m.getReturnType().getSimpleName()); |
| 75 | + componentMap.put(m.getReturnType(), m.invoke(this)); |
| 76 | + resolvedThisTurn.add(m); |
| 77 | + } else { |
| 78 | + var params = resolveParametersOrFail(m); |
| 79 | + if(params == null) continue; |
| 80 | + logger.log(System.Logger.Level.DEBUG, "Found " + m.getName() + " parameterized to fulfill " + m.getReturnType().getSimpleName()); |
| 81 | + componentMap.put(m.getReturnType(), m.invoke(this, params.toArray())); |
| 82 | + resolvedThisTurn.add(m); |
| 83 | + } |
| 84 | + } catch (Exception e) { |
| 85 | + logger.log(System.Logger.Level.ERROR, "Skipping bean " + m.getName() + " because it failed", e); |
| 86 | + } |
| 87 | + } |
| 88 | + if(resolvedThisTurn.isEmpty() && !toResolve.isEmpty()) { |
| 89 | + throw new UnsupportedOperationException("Probably circular dependency in config, cannot resolve"); |
| 90 | + } else { |
| 91 | + toResolve.removeAll(resolvedThisTurn); |
| 92 | + } |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + private ArrayList<Object> resolveParametersOrFail(Method m) { |
| 97 | + try { |
| 98 | + var params = new ArrayList<>(); |
| 99 | + for (Parameter param : m.getParameters()) { |
| 100 | + Class<?> paramType = param.getType(); |
| 101 | + Object resolvedParam = componentMap.get(paramType); |
| 102 | + if (resolvedParam == null) { |
| 103 | + resolvedParam = componentMap.entrySet().stream() |
| 104 | + .filter(e -> paramType.isAssignableFrom(e.getKey())) |
| 105 | + .findFirst() |
| 106 | + .orElseThrow() |
| 107 | + .getValue(); |
| 108 | + } |
| 109 | + params.add(resolvedParam); |
| 110 | + } |
| 111 | + return params; |
| 112 | + } catch (Exception ex) { |
| 113 | + logger.log(System.Logger.Level.DEBUG, "Can't resolve " + m.getName() + " yet, unresolved dependencies"); |
| 114 | + return null; |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + /** |
| 119 | + * Retrieves the current environment. |
| 120 | + * |
| 121 | + * @return the current environment as a String |
| 122 | + */ |
| 123 | + public String getEnvironment() { |
| 124 | + return environment; |
| 125 | + } |
| 126 | + |
| 127 | + /** |
| 128 | + * Retrieves the resolved properties. |
| 129 | + * |
| 130 | + * @return the resolved properties as a Properties object |
| 131 | + */ |
| 132 | + public Properties getResolvedProperties() { |
| 133 | + return resolvedProperties; |
| 134 | + } |
| 135 | + |
| 136 | + /** |
| 137 | + * Gets the value of the specified property as an integer. If the property exists in the resolved properties, |
| 138 | + * it will be parsed as an integer and returned. If the property does not exist, the default value will be returned. |
| 139 | + * |
| 140 | + * @param propName the name of the property to retrieve the value from |
| 141 | + * @param def the default value to return if the property does not exist |
| 142 | + * @return the value of the property as an integer, or the default value if the property does not exist |
| 143 | + */ |
| 144 | + protected int propAsIntWithDefault(String propName, int def) { |
| 145 | + if(resolvedProperties.containsKey(propName)) { |
| 146 | + return Integer.parseInt(resolvedProperties.getProperty(propName)); |
| 147 | + } |
| 148 | + return def; |
| 149 | + } |
| 150 | + |
| 151 | + /** |
| 152 | + * Retrieves the value of the specified property and throws an exception if missing. |
| 153 | + * |
| 154 | + * @param propName the name of the property to retrieve |
| 155 | + * @return the value of the property |
| 156 | + * @throws IllegalArgumentException if the property is missing in the configuration |
| 157 | + */ |
| 158 | + protected String mandatoryStringProp(String propName) { |
| 159 | + if(!resolvedProperties.containsKey(propName)) { |
| 160 | + throw new IllegalArgumentException("Missing property in configuration " + propName); |
| 161 | + } |
| 162 | + return resolvedProperties.getProperty(propName); |
| 163 | + } |
| 164 | + |
| 165 | + /** |
| 166 | + * Retrieves an instance of the specified class from the component map. Fastest lookup is by direct class type. |
| 167 | + * However, if the class is not found in the map, it searches for a compatible class that would fulfill the |
| 168 | + * interface provided. If no compatible class is found, an exception is thrown. |
| 169 | + * |
| 170 | + * @param clazz the class to retrieve an instance of |
| 171 | + * @param <T> the generic type of the class, the function is T <= class T |
| 172 | + * @return an instance of the specified class |
| 173 | + * @throws NoSuchElementException if no compatible class is found in the component map |
| 174 | + */ |
| 175 | + public <T> T getBean(Class<T> clazz) { |
| 176 | + var cmp = componentMap.get(clazz); |
| 177 | + if(cmp == null) { |
| 178 | + cmp = componentMap.entrySet().stream().filter(e -> clazz.isAssignableFrom(e.getKey())).findFirst() |
| 179 | + .orElseThrow().getValue(); |
| 180 | + } |
| 181 | + return (T) cmp; |
| 182 | + } |
| 183 | + |
| 184 | + /** |
| 185 | + * Adds a bean to the component map and returns it. |
| 186 | + * |
| 187 | + * @param beanToAdd the bean to be added to the component map |
| 188 | + * @param <T> the type of the bean |
| 189 | + * @return the added bean |
| 190 | + */ |
| 191 | + public <T> T asBean(T beanToAdd) { |
| 192 | + componentMap.put(beanToAdd.getClass(), beanToAdd); |
| 193 | + return beanToAdd; |
| 194 | + } |
| 195 | + |
| 196 | +} |
0 commit comments