Java Code Examples for com.typesafe.config.Config

The following are top voted examples for showing how to use com.typesafe.config.Config. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ytk-learn   File: RandomParamsUtils.java   View source code 6 votes vote down vote up
public static void main(String []args) {
    Config config = ConfigFactory.parseFile(new File("config/model/fm.conf"));
    RandomParams randomParams = new RandomParams(config, "");
    RandomParamsUtils randomParamsUtils = new RandomParamsUtils(randomParams);

    System.out.println("normal sample:");
    for (int i = 0; i < 50; i++) {
        System.out.println(randomParamsUtils.next());
    }

    System.out.println("uniform sample:");
    for (int i = 0; i < 50000; i++) {
        double r = randomParamsUtils.next();
        if (r < -0.01 || r > 0.01) {
            System.out.println("error");
            break;
        }
    }
}
 
Example 2
Project: obevo   File: ParamReader.java   View source code 6 votes vote down vote up
private static ListIterable<IntToObjectFunction<DbDeployerAppContext>> getAppContext(final Config config) {
    final String sourcePath = config.getString("sourcePath");
    String env = getStringOptional(config, "env");

    final String[] envArgs = env != null ? env.split(",") : new String[] { null };
    final String username = getStringOptional(config, "username");
    final String password = getStringOptional(config, "password");
    return ArrayAdapter.adapt(envArgs).collect(new Function<String, IntToObjectFunction<DbDeployerAppContext>>() {
        @Override
        public IntToObjectFunction<DbDeployerAppContext> valueOf(final String envArg) {
            return new IntToObjectFunction<DbDeployerAppContext>() {
                @Override
                public DbDeployerAppContext valueOf(int stepNumber) {
                    String stepSourcePath = replaceStepNumber(sourcePath, stepNumber, config);

                    DbEnvironment dbEnvironment = DbEnvironmentFactory.getInstance().readOneFromSourcePath(stepSourcePath, envArg != null ? new String[] {envArg} : new String[0]);
                    if (username != null && password != null) {
                        return dbEnvironment.buildAppContext(username, password);
                    } else {
                        return dbEnvironment.buildAppContext();
                    }
                }
            };
        }
    });
}
 
Example 3
Project: oryx2   File: MLUpdate.java   View source code 6 votes vote down vote up
protected MLUpdate(Config config) {
  this.testFraction = config.getDouble("oryx.ml.eval.test-fraction");
  int candidates = config.getInt("oryx.ml.eval.candidates");
  this.evalParallelism = config.getInt("oryx.ml.eval.parallelism");
  this.threshold = ConfigUtils.getOptionalDouble(config, "oryx.ml.eval.threshold");
  this.maxMessageSize = config.getInt("oryx.update-topic.message.max-size");
  Preconditions.checkArgument(testFraction >= 0.0 && testFraction <= 1.0);
  Preconditions.checkArgument(candidates > 0);
  Preconditions.checkArgument(evalParallelism > 0);
  Preconditions.checkArgument(maxMessageSize > 0);
  if (testFraction == 0.0) {
    if (candidates > 1) {
      log.info("Eval is disabled (test fraction = 0) so candidates is overridden to 1");
      candidates = 1;
    }
  }
  this.candidates = candidates;
  this.hyperParamSearch = config.getString("oryx.ml.eval.hyperparam-search");
}
 
Example 4
Project: tscfg-docgen   File: PathMatcherConfigProvider.java   View source code 6 votes vote down vote up
@Override
public Config getConfig() throws IOException {
  PathMatcher pathMatcher;

  try {
    pathMatcher = FileSystems.getDefault().getPathMatcher(inputFilePattern);
  } catch (IllegalArgumentException e) {
    throw new IllegalArgumentException(
        "Invalid input file pattern: " + inputFilePattern);
  }

  try (Stream<Path> pathStream = Files.walk(baseDirectory)) {
    return pathStream
        .filter(p -> Files.isRegularFile(p) && pathMatcher.matches(p))
        .map(p -> ConfigFactory.parseFile(p.toFile()))
        .reduce(ConfigFactory.empty(), Config::withFallback)
        .resolve(
            ConfigResolveOptions.defaults()
                .setAllowUnresolved(true)
                .setUseSystemEnvironment(false)
        );
  }
}
 
