Java Code Examples for com.typesafe.config.Config#getStringList()

The following examples show how to use com.typesafe.config.Config#getStringList() . 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: ZooKeeperOutput.java    From envelope with Apache License 2.0 6 votes vote down vote up
@Override
public void configure(Config config) {
  String connectionString = config.getString(ZooKeeperConnection.CONNECTION_CONFIG);
  keyFieldNames = config.getStringList(KEY_FIELD_NAMES_CONFIG);
  schema = ComponentFactory.create(Schema.class, config.getConfig(SCHEMA_CONFIG), true).getSchema();
  
  if (config.hasPath(ZNODE_PREFIX_CONFIG)) {
    znodePrefix = config.getString(ZNODE_PREFIX_CONFIG);
  }
  else {
    znodePrefix = DEFAULT_ZNODE_PREFIX;
  }

  connection = new ZooKeeperConnection(connectionString);

  if (config.hasPath(SESSION_TIMEOUT_MS_CONFIG)) {
    connection.setSessionTimeoutMs(config.getInt(SESSION_TIMEOUT_MS_CONFIG));
  }
  if (config.hasPath(CONNECTION_TIMEOUT_MS_CONFIG)) {
    connection.setConnectionTimeoutMs(config.getInt(CONNECTION_TIMEOUT_MS_CONFIG));
  }
}
 
Example 2
Source File: CliConfig.java    From helios with Apache License 2.0 6 votes vote down vote up
public static CliConfig fromConfig(final Config config) {
  checkNotNull(config);
  final Map<String, Object> defaultSettings = ImmutableMap.of(
      DOMAINS_KEY, EMPTY_STRING_LIST,
      SRV_NAME_KEY, "helios",
      MASTER_ENDPOINTS_KEY, EMPTY_STRING_LIST
  );
  final Config configWithDefaults = config.withFallback(ConfigFactory.parseMap(defaultSettings));
  final List<String> domains = configWithDefaults.getStringList(DOMAINS_KEY);
  final String srvName = configWithDefaults.getString(SRV_NAME_KEY);
  final List<URI> masterEndpoints = Lists.newArrayList();
  for (final String endpoint : configWithDefaults.getStringList(MASTER_ENDPOINTS_KEY)) {
    masterEndpoints.add(URI.create(endpoint));
  }
  return new CliConfig(domains, srvName, masterEndpoints);
}
 
Example 3
Source File: FlatSchemaValidation.java    From envelope with Apache License 2.0 6 votes vote down vote up
@Override
public ValidationResult validate(Config config) {
  try {
    List<String> names = config.getStringList(this.namesPath);
    List<String> types = config.getStringList(this.typesPath);
    List<StructField> fields = Lists.newArrayList();

    for (int fieldNum = 0; fieldNum < names.size(); fieldNum++) {
      fields.add(DataTypes.createStructField(names.get(fieldNum),
        ConfigurationDataTypes.getSparkDataType(types.get(fieldNum)), true));
    }
    DataTypes.createStructType(fields);
  }
  catch (Exception e) {
    return new ValidationResult(this, Validity.INVALID, "Flat schema configuration is invalid");
  }

  return new ValidationResult(this, Validity.VALID, "Flat schema configuration is valid");
}
 
Example 4
Source File: DataParams.java    From ytk-learn with MIT License 6 votes vote down vote up
public DataParams(Config config, String prefix) {
    train = new Train(config, prefix + KEY);
    test = new Test(config, prefix + KEY);
    delim = new Delim(config, prefix + KEY);
    y_sampling = config.getStringList(prefix + KEY + "y_sampling");

    assigned = config.getBoolean(prefix + KEY + "assigned");
    unassigned_mode = UnassignedMode.getMode(config.getString(prefix + KEY + "unassigned_mode"));

    for (String s : y_sampling) {
        CheckUtils.check(s.matches("\\d+@(-?\\d+)(\\.\\d+)?"),
                "%sy_sampling:%s must be the format of labelindex@rate. e.g 0@#0.1",
                prefix + KEY, s);
    }

    CheckUtils.check(unassigned_mode != UnassignedMode.UNKNOWN,
            "unknown %sunassigned_mode:%s, only support:%s",
            prefix + KEY, unassigned_mode.toString(), UnassignedMode.allToString());

}
 
