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

The following examples show how to use com.typesafe.config.Config#getConfig() . 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: 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 2
Source File: ApplicationConfig.java    From xio with Apache License 2.0 6 votes vote down vote up
public ApplicationConfig(Config config) {
  this.config = config;
  name = config.getString("name");
  bossThreads = config.getInt("settings.bossThreads");
  bossNameFormat = config.getString("settings.bossNameFormat");
  workerThreads = config.getInt("settings.workerThreads");
  workerNameFormat = config.getString("settings.workerNameFormat");
  zookeeperCluster = config.getString("settings.zookeeper.cluster");
  ipFilterPath = config.getString("settings.configurationManager.ipFilter.path");
  http1FilterPath = config.getString("settings.configurationManager.http1Filter.path");
  globalSoftReqPerSec = config.getDouble("settings.global_soft_req_per_sec");
  globalHardReqPerSec = config.getDouble("settings.global_hard_req_per_sec");
  softReqPerSec = config.getDouble("settings.soft_req_per_sec");
  hardReqPerSec = config.getDouble("settings.hard_req_per_sec");
  rateLimiterPoolSize = config.getInt("settings.rate_limiter_pool_size");
  clientPoolSize = config.getInt("clientLimits.clientPoolSize");
  tracingConfig = new TracingConfig(name, config.getConfig("settings.tracing"));
}
 
Example 3
Source File: ReplicationConfiguration.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
public Builder withDataFlowTopologyConfig(Config config) {
  Preconditions.checkArgument(config.hasPath(DATA_FLOW_TOPOLOGY),
      "missing required config entery " + DATA_FLOW_TOPOLOGY);

  this.dataFlowTopologyConfig = config.getConfig(DATA_FLOW_TOPOLOGY);
  return this;
}
 
Example 4
Source File: StreamingStep.java    From envelope with Apache License 2.0 5 votes vote down vote up
private TranslateFunction getTranslateFunction(Config config, boolean configure) {
  if (configure) {
    if (translateFunction == null) {
      StreamInput streamInput = (StreamInput)getInput(true);
      translateFunction = new TranslateFunction(config.getConfig(TRANSLATOR_PROPERTY));

      SchemaNegotiator.negotiate(streamInput, translateFunction);
    }

    return translateFunction;
  }
  else {
    return new TranslateFunction(config.getConfig(TRANSLATOR_PROPERTY));
  }
}
 
Example 5
Source File: HadoopFsEndPointFactory.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Override
public HadoopFsEndPoint buildSource(Config sourceConfig, Config selectionConfig) {
  Preconditions.checkArgument(sourceConfig.hasPath(HADOOP_FS_CONFIG_KEY),
      "missing required config entery " + HADOOP_FS_CONFIG_KEY);

  return new SourceHadoopFsEndPoint(new HadoopFsReplicaConfig(sourceConfig.getConfig(HADOOP_FS_CONFIG_KEY)), selectionConfig);
}
 
Example 6
Source File: ReplicationConfiguration.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
public Builder withReplicationSource(Config config)
    throws InstantiationException, IllegalAccessException, ClassNotFoundException {
  Preconditions.checkArgument(config.hasPath(REPLICATION_SOURCE),
      "missing required config entry " + REPLICATION_SOURCE);

  Config sourceConfig = config.getConfig(REPLICATION_SOURCE);
  String endPointFactory = sourceConfig.hasPath(END_POINT_FACTORY_CLASS)
      ? sourceConfig.getString(END_POINT_FACTORY_CLASS) : DEFAULT_END_POINT_FACTORY_CLASS;

  EndPointFactory factory = endPointFactoryResolver.resolveClass(endPointFactory).newInstance();
  this.source = factory.buildSource(sourceConfig, this.selectionConfig);
  return this;
}
 