Example 5
Project: StubbornJava   File: ConnectionPool.java   View source code 6 votes vote down vote up
public static HikariDataSource getDataSourceFromConfig(
    Config conf
    , MetricRegistry metricRegistry
    , HealthCheckRegistry healthCheckRegistry) {

    HikariConfig jdbcConfig = new HikariConfig();
    jdbcConfig.setPoolName(conf.getString("poolName"));
    jdbcConfig.setMaximumPoolSize(conf.getInt("maximumPoolSize"));
    jdbcConfig.setMinimumIdle(conf.getInt("minimumIdle"));
    jdbcConfig.setJdbcUrl(conf.getString("jdbcUrl"));
    jdbcConfig.setUsername(conf.getString("username"));
    jdbcConfig.setPassword(conf.getString("password"));

    jdbcConfig.addDataSourceProperty("cachePrepStmts", conf.getBoolean("cachePrepStmts"));
    jdbcConfig.addDataSourceProperty("prepStmtCacheSize", conf.getInt("prepStmtCacheSize"));
    jdbcConfig.addDataSourceProperty("prepStmtCacheSqlLimit", conf.getInt("prepStmtCacheSqlLimit"));
    jdbcConfig.addDataSourceProperty("useServerPrepStmts", conf.getBoolean("useServerPrepStmts"));

    // Add HealthCheck
    jdbcConfig.setHealthCheckRegistry(healthCheckRegistry);

    // Add Metrics
    jdbcConfig.setMetricRegistry(metricRegistry);
    return new HikariDataSource(jdbcConfig);
}
 
Example 6
Project: Re-Collector   File: ConfigurationRegistry.java   View source code 6 votes vote down vote up
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()));
        }
    }
}
 
Example 7
Project: Re-Collector   File: ConfigurationRegistry.java   View source code 6 votes vote down vote up
private void buildInputs(final Config inputConfigs) {
    final Map<String, InputConfiguration.Factory<? extends InputConfiguration>> factories = ConfigurationRegistry.this.inputConfigFactories;

    dispatchConfig(inputConfigs, (type, id, config) -> {
        if (factories.containsKey(type)) {
            final InputConfiguration cfg = factories.get(type).create(id, config);

            if (validator.isValid(cfg)) {
                final InputService input = cfg.createInput();
                services.add(input);
                inputs.add(input);
            }
        } else {
            errors.add(new ConfigurationError("Unknown input type \"" + type + "\" for " + id));
        }
    });
}
 
Example 8
Project: oryx2   File: DeleteOldDataIT.java   View source code 6 votes vote down vote up
@Test
public void testDeleteOldData() throws Exception {
  Path tempDir = getTempDir();
  Path dataDir = tempDir.resolve("data");
  Path modelDir = tempDir.resolve("model");
  Map<String,Object> overlayConfig = new HashMap<>();
  overlayConfig.put("oryx.batch.update-class", MockBatchUpdate.class.getName());
  ConfigUtils.set(overlayConfig, "oryx.batch.storage.data-dir", dataDir);
  ConfigUtils.set(overlayConfig, "oryx.batch.storage.model-dir", modelDir);
  overlayConfig.put("oryx.batch.storage.max-age-data-hours", 0);
  overlayConfig.put("oryx.batch.storage.max-age-model-hours", 0);
  overlayConfig.put("oryx.batch.streaming.generation-interval-sec", GEN_INTERVAL_SEC);
  Config config = ConfigUtils.overlayOn(overlayConfig, getConfig());

  startMessaging();
  startServerProduceConsumeTopics(config, DATA_TO_WRITE, WRITE_INTERVAL_MSEC);
  assertEquals(0, IOUtils.listFiles(dataDir, "*").size());
  assertEquals(0, IOUtils.listFiles(modelDir, "*").size());
}
 