Example 5
Source File: ReplicationConfiguration.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
public Builder withReplicationReplica(Config config)
    throws InstantiationException, IllegalAccessException, ClassNotFoundException {
  Preconditions.checkArgument(config.hasPath(REPLICATION_REPLICAS),
      "missing required config entery " + REPLICATION_REPLICAS);

  Config replicasConfig = config.getConfig(REPLICATION_REPLICAS);
  Preconditions.checkArgument(replicasConfig.hasPath(REPLICATOIN_REPLICAS_LIST),
      "missing required config entery " + REPLICATOIN_REPLICAS_LIST);
  List<String> replicaNames = replicasConfig.getStringList(REPLICATOIN_REPLICAS_LIST);

  for (String replicaName : replicaNames) {
    Preconditions.checkArgument(replicasConfig.hasPath(replicaName), "missing replica name " + replicaName);
    Config subConfig = replicasConfig.getConfig(replicaName);

    // each replica could have own EndPointFactory resolver
    String endPointFactory = subConfig.hasPath(END_POINT_FACTORY_CLASS)
        ? subConfig.getString(END_POINT_FACTORY_CLASS) : DEFAULT_END_POINT_FACTORY_CLASS;
    EndPointFactory factory = endPointFactoryResolver.resolveClass(endPointFactory).newInstance();
    this.replicas.add(factory.buildReplica(subConfig, replicaName, this.selectionConfig));
  }
  return this;
}
 
Example 6
Source File: UserProfileActor.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
public void validateProfileVisibilityFields(
    List<String> fieldList, String fieldTypeKey, ActorRef actorRef) {
  String conflictingFieldTypeKey =
      JsonKey.PUBLIC_FIELDS.equalsIgnoreCase(fieldTypeKey) ? JsonKey.PRIVATE : JsonKey.PUBLIC;

  Config userProfileConfig = Util.getUserProfileConfig(actorRef);

  List<String> fields = userProfileConfig.getStringList(fieldTypeKey);
  List<String> fieldsCopy = new ArrayList<String>(fields);
  fieldsCopy.retainAll(fieldList);

  if (!fieldsCopy.isEmpty()) {
    ProjectCommonException.throwClientErrorException(
        ResponseCode.invalidParameterValue,
        ProjectUtil.formatMessage(
            ResponseCode.invalidParameterValue.getErrorMessage(),
            fieldsCopy.toString(),
            StringFormatter.joinByDot(JsonKey.PROFILE_VISIBILITY, conflictingFieldTypeKey)));
  }
}
 
Example 7
Source File: MessagesService.java    From BungeeChat2 with GNU General Public License v3.0 5 votes vote down vote up
public static Predicate<BungeeChatAccount> getServerListPredicate(Config section) {
  if (!section.getBoolean("enabled")) return account -> true;
  else {
    // TODO: Use wildcard string
    List<String> allowedServers = section.getStringList("list");

    return account -> allowedServers.contains(account.getServerName());
  }
}
 
Example 8
Source File: SigningSignatureHandler.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
/**
 * @param factory A {@link WaveSignerFactory}.
 * @param config the configuration.
 */
@Inject
public SigningSignatureHandlerProvider(WaveSignerFactory factory, Config config) {
  this.privateKey = config.getString("federation.certificate_private_key");
  this.certs = config.getStringList("federation.certificate_files");
  this.certDomain = config.getString("federation.certificate_domain");
  this.waveSignerFactory = factory;
}
 
Example 9
Source File: HiveOutput.java    From envelope with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(Config config) {
  tableName = config.getString(TABLE_CONFIG);

  if (config.hasPath(PARTITION_BY_CONFIG)) {
    List<String> colNames = config.getStringList(PARTITION_BY_CONFIG);
    partitionColumns = colNames.toArray(new String[0]);
  }

  doesAlignColumns = ConfigUtils.getOrElse(config, ALIGN_COLUMNS_CONFIG, false);

  if (config.hasPath(LOCATION_CONFIG) || config.hasPath(OPTIONS_CONFIG)) {
    options = new ConfigUtils.OptionMap(config);

    if (config.hasPath(LOCATION_CONFIG)) {
      options.resolve("path", LOCATION_CONFIG);
    }

    if (config.hasPath(OPTIONS_CONFIG)) {
      Config optionsConfig = config.getConfig(OPTIONS_CONFIG);
      for (Map.Entry<String, ConfigValue> entry : optionsConfig.entrySet()) {
        String param = entry.getKey();
        String value = entry.getValue().unwrapped().toString();
        if (value != null) {
          options.put(param, value);
        }
      }
    }
  }
}
 
