【问题标题】:Resolve a standalone string/file using typesafe config使用类型安全配置解析独立的字符串/文件
【发布时间】:2017-03-31 05:24:47
【问题描述】:

我正在寻找一种表达方式:

val c: Config = ConfigFactory.parseString("a=fox,b=dog")
val s: String = """This is a "quick" brown ${a}.\nThat is a lazy, lazy ${b}."""
println(c.resolveString(s))

// Should print:
// > This is a "quick" brown fox.
// > That is a lazy lazy dog.

我的两个想法:

  • 只需找到带有正则表达式的占位符并从配置中一一替换
  • 将 s 转换为具有单个值的配置并使用 resolveWith - 但似乎引用可能真的很棘手

也许有更简单的方法?

【问题讨论】:

  • 有什么理由不只提取值“a”和“b”并将它们传递给字符串插值器?
  • 我不知道这完全是“a”和“b”。它可以是更多变量,配置中的任何内容。

标签: scala config typesafe-config


【解决方案1】:

一个简单的解决方案:

class Resolver(vars: Config) {
  private lazy val placeholderRegex = "(?<=\\$\\{).*?(?=\\})".r

  def resolveString(s: String): String = {
    placeholderRegex.findAllIn(s).foldLeft(s) { (str, v) =>
      if (vars.hasPath(v)) str.replaceAll("\\Q${" + v + "}\\E", vars.getString(v)) else str
    }
  }

如果字符串不是很大并且其中没有大量不同的占位符应该没问题。

【讨论】:

    【解决方案2】:

    我有类似的情况,我之前自动推送弹性搜索索引定义 我启动了使用这些索引定义的作业。

    在我的例子中,包含变量引用的字符串是 JSON 索引/模板定义,也来自类型安全配置。 (参见下面的 es.template_or_index.json。)

    我使用我在上面写的实用方法解析这些引用 的 apache.commons StrSubstitutor。

    (参见:VariableReferenceResolver.resolveReferences(字符串模板),下文)

    以下是我的配置示例。请注意属性“es.animal”是如何注入到索引/模板 json 中的。 使用类型安全配置库的开箱即用功能无法做到这一点(但我认为这会 成为他们添加的一个很棒的功能!)

     es {
          // user and password credentials should not be checked in to git. deployer is expected to
          // set these parameters into the their environment in whatever way is convenient -- .bashrc or whatever.
          user = dummy
          user = ${?ES_USER}
          password = dummy.passwd
          password = ${?ES_PASSWORD}
          hostPort = "localhost:9200"
          hostPort = ${?ES_HOST_PORT}
          protocol = http
          protocol = ${?ES_PROTOCOL}
    
          animal = horse            // This gets injected into the configuration property es.template_or_index.json
    
    
          // Note: for template json there is a second round of interpolation performed so the json can reference any defined
          // property of this configuration file (or anything it includes)
          template_or_index {
            name = test_template
            json = """
          {
              "template": "${es.animal}_sql-*",
              "settings": {
                "number_of_shards": 50,
                "number_of_replicas": 2
              },
              "mappings": {
                     "test_results" : {
                         "date_detection": false,
                         "properties" : {
                             "timestamp" : { "type" : "date"},
                             "yyyymmdd" : { "type" : "string", "index" : "not_analyzed"}
                         }
                     }
              }
            }
            """
          }
     }
    
    
    
    package com.foo
    
    import com.typesafe.config.Config;
    import org.apache.commons.lang.text.StrLookup;
    import org.apache.commons.lang.text.StrSubstitutor;
    
    public class VariableReferenceResolver {
        final StrSubstitutor substitutor;
    
        static class ConfigStrLookup extends StrLookup {
              private final Config config;
    
              ConfigStrLookup(Config config) {
                  this.config = config;
              }
    
              public String lookup(String key) {
                  return config.getString(key);
              }
          }
    
        public VariableReferenceResolver (Config config) {
            substitutor=new StrSubstitutor(new ConfigStrLookup(config));
    
        }
    
        public String resolveReferences(String template) {
            return substitutor.replace(template);
        }
    }
    
    
    public class OtherClass { 
        private static void getIndexConfiguration(String path) throws IOException {
            System.setProperty("config.file", path);
            Config config = ConfigFactory.load();
            String user =  config.getString("es.user");
            String password =  config.getString("es.password");
            String protocol =  config.getString("es.protocol");
            String hostPort =  config.getString("es.hostPort");
            String indexOrTemplateJson = config.getString("es.template_or_index.json");
            String indexOrTemplateName = config.getString("es.template_or_index.name");
            VariableReferenceResolver resolver = new VariableReferenceResolver(config);
            String resolvedIndexOrTemplateJson = resolver.resolveReferences(indexOrTemplateJson);
    
            File jsonFile = File.createTempFile("index-or-template-json", indexOrTemplateName);
            Files.write(Paths.get(jsonFile.getAbsolutePath()), resolvedIndexOrTemplateJson.getBytes());
    
            curlIndexOrTemplateCreateCommand =
                    String.format(
                            "curl  -XPUT  -k -u %s:%s %s://%s/_template/%s -d @%s",
                            user, password, protocol, hostPort, indexOrTemplateName,  jsonFile.getAbsolutePath());
        }
    
    
                ....
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-17
      • 2016-05-16
      • 1970-01-01
      • 1970-01-01
      • 2019-08-10
      相关资源
      最近更新 更多