Java Code Examples for com.typesafe.config.ConfigFactory#parseString()

The following examples show how to use com.typesafe.config.ConfigFactory#parseString() . 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: PatternMetricFilterTest.java    From kite with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnrecognizedPatternType() throws Exception {
  String str = "{" + 
    "\n metricFilter : {" +
    "\n includes : { " +
    "\n \"unRecognizedType:foo\" : \"glob:*\"" +
    "\n }" +
    "\n }}";

  Config config = ConfigFactory.parseString(str);
  try {
    PatternMetricFilter.parse(new Configs(), config);
    fail();
  } catch (MorphlineCompilationException e) {
    ; // expected
  }
}
 
Example 2
Source File: AkkaUtils.java    From akka-tutorial with Apache License 2.0 6 votes vote down vote up
/**
 * Load a {@link Config}.
 *
 * @param resource the path of the config resource
 * @return the {@link Config}
 */
private static Config loadConfig(String resource, VariableBinding... bindings) {
	try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource)) {
		if (in == null) {
			throw new FileNotFoundException("Could not get the resource " + resource);
		}
		Stream<String> content = new BufferedReader(new InputStreamReader(in)).lines();
		for (VariableBinding binding : bindings) {
			content = content.map(binding::apply);
		}
		String result = content.collect(Collectors.joining("\n"));
		return ConfigFactory.parseString(result);
	} catch (IOException e) {
		throw new IllegalStateException("Could not load resource " + resource);
	}
}
 
Example 3
Source File: MorphlineTest.java    From kite with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void internalExtractURIQueryParams(String paramName, String url, List expected, int maxParams) throws Exception {
  String fileName = "test-morphlines/extractURIQueryParameters";
  String overridesStr = "queryParam : " + ConfigUtil.quoteString(paramName);
  if (maxParams >= 0) {
    fileName += "WithMaxParameters";
    overridesStr += "\nmaxParameters : " + maxParams;
  }
  Config override = ConfigFactory.parseString(overridesStr);
  morphline = createMorphline(fileName, override);
  Record record = new Record();
  record.put("in", url);
  Record expectedRecord = new Record();
  expectedRecord.put("in", url);
  expectedRecord.getFields().putAll("out", expected);
  processAndVerifySuccess(record, expectedRecord);
}
 
