com.typesafe.config.ConfigValue Java Examples

The following examples show how to use com.typesafe.config.ConfigValue. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AzkabanCompactionJobLauncher.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
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()));
}
 
Example #2
Source File: QueryOptions.java    From casquatch with Apache License 2.0 6 votes vote down vote up
/**
 * Create QueryOptions from Config object. Used on CasquatchDao initialization
 * @param config populated config object
 */
QueryOptions(Config config) {
    if(log.isTraceEnabled()) {
        log.trace("Creating Query Options From Config");
        for (Map.Entry<String, ConfigValue> entry : config.entrySet()) {
            log.debug("{}: {} -> {}","Query Options",entry.getKey(),entry.getValue().render());
        }
    }
    if(config.hasPath("ignore-non-primary-keys")) this.ignoreNonPrimaryKeys=config.getBoolean("ignore-non-primary-keys");
    if(config.hasPath("consistency")) this.consistency=config.getString("consistency");
    if(config.hasPath("limit")) this.limit=config.getInt("limit");
    if(config.hasPath("persist-nulls")) this.persistNulls=config.getBoolean("persist-nulls");
    if(config.hasPath("profile")) this.profile=config.getString("profile");
    if(config.hasPath("ttl")) this.ttl=config.getInt("ttl");

}
 
Example #3
Source File: LoadTestApplication.java    From casquatch with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

		//Create CasquatchDao from config
		CasquatchDao db=CasquatchDao.builder().build();

		//Load loadtest config
		ConfigFactory.invalidateCaches();
		Config config = ConfigFactory.load().getConfig("loadtest");
		if(log.isTraceEnabled()) {
			for (Map.Entry<String, ConfigValue> entry : config.entrySet()) {
				log.trace("Config: {} -> {}", entry.getKey(), entry.getValue().render());
			}
		}
		LoadTestConfig loadTestConfig = ConfigBeanFactory.create(config,LoadTestConfig.class);

		//Run for each entity
		if(loadTestConfig.getEntities().size()>0) {
			for (Class entity : loadTestConfig.getEntityClasses()) {
				new LoadWrapper<>(entity, db).run(loadTestConfig);
			}
		}
		System.exit(0);
	}
 
Example #4
Source File: DittoService.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private Config appendDittoInfo(final Config config) {
    final String instanceId = InstanceIdentifierSupplier.getInstance().get();

    final ConfigValue service = ConfigFactory.empty()
            .withValue("name", ConfigValueFactory.fromAnyRef(serviceName))
            .withValue("instance-id", ConfigValueFactory.fromAnyRef(instanceId))
            .root();

    final ConfigValue vmArgs =
            ConfigValueFactory.fromIterable(ManagementFactory.getRuntimeMXBean().getInputArguments());

    final ConfigValue env = ConfigValueFactory.fromMap(System.getenv());

    return config.withValue("ditto.info",
            ConfigFactory.empty()
                    .withValue("service", service)
                    .withValue("vm-args", vmArgs)
                    .withValue("env", env)
                    .root());
}
 
Example #5
Source File: FileContextBasedFsStateStoreFactory.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@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 FileContextBasedFsStateStore<T>(stateStoreFs, stateStoreRootDir, stateClass);
  } catch (IOException e) {
    throw new RuntimeException("Failed to create FsStateStore with factory", e);
  }

}
 
Example #6
Source File: AliasesAppender.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @throws java.lang.NullPointerException if {@code vcapConfig} is {@code null}.
 */
@Override
public Config apply(final Config vcapConfig) {
    checkNotNull(vcapConfig, "VCAP config");
    if (systemConfigAliases.isEmpty()) {
        return vcapConfig;
    }

    final Map<String, ConfigValue> aliasesConfigMap = new HashMap<>(systemConfigAliases.size());

    for (final Map.Entry<String, String> systemConfigAlias : systemConfigAliases.entrySet()) {
        final String alias = systemConfigAlias.getKey();
        final String originalKey = systemConfigAlias.getValue();
        @Nullable final ConfigValue originalValue = tryToGetOriginalValueOrNull(vcapConfig, originalKey, alias);
        if (null != originalValue) {
            aliasesConfigMap.put(alias, originalValue);
        }
    }

    return vcapConfig.withFallback(ConfigFactory.parseMap(aliasesConfigMap));
}
 