Example 7
Source File: AlertEmailPublisher.java    From eagle with Apache License 2.0 5 votes vote down vote up
private Properties parseMailClientConfig(Config config) {
    Properties props = new Properties();
    Config mailConfig = null;
    if (config.hasPath(EAGLE_COORDINATOR_EMAIL_SERVICE)) {
        mailConfig = config.getConfig(EAGLE_COORDINATOR_EMAIL_SERVICE);
    } else if (config.hasPath(EAGLE_APPLICATION_EMAIL_SERVICE)) {
        mailConfig = config.getConfig(EAGLE_APPLICATION_EMAIL_SERVICE);
    }
    String mailSmtpServer = mailConfig.getString(EAGLE_EMAIL_SMTP_SERVER);
    String mailSmtpPort = mailConfig.getString(EAGLE_EMAIL_SMTP_PORT);
    String mailSmtpAuth =  mailConfig.getString(EAGLE_EMAIL_SMTP_AUTH);

    props.put(AlertEmailConstants.CONF_MAIL_HOST, mailSmtpServer);
    props.put(AlertEmailConstants.CONF_MAIL_PORT, mailSmtpPort);
    props.put(AlertEmailConstants.CONF_MAIL_AUTH, mailSmtpAuth);

    if (Boolean.parseBoolean(mailSmtpAuth)) {
        String mailSmtpUsername = mailConfig.getString(EAGLE_EMAIL_SMTP_USERNAME);
        String mailSmtpPassword = mailConfig.getString(EAGLE_EMAIL_SMTP_PASSWORD);
        props.put(AlertEmailConstants.CONF_AUTH_USER, mailSmtpUsername);
        props.put(AlertEmailConstants.CONF_AUTH_PASSWORD, mailSmtpPassword);
    }

    String mailSmtpConn = mailConfig.hasPath(EAGLE_EMAIL_SMTP_CONN) ? mailConfig.getString(EAGLE_EMAIL_SMTP_CONN) : AlertEmailConstants.CONN_PLAINTEXT;
    if (mailSmtpConn.equalsIgnoreCase(AlertEmailConstants.CONN_TLS)) {
        props.put("mail.smtp.starttls.enable", "true");
    }
    if (mailSmtpConn.equalsIgnoreCase(AlertEmailConstants.CONN_SSL)) {
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
    }

    String mailSmtpDebug = mailConfig.hasPath(EAGLE_EMAIL_SMTP_DEBUG) ? mailConfig.getString(EAGLE_EMAIL_SMTP_DEBUG) : "false";
    props.put(AlertEmailConstants.CONF_MAIL_DEBUG, mailSmtpDebug);
    return props;
}
 
Example 8
Source File: DefaultScopedConfig.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private static Config tryToGetAsConfig(final Config originalConfig, final String configPath) {
    try {
        return originalConfig.getConfig(configPath);
    } catch (final ConfigException.Missing | ConfigException.WrongType e) {
        final String msgPattern = "Failed to get nested Config at <{0}>!";
        throw new DittoConfigError(MessageFormat.format(msgPattern, configPath), e);
    }
}
 
Example 9
Source File: HeliosConfig.java    From helios with Apache License 2.0 5 votes vote down vote up
/**
 * Return the requested configuration, or an empty configuration if profile is null.
 *
 * @param profilesPath The path at which profiles are nested.
 * @param profile      The name of the profile to load.
 * @param rootConfig   The config file root to load profiles from.
 */
static Config getProfile(
    final String profilesPath, final String profile, final Config rootConfig) {
  final String key = profilesPath + profile;
  if (rootConfig.hasPath(key)) {
    log.info("Using configuration profile: " + key);
    return rootConfig.getConfig(key);
  }

  throw new RuntimeException("The configuration profile " + profile + " does not exist");
}
 
Example 10
Source File: ConfigMapper.java    From atomix with Apache License 2.0 5 votes vote down vote up
protected Map getMapValue(Class<?> beanClass, Type parameterType, Class<?> parameterClass, Config config, String configPath, String configPropName) {
  Type[] typeArgs = ((ParameterizedType) parameterType).getActualTypeArguments();
  Type keyType = typeArgs[0];
  Type valueType = typeArgs[1];

  Map<Object, Object> map = new HashMap<>();
  Config childConfig = config.getConfig(configPropName);
  Class valueClass = (Class) (valueType instanceof ParameterizedType ? ((ParameterizedType) valueType).getRawType() : valueType);
  for (String key : config.getObject(configPropName).unwrapped().keySet()) {
    Object value = getValue(Map.class, valueType, valueClass, childConfig, toPath(configPath, configPropName), key);
    map.put(getKeyValue(keyType, key), value);
  }
  return map;
}
 
