KeyValue(Map.Entry<String, ConfigValue> keyValue) { key = keyValue.getKey(); description = createDescription(keyValue.getValue()); try { if (keyValue.getValue().valueType() == ConfigValueType.NULL) { valueType = "N/A (null)"; defaultValue = "null"; } else { valueType = keyValue.getValue().valueType().name().toLowerCase(); defaultValue = render(keyValue.getValue()); } } catch (ConfigException.NotResolved e) { valueType = "N/A (unresolved)"; defaultValue = keyValue.getValue().render(); } }
@Test public void testNestedObject() throws Exception { final String JSON = "{\"array\":[1,2],\"obj\":{\"first\":true}}"; ConfigObject value = MAPPER.readValue(JSON, ConfigObject.class); assertEquals(ConfigValueType.OBJECT, value.valueType()); assertEquals(2, value.size()); ConfigList array = (ConfigList) value.get("array"); assertEquals(ConfigValueType.LIST, array.valueType()); assertEquals(2, (array.unwrapped().size())); ConfigValue objValue = value.get("obj"); assertEquals(ConfigValueType.OBJECT, objValue.valueType()); ConfigObject obj = (ConfigObject) objValue; assertEquals(1, (obj.size())); }
/** * Initializes the configuration class by loading the configuration file. * @param conf overrides the default configuration */ public static void init(com.typesafe.config.Config conf) { try { config = ConfigFactory.load().getConfig(PARA); if (conf != null) { config = conf.withFallback(config); } configMap = new HashMap<>(); for (Map.Entry<String, ConfigValue> con : config.entrySet()) { if (con.getValue().valueType() != ConfigValueType.LIST) { configMap.put(con.getKey(), config.getString(con.getKey())); } } } catch (Exception ex) { logger.warn("Para configuration file 'application.(conf|json|properties)' is missing from classpath."); config = com.typesafe.config.ConfigFactory.empty(); } }
/** * Parse a play configuration. * * @param config play configuration * @return ebean parsed configuration * @see com.typesafe.config.Config */ public static EbeanParsedConfig parseFromConfig(Config config) { Config playEbeanConfig = config.getConfig("play.ebean"); String defaultDatasource = playEbeanConfig.getString("defaultDatasource"); String ebeanConfigKey = playEbeanConfig.getString("config"); Map<String, List<String>> datasourceModels = new HashMap<>(); if (config.hasPath(ebeanConfigKey)) { Config ebeanConfig = config.getConfig(ebeanConfigKey); ebeanConfig.root().forEach((key, raw) -> { List<String> models; if (raw.valueType() == ConfigValueType.STRING) { // Support legacy comma separated string models = Arrays.asList(((String) raw.unwrapped()).split(",")); } else { models = ebeanConfig.getStringList(key); } datasourceModels.put(key, models); }); } return new EbeanParsedConfig(defaultDatasource, datasourceModels); }
public static ConfigValue expandSugar(Class<?> type, ConfigValue config, PluginRegistry pluginRegistry) { if ((type != null) && type.isAssignableFrom(ConfigValue.class)) { return ConfigValueFactory.fromAnyRef(config.unwrapped(), "unchanged for raw ConfigValue field " + config.origin().description()); } CodableClassInfo typeInfo = new CodableClassInfo(type, pluginRegistry.config(), pluginRegistry); PluginMap pluginMap = typeInfo.getPluginMap(); ConfigValue valueOrResolvedRoot = resolveType(type, config, pluginMap); if (valueOrResolvedRoot.valueType() != ConfigValueType.OBJECT) { return valueOrResolvedRoot; } ConfigObject root = (ConfigObject) valueOrResolvedRoot; String classField = pluginMap.classField(); if (root.get(classField) != null) { try { type = pluginMap.getClass((String) root.get(classField).unwrapped()); } catch (ClassNotFoundException ignored) { // try not to throw exceptions or at least checked exceptions from this helper method } } return expandSugarSkipResolve(type, root, pluginRegistry); }
protected JsonNode currentNumericNode() throws JsonParseException { ConfigValue configValue = currentNode(); if ((configValue == null) || (configValue.valueType() != ConfigValueType.NUMBER)) { JsonToken t = (configValue == null) ? null : ConfigNodeCursor.forConfigValue(configValue); throw _constructError("Current token ("+t+") not numeric, can not use numeric value accessors"); } Number value = (Number) configValue.unwrapped(); if (value instanceof Double) { return JsonNodeFactory.instance.numberNode((Double) value); } if (value instanceof Long) { return JsonNodeFactory.instance.numberNode((Long) value); } if (value instanceof Integer) { return JsonNodeFactory.instance.numberNode((Integer) value); } // only possible if Config has since added more numeric types throw _constructError(value.getClass() + " is not a supported numeric config type"); }
public HoconTreeTraversingParser(ConfigObject n, ObjectCodec codec) { super(0); _rootObject = n; _objectCodec = codec; if (n.valueType() == ConfigValueType.LIST) { _nextToken = JsonToken.START_ARRAY; _nodeCursor = new HoconNodeCursor.Array(n, null); } else if (n.valueType() == ConfigValueType.OBJECT) { if (HoconNodeCursor.isNumericallyIndexed(n)) { _nextToken = JsonToken.START_ARRAY; _nodeCursor = new HoconNodeCursor.NumericallyIndexedObjectBackedArray(n, null); } else { _nextToken = JsonToken.START_OBJECT; _nodeCursor = new HoconNodeCursor.Object(n, null); } } else { // value node _nodeCursor = new HoconNodeCursor.RootValue(n, null); } }
private static String render(ConfigValue value) { String result; if (value.valueType().equals(ConfigValueType.LIST)) { result = "[" + ((ConfigList) value).stream() .map(KeyValue::render) .collect(Collectors.joining(", ")) + "]"; } else if (value.valueType().equals(ConfigValueType.STRING)) { result = '"' + value.unwrapped().toString() + '"'; } else { result = value.unwrapped().toString(); } return result; }
private static Set<Map.Entry<String, ConfigValue>> nullValues(ConfigObject config) { Set<Map.Entry<String, ConfigValue>> result = new HashSet<>(); for (Map.Entry<String, ConfigValue> entry : config.entrySet()) { try { if (entry.getValue().valueType() == ConfigValueType.NULL) { result.add(entry); } else if (entry.getValue().valueType() == ConfigValueType.OBJECT) { result.addAll(nullValues((ConfigObject) entry.getValue())); } } catch (ConfigException.NotResolved e) { // unresolved substitutions are handled elsewhere, here we just ignore them } } return result; }
@Test public void testSimpleArray() throws Exception { final String JSON = "[1,true,\"foo\"]"; ConfigList value = MAPPER.readValue(JSON, ConfigList.class); assertEquals(ConfigValueType.LIST, value.valueType()); assertEquals(3, value.size()); assertEquals(ConfigValueType.NUMBER, value.get(0).valueType()); assertEquals(true, value.get(1).unwrapped()); assertEquals(ConfigValueType.STRING, value.get(2).valueType()); }
@Test public void testNestedArray() throws Exception { final String JSON = "[1,[false,45],{\"foo\":13}]"; ConfigList value = MAPPER.readValue(JSON, ConfigList.class); assertEquals(ConfigValueType.LIST, value.valueType()); assertEquals(3, value.size()); assertEquals(ConfigValueType.NUMBER, value.get(0).valueType()); assertEquals(ConfigValueType.LIST, value.get(1).valueType()); assertEquals(ConfigValueType.OBJECT, value.get(2).valueType()); }
@Test public void testSimpleObject() throws Exception { final String JSON = "{\"a\":12.5,\"b\":\"Text\"}"; ConfigObject value = MAPPER.readValue(JSON, ConfigObject.class); assertEquals(ConfigValueType.OBJECT, value.valueType()); assertEquals(2, value.size()); assertEquals(ConfigValueType.NUMBER, value.get("a").valueType()); assertEquals(12.5, value.get("a").unwrapped()); assertEquals(ConfigValueType.STRING, value.get("b").valueType()); assertEquals("Text", value.get("b").unwrapped()); }
private static ConfigValueType getValueTypeOrNull(Class<?> parameterClass) { if (parameterClass == Boolean.class || parameterClass == boolean.class) { return ConfigValueType.BOOLEAN; } else if (parameterClass == Integer.class || parameterClass == int.class) { return ConfigValueType.NUMBER; } else if (parameterClass == Double.class || parameterClass == double.class) { return ConfigValueType.NUMBER; } else if (parameterClass == Long.class || parameterClass == long.class) { return ConfigValueType.NUMBER; } else if (parameterClass == String.class) { return ConfigValueType.STRING; } else if (parameterClass == Duration.class) { return null; } else if (parameterClass == ConfigMemorySize.class) { return null; } else if (parameterClass == List.class) { return ConfigValueType.LIST; } else if (parameterClass == Map.class) { return ConfigValueType.OBJECT; } else if (parameterClass == Config.class) { return ConfigValueType.OBJECT; } else if (parameterClass == ConfigObject.class) { return ConfigValueType.OBJECT; } else if (parameterClass == ConfigList.class) { return ConfigValueType.LIST; } else { return null; } }
private static void initializeUDFs(Config config) { if (!config.hasPath("udfs")) return; if (!config.getValue("udfs").valueType().equals(ConfigValueType.LIST)) { throw new RuntimeException("UDFs must be provided as a list"); } ConfigList udfList = config.getList("udfs"); for (ConfigValue udfValue : udfList) { ConfigValueType udfValueType = udfValue.valueType(); if (!udfValueType.equals(ConfigValueType.OBJECT)) { throw new RuntimeException("UDF list must contain UDF objects"); } Config udfConfig = ((ConfigObject)udfValue).toConfig(); for (String path : Lists.newArrayList("name", "class")) { if (!udfConfig.hasPath(path)) { throw new RuntimeException("UDF entries must provide '" + path + "'"); } } String name = udfConfig.getString("name"); String className = udfConfig.getString("class"); // null third argument means that registerJava will infer the return type Contexts.getSparkSession().udf().registerJava(name, className, null); LOG.info("Registered Spark SQL UDF: " + name); } }
public static void getArgumentDescriptions(Map<String, String> argumentDescriptions, Config config, AbstractV1Method method) { if (config.hasPath("arguments")) { config.getConfig("arguments").entrySet().forEach(entry -> { if (entry.getValue().valueType() != ConfigValueType.STRING) { throw new IllegalArgumentException("Description for argument at path " + entry.getKey() + " for method " + method.getDeclaration() + " must be a string"); } argumentDescriptions.put(entry.getKey(), (String) entry.getValue().unwrapped()); }); } }
public static Map<String, String> readMappings(File file) { Config config = ConfigFactory.parseFile(file); Map<String, String> mappings = new HashMap<>(); config.entrySet().forEach(entry -> { if (entry.getValue().valueType() != ConfigValueType.STRING) { throw new IllegalArgumentException("Invalid mapping: expected STRING, got " + entry.getValue().valueType().name() + " at " + entry.getKey()); } mappings.put(entry.getKey(), (String) entry.getValue().unwrapped()); }); return mappings; }
@SuppressWarnings({ "unchecked", "rawtypes" }) private Object getConfigValue(Class<?> paramClass, Type paramType, String path) { Optional<Object> extractedValue = ConfigExtractors.extractConfigValue(config, paramClass, path); if (extractedValue.isPresent()) { return extractedValue.get(); } ConfigValue configValue = config.getValue(path); ConfigValueType valueType = configValue.valueType(); if (valueType.equals(ConfigValueType.OBJECT) && Map.class.isAssignableFrom(paramClass)) { ConfigObject object = config.getObject(path); return object.unwrapped(); } else if (valueType.equals(ConfigValueType.OBJECT)) { Object bean = ConfigBeanFactory.create(config.getConfig(path), paramClass); return bean; } else if (valueType.equals(ConfigValueType.LIST) && List.class.isAssignableFrom(paramClass)) { Type listType = ((ParameterizedType) paramType).getActualTypeArguments()[0]; Optional<List<?>> extractedListValue = ListExtractors.extractConfigListValue(config, listType, path); if (extractedListValue.isPresent()) { return extractedListValue.get(); } else { List<? extends Config> configList = config.getConfigList(path); return configList.stream() .map(cfg -> { Object created = ConfigBeanFactory.create(cfg, (Class) listType); return created; }) .collect(Collectors.toList()); } } throw new RuntimeException("Cannot obtain config value for " + paramType + " at path: " + path); }
@SuppressWarnings("unchecked") private Config dbconf(final Config conf, final String type) { String dbtype = "databases." + type; ConfigValue value = conf.getValue(dbtype); if (value.valueType() == ConfigValueType.OBJECT) { return ((ConfigObject) value).toConfig(); } List<Config> list = (List<Config>) conf.getConfigList(dbtype); ClassLoader loader = getClass().getClassLoader(); return list.stream() .filter(it -> dataSourcePresent(loader, it.getString("dataSourceClassName"))) .findFirst() .orElse(list.get(0)); }
static JsonToken forConfigValue(ConfigValue configValue) { ConfigValueType valueType = configValue.valueType(); switch (valueType) { case NUMBER: if (configValue.unwrapped() instanceof Double) { return JsonToken.VALUE_NUMBER_FLOAT; } else { return JsonToken.VALUE_NUMBER_INT; } case BOOLEAN: if (configValue.unwrapped().equals(Boolean.TRUE)) { return JsonToken.VALUE_TRUE; } else { return JsonToken.VALUE_FALSE; } case NULL: return JsonToken.VALUE_NULL; case STRING: return JsonToken.VALUE_STRING; case OBJECT: return JsonToken.START_OBJECT; case LIST: return JsonToken.START_ARRAY; default: // not possible unless the set of enums changes on us later throw new IllegalArgumentException(valueType.name() + " is not a supported ConfigValueType"); } }
@Override public boolean currentHasChildren() { // note: ONLY to be called for container nodes ConfigValue currentValue = currentNode(); if (currentValue.valueType() == ConfigValueType.LIST) { return !((ConfigList) currentValue).isEmpty(); } else { return !((ConfigObject) currentValue).isEmpty(); } }
protected ConfigValue currentNumericNode() throws JsonParseException { ConfigValue n = currentNode(); if (n == null || n.valueType() != ConfigValueType.NUMBER) { JsonToken t = (n == null) ? null : asJsonToken(n); throw _constructError("Current token ("+t+") not numeric, can not use numeric value accessors"); } return n; }
private void checkType(String name, ConfigValue value, ConfigValueType type) { if (!type.equals(value.valueType())) { throw new SwiftConfigException(value.origin(), "'" + name + "': wrong type (" + value.valueType() + "). Must be a " + type); } }
public static int getPassThruCost(Config config, String key) { ConfigValue val = config.getValue(key); return val.valueType() == ConfigValueType.STRING ? -1 : ((Number)val.unwrapped()).intValue(); }
public PluginMap(@Nonnull String category, @Nonnull Config config) { this.config = config; this.category = checkNotNull(category); classField = config.getString("_field"); boolean errorMissing = config.getBoolean("_strict"); if (config.hasPath("_class")) { String baseClassName = config.getString("_class"); try { baseClass = Class.forName(baseClassName); } catch (ClassNotFoundException e) { log.error("could not find specified base class {} for category {}", baseClassName, category); throw new RuntimeException(e); } } else { baseClass = null; } Set<String> labels = config.root().keySet(); BiMap<String, Class<?>> mutableMap = HashBiMap.create(labels.size()); Map<String, String> mutableAliasMap = new HashMap<>(); Set<String> mutableInlinedAliasSet = new HashSet<>(); for (String label : labels) { if (!((label.charAt(0) != '_') || "_array".equals(label) || "_default".equals(label))) { continue; } ConfigValue configValue = config.root().get(label); String className; if (configValue.valueType() == ConfigValueType.STRING) { className = (String) configValue.unwrapped(); } else if (configValue.valueType() == ConfigValueType.OBJECT) { ConfigObject configObject = (ConfigObject) configValue; className = configObject.toConfig().getString("_class"); if (configObject.toConfig().hasPath("_inline") && configObject.toConfig().getBoolean("_inline")) { mutableInlinedAliasSet.add(label); } } else if (configValue.valueType() == ConfigValueType.NULL) { continue; } else { throw new ConfigException.WrongType(configValue.origin(), label, "STRING OR OBJECT", configValue.valueType().toString()); } if (labels.contains(className)) { // points to another alias mutableAliasMap.put(label, className); } else { try { Class<?> foundClass = findAndValidateClass(className); mutableMap.put(label, foundClass); } catch (ClassNotFoundException maybeSwallowed) { if (errorMissing) { throw new RuntimeException(maybeSwallowed); } else { log.warn("plugin category {} with alias {} is pointing to missing class {}", category, label, className); } } } } map = Maps.unmodifiableBiMap(mutableMap); aliases = Collections.unmodifiableMap(mutableAliasMap); checkAliasesForCycles(); inlinedAliases = Collections.unmodifiableSet(mutableInlinedAliasSet); }
protected static boolean isArray(ConfigValue value) { return value.valueType() == ConfigValueType.LIST; }
protected static boolean isObject(ConfigValue value) { return value.valueType() == ConfigValueType.OBJECT; }