Example 10
Source File: Util.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
private static void validateUserProfileConfig(Config userProfileConfig) {
  if (CollectionUtils.isEmpty(userProfileConfig.getStringList(JsonKey.FIELDS))) {
    ProjectLogger.log(
        "Util:validateUserProfileConfig: User profile fields is not configured.",
        LoggerEnum.ERROR.name());
    ProjectCommonException.throwServerErrorException(ResponseCode.invaidConfiguration, "");
  }
  List<String> publicFields = null;
  List<String> privateFields = null;
  try {
    publicFields = userProfileConfig.getStringList(JsonKey.PUBLIC_FIELDS);
    privateFields = userProfileConfig.getStringList(JsonKey.PRIVATE_FIELDS);
  } catch (Exception e) {
    ProjectLogger.log(
        "Util:validateUserProfileConfig: Invalid configuration for public / private fields.",
        LoggerEnum.ERROR.name());
  }

  if (CollectionUtils.isNotEmpty(privateFields) && CollectionUtils.isNotEmpty(publicFields)) {
    for (String field : publicFields) {
      if (privateFields.contains(field)) {
        ProjectLogger.log(
            "Field "
                + field
                + " in user configuration is conflicting in publicFields and privateFields.",
            LoggerEnum.ERROR.name());
        ProjectCommonException.throwServerErrorException(
            ResponseCode.errorConflictingFieldConfiguration,
            ProjectUtil.formatMessage(
                ResponseCode.errorConflictingFieldConfiguration.getErrorMessage(),
                field,
                JsonKey.USER,
                JsonKey.PUBLIC_FIELDS,
                JsonKey.PRIVATE_FIELDS));
      }
    }
  }
}
 
Example 11
Source File: SelectDeriver.java    From envelope with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(Config config) {
  if (config.hasPath(STEP_NAME_CONFIG)) {
    stepName = config.getString(STEP_NAME_CONFIG);
  }

  if (config.hasPath(INCLUDE_FIELDS)) {
    includeFields = config.getStringList(INCLUDE_FIELDS);
    useIncludeFields = true;
  }
  else {
    excludeFields = config.getStringList(EXCLUDE_FIELDS);
    useIncludeFields = false;
  }
}
 
Example 12
Source File: Args.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void initBackupProperty(Config config) {
    INSTANCE.backupPriority = config.hasPath("node.backup.priority")
            ? config.getInt("node.backup.priority") : 0;
    INSTANCE.backupPort = config.hasPath("node.backup.port")
            ? config.getInt("node.backup.port") : 5555;
    INSTANCE.backupMembers = config.hasPath("node.backup.members")
            ? config.getStringList("node.backup.members") : new ArrayList<>();
}
 
Example 13
Source File: TlsConfig.java    From xio with Apache License 2.0 5 votes vote down vote up
private static ApplicationProtocolConfig buildAlpnConfig(Config config) {
  ApplicationProtocolConfig.Protocol protocol =
      config.getEnum(ApplicationProtocolConfig.Protocol.class, "protocol");
  ApplicationProtocolConfig.SelectorFailureBehavior selectorBehavior =
      config.getEnum(ApplicationProtocolConfig.SelectorFailureBehavior.class, "selectorBehavior");
  ApplicationProtocolConfig.SelectedListenerFailureBehavior selectedBehavior =
      config.getEnum(
          ApplicationProtocolConfig.SelectedListenerFailureBehavior.class, "selectedBehavior");
  List<String> supportedProtocols = config.getStringList("supportedProtocols");
  return new ApplicationProtocolConfig(
      protocol, selectorBehavior, selectedBehavior, supportedProtocols);
}
 