Example 4
Source File: DefaultAkkaReplicatorConfig.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Returns an instance of {@code DefaultAkkaReplicatorConfig} based on the settings of the specified Config.
 *
 * @param name the name of the replicator.
 * @param role the cluster role of members with replicas of the distributed collection.
 * @param config is supposed to provide the settings of the Replicator config at {@value #CONFIG_PATH}.
 * @return the instance.
 * @throws org.eclipse.ditto.services.utils.config.DittoConfigError if {@code config} is invalid.
 */
public static DefaultAkkaReplicatorConfig of(final Config config, final CharSequence name,
        final CharSequence role) {
    final Map<String, Object> specificConfig = new HashMap<>(2);
    specificConfig.put(AkkaReplicatorConfigValue.NAME.getConfigPath(), checkNotNull(name, "name"));
    specificConfig.put(AkkaReplicatorConfigValue.ROLE.getConfigPath(), checkNotNull(role, "role"));

    // TODO Ditto issue #439: replace ConfigWithFallback - it breaks AbstractConfigValue.withFallback!
    // Workaround: re-parse my config
    final ConfigWithFallback configWithFallback = ConfigWithFallback.newInstance(config, CONFIG_PATH,
            AkkaReplicatorConfigValue.values());
    final Config fallback =
            ConfigFactory.parseString(configWithFallback.root().render(ConfigRenderOptions.concise()));

    return new DefaultAkkaReplicatorConfig(ConfigFactory.parseMap(specificConfig)
            .withFallback(fallback));
}
 
Example 5
Source File: MongoDbUriSupplierTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void turnOffSsl() {
    final Config options = ConfigFactory.parseString("ssl=false");
    final Config config = ConfigFactory.parseString(
            String.format("%s=\"%s\"\n%s=%s", KEY_URI, SOURCE_URI, KEY_OPTIONS, options.root().render()));
    final MongoDbUriSupplier underTest = MongoDbUriSupplier.of(config);

    final String targetUri = underTest.get();

    assertThat(targetUri).isEqualTo(SOURCE_URI.replaceAll("ssl=true", "ssl=false"));
}
 
Example 6
Source File: ValidatedConfigurationTest.java    From divolte-collector with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void shouldNotAllowAccessToInvalidConfiguration() {
    final Config empty = ConfigFactory.parseString("");
    final ValidatedConfiguration vc = new ValidatedConfiguration(() -> empty);

    assertFalse(vc.isValid());

    // This throws IllegalArgumentException in case of invalid configuration
    vc.configuration();
}
 
Example 7
Source File: GatewayHttpConfigTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMultipleCommaSeparatedMediaTypes() {
    final Config gatewayTestConfig = ConfigFactory.parseString("http {\n additional-accepted-media-types = " +
            "\"application/json,application/x-www-form-urlencoded,text/plain\"\n}");

    final GatewayHttpConfig underTest = GatewayHttpConfig.of(gatewayTestConfig);

    softly.assertThat(underTest.getAdditionalAcceptedMediaTypes())
            .as(HttpConfig.GatewayHttpConfigValue.ADDITIONAL_ACCEPTED_MEDIA_TYPES.getConfigPath())
            .contains(MediaTypes.APPLICATION_JSON.toString(),
                    MediaTypes.APPLICATION_X_WWW_FORM_URLENCODED.toString(),
                    MediaTypes.TEXT_PLAIN.toString());
}
 
Example 8
Source File: MongoDbUriSupplierTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void uriWithoutPathOrQueryIsOkay() {
    final String sourceUri = "mongodb://username:password@localhost:12345";
    final Config config = ConfigFactory.parseString(String.format("%s=\"%s\"", KEY_URI, sourceUri));
    final MongoDbUriSupplier underTest = MongoDbUriSupplier.of(config);

    final String targetUri = underTest.get();

    assertThat(targetUri).isEqualTo(sourceUri);
}
 
Example 9
Source File: LoadSolrBuilder.java    From kite with Apache License 2.0 5 votes vote down vote up
private RetryPolicyFactory parseRetryPolicyFactory(Config retryPolicyConfig) {      
  if (retryPolicyConfig == null && !DISABLE_RETRY_POLICY_BY_DEFAULT) {
    // ask RetryPolicyFactoryParser to return a retry policy with reasonable defaults
    retryPolicyConfig = ConfigFactory.parseString(
        "{" + RetryPolicyFactoryParser.BOUNDED_EXPONENTIAL_BACKOFF_RETRY_NAME + "{}}");
  }
  if (retryPolicyConfig == null) {
    return null;
  } else {
    return new RetryPolicyFactoryParser().parse(retryPolicyConfig);
  }
}
 
Example 10
Source File: GatewayHttpConfigTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testNonParsableMediaType() {
    final Config gatewayTestConfig = ConfigFactory.parseString("http {\n additional-accepted-media-types = \"application-json\"\n}");

    final GatewayHttpConfig underTest = GatewayHttpConfig.of(gatewayTestConfig);

    softly.assertThat(underTest.getAdditionalAcceptedMediaTypes())
            .as(HttpConfig.GatewayHttpConfigValue.ADDITIONAL_ACCEPTED_MEDIA_TYPES.getConfigPath())
            .contains("application-json");
}
 
Example 11
Source File: ConfigsTest.java    From kite with Apache License 2.0 5 votes vote down vote up
@Test
public void testEmptyStringThrowsSyntaxError() throws Exception {
  Config config = ConfigFactory.parseString("foo : \"\"");
  try {
    new Configs().getTimeUnit(config, "foo");
    fail();
  } catch (IllegalArgumentException e) {
    ; // expected
  }
}
 
Example 12
Source File: TestRunner.java    From envelope with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpectedCoreEvents() throws Exception {
  EventManager.reset();

  String executionKey = UUID.randomUUID().toString();
  Config executionKeyConfig = ConfigFactory.parseString("execution_key = " + executionKey);
  Config config = ConfigUtils.configFromResource("/event/expected_core_events.conf");
  config = config.withFallback(executionKeyConfig).resolve();

  new Runner().run(config);

  List<Event> events = TestingEventHandler.getHandledEvents(executionKey);

  List<String> eventTypes = Lists.newArrayList();
  for (Event event : events) {
    eventTypes.add(event.getEventType());
  }

  List<String> expectedEventTypes = Lists.newArrayList(
      CoreEventTypes.PIPELINE_STARTED,
      CoreEventTypes.PIPELINE_FINISHED,
      CoreEventTypes.DATA_STEP_DATA_GENERATED,
      CoreEventTypes.DATA_STEP_WRITTEN_TO_OUTPUT,
      CoreEventTypes.EXECUTION_MODE_DETERMINED,
      CoreEventTypes.STEPS_EXTRACTED
  );

  for (String expectedEventType : expectedEventTypes) {
    assertTrue("Does not contain event type: " + expectedEventType, eventTypes.contains(expectedEventType));
  }
}
 
Example 13
Source File: MongoDbUriSupplierTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void preserveMongoDbSourceUriWithoutConfiguration() {
    final Config config = ConfigFactory.parseString(String.format("%s=\"%s\"", KEY_URI, SOURCE_URI));
    final MongoDbUriSupplier underTest = MongoDbUriSupplier.of(config);

    final String targetUri = underTest.get();

    assertThat(targetUri).isEqualTo(SOURCE_URI);
}
 
Example 14
Source File: GrokDictionaryTest.java    From kite with Apache License 2.0 5 votes vote down vote up
@Test
public void testResourceLoad() {
  String str = "{ dictionaryResources : [grok-dictionaries/grok-patterns] }";
  GrokDictionaries dicts = new GrokDictionaries(ConfigFactory.parseString(str), new Configs());
  Pattern pattern = dicts.compileExpression("%{TIMESTAMP_ISO8601:timestamp}");
  assertTrue(pattern.matcher("2007-03-01T13:00:00").matches());
  assertTrue(pattern.matcher("2007-03-01T13:00:00Z").matches());
  assertTrue(pattern.matcher("2007-03-01T13:00:00+01:00").matches());
  assertTrue(pattern.matcher("2007-03-01T13:00:00+0100").matches());
  assertTrue(pattern.matcher("2007-03-01T13:00:00+01").matches());
  assertFalse(pattern.matcher("2007-03-01T13:00:00Z+01:00").matches());
}
 
Example 15
Source File: MorphlineTest.java    From kite with Apache License 2.0 5 votes vote down vote up
@Test
public void testFindReplaceWithGrokWithReplaceFirst() throws Exception {
  Config override = ConfigFactory.parseString("replaceFirst : true");
  morphline = createMorphline("test-morphlines/findReplaceWithGrok", override);    
  Record record = new Record();
  record.put("text", "hello ic world ic");
  Record expected = new Record();
  expected.put("text", "hello! ic world ic");
  processAndVerifySuccess(record, expected);
}
 
Example 16
Source File: TokenStoreListener.java    From envelope with Apache License 2.0 5 votes vote down vote up
public synchronized static TokenStoreListener get() {
  if (INSTANCE == null) {
    LOG.trace("SparkConf: " + SparkEnv.get().conf().toDebugString());
    Config config = ConfigFactory.parseString(SparkEnv.get().conf().get(ENVELOPE_CONFIGURATION_SPARK));
    INSTANCE = new TokenStoreListener(ConfigUtils.getOrElse(config, SECURITY_PREFIX, ConfigFactory.empty()));
  }
  return INSTANCE;
}
 
Example 17
Source File: StaticFileTest.java    From lagom-openapi with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("Service with incorrect config should be return 404")
void shouldReturn404() {
    Config config = ConfigFactory.parseString("openapi.file = file");
    Test1ServiceImpl service = new Test1ServiceImpl(config);
    assertThatExceptionOfType(NotFound.class)
        .isThrownBy(() -> service.openapi(empty()).invokeWithHeaders(null, null))
        .withMessage("OpenAPI specification not found")
        .has(new Condition<>(thr -> thr.errorCode().http() == 404, "Error code must be 404"));
}
 
Example 18
Source File: AkkaRpcServiceUtils.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
public static long extractMaximumFramesize(Configuration configuration) {
	String maxFrameSizeStr = configuration.getString(AkkaOptions.FRAMESIZE);
	String akkaConfigStr = String.format(SIMPLE_AKKA_CONFIG_TEMPLATE, maxFrameSizeStr);
	Config akkaConfig = ConfigFactory.parseString(akkaConfigStr);
	return akkaConfig.getBytes(MAXIMUM_FRAME_SIZE_PATH);
}
 
Example 19
Source File: ConfigUtil.java    From sunbird-lms-service with MIT License 4 votes vote down vote up
public static Config getConfigFromJsonString(String jsonString, String configType) {
  ProjectLogger.log("ConfigUtil: getConfigFromJsonString called", LoggerEnum.DEBUG.name());

  if (null == jsonString || StringUtils.isBlank(jsonString)) {
    ProjectLogger.log(
        "ConfigUtil:getConfigFromJsonString: Empty string", LoggerEnum.ERROR.name());
    ProjectCommonException.throwServerErrorException(
        ResponseCode.errorConfigLoadEmptyString,
        ProjectUtil.formatMessage(
            ResponseCode.errorConfigLoadEmptyString.getErrorMessage(), configType));
  }

  Config jsonConfig = null;
  try {
    jsonConfig = ConfigFactory.parseString(jsonString);
  } catch (Exception e) {
    ProjectLogger.log(
        "ConfigUtil:getConfigFromJsonString: Exception occurred during parse with error message = "
            + e.getMessage(),
        LoggerEnum.ERROR.name());
    ProjectCommonException.throwServerErrorException(
        ResponseCode.errorConfigLoadParseString,
        ProjectUtil.formatMessage(
            ResponseCode.errorConfigLoadParseString.getErrorMessage(), configType));
  }

  if (null == jsonConfig || jsonConfig.isEmpty()) {
    ProjectLogger.log(
        "ConfigUtil:getConfigFromJsonString: Empty configuration", LoggerEnum.ERROR.name());
    ProjectCommonException.throwServerErrorException(
        ResponseCode.errorConfigLoadEmptyConfig,
        ProjectUtil.formatMessage(
            ResponseCode.errorConfigLoadEmptyConfig.getErrorMessage(), configType));
  }

  ProjectLogger.log(
      "ConfigUtil:getConfigFromJsonString: Successfully constructed type safe configuration",
      LoggerEnum.DEBUG.name());

  return jsonConfig;
}
 
Example 20
Source File: S3BackupSpec.java    From ts-reaktive with MIT License 4 votes vote down vote up
public S3BackupSpec() {
    super(ConfigFactory.parseString(
        "ts-reaktive.backup.backup.event-chunk-max-size = 2\n"
      + "ts-reaktive.backup.backup.event-chunk-max-duration = 1 second\n"));
}