@Test(expected = RktLauncherServiceException.class) public void shouldThrowIfInvalidConfig() { //language=JSON final String json = "{\n" + " \"rkt\": \"/usr/local/bin/rkt\",\n" + " \"daemon\": \"systemd-run\",\n" + " \"globalOptions\": {\n" + " \"insecureOptions\": [\"image\"]\n" + " }\n" + "}\n"; final Config config = mock(Config.class); final ConfigValue configValue = mock(ConfigValue.class); when(environment.config()).thenReturn(config); when(config.getValue("rktLauncher")).thenReturn(configValue); when(configValue.render(any())).thenReturn(json); rktLauncherApi.create(environment); }
private void dispatchConfig(Config config, ConfigCallback callback) { for (Map.Entry<String, ConfigValue> entry : config.root().entrySet()) { final String id = entry.getKey(); try { final Config entryConfig = ((ConfigObject) entry.getValue()).toConfig(); final String type = entryConfig.getString("type"); if (Strings.isNullOrEmpty(type)) { errors.add(new ConfigurationError("Missing type field for " + id + " (" + entryConfig + ")")); continue; } callback.call(type, id, entryConfig); } catch (ConfigException e) { errors.add(new ConfigurationError("[" + id + "] " + e.getMessage())); } } }
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(); } }
@GetMapping public String get(HttpServletRequest req, Model model) { if (!utils.isAuthenticated(req) || !utils.isAdmin(utils.getAuthUser(req))) { return "redirect:" + HOMEPAGE; } Map<String, Object> configMap = new LinkedHashMap<String, Object>(); for (Map.Entry<String, ConfigValue> entry : Config.getConfig().entrySet()) { ConfigValue value = entry.getValue(); configMap.put(Config.PARA + "_" + entry.getKey(), value != null ? value.unwrapped() : "-"); } configMap.putAll(System.getenv()); model.addAttribute("path", "admin.vm"); model.addAttribute("title", utils.getLang(req).get("admin.title")); model.addAttribute("configMap", configMap); model.addAttribute("version", pc.getServerVersion()); return "base"; }
private static Config applySystemProperties(Config config, Config reference){ for (Entry<String, ConfigValue> entry : reference.entrySet()) { String property = System.getProperty(entry.getKey()); if (property != null && !property.isEmpty()) { // hack to deal with array of strings if (property.startsWith("[") && property.endsWith("]")) { property = property.substring(1, property.length()-1); if (property.trim().isEmpty()) { continue; } String[] strings = property.split(","); if (strings != null && strings.length > 0) { List<String> listStrings = new ArrayList<>(); for (String str : strings) { listStrings.add(str.trim()); } config = config.withValue(entry.getKey(), ConfigValueFactory.fromAnyRef(listStrings)); } } else { config = config.withValue(entry.getKey(), ConfigValueFactory.fromAnyRef(property)); } logger.info("Applying provided system property to config: -D{}={}", entry.getKey(), property); } } return config; }
/** * Create a {@link BaggageHandlerRegistry} instance by parsing the mappings configured in the provided * {@link Config} * * @param config a typesafe config * @return a {@link BaggageHandlerRegistry} instance with handlers loaded for the configured bag keys */ static BaggageHandlerRegistry create(Config config) { Map<BagKey, BaggageHandler<?>> mapping = new TreeMap<>(); for (Entry<String, ConfigValue> x : config.getConfig(BAGS_CONFIGURATION_KEY).entrySet()) { String bagHandlerClassName = x.getValue().unwrapped().toString(); Integer bagNumber = parseBagKey(x.getKey(), bagHandlerClassName); if (bagNumber == null) continue; BagKey key = BagKey.indexed(bagNumber); BaggageHandler<?> handler = resolveHandler(bagHandlerClassName); if (handler == null) continue; mapping.put(key, handler); } if (mapping.size() == 0) { log.warn("No baggage handlers are registered -- if this is unexpected, ensure `bag` is correctly configured"); } else { String handlersString = mapping.entrySet().stream() .map(e -> "\t" + e.getKey().toString() + ": " + e.getValue().getClass().getName().toString()) .collect(Collectors.joining("\n")); log.info(mapping.size() + " baggage handlers registered:\n" + handlersString); } return new BaggageHandlerRegistry(new Registrations(mapping)); }
@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())); }
@SuppressWarnings("unchecked") public <E> EventClassifier<E> getEventClassifier(Class<E> eventType) { return (EventClassifier<E>) classifiers.computeIfAbsent(eventType, t -> { ConfigValue value = config.getConfig("ts-reaktive.replication.event-classifiers").root().get(eventType.getName()); if (value == null) { throw new IllegalArgumentException("You must configure ts-reaktive.replication.event-classifiers.\"" + eventType.getName() + "\" with an EventClassifier implementation."); } String className = (String) value.unwrapped(); try { Class<?> type = getClass().getClassLoader().loadClass(className); Constructor<?> constr = type.getDeclaredConstructor(); constr.setAccessible(true); return (EventClassifier<E>) constr.newInstance(); } catch (Exception e) { throw new IllegalArgumentException(e); } }); }
/** * Create the hibernate service which initializes the session factory * * @param conf application configuration * @throws UnsupportedOperationException if a mapping file is invalid */ public HibernateService(Config conf) { Configuration hibernateConf = new Configuration(); Config hc = conf.getConfig(HIBERNATE_KEY).atPath(HIBERNATE_KEY); for (Map.Entry<String, ConfigValue> entry : hc.entrySet()) { String key = entry.getKey(); if (key.startsWith(MAPPING_KEY)) { logger.info("Loading hibernate map from " + conf.getString(key)); try { hibernateConf.addResource(conf.getString(key)); } catch (MappingException e) { String msg = "Something wrong with mapping: " + conf.getString(key); throw new UnsupportedOperationException(msg, e); } } else { logger.info("Setting hibernate property: " + key + "=" + conf.getString(key)); hibernateConf.setProperty(key, conf.getString(key)); } } sessionFactory = hibernateConf.buildSessionFactory(); }
/** * Creates a new custom tag mappings object from the given configuration. The keys of the * configuration are well-known tag names, and the values are the custom tag names. * * @param config config holding custom tags * @throws IllegalArgumentException if any configuration value is not a string or is empty */ public CustomTagMappings(Config config) { ImmutableMap.Builder<String, String> b = ImmutableMap.builder(); if (config != null) { for (Map.Entry<String,ConfigValue> e : config.entrySet()) { String key = e.getKey(); ConfigValue value = e.getValue(); switch (value.valueType()) { case STRING: String customTagName = (String) value.unwrapped(); if (customTagName.isEmpty()) { throw new IllegalArgumentException("Tag mapping " + key + " is empty"); } b.put(key, customTagName); break; default: throw new IllegalArgumentException("Tag mapping " + key + " is not a string: " + value); } } } customTagNames = b.build(); }
/** * Creates a new timeouts object from the given configuration. It is * expected that every value in the recursive tree of the configuration is * numeric. Each (recursive) key in the config serves as the key for a * timeout. * * @param config config holding timeouts * @throws IllegalArgumentException if any configuration value is non-numeric */ public AWSTimeouts(Config config) { ImmutableMap.Builder<String, Long> b = ImmutableMap.builder(); if (config != null) { for (Map.Entry<String,ConfigValue> e : config.entrySet()) { String key = e.getKey(); ConfigValue value = e.getValue(); switch (value.valueType()) { case NUMBER: long num =((Number) value.unwrapped()).longValue(); if (num <= 0L) { throw new IllegalArgumentException("Timeout " + key + " is negative: " + value); } b.put(key, num); break; default: throw new IllegalArgumentException("Timeout " + key + " is not a number: " + value); } } } timeouts = b.build(); }
/** * Returns a map view of the data associated with the specified key. If the key corresponds * to a string list, each element of the list will be mapped to itself. If the key corresponds * to a nested configuration, the map will contain those entries of the nested configuration which * have string values (but not, for example, further nested configurations). If the key * corresponds to some other type, throws an exception from the underlying typesafe config * implementation. * * @param config the configuration * @param key the key * @return a map view of the data associated with the specified key */ public static Map<String, String> getStringMap(Config config, String key) { ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); try { for (String value : config.getStringList(key)) { builder.put(value, value); } } catch (ConfigException.WrongType e) { Config nestedConfig = config.getConfig(key); for (Map.Entry<String, ConfigValue> entry : nestedConfig.root().entrySet()) { String nestedKey = entry.getKey(); String quotelessKey = stripQuotes(nestedKey); try { builder.put(quotelessKey, nestedConfig.getString(nestedKey)); } catch (ConfigException.WrongType ignore) { LOG.warn("Ignoring non-string-valued key: '{}'", quotelessKey); } } } return builder.build(); }
public static void main(String[] args) { for (Entry<String, ConfigValue> configSet : U.getConfig().entrySet()) { log.debug("{} is {}", configSet.getKey(), configSet.getValue()); } Runnable time = new Runnable() { @Override public void run() { log.debug("{}", new DateTime()); } }; U.schedule(time, 1, 6); Packet packet=Packet.newBuilder().setCmdId(11).setChatMsgAck(ChatMsgAck.newBuilder().setResult(123)).build(); System.out.println(TextFormat.printToString(packet)); System.out.println(packet.toString()); }
public PagerDutyHandler(Config config) { // Load API key list pipeline_name=api_key Config apiKeyConfig = config.getConfig("pagerduty.pipeline_api_keys"); for (Map.Entry<String, ConfigValue> entry : apiKeyConfig.entrySet()) { pipelineApiKeys.put(entry.getKey(), entry.getValue().unwrapped().toString()); } statusesToAlertOn = config.getStringList("pagerduty.statuses_to_alert"); try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { LOGGER.warn("Unable to discern hostname, using blank hostname"); hostname = ""; } }
/** * Parse the Roles specified in the Config object. * * @param config * @return a map of Name-Role */ protected Map<String, Role> parseDefinedRoles(Config config) { // Parse the defined Roles Map<String, Role> roleMap = new HashMap<>(); if (!config.hasPath("roles")) { log.trace("'{}' has no roles", config); } else if (config.hasPath("roles")) { log.trace("Parsing Role definitions"); Config roleConfig = config.getConfig("roles"); for (Map.Entry<String, ConfigValue> entry : roleConfig.entrySet()) { String name = entry.getKey(); List<String> permissions = roleConfig.getStringList(name); Role role = new Role(name, permissions.toArray(new String[permissions.size()])); roleMap.put(role.getName(), role); } } return Collections.unmodifiableMap(roleMap); }
private void readConfigValue(ConfigValue value, CommentedConfigurationNode node) { if (!value.origin().comments().isEmpty()) { node.setComment(CRLF_MATCH.matcher(Joiner.on('\n').join(value.origin().comments())).replaceAll("")); } switch (value.valueType()) { case OBJECT: if (((ConfigObject) value).isEmpty()) { node.setValue(ImmutableMap.of()); } else { for (Map.Entry<String, ConfigValue> ent : ((ConfigObject) value).entrySet()) { readConfigValue(ent.getValue(), node.getNode(ent.getKey())); } } break; case LIST: List<ConfigValue> values = (ConfigList) value; for (int i = 0; i < values.size(); ++i) { readConfigValue(values.get(i), node.getNode(i)); } break; case NULL: return; default: node.setValue(value.unwrapped()); } }
void parseJson(String jsonString, LogRecord logRecord) { String cleanedJsonString = IngestUtilities.removeUnprintableCharacters(jsonString); Config cfg = ConfigFactory.parseString(cleanedJsonString); for (Map.Entry<String, ConfigValue> entry : cfg.entrySet()) { String key = entry.getKey(); ConfigValue value = entry.getValue(); switch (value.valueType()) { case BOOLEAN: case NUMBER: case OBJECT: case STRING: logRecord.setValue(key, ObjectUtils.toString(value.unwrapped())); break; case LIST: ConfigList list = (ConfigList) value; Gson gson = new Gson(); String json = gson.toJson(list.unwrapped()); logRecord.setValue(key, json); break; case NULL: default: // skip } } }
private Object checkValue(String k, ConfigValue value, ConfigPropertyType<?> t) { Object v = value.unwrapped(); switch (value.valueType()) { case STRING: // allow auto-conversion from string return t.check(k, value.unwrapped(), value.origin()); case NUMBER: if (t.getBaseType() != ConfigPropertyType.INT && t.getBaseType() != ConfigPropertyType.FLOAT) { throw invalidValue(value, k, v, t.getBaseType()); } if (t.getBaseType() == ConfigPropertyType.INT) { Number n = (Number) value.unwrapped(); if (n.intValue() != n.doubleValue()) { throw invalidValue(value, k, v, t.getBaseType()); } } return t.check(k, v, null); case BOOLEAN: if (t.getBaseType() != ConfigPropertyType.BOOLEAN) { throw invalidValue(value, k, v, t.getBaseType()); } return value.unwrapped(); default: return t.check(k, v, value.origin()); } }
/** * Resolves encrypted config value(s) by considering on the path with "encConfigPath" as encrypted. * (If encConfigPath is absent or encConfigPath does not exist in config, config will be just returned untouched.) * It will use Password manager via given config. Thus, convention of PasswordManager need to be followed in order to be decrypted. * Note that "encConfigPath" path will be removed from the config key, leaving child path on the config key. * e.g: * encConfigPath = enc.conf * - Before : { enc.conf.secret_key : ENC(rOF43721f0pZqAXg#63a) } * - After : { secret_key : decrypted_val } * * @param config * @param encConfigPath * @return */ public static Config resolveEncrypted(Config config, Optional<String> encConfigPath) { if (!encConfigPath.isPresent() || !config.hasPath(encConfigPath.get())) { return config; } Config encryptedConfig = config.getConfig(encConfigPath.get()); PasswordManager passwordManager = PasswordManager.getInstance(configToProperties(config)); Map<String, String> tmpMap = Maps.newHashMap(); for (Map.Entry<String, ConfigValue> entry : encryptedConfig.entrySet()) { String val = entry.getValue().unwrapped().toString(); val = passwordManager.readPassword(val); tmpMap.put(entry.getKey(), val); } return ConfigFactory.parseMap(tmpMap).withFallback(config); }
public AzkabanCompactionJobLauncher(String jobId, Properties props) { super(jobId, LOG); this.properties = new Properties(); this.properties.putAll(props); // load dynamic configuration and add them to the job properties Config propsAsConfig = ConfigUtils.propertiesToConfig(props); DynamicConfigGenerator dynamicConfigGenerator = DynamicConfigGeneratorFactory.createDynamicConfigGenerator(propsAsConfig); Config dynamicConfig = dynamicConfigGenerator.generateDynamicConfig(propsAsConfig); // add the dynamic config to the job config for (Map.Entry<String, ConfigValue> entry : dynamicConfig.entrySet()) { this.properties.put(entry.getKey(), entry.getValue().unwrapped().toString()); } this.compactor = getCompactor(getCompactorFactory(), getCompactorListener(getCompactorListenerFactory())); }
@Override public <T extends State> StateStore<T> createStateStore(Config config, Class<T> stateClass) { // Add all job configuration properties so they are picked up by Hadoop Configuration conf = new Configuration(); for (Map.Entry<String, ConfigValue> entry : config.entrySet()) { conf.set(entry.getKey(), entry.getValue().unwrapped().toString()); } try { String stateStoreFsUri = ConfigUtils.getString(config, ConfigurationKeys.STATE_STORE_FS_URI_KEY, ConfigurationKeys.LOCAL_FS_URI); FileSystem stateStoreFs = FileSystem.get(URI.create(stateStoreFsUri), conf); String stateStoreRootDir = config.getString(ConfigurationKeys.STATE_STORE_ROOT_DIR_KEY); return new FsStateStore(stateStoreFs, stateStoreRootDir, stateClass); } catch (IOException e) { throw new RuntimeException("Failed to create FsStateStore with factory", e); } }
/** * 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(); } }
/** * Bind a {@link Config} and make it available for injection. Each property of the config is also * binded it and ready to be injected with {@link javax.inject.Named}. * * @param binder Guice binder. * @param config App config. */ @SuppressWarnings("unchecked") private void bindConfig(final Binder binder, final Config config) { // root nodes traverse(binder, "", config.root()); // terminal nodes for (Entry<String, ConfigValue> entry : config.entrySet()) { String name = entry.getKey(); Named named = Names.named(name); Object value = entry.getValue().unwrapped(); if (value instanceof List) { List<Object> values = (List<Object>) value; Type listType = values.size() == 0 ? String.class : Types.listOf(values.iterator().next().getClass()); Key<Object> key = (Key<Object>) Key.get(listType, Names.named(name)); binder.bind(key).toInstance(values); } else { binder.bindConstant().annotatedWith(named).to(value.toString()); } } // bind config binder.bind(Config.class).toInstance(config); }
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); }
private static ConfigList expandSugarArray(ConfigValue fieldValue, Class<?> elementType, PluginRegistry pluginRegistry, boolean nested) { ConfigList fieldList = (ConfigList) fieldValue; List<Object> newList = new ArrayList<>(fieldList.size()); for (ConfigValue listEntry : fieldList) { ConfigValue listObject; if (nested) { listObject = expandSugarArray(listEntry, elementType, pluginRegistry, false); } else { listObject = expandSugar(elementType, listEntry, pluginRegistry); } newList.add(listObject.unwrapped()); } return ConfigValueFactory.fromIterable(newList, fieldList.origin().description()); }
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"); }
/** * Instantiate an object without a compile time expected type. This expects a config of the * form "{plugin-category: {...}}". ie. there should be exactly one top level key and that * key should be a valid, loaded, plug-in category. */ public <T> T decodeObject(Config config) throws JsonProcessingException, IOException { if (config.root().size() != 1) { throw new ConfigException.Parse(config.root().origin(), "config root must have exactly one key"); } String category = config.root().keySet().iterator().next(); PluginMap pluginMap = pluginRegistry.asMap().get(category); if (pluginMap == null) { throw new ConfigException.BadValue(config.root().get(category).origin(), category, "top level key must be a valid category"); } ConfigValue configValue = config.root().get(category); return (T) decodeObject(pluginMap.baseClass(), configValue); }
private Set<Entry<String, ConfigValue>> buildProperties(BeanDefinitionBuilder beanDefinition) { Set<String> paths = beanDefinitions.keySet(); Set<Entry<String, ConfigValue>> entries = new HashSet<>(); try { for (Entry<String, ConfigValue> entry : config.getConfig(path).root().entrySet()) { String fullPath = path.concat(".").concat(entry.getKey()); if (paths.contains(fullPath)) { beanDefinition.addPropertyReference(entry.getKey(), beanDefinitions.get(fullPath).getId()); } else { entries.add(entry); } } } catch (ConfigException.Missing e) { this.log.debug(format("No configuration found on path %s", path)); } return entries; }
@Override protected Map<String, String> parse(ResourceObject file) throws IOException, ResourceObjectException { Config config = file.parsedTo(parser).asIs(); Map<String, String> result = new HashMap<String, String>(); Set<Entry<String, ConfigValue>> entrySet = config.entrySet(); for (Entry<String, ConfigValue> entry : entrySet) { ConfigValue value = entry.getValue(); switch (value.valueType()) { case BOOLEAN: case NUMBER: case STRING: result.put(entry.getKey(), String.valueOf(value.unwrapped())); break; default: result.put(entry.getKey(), value.render()); } } return result; }
@Override public Config toConfig() { Config config = emptyConfig(); for (String name : names()) { try { Option<? extends ConfigValue> configValue = configValue(jndiContext.lookup(name)); if (configValue.isSome()) { config = config.withValue(name, configValue.get()); } } catch (NamingException ignored) { } } return config; }
Option<? extends ConfigValue> configValue(Object object) { if (object instanceof javax.naming.Context) { javax.naming.Context jndiContext = (javax.naming.Context) object; return some(withJndiContext(jndiContext).toConfig().root()); } if (object instanceof String) { try { return some( ConfigFactory.parseString( String.format("value: %s", (String) object), getParseOptions() ).root().get("value") ); } catch (Exception ignored) { } } return none(); }
public static NormalizeSettings create(Config config) { Config normalize = config.getConfig("model.normalize"); Boolean sparse = normalize.hasPath("sparse") ? normalize.getBoolean("sparse") : null; Transform defaultTransform = Transform.forName(normalize.getString("default-transform")); Function<Object, Integer> lookup = InboundSettings.create(config).getLookupFunction(); Map<Integer, Transform> transforms = Maps.newHashMap(); load(normalize, "z-transform", Transform.Z, lookup, transforms); load(normalize, "log-transform", Transform.LOG, lookup, transforms); load(normalize, "linear-transform", Transform.LINEAR, lookup, transforms); load(normalize, "no-transform", Transform.NONE, lookup, transforms); Map<Integer, Double> scale = Maps.newHashMap(); if (normalize.hasPath("scale")) { Config scaleConfig = normalize.getConfig("scale"); for (Map.Entry<String, ConfigValue> e : scaleConfig.entrySet()) { scale.put(lookup.apply(e.getKey()), scaleConfig.getDouble(e.getKey())); } } return new NormalizeSettings(sparse, defaultTransform, transforms, scale); }
/** * Method called to create a new context for iterating all * contents of the current structured value (JSON array or object) * @return a cursor over the children of this node */ public final HoconNodeCursor iterateChildren() { ConfigValue n = currentNode(); if (n == null) throw new IllegalStateException("No current node"); boolean numericallyIndexed = isNumericallyIndexed(n); if (!numericallyIndexed) { if (isArray(n)) { // false since we have already returned START_ARRAY return new Array(n, this); } if (isObject(n)) { return new Object(n, this); } } else { return new NumericallyIndexedObjectBackedArray(n, this); } throw new IllegalStateException("Current node of type "+n.getClass().getName()); }
@Test public void shouldCreate() throws ExecutionException, InterruptedException { //language=JSON final String json = "{\n" + " \"rkt\": \"/usr/local/bin/rkt\",\n" + " \"daemon\": [\n" + " \"systemd-run\",\n" + " \"--slice=machine\"\n" + " ],\n" + " \"globalOptions\": {\n" + " \"insecureOptions\": [\"image\"]\n" + " }\n" + "}\n"; final Config config = mock(Config.class); final ConfigValue configValue = mock(ConfigValue.class); when(environment.config()).thenReturn(config); when(config.getValue("rktLauncher")).thenReturn(configValue); when(configValue.render(any())).thenReturn(json); final Environment.RoutingEngine routingEngine = mock(Environment.RoutingEngine.class); when(environment.routingEngine()).thenReturn(routingEngine); when(routingEngine.registerAutoRoute(any())).thenAnswer(invocation -> { final Route<AsyncHandler<String>> route = invocation.getArgument(0); assertEquals("pong", route.handler().invoke(null).toCompletableFuture().get()); return routingEngine; }); when(routingEngine.registerRoutes(any())).thenReturn(routingEngine); rktLauncherApi.create(environment); verify(routingEngine).registerAutoRoute(any()); verify(routingEngine, times(2)).registerRoutes(any()); }
private Map<Language, List<DataModelTypePattern>> loadDataModelTypePatterns(Config config) { Map<Language, List<DataModelTypePattern>> rulesByLang = new HashMap<>(); ConfigObject configObject = config.getObject("rules.syntatic-pattern"); configObject.keySet().forEach(strLang -> { Language language = Language.valueOf(strLang.toUpperCase()); rulesByLang.compute(language, (l, r) -> { List<DataModelTypePattern> rules = new ArrayList<>(); List<? extends Config> patternCfg = configObject.toConfig().getConfigList(strLang); for (Config cfg : patternCfg) { Map.Entry<String, ConfigValue> entry = cfg.entrySet().stream().findFirst().orElse(null); String modelStr = entry.getKey(); @SuppressWarnings("unchecked") List<String> patternList = (List<String>) entry.getValue().unwrapped(); rules.addAll(patternList.stream() .map(p -> new DataModelTypePattern(p, DataModelType.valueOf(modelStr))) .collect(Collectors.toList())); } logger.info(marker, "Loaded {} Data Model Type patterns for '{}'", rules.size(), l); return rules; }); }); return rulesByLang; }
public NamespaceProcessor(Config config) { super(config); prefixes = new HashMap<>(); for (Map.Entry<String, ConfigValue> e : getConfig().entrySet()) { prefixes.put((String) e.getValue().unwrapped(), e.getKey() + ":"); } }