Example 14
Source File: Openscoring.java    From openscoring with GNU Affero General Public License v3.0 4 votes vote down vote up
static
private LoadingModelEvaluatorBuilder createLoadingModelEvaluatorBuilder(Config config){
	Config modelEvaluatorBuilderConfig = config.getConfig("modelEvaluatorBuilder");

	LoadingModelEvaluatorBuilder modelEvaluatorBuilder = new LoadingModelEvaluatorBuilder();

	Class<? extends ModelEvaluatorFactory> modelEvaluatorFactoryClazz = loadClass(ModelEvaluatorFactory.class, modelEvaluatorBuilderConfig);
	modelEvaluatorBuilder.setModelEvaluatorFactory(newInstance(modelEvaluatorFactoryClazz));

	Class<? extends ValueFactoryFactory> valueFactoryFactoryClazz = loadClass(ValueFactoryFactory.class, modelEvaluatorBuilderConfig);
	modelEvaluatorBuilder.setValueFactoryFactory(newInstance(valueFactoryFactoryClazz));

	modelEvaluatorBuilder.setOutputFilter(OutputFilters.KEEP_FINAL_RESULTS);

	// Jackson does not support the JSON serialization of <code>null</code> map keys
	ResultMapper resultMapper = new ResultMapper(){

		private FieldName defaultTargetName = FieldName.create(ModelResponse.DEFAULT_TARGET_NAME);


		@Override
		public FieldName apply(FieldName name){

			// A "phantom" default target field
			if(name == null){
				return this.defaultTargetName;
			}

			return name;
		}
	};

	modelEvaluatorBuilder.setResultMapper(resultMapper);

	boolean validate = modelEvaluatorBuilderConfig.getBoolean("validate");

	if(validate){
		Schema schema;

		try {
			schema = JAXBUtil.getSchema();
		} catch(SAXException | IOException e){
			throw new RuntimeException(e);
		}

		modelEvaluatorBuilder
			.setSchema(schema)
			.setValidationEventHandler(new SimpleValidationEventHandler());
	}

	boolean locatable = modelEvaluatorBuilderConfig.getBoolean("locatable");

	modelEvaluatorBuilder.setLocatable(locatable);

	VisitorBattery visitors = new VisitorBattery();

	List<String> visitorClassNames = modelEvaluatorBuilderConfig.getStringList("visitorClasses");
	for(String visitorClassName : visitorClassNames){
		Class<?> clazz = loadClass(Object.class, visitorClassName);

		if((Visitor.class).isAssignableFrom(clazz)){
			Class<? extends Visitor> visitorClazz = clazz.asSubclass(Visitor.class);

			visitors.add(visitorClazz);
		} else

		if((VisitorBattery.class).isAssignableFrom(clazz)){
			Class<? extends VisitorBattery> visitorBatteryClazz = clazz.asSubclass(VisitorBattery.class);

			VisitorBattery visitorBattery = newInstance(visitorBatteryClazz);

			visitors.addAll(visitorBattery);
		} else

		{
			throw new IllegalArgumentException(new ClassCastException(clazz.toString()));
		}
	}

	modelEvaluatorBuilder.setVisitors(visitors);

	return modelEvaluatorBuilder;
}
 
Example 15
Source File: TypesafeConfigExamples.java    From StubbornJava with MIT License 4 votes vote down vote up
public static void main(String[] args) {
    // {{start:resource}}
    Config defaultConfig = ConfigFactory.parseResources("defaults.conf");
    // {{end:resource}}

    // {{start:fallback}}
    Config fallbackConfig = ConfigFactory.parseResources("overrides.conf")
                                         .withFallback(defaultConfig)
                                         .resolve();
    // {{end:fallback}}

    // {{start:text}}
    log.info("name: {}", defaultConfig.getString("conf.name"));
    log.info("name: {}", fallbackConfig.getString("conf.name"));
    log.info("title: {}", defaultConfig.getString("conf.title"));
    log.info("title: {}", fallbackConfig.getString("conf.title"));
    // {{end:text}}

    // {{start:resolved}}
    log.info("combined: {}", fallbackConfig.getString("conf.combined"));
    // {{end:resolved}}

    // {{start:durations}}
    log.info("redis.ttl minutes: {}", fallbackConfig.getDuration("redis.ttl", TimeUnit.MINUTES));
    log.info("redis.ttl seconds: {}", fallbackConfig.getDuration("redis.ttl", TimeUnit.SECONDS));
    // {{end:durations}}

    // {{start:memorySize}}
    // Any path in the configuration can be treated as a separate Config object.
    Config uploadService = fallbackConfig.getConfig("uploadService");
    log.info("maxChunkSize bytes: {}", uploadService.getMemorySize("maxChunkSize").toBytes());
    log.info("maxFileSize bytes: {}", uploadService.getMemorySize("maxFileSize").toBytes());
    // {{end:memorySize}}

    // {{start:whitelist}}
    List<Integer> whiteList = fallbackConfig.getIntList("conf.nested.whitelistIds");
    log.info("whitelist: {}", whiteList);
    List<String> whiteListStrings = fallbackConfig.getStringList("conf.nested.whitelistIds");
    log.info("whitelist as Strings: {}", whiteListStrings);
    // {{end:whitelist}}


    // {{start:booleans}}
    log.info("yes: {}", fallbackConfig.getBoolean("featureFlags.featureA"));
    log.info("true: {}", fallbackConfig.getBoolean("featureFlags.featureB"));
    // {{end:booleans}}
}
 