Example #7
Source File: VcapServicesStringParser.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Config apply(final String systemVcapServices) {
    checkNotNull(systemVcapServices, "system VCAP services string");
    if (systemVcapServices.isEmpty()) {
        return ConfigFactory.empty();
    }

    final Config vcapServicesConfig = tryToParseString(systemVcapServices);
    final Set<Map.Entry<String, ConfigValue>> vcapServicesConfigEntries = vcapServicesConfig.entrySet();

    final Map<String, Object> result = new HashMap<>(vcapServicesConfigEntries.size());
    for (final Map.Entry<String, ConfigValue> serviceConfigEntry : vcapServicesConfigEntries) {
        result.put(serviceConfigEntry.getKey(), convertConfigListToConfigObject(serviceConfigEntry.getValue()));
    }
    return ConfigFactory.parseMap(result);
}
 
Example #8
Source File: BaggageHandlerRegistry.java    From tracingplane-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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));
}
 
Example #9
Source File: Replication.java    From ts-reaktive with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <E> EventClassifier<E> getEventClassifier(Class<E> eventType) {
    return (EventClassifier<E>) classifiers.computeIfAbsent(eventType, t -> {
        ConfigValue value = config.getConfig("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);
        }
    });
}
 
Example #10
Source File: FsStateStoreFactory.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #11
Source File: Config.java    From para with Apache License 2.0 6 votes vote down vote up
/**
 * 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 invalid or missing from classpath.");
		config = com.typesafe.config.ConfigFactory.empty();
	}
}
 
Example #12
Source File: ConfigUtils.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #13
Source File: SwiftConfigSchema.java    From swift-k with Apache License 2.0 6 votes vote down vote up
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());
    }
}
 
Example #14
Source File: VcapServicesStringParser.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private static ConfigObject getAsConfigObject(final ConfigList configList) {
    final Map<String, ConfigValue> flattenedConfigValues = new HashMap<>(configList.size());

    for (int i = 0; i < configList.size(); i++) {
        final ConfigValue configValue = configList.get(i);
        final String configPath;
        if (ConfigValueType.OBJECT == configValue.valueType()) {
            configPath = getName((ConfigObject) configValue);
        } else {
            configPath = String.valueOf(i);
        }
        flattenedConfigValues.put(configPath, configValue);
    }

    return ConfigValueFactory.fromMap(flattenedConfigValues);
}
 
Example #15
Source File: KafkaOutput.java    From envelope with Apache License 2.0 5 votes vote down vote up
private Map<String, ?> getSerializerConfiguration() {
  Map<String, Object> configs = Maps.newHashMap();
  
  for (Map.Entry<String, ConfigValue> entry : config.entrySet()) {
    String propertyName = entry.getKey();
    if (propertyName.startsWith(SERIALIZER_CONFIG_PREFIX)) {
      String paramName = propertyName.substring(SERIALIZER_CONFIG_PREFIX.length());
      String paramValue = config.getString(propertyName);

      configs.put(paramName, paramValue);
    }
  }
  
  return configs;
}
 
Example #16
Source File: ConfigMapper.java    From atomix with Apache License 2.0 5 votes vote down vote up
/**
 * Applies the given configuration to the given type.
 *
 * @param config the configuration to apply
 * @param clazz  the class to which to apply the configuration
 */