Example 11
Source File: PyCobaltCorefTest.java    From Graphene with GNU General Public License v3.0 5 votes vote down vote up
@BeforeClass
public static void beforeAll() {
	Config config = ConfigFactory
               .load("reference.local")
               .withFallback(ConfigFactory.load("reference"));

	coreference = new PyCobaltCoref(config.getConfig("graphene.coreference.settings"));
}
 
Example 12
Source File: SchemaUtils.java    From envelope with Apache License 2.0 5 votes vote down vote up
public static Set<InstantiatedComponent> getSchemaComponents(Config config,
    boolean configure, String ...schemaConfigPaths) {

  Set<InstantiatedComponent> components = Sets.newHashSet();

  for (String schemaConfigPath : schemaConfigPaths) {
    Config schemaConfig = config.getConfig(schemaConfigPath);
    Schema schema = ComponentFactory.create(Schema.class, schemaConfig, configure);
    components.add(new InstantiatedComponent(
      schema, config.getConfig(schemaConfigPath), schemaConfigPath));
  }

  return components;
}
 
Example 13
Source File: DataFlowTopologyPickerByHadoopFsSource.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Override
public Config getPreferredRoutes(Config allTopologies, EndPoint source) {
  Preconditions.checkArgument(source instanceof HadoopFsEndPoint,
      "source is NOT expectecd class " + HadoopFsEndPoint.class.getCanonicalName());

  HadoopFsEndPoint hadoopFsSource = (HadoopFsEndPoint)source;
  String clusterName = hadoopFsSource.getClusterName();

  Preconditions.checkArgument(allTopologies.hasPath(clusterName),
      "Can not find preferred topology for cluster name " + clusterName);
  return allTopologies.getConfig(clusterName);
}
 
Example 14
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 15
Source File: BungeeChat.java    From BungeeChat2 with GNU General Public License v3.0 4 votes vote down vote up
public void onEnable(boolean prinLoadScreen) {
  Configuration.load();
  PlaceHolderUtil.loadConfigSections();

  PlaceHolders.registerPlaceHolders();

  final Config accountDatabase = Configuration.get().getConfig("AccountDatabase");
  final Config databaseCredentials = accountDatabase.getConfig("credentials");
  final Config connectionProperties = accountDatabase.getConfig("properties");
  final ImmutableMap<String, String> connectionPropertiesMap =
      connectionProperties.entrySet().stream()
          .collect(
              MapUtils.immutableMapCollector(
                  Map.Entry::getKey, entry -> entry.getValue().unwrapped().toString()));

  if (accountDatabase.getBoolean("enabled")) {
    try {
      AccountManager.setAccountStorage(
          new AccountSQLStorage(
              databaseCredentials.getString("ip"),
              databaseCredentials.getInt("port"),
              databaseCredentials.getString("database"),
              databaseCredentials.getString("user"),
              databaseCredentials.getString("password"),
              databaseCredentials.getString("tablePrefix"),
              connectionPropertiesMap));
    } catch (SQLException e) {
      LoggerHelper.error("Could not connect to specified database. Using file storage", e);

      AccountManager.setAccountStorage(new AccountFileStorage());
    }
  } else {
    AccountManager.setAccountStorage(new AccountFileStorage());
  }

  bungeeChatCommand = new BungeeChatCommand();
  bungeecordAccountManager = new BungeecordAccountManager();
  channelTypeCorrectorListener = new ChannelTypeCorrectorListener();
  bungeeChatEventsListener = new BungeeChatEventsListener();
  commandTabCompleteListener = new CommandTabCompleteListener();

  ProxyServer.getInstance().getPluginManager().registerCommand(this, bungeeChatCommand);
  ProxyServer.getInstance().getPluginManager().registerListener(this, bungeecordAccountManager);
  ProxyServer.getInstance()
      .getPluginManager()
      .registerListener(this, channelTypeCorrectorListener);
  ProxyServer.getInstance().getPluginManager().registerListener(this, bungeeChatEventsListener);
  ProxyServer.getInstance().getPluginManager().registerListener(this, commandTabCompleteListener);

  Config prefixDefaults = Configuration.get().getConfig("PrefixSuffixSettings");

  BungeecordModuleManager.registerPluginModules();
  ModuleManager.enableModules();
  HookManager.addHook(storedDataHookName, new StoredDataHook());
  HookManager.addHook(
      defaultHookName,
      new DefaultHook(
          prefixDefaults.getString("defaultPrefix"), prefixDefaults.getString("defaultSuffix")));
  ServerNameUtil.loadAliases();

  // Refresh Cache and cache version
  getLatestVersion(true);

  if (prinLoadScreen) {
    MetricManager.sendMetrics(this);

    loadScreen();
  }

  // Finally initialize BungeeChat command map
  commandTabCompleteListener.updateBungeeChatCommands();
}
 