Example 9
Project: obevo   File: ParamReader.java   View source code 6 votes vote down vote up
private Collection<Object[]> getAppContextAndJdbcDsParams(final int numConnections) {
    return getSysConfigs().flatCollect(new Function<Config, ListIterable<Object[]>>() {
        @Override
        public ListIterable<Object[]> valueOf(final Config config) {
            ListIterable<IntToObjectFunction<DbDeployerAppContext>> appContexts = getAppContext(config);
            return appContexts.collect(new Function<IntToObjectFunction<DbDeployerAppContext>, Object[]>() {
                @Override
                public Object[] valueOf(IntToObjectFunction<DbDeployerAppContext> appContext) {
                    return new Object[] {
                            appContext,
                            getJdbcDs(config, numConnections)
                    };
                }
            });
        }
    });
}
 
Example 10
Project: conf4j   File: ConsulFileConfigurationSource.java   View source code 6 votes vote down vote up
private Config buildConfigIfAbsent(Config currentConfig) {
    if (currentConfig != null) return currentConfig;

    Optional<String> configurationFile = kvClient.getValueAsString(configurationFilePath).toJavaUtil();
    if (configurationFile.isPresent()) {
        return ConfigFactory.parseString(configurationFile.get());
    }

    logger.debug("Missing configuration file at path: {}, ignore flag set to: {}", configurationFilePath, ignoreMissingResource);

    if (ignoreMissingResource) {
        return ConfigFactory.empty();
    }

    throw new IllegalStateException("Missing required configuration resource at path: " + configurationFilePath);
}
 
Example 11
Project: Stargraph   File: Rules.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
private Map<Language, List<QueryPlanPatterns>> loadQueryPlanPatterns(Config config) {
    Map<Language, List<QueryPlanPatterns>> rulesByLang = new LinkedHashMap<>();
    ConfigObject configObject = config.getObject("rules.planner-pattern");

    configObject.keySet().forEach(strLang -> {
        Language language = Language.valueOf(strLang.toUpperCase());
        List<QueryPlanPatterns> plans = new ArrayList<>();

        List<? extends ConfigObject> innerCfg = configObject.toConfig().getObjectList(strLang);
        innerCfg.forEach(e -> {
            Map<String, Object> plan = e.unwrapped();
            String planId = plan.keySet().toArray(new String[1])[0];
            List<String> triplePatterns = (List<String>)plan.values().toArray()[0];
            plans.add(new QueryPlanPatterns(planId,
                    triplePatterns.stream().map(TriplePattern::new).collect(Collectors.toList())));
        });

        rulesByLang.put(language, plans);
    });

    return rulesByLang;
}
 
Example 12
Project: oryx2   File: BatchUpdateFunction.java   View source code 6 votes vote down vote up
BatchUpdateFunction(Config config,
                    Class<K> keyClass,
                    Class<M> messageClass,
                    Class<? extends Writable> keyWritableClass,
                    Class<? extends Writable> messageWritableClass,
                    String dataDirString,
                    String modelDirString,
                    BatchLayerUpdate<K,M,U> updateInstance,
                    JavaStreamingContext streamingContext) {
  this.keyClass = keyClass;
  this.messageClass = messageClass;
  this.keyWritableClass = keyWritableClass;
  this.messageWritableClass = messageWritableClass;
  this.dataDirString = dataDirString;
  this.modelDirString = modelDirString;
  this.updateBroker = ConfigUtils.getOptionalString(config, "oryx.update-topic.broker");
  this.updateTopic = ConfigUtils.getOptionalString(config, "oryx.update-topic.message.topic");
  this.updateInstance = updateInstance;
  this.sparkContext = streamingContext.sparkContext();
}
 
Example 13
Project: conf4j   File: MergeConfigurationSourceTest.java   View source code 6 votes vote down vote up
@Test
public void testConfigurationSourceMerging() {
    String filePath = getClass().getResource("fallback.conf").getPath();
    FilesystemConfigurationSource fallbackSource = FilesystemConfigurationSource.builder()
            .withFilePath(filePath)
            .build();

    ClasspathConfigurationSource source = ClasspathConfigurationSource.builder()
            .withResourcePath("org/conf4j/core/source/test.conf")
            .build();

    MergeConfigurationSource mergeSource = MergeConfigurationSource.builder()
            .withSource(source)
            .withFallback(fallbackSource)
            .build();

    Config config = mergeSource.getConfig();
    assertThat(config).isNotNull();
    assertThat(config.getString("message")).isEqualTo("config-loaded-successfully");
    assertThat(config.getString("override")).isEqualTo("overriding-works");
    assertThat(config.getInt("defaultProperty")).isEqualTo(555);
}
 