@SuppressWarnings("unchecked")
protected <T> T map(Config config, String path, String name, Class<T> clazz) {
  T instance = newInstance(config, name, clazz);

  // Map config property names to bean properties.
  Map<String, String> propertyNames = new HashMap<>();
  for (Map.Entry<String, ConfigValue> configProp : config.root().entrySet()) {
    String originalName = configProp.getKey();
    String camelName = toCamelCase(originalName);
    // if a setting is in there both as some hyphen name and the camel name,
    // the camel one wins
    if (!propertyNames.containsKey(camelName) || originalName.equals(camelName)) {
      propertyNames.put(camelName, originalName);
    }
  }

  // First use setters and then fall back to fields.
  mapSetters(instance, clazz, path, name, propertyNames, config);
  mapFields(instance, clazz, path, name, propertyNames, config);

  // If any properties present in the configuration were not found on config beans, throw an exception.
  if (!propertyNames.isEmpty()) {
    checkRemainingProperties(propertyNames.keySet(), describeProperties(instance), toPath(path, name), clazz);
  }
  return instance;
}
 
Example #17
Source File: ConfigBeanImpl.java    From mpush with Apache License 2.0 5 votes vote down vote up
private static Object getListValue(Class<?> beanClass, Type parameterType, Class<?> parameterClass, Config config, String configPropName) {
    Type elementType = ((ParameterizedType) parameterType).getActualTypeArguments()[0];

    if (elementType == Boolean.class) {
        return config.getBooleanList(configPropName);
    } else if (elementType == Integer.class) {
        return config.getIntList(configPropName);
    } else if (elementType == Double.class) {
        return config.getDoubleList(configPropName);
    } else if (elementType == Long.class) {
        return config.getLongList(configPropName);
    } else if (elementType == String.class) {
        return config.getStringList(configPropName);
    } else if (elementType == Duration.class) {
        return config.getDurationList(configPropName);
    } else if (elementType == ConfigMemorySize.class) {
        return config.getMemorySizeList(configPropName);
    } else if (elementType == Object.class) {
        return config.getAnyRefList(configPropName);
    } else if (elementType == Config.class) {
        return config.getConfigList(configPropName);
    } else if (elementType == ConfigObject.class) {
        return config.getObjectList(configPropName);
    } else if (elementType == ConfigValue.class) {
        return config.getList(configPropName);
    } else {
        throw new ConfigException.BadBean("Bean property '" + configPropName + "' of class " + beanClass.getName() + " has unsupported list element type " + elementType);
    }
}
 
Example #18
Source File: ConfigCenterTest.java    From mpush with Apache License 2.0 5 votes vote down vote up
public static void print(String s, ConfigValue configValue, Map<String, String> map) {
    if (s.startsWith("mp") && !s.endsWith("\"")) {
        String[] keys = s.split("\\.");
        if (keys.length >= 4) return;
        for (int i = keys.length - 1; i > 0; i--) {
            String key = keys[i];
            String value = map.get(key);
            if (value != null) continue;
            String p = keys[i - 1];
            map.put(key, p + "." + key.replace('-', '_') + "(" + p + ")");
        }
    }
}
 
Example #19
Source File: HoconNodeCursor.java    From jackson-dataformat-hocon with Apache License 2.0 5 votes vote down vote up
public NumericallyIndexedObjectBackedArray(ConfigValue n, HoconNodeCursor p) {
    super(JsonStreamContext.TYPE_ARRAY, p);
    TreeMap<Integer, ConfigValue> sortedContents = new TreeMap<Integer, ConfigValue>();
    for (Map.Entry<String, ConfigValue> entry: ((ConfigObject) n).entrySet()) {
        try {
            Integer key = Integer.parseInt(entry.getKey());
            sortedContents.put(key, entry.getValue());
        } catch (NumberFormatException e) {
            throw new IllegalStateException("Key: '" + entry.getKey() +
                    "' in object could not be parsed to an Integer, therefor we cannot be using a " +
                    getClass().getSimpleName());
        }
    }
    _contents = sortedContents.values().iterator();
}
 