Example 16
Source File: RouteConfig.java    From xio with Apache License 2.0 4 votes vote down vote up
public static RouteConfig fromConfig(String key, Config config) {
  return new RouteConfig(config.getConfig(key));
}
 
Example 17
Source File: ConfigBeanImpl.java    From mpush with Apache License 2.0 4 votes vote down vote up
private static Object getValue(Class<?> beanClass, Type parameterType, Class<?> parameterClass, Config config,
                               String configPropName) {
    if (parameterClass == Boolean.class || parameterClass == boolean.class) {
        return config.getBoolean(configPropName);
    } else if (parameterClass == Integer.class || parameterClass == int.class) {
        return config.getInt(configPropName);
    } else if (parameterClass == Double.class || parameterClass == double.class) {
        return config.getDouble(configPropName);
    } else if (parameterClass == Long.class || parameterClass == long.class) {
        return config.getLong(configPropName);
    } else if (parameterClass == String.class) {
        return config.getString(configPropName);
    } else if (parameterClass == Duration.class) {
        return config.getDuration(configPropName);
    } else if (parameterClass == ConfigMemorySize.class) {
        return config.getMemorySize(configPropName);
    } else if (parameterClass == Object.class) {
        return config.getAnyRef(configPropName);
    } else if (parameterClass == List.class) {
        return getListValue(beanClass, parameterType, parameterClass, config, configPropName);
    } else if (parameterClass == Map.class) {
        // we could do better here, but right now we don't.
        Type[] typeArgs = ((ParameterizedType) parameterType).getActualTypeArguments();
        if (typeArgs[0] != String.class || typeArgs[1] != Object.class) {
            throw new ConfigException.BadBean("Bean property '" + configPropName + "' of class " + beanClass.getName() + " has unsupported Map<" + typeArgs[0] + "," + typeArgs[1] + ">, only Map<String,Object> is supported right now");
        }
        return config.getObject(configPropName).unwrapped();
    } else if (parameterClass == Config.class) {
        return config.getConfig(configPropName);
    } else if (parameterClass == ConfigObject.class) {
        return config.getObject(configPropName);
    } else if (parameterClass == ConfigValue.class) {
        return config.getValue(configPropName);
    } else if (parameterClass == ConfigList.class) {
        return config.getList(configPropName);
    } else if (hasAtLeastOneBeanProperty(parameterClass)) {
        return createInternal(config.getConfig(configPropName), parameterClass);
    } else {
        throw new ConfigException.BadBean("Bean property " + configPropName + " of class " + beanClass.getName() + " has unsupported type " + parameterType);
    }
}
 
Example 18
Source File: ZookeeperConfig.java    From xio with Apache License 2.0 4 votes vote down vote up
public ZookeeperConfig(Config config) {
  this.membershipPath = config.getString("membershipPath");
  this.retryConfig = new RetryConfig(config.getConfig("retry"));
}
 
Example 19
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 20
Source File: ConfigUtils.java    From incubator-gobblin with Apache License 2.0 3 votes vote down vote up
/**
 * Return {@link Config} value at <code>path</code> if <code>config</code> has path. If not return <code>def</code>
 *
 * @param config in which the path may be present
 * @param path key to look for in the config object
 * @return config value at <code>path</code> if <code>config</code> has path. If not return <code>def</code>
 */
public static Config getConfig(Config config, String path, Config def) {
  if (config.hasPath(path)) {
    return config.getConfig(path);
  }
  return def;
}