properties - read a property from another property(multiple levels) in java -
my situation this
i having property file
url.dev.a=devlocalhost url.qa.a=qalocalhost env=dev totalurl=${url.${env}.a}
here expecting totalurl devlocalhost
how can in property file.
the following class cleaned open source project work with. if can't used is, can atleast starting point exploration.
package snippet; import java.util.enumeration; import java.util.properties; import java.util.regex.matcher; import java.util.regex.pattern; public class propertyreplace { /** * replaces java properties in properties of form %<java * property> java property value. * * @param properties * , properties replacement takes place */ public static void replaceenviron(properties properties) { enumeration<object> enumeration = properties.keys(); while (enumeration.hasmoreelements()) { string key = (string) enumeration.nextelement(); string value = properties.getproperty(key); system.out.println("finding value key " + key); string updatedvalue = getupdatedvalue(value, properties); if (updatedvalue == null) updatedvalue = ""; properties.setproperty(key, updatedvalue); } } /** * value given mpf property. * * @param value * , original value * @param properties * , properties replacements taken * @return modified value */ private static string getupdatedvalue(string value, properties properties) { system.out.println("value = " + value); if (value == null) return null; pattern p = pattern.compile("[^%]*(%[^%]*%).*"); matcher m = p.matcher(value); while (m.matches()) { string var = m.group(1); string varvalue = getupdatedvalue(properties.getproperty(var.substring(1, var.length() - 1)), properties); if (varvalue == null) { varvalue = system.getproperty(var.substring(1, var.length() - 1), null); if (varvalue == null) { varvalue = system.getenv(var.substring(1, var.length() - 1)); if (varvalue == null) varvalue = ""; } } value = value.replaceall(var, varvalue); m = p.matcher(value); } system.out.println("return: " + value); return value; } public static void main(string[] args) { properties props = new properties(); // url.dev.a=devlocalhost // url.qa.a=qalocalhost // env=dev // totalurl=${url.${env}.a} props.setproperty("url.dev.a", "devlocalhost"); props.setproperty("url.qa.a", "qalocalhost"); props.setproperty("env", "dev"); props.setproperty("totalurlx", "url.%env%.a"); props.setproperty("totalurl", "%totalurlx%"); replaceenviron(props); system.out.println(props); } }
Comments
Post a Comment