Example #20
Source File: HBaseUtils.java    From envelope with Apache License 2.0 5 votes vote down vote up
public static Configuration getHBaseConfiguration(Config config) throws IOException {
  Configuration hbaseConfiguration = HBaseConfiguration.create();
  if (config.hasPath(ZK_QUORUM_PROPERTY)) {
    String zkQuorum = config.getString(ZK_QUORUM_PROPERTY);
    hbaseConfiguration.set(HConstants.ZOOKEEPER_QUORUM, zkQuorum);
  }
  LOG.debug("HBase:: Using ZK quorum: {}", hbaseConfiguration.get(HConstants.ZOOKEEPER_QUORUM));
  LOG.debug("HBase:: Using security: {}", hbaseConfiguration.get("hadoop.security.authentication"));

  // Add any other pass-through options starting with HBASE_PASSTHRU_PREFIX
  if (config.hasPath(HBASE_PASSTHRU_PREFIX)) {
    Config hbaseConfigs = config.getConfig(HBASE_PASSTHRU_PREFIX);
    for (Map.Entry<String, ConfigValue> entry : hbaseConfigs.entrySet()) {
      String param = entry.getKey();
      String value = null;
      switch (entry.getValue().valueType()) {
        case STRING:
          value = (String) entry.getValue().unwrapped();
          break;
        default:
          LOG.warn("Only string parameters currently " +
              "supported, auto-converting to String [{}]", param);
          value = entry.getValue().unwrapped().toString();
      }
      if (value != null) {
        hbaseConfiguration.set(param, value);
      }
    }
  }
  return hbaseConfiguration;
}
 
Example #21
Source File: HoconTreeTraversingParser.java    From jackson-dataformat-hocon with Apache License 2.0 5 votes vote down vote up
@Override
public NumberType getNumberType() throws IOException, JsonParseException {
	ConfigValue n = currentNumericNode();
	if(n == null)
		return null;
	
	Number value = (Number) n.unwrapped();
	if(value instanceof Double) {
		return NumberType.DOUBLE;
	} else if(value instanceof Long) {
		return NumberType.LONG;
	} else {
		return NumberType.INT;
	}
}
 
Example #22
Source File: DremioConfig.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private void check(){
  final Config inner = getInnerConfig();
  final Config ref = reference.resolve();

  // make sure types are right
  inner.checkValid(ref);

  // make sure we don't have any extra paths. these are typically typos.
  List<String> invalidPaths = new ArrayList<>();
  for(Entry<String, ConfigValue> entry : inner.entrySet()){
    if(!ref.hasPath(entry.getKey())){
      invalidPaths.add(entry.getKey());
    }
  }

  if(!invalidPaths.isEmpty()){
    StringBuilder sb = new StringBuilder();
    sb.append("Failure reading configuration file. The following properties were invalid:\n");
    for(String s : invalidPaths){
      sb.append("\t");
      sb.append(s);
      sb.append("\n");
    }

    throw new RuntimeException(sb.toString());
  }
}
 
Example #23
Source File: TemporaryJobs.java    From helios with Apache License 2.0 5 votes vote down vote up
private static List<String> getListByKey(final String key, final Config config) {
  final ConfigList endpointList = config.getList(key);
  final List<String> stringList = Lists.newArrayList();
  for (final ConfigValue v : endpointList) {
    if (v.valueType() != ConfigValueType.STRING) {
      throw new RuntimeException("Item in " + key + " list [" + v + "] is not a string");
    }
    stringList.add((String) v.unwrapped());
  }
  return stringList;
}
 