Example 14
Project: ytk-learn   File: CommonParams.java   View source code 6 votes vote down vote up
public static CommonParams loadParams(Config config) {

        CommonParams params = new CommonParams();

        params.dataParams = new DataParams(config, "");
        params.featureParams = new FeatureParams(config, "");
        params.lossParams = new LossParams(config, "");
        params.modelParams = new ModelParams(config, "");
        String optimizer = config.getString("optimization.optimizer");

        params.lsParams = new LineSearchParams(config, "optimization.");
        params.verbose = config.getBoolean("verbose");

        CheckUtils.check(optimizer.equals("line_search"), "optimization.optimizer only support:%s", "line_search");

        return params;
    }
 
Example 15
Project: oryx2   File: BatchLayer.java   View source code 6 votes vote down vote up
public BatchLayer(Config config) {
  super(config);
  this.keyWritableClass = ClassUtils.loadClass(
      config.getString("oryx.batch.storage.key-writable-class"), Writable.class);
  this.messageWritableClass = ClassUtils.loadClass(
      config.getString("oryx.batch.storage.message-writable-class"), Writable.class);
  this.updateClassName = config.getString("oryx.batch.update-class");
  this.dataDirString = config.getString("oryx.batch.storage.data-dir");
  this.modelDirString = config.getString("oryx.batch.storage.model-dir");
  this.maxDataAgeHours = config.getInt("oryx.batch.storage.max-age-data-hours");
  this.maxModelAgeHours = config.getInt("oryx.batch.storage.max-age-model-hours");
  Preconditions.checkArgument(!dataDirString.isEmpty());
  Preconditions.checkArgument(!modelDirString.isEmpty());
  Preconditions.checkArgument(maxDataAgeHours >= 0 || maxDataAgeHours == NO_MAX_AGE);
  Preconditions.checkArgument(maxModelAgeHours >= 0 || maxModelAgeHours == NO_MAX_AGE);
}
 
Example 16
Project: Re-Collector   File: FileInputConfigurationValidatorTest.java   View source code 6 votes vote down vote up
@Test
public void testReaderInterval() throws Exception {
    final Config config = mock(Config.class);

    when(config.hasPath("path")).thenReturn(true);
    when(config.getString("path")).thenReturn("target/foo.txt");

    when(config.hasPath("reader-interval")).thenReturn(true);
    when(config.getDuration("reader-interval", TimeUnit.MILLISECONDS)).thenReturn(250L);

    assertEquals(0, validateConfig(config).size());

    when(config.getDuration("reader-interval", TimeUnit.MILLISECONDS)).thenReturn(0L);

    assertEquals("Invalid interval should throw an error", 1, validateConfig(config).size());
    assertEquals("Too small reader interval should show correct error message",
            "Reader interval too small: \"0\"",
            validateConfig(config).iterator().next().getMessage());
}
 
Example 17
Project: oryx2   File: SpeedLayerIT.java   View source code 5 votes vote down vote up
@Test
public void testSpeedLayer() throws Exception {
  Map<String,Object> overlayConfig = new HashMap<>();
  overlayConfig.put("oryx.speed.model-manager-class", MockSpeedModelManager.class.getName());
  overlayConfig.put("oryx.speed.streaming.generation-interval-sec", 3);
  Config config = ConfigUtils.overlayOn(overlayConfig, getConfig());

  startMessaging();

  List<KeyMessage<String,String>> updates = startServerProduceConsumeTopics(config, 1000, 10);

  int inputToUpdate = 0;
  int receivedUpdates = 0;
  int models = 0;
  for (KeyMessage<String,String> update : updates) {
    String key = update.getKey();
    String message = update.getMessage();
    if (message.contains(",")) {
      // it's an input converted to update
      assertEquals("UP", key);
      inputToUpdate++;
    } else {
      // Else should be just an int
      boolean shouldBeModel = Integer.parseInt(message) % 10 == 0;
      assertEquals(shouldBeModel ? "MODEL" : "UP", key);
      if (shouldBeModel) {
        models++;
      } else {
        receivedUpdates++;
      }
    }
  }

  log.info("Received {} models, {} inputs converted to updates, and {} other updates",
           models, inputToUpdate, receivedUpdates);

  assertEquals(1, models);
  assertEquals(9, receivedUpdates);
  assertEquals(1000, inputToUpdate);
}
 