Example 16
Source File: AbstractBaseRobotAgent.java    From incubator-retired-wave with Apache License 2.0 4 votes vote down vote up
@Inject
ServerFrontendAddressHolder(Config config) {
  this.addresses = config.getStringList("core.http_frontend_addresses");
}
 
Example 17
Source File: TradingSystem.java    From parity with Apache License 2.0 4 votes vote down vote up
private static void main(Config config) throws IOException {
    MarketData marketData = marketData(config);

    MarketReporting marketReporting = marketReporting(config);

    List<String> instruments = config.getStringList("instruments");

    OrderBooks books = new OrderBooks(instruments, marketData, marketReporting);

    OrderEntry orderEntry = orderEntry(config, books);

    marketData.version();
    marketReporting.version();

    new Events(marketData, marketReporting, orderEntry).run();
}
 
Example 18
Source File: AppConfig.java    From turbo-rpc with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
private static AppConfig parse(Config config)
		throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
		NoSuchMethodException, SecurityException, ClassNotFoundException {

	String group = getStringOrElse(config, "group", TurboService.DEFAULT_GROUP);
	String app = getStringOrElse(config, "app", TurboService.DEFAULT_GROUP);
	int globalTimeout = getIntOrElse(config, "globalTimeout", 0);
	int maxRequestWait = getIntOrElse(config, "maxRequestWait", 10000);
	int connectPerServer = getIntOrElse(config, "connectPerServer", 1);
	int serverErrorThreshold = getIntOrElse(config, "serverErrorThreshold", 16);
	int connectErrorThreshold = getIntOrElse(config, "connectErrorThreshold",
			2 * serverErrorThreshold / connectPerServer);

	String serializerClass = config.getString("serializer.class");

	String loadBalanceFactoryClass = getStringOrElse(config, "loadBalanceFactory.class",
			RoundRobinLoadBalanceFactory.class.getName());

	LoadBalanceFactory loadBalanceFactory = (LoadBalanceFactory) Class//
			.forName(loadBalanceFactoryClass)//
			.getDeclaredConstructor()//
			.newInstance();

	String discoverClass = getStringOrElse(config, "discover.class", DirectConnectDiscover.class.getName());
	List<String> discoverAddressList = config.getStringList("discover.address");

	Discover discover = (Discover) Class//
			.forName(discoverClass)//
			.getDeclaredConstructor()//
			.newInstance();

	List<HostPort> hostPorts = discoverAddressList//
			.stream()//
			.map(str -> new HostPort(str))//
			.collect(Collectors.toList());

	discover.init(hostPorts);

	AppConfig appConfig = new AppConfig();
	appConfig.setGroup(group);
	appConfig.setApp(app);
	appConfig.setSerializer(serializerClass);
	appConfig.setGlobalTimeout(globalTimeout);
	appConfig.setMaxRequestWait(maxRequestWait);
	appConfig.setConnectPerServer(connectPerServer);
	appConfig.setServerErrorThreshold(serverErrorThreshold);
	appConfig.setConnectErrorThreshold(connectErrorThreshold);
	appConfig.setLoadBalanceFactory(loadBalanceFactory);
	appConfig.setDiscover(discover);

	return appConfig;
}
 
Example 19
Source File: DispatcherActor.java    From Nickle-Scheduler with Apache License 2.0 4 votes vote down vote up
/**
 * 初始化master str列表
 */
private void initMasterList() {
    Config config = getContext().getSystem().settings().config();
    masterList = config.getStringList("remote.actor.path");
}
 
Example 20
Source File: ConfigUtils.java    From oryx with Apache License 2.0 2 votes vote down vote up
/**
 * @param config configuration to query for value
 * @param key configuration path key
 * @return value for given key, or {@code null} if none exists
 */
public static List<String> getOptionalStringList(Config config, String key) {
  return config.hasPath(key) ? config.getStringList(key) : null;
}