Example #24
Source File: VcapServicesStringParserTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void getReturnsExpected() {
    // MongoDB config acts as sample.
    final JsonObject expectedMongoDbServiceConfigJsonObject = JsonObject.newBuilder()
            .set("ditto-mongodb-staging", JsonObject.newBuilder()
                    .set("binding_name", JsonValue.nullLiteral())
                    .set("credentials", JsonObject.newBuilder()
                            .set("readonly", false)
                            .set("replicaset", "stretched-0815")
                            .build())
                    .set("instance_name", "ditto-mongodb-staging")
                    .set("label", "MongoDB-Service")
                    .set("name", "ditto-mongodb-staging")
                    .set("plan", "Database on Dedicated Replica Set - Stretched")
                    .set("provider", JsonValue.nullLiteral())
                    .set("syslog_drain_url", JsonValue.nullLiteral())
                    .set("tags", JsonArray.newBuilder()
                            .add("mongodb", "mongo", "database", "db", "mongoose")
                            .build())
                    .set("volume_mounts", JsonArray.empty())
                    .build())
            .build();

    final ConfigValue expectedMongoDbServiceConfig =
            ConfigFactory.parseString(expectedMongoDbServiceConfigJsonObject.toString()).root();

    final Config actual = underTest.apply(knownSystemVcapServicesString);

    assertThat(actual.getValue("MongoDB-Service")).isEqualTo(expectedMongoDbServiceConfig);
}
 
Example #25
Source File: SparkNameFunction.java    From spectator with Apache License 2.0 5 votes vote down vote up
private static SparkNameFunction fromPatternList(List<? extends Config> patterns, Registry registry) {
  final List<NameMatcher> matchers = new ArrayList<>();
  for (Config config : patterns) {
    final Pattern pattern = Pattern.compile(config.getString("pattern"));
    final Map<String, Integer> tagsMap = new LinkedHashMap<>();
    final Config tagsCfg = config.getConfig("tags");
    for (Map.Entry<String, ConfigValue> entry : tagsCfg.entrySet()) {
      tagsMap.put(entry.getKey(), (Integer) entry.getValue().unwrapped());
    }
    matchers.add(new NameMatcher(pattern, registry, config.getInt("name"), tagsMap));
  }
  return new SparkNameFunction(matchers);
}
 
Example #26
Source File: DrillConfigIterator.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public OptionValue next() {
  final Entry<String, ConfigValue> e = entries.next();
  final ConfigValue cv = e.getValue();
  final String name = e.getKey();
  OptionValue optionValue = null;
  switch(cv.valueType()) {
  case BOOLEAN:
    optionValue = OptionValue.create(AccessibleScopes.BOOT, name, (Boolean) cv.unwrapped(), OptionScope.BOOT);
    break;

  case LIST:
  case OBJECT:
  case STRING:
    optionValue = OptionValue.create(AccessibleScopes.BOOT, name, cv.render(),OptionScope.BOOT);
    break;

  case NUMBER:
    optionValue = OptionValue.create(OptionValue.AccessibleScopes.BOOT, name, ((Number) cv.unwrapped()).longValue(),OptionScope.BOOT);
    break;

  case NULL:
    throw new IllegalStateException("Config value \"" + name + "\" has NULL type");

  default:
    throw new IllegalStateException("Unknown type: " + cv.valueType());
  }

  return optionValue;
}
 
Example #27
Source File: BaseMessageTemplates.java    From UHC with MIT License 5 votes vote down vote up
@Override
public List<String> getRawStrings(String path) {
    final ConfigValue value = config.getValue(path);

    if (value.valueType() == ConfigValueType.LIST) {
        return config.getStringList(path);
    }

    return Lists.newArrayList(config.getString(path));
}
 
Example #28
Source File: TypesafeConfigModule.java    From typesafeconfig-guice with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #29
Source File: AliasesAppender.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Nullable
private static ConfigValue tryToGetOriginalValueOrNull(final Config vcapConfig, final String originalKey,
        final String alias) {

    try {
        return getOriginalValueOrNull(vcapConfig, originalKey);
    } catch (final ConfigException e) {
        LOGGER.warn("Failed to retrieve value for creating alias {} -> {}!", originalKey, alias, e);
        return null;
    }
}
 
Example #30
Source File: Configuration.java    From NOVA-Core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void addComment(ConfigValue val, String comment) {
	if (abstractConfigValueClass.isInstance(val) && originField != null && appendComments != null) {
		try {
			Object newOrigin = appendComments.invoke(val.origin(), Collections.singletonList(comment));
			originField.set(val, newOrigin);
		} catch (InvocationTargetException | IllegalAccessException e) {
			e.printStackTrace();
		}
	}
}