Example 18
Project: Re-Collector   File: MemoryReporterServiceConfiguration.java   View source code 5 votes vote down vote up
@Inject
public MemoryReporterServiceConfiguration(final Config config) {
    if (config.hasPath("debug")) {
        final Config debug = config.getConfig("debug");

        if (debug.hasPath("memory-reporter")) {
            this.enable = debug.getBoolean("memory-reporter");
        }

        if (debug.hasPath("memory-reporter-interval")) {
            this.interval = debug.getDuration("memory-reporter-interval", TimeUnit.MILLISECONDS);
        }
    }
}
 
Example 19
Project: hashsdn-controller   File: RemoteRpcProviderTest.java   View source code 5 votes vote down vote up
@BeforeClass
public static void setup() throws InterruptedException {
    moduleConfig = new RemoteRpcProviderConfig.Builder("odl-cluster-rpc")
            .withConfigReader(ConfigFactory::load).build();
    final Config config = moduleConfig.get();
    system = ActorSystem.create("odl-cluster-rpc", config);

}
 
Example 20
Project: bench   File: ActorBootstrap.java   View source code 5 votes vote down vote up
private static Config parseClusterConfig(@NotNull final String jsonConfig) throws ValidationException {
    try {
        return ConfigFactory.parseString(jsonConfig, Constants.CONFIG_PARSE_OPTIONS);
    } catch (ConfigException e) {
        throw ValidationException.create("Cluster configuration error for " + jsonConfig, e);
    }
}
 
Example 21
Project: Graphene   File: CoreferenceTest.java   View source code 5 votes vote down vote up
@BeforeClass
public static void beforeAll() {
	Config config = ConfigFactory
               .load("reference.local")
               .withFallback(ConfigFactory.load("reference"));

	coreference = new Coreference(config.getConfig("graphene.coreference"));
}
 
Example 22
Project: ytk-learn   File: GBMLRDataFlow.java   View source code 5 votes vote down vote up
public GBMLRDataFlow(IFileSystem fs,
                        Config config,
                        ThreadCommSlave comm,
                        int threadNum,
                        boolean needPyTransform,
                        String pyTransformScript) throws Exception {
    super(fs, config,
            comm,
            threadNum,
            needPyTransform,
            pyTransformScript);

    this.K = config.getInt("k");
    //this.seed = config.getInt("seed");
    this.randomSampleRate = config.getDouble("instance_sample_rate");
    this.randomFeatureRate = config.getDouble("feature_sample_rate");
    this.uniformBaseScore = (float) LossFunctions.createLossFunction(commonParams.lossParams.loss_function).
                            pred2Score(config.getDouble("uniform_base_prediction"));
    this.sampleDepdtBaseScore = config.getBoolean("sample_dependent_base_prediction");
    this.treeNum = config.getInt("tree_num");
    this.learningRate = config.getDouble("learning_rate");
    this.randomParams = new RandomParams(config, "");

    this.type = Type.getType(config.getString("type"));
    if (type == Type.RF) {
        this.learningRate = 1.0;
    }

    CheckUtils.check(K >= 2, "K:%d must >= 2", K);

    LOG_UTILS.importantInfo("K:" + K);
    //comm.LOG_UTILS.importantInfo("seed:" + seed);
    LOG_UTILS.importantInfo("random:" + randomParams);
    LOG_UTILS.importantInfo("instance_sample_rate:" + randomSampleRate);
    LOG_UTILS.importantInfo("feature_sample_rate:" + randomFeatureRate);
    LOG_UTILS.importantInfo("uniform_base_prediction:" + uniformBaseScore);
    LOG_UTILS.importantInfo("tree_num:" + treeNum);
    LOG_UTILS.importantInfo("learning_rate:" + learningRate);
    LOG_UTILS.importantInfo("type:" + type);
}
 
Example 23
Project: newrelic-api-client-java   File: APIKeyset.java   View source code 5 votes vote down vote up
/**
 * Populate 
 * 
 * @param conf the config for the whole API project
 * @param accountName the name of the account to pull from the config
 */
public APIKeyset(Config conf, String account) {
	
	// Set all the local values from the config
	String prefix = "newrelic-api-client.accounts." + account;
	this.accountName = APIApplication.getConfString(prefix + ".accountName");
	this.adminName = APIApplication.getConfString(prefix + ".adminName");
	this.accountId = APIApplication.getConfString(prefix + ".accountId");
	this.licenseKey = APIApplication.getConfString(prefix + ".licenseKey");
	this.restKey = APIApplication.getConfString(prefix + ".restKey");
	this.adminKey = APIApplication.getConfString(prefix + ".adminKey");
	this.insightsQueryKey = APIApplication.getConfString(prefix + ".insightsQueryKey");
	this.insightsInsertKey = APIApplication.getConfString(prefix + ".insightsInsertKey");
}
 
Example 24
Project: bench   File: JMSLeaderClusterClientFactory.java   View source code 5 votes vote down vote up
public JMSLeaderClusterClientFactory(@NotNull final Config factoryConfig,
                                     @NotNull final ActorRegistry actorRegistry) {
    this.actorRegistry = requireNonNull(actorRegistry);
    try {
        this.serverEndpoint = new JMSEndpoint(factoryConfig);
        this.server = new FFMQServer(serverEndpoint);
    } catch (JMSException e) {
        throw propagate(e);
    }
}
 
Example 25
Project: ocraft-s2client   File: S2ControllerTest.java   View source code 5 votes vote down vote up
@Test
void allowsStartingGameFromCustomConfiguration() throws IOException {
    initStarcraft2Executable(LINUX_USER_DIR);

    Config cfg = starcraft2Game()
            .withExecutablePath(gameRoot())
            .withListenIp(CFG_NET_IP_CUSTOM)
            .withPort(CFG_NET_PORT_CUSTOM)
            .withWindowSize(CFG_WINDOW_W_CUSTOM, CFG_WINDOW_H_CUSTOM)
            .withWindowPosition(CFG_WINDOW_X_CUSTOM, CFG_WINDOW_Y_CUSTOM)
            .withDataVersion(CFG_EXE_DATA_VER_CUSTOM)
            .getGameConfiguration();

    assertThat(cfg.getConfig(OcraftConfig.GAME)).as("custom game cfg").isEqualTo(expectedCustomConfiguration());
}
 
Example 26
Project: ytk-learn   File: FFMModelDataFlow.java   View source code 5 votes vote down vote up
public FFMModelDataFlow(IFileSystem fs,
                       Config config,
                       ThreadCommSlave comm,
                       int threadNum,
                       boolean needPyTransform,
                       String pyTransformScript) throws Exception {
    super(fs, config,
            comm,
            threadNum,
            needPyTransform,
            pyTransformScript);

    List<Integer> klist = config.getIntList("k");
    K = new int[klist.size()];
    for (int i = 0; i < klist.size(); i++) {
        K[i] = klist.get(i);
    }
    //seed = config.getInt("seed");
    biasNeedLatentFactor = config.getBoolean("bias_need_latent_factor");

    needFirstOrder = (K[0] >= 1);
    needSecondOrder = (K[1] >= 1);

    fieldDelim = config.getString("data.delim.field_delim");
    fieldDictPath = config.getString("model.field_dict_path");

    randomParams = new RandomParams(config, "");

    LOG_UTILS.importantInfo("K:" + Arrays.toString(K));
    //LOG_UTILS.importantInfo("seed:" + seed);
    LOG_UTILS.importantInfo("random:" + randomParams);
    LOG_UTILS.importantInfo("bias_need_latent_factor:" + biasNeedLatentFactor);
    LOG_UTILS.importantInfo("need_first_order:" + needFirstOrder + ", need_second_order:" + needSecondOrder);
    LOG_UTILS.importantInfo("field_delim:" + fieldDelim + ", field_dict_path:" + fieldDictPath);

}
 
Example 27
Project: ocraft-s2client   File: S2ControllerTest.java   View source code 5 votes vote down vote up
private Config expectedCustomConfiguration() {
    return ConfigFactory.parseMap(Map.of(
            GAME_NET_IP, CFG_NET_IP_CUSTOM,
            GAME_NET_PORT, CFG_NET_PORT_CUSTOM,
            GAME_WINDOW_W, CFG_WINDOW_W_CUSTOM,
            GAME_WINDOW_H, CFG_WINDOW_H_CUSTOM,
            GAME_WINDOW_X, CFG_WINDOW_X_CUSTOM,
            GAME_WINDOW_Y, CFG_WINDOW_Y_CUSTOM,
            GAME_EXE_DATA_VER, CFG_EXE_DATA_VER_CUSTOM
    )).withFallback(expectedConfiguration()).getConfig(OcraftConfig.GAME);
}
 
Example 28
Project: bench   File: ClusterClientsTest.java   View source code 5 votes vote down vote up
@Test
public void factory_is_created_from_cluster_config() {
    Config clusterConfig = ConfigFactory.parseString("{\"" + ClusterClients.FACTORY_CLASS + "\":\"" + DummyClusterClientFactory.class.getName() + "\"," + //
                                                             "\"" + ClusterClients.FACTORY_CONFIG + "\":{}}");

    AgentClusterClientFactory factory = ClusterClients.newFactory(AgentClusterClientFactory.class,
                                                                  clusterConfig,
                                                                  actorRegistry);

    assertNotNull(factory);
    assertThat(factory, instanceOf(DummyClusterClientFactory.class));
}
 
Example 29
Project: conf4j   File: EtcdFileConfigurationSourceTest.java   View source code 5 votes vote down vote up
@Test
public void testIgnoreMissingFileOption() throws Exception {
    String filePath = RandomStringUtils.randomAlphanumeric(15);
    EtcdFileConfigurationSource source = createConfigurationSource(filePath, true);

    Config config = source.getConfig();
    assertThat(config).isNotNull();
    assertThat(config).isEqualTo(ConfigFactory.empty());
}
 
Example 30
Project: conf4j   File: RootConfigurationProvider.java   View source code 5 votes vote down vote up
private T loadConfiguration() {
    Config config = configurationSource.getConfig().resolve();
    if (!configRootPath.equals(EMPTY_STRING)) {
        config = config.getConfig(configRootPath);
    }

    configurationExtensions.beforeTypeConversion(config, configurationClass);
    Map<String, Object> configMap = config.root().unwrapped();
    T configurationBean = mapper.convertValue(configMap, configurationClass);
    configurationExtensions.afterConfigBeanAssembly(configurationBean);

    return configurationBean;
}
 
Example 31
Project: ytk-learn   File: TrainWorker.java   View source code 5 votes vote down vote up
public String getTrainDataPath() {
    String configRealPath = (new File(configFile).exists()) ? configFile : configPath;
    File realFile = new File(configRealPath);
    CheckUtils.check(realFile.exists(), "config file(%s) doesn't exist!", configRealPath);
    Config config = ConfigFactory.parseFile(realFile);
    config = updateConfigWithCustom(config);
    return config.getString("data.train.data_path");
}
 
Example 32
Project: bench   File: JgroupsLeaderClusterClientFactoryTest.java   View source code 5 votes vote down vote up
@Test
public void constructor_with_config_parameter_creates_jChannel() {
    Config factoryConfig = new JgroupsClusterConfigs().agentFactoryConfig();
    JgroupsLeaderClusterClientFactory clientFactory2 = new JgroupsLeaderClusterClientFactory(factoryConfig,
                                                                                             actorRegistry);

    assertNotNull(clientFactory2.getJChannel());

    clientFactory2.close();
}
 
Example 33
Project: oryx2   File: ConfigUtilsTest.java   View source code 5 votes vote down vote up
@Test
public void testSerialize() {
  String serialized = ConfigUtils.serialize(ConfigUtils.getDefault());
  assertContains(serialized, "update-class");
  Config deserialized = ConfigUtils.deserialize(serialized);
  assertEquals(
      ConfigUtils.getDefault().getString("oryx.serving.api.port"),
      deserialized.getString("oryx.serving.api.port"));
}
 
Example 34
Project: CodeBroker   File: AkkaBootService.java   View source code 5 votes vote down vote up
public void initActorSystem(File file, String akkaName, String configName) {
    logger.debug("init Actor System start: akkaName=" + akkaName + " configName:" + configName);

    Config cg = ConfigFactory.parseFile(file);

    cg.withFallback(ConfigFactory.defaultReference(Thread.currentThread().getContextClassLoader()));
    Config config = ConfigFactory.load(cg).getConfig(configName);
    system = ActorSystem.create(akkaName, config);
    inbox = Inbox.create(system);
    logger.debug("init Actor System end");
}
 
Example 35
Project: tsc-reload   File: ReloadableConfig.java   View source code 5 votes vote down vote up
public ReloadableConfig(List<File> scannedFiles, Duration checkInterval, Supplier<Config> configSupplier) {
    super(configSupplier.get());
    this.scannedFiles = scannedFiles;
    this.checkInterval = checkInterval;
    this.configSupplier = configSupplier;
    this.configWithTimestamps = new ConfigWithTimestamps(configSupplier.get(), optionalLastModified().get(), Instant.now());
}
 
Example 36
Project: hashsdn-controller   File: AbstractConfig.java   View source code 5 votes vote down vote up
protected Config merge() {
    Config config = ConfigFactory.parseMap(configHolder);
    if (fallback != null) {
        config = config.withFallback(fallback);
    }

    return config;
}
 
Example 37
Project: vars-annotation   File: SampleBC.java   View source code 5 votes vote down vote up
private void createAssociation(String sampleBy, String sampleId) {
    Config config = toolBox.getConfig();
    Association a1 = new Association(config.getString("app.annotation.sample.association.equipment"),
            sampleBy, Association.VALUE_NIL);
    Association a2 = new Association(config.getString("app.annotation.sample.association.reference"),
            Association.VALUE_SELF, sampleId);
    EventBus eventBus = toolBox.getEventBus();
    List<Annotation> selectedAnnotations = new ArrayList<>(toolBox.getData().getSelectedAnnotations());
    CreateAssociationsCmd cmd1 = new CreateAssociationsCmd(a1, selectedAnnotations);
    CreateAssociationsCmd cmd2 = new CreateAssociationsCmd(a2, selectedAnnotations);
    eventBus.send(cmd1);
    eventBus.send(cmd2);
}
 
Example 38
Project: tg-eventstore   File: StacksConfiguredDataSource.java   View source code 5 votes vote down vote up
public static PooledDataSource pooledReadOnlyDb(Config config, int maxPoolSize) {
    return pooled(
            config.getString("read_only_cluster"),
            config.getInt("port"),
            config.getString("username"),
            config.getString("password"),
            config.getString("database"),
            config.getString("driver"),
            maxPoolSize
    );
}
 
Example 39
Project: conf4j   File: ClasspathConfigurationSourceTest.java   View source code 5 votes vote down vote up
@Test
public void testIgnoreMissingFileOption() throws Exception {
    String filePath = RandomStringUtils.randomAlphanumeric(15);
    ClasspathConfigurationSource source = ClasspathConfigurationSource.builder()
            .withResourcePath(filePath)
            .ignoreMissingResource()
            .build();

    Config config = source.getConfig();
    assertThat(config).isNotNull();
    assertThat(config).isEqualTo(ConfigFactory.empty());
}
 
Example 40
Project: tg-eventstore   File: StacksConfiguredDataSource.java   View source code 5 votes vote down vote up
public static PooledDataSource pooledMasterDb(Config config, int maxPoolSize) {
    return pooled(
            config.getString("hostname"),
            config.getInt("port"),
            config.getString("username"),
            config.getString("password"),
            config.getString("database"),
            config.getString("driver"),
            maxPoolSize
    );
}