javaregexstringenvironment-variables

Replace environment variable place-holders with their actual value?


In my Application.properties file I am using a key and value like that

report.custom.templates.path=${CATALINA_HOME}\\\\Medic\\\\src\\\\main\\\\reports\\\\AllReports\\\\

I need to replace the ${CATALINA_HOME} with its actual path:

{CATALINA_HOME} = C:\Users\s57893\softwares\apache-tomcat-7.0.27

Here is my code:

public class ReadEnvironmentVar {  

 public static void main(String args[]) {

    String path = getConfigBundle().getString("report.custom.templates.path");
    System.out.println("Application Resources : " + path);
    String actualPath = resolveEnvVars(path);
    System.out.println("Actual Path : " + actualPath);

   }

private static ResourceBundle getConfigBundle() {
    return ResourceBundle.getBundle("medicweb");
 }

private static String resolveEnvVars(String input) {
    if (null == input) {
        return null;
     }

    Pattern p = Pattern.compile("\\$\\{(\\w+)\\}|\\$(\\w+)");
    Matcher m = p.matcher(input);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        String envVarName = null == m.group(1) ? m.group(2) : m.group(1);
        String envVarValue = System.getenv(envVarName);
        m.appendReplacement(sb, null == envVarValue ? "" : envVarValue);
     }
    m.appendTail(sb);
    return sb.toString();
  }
}

from my code I am getting the result as -

Actual Path :

 C:Userss57893softwaresapache-tomcat-7.0.27\Medic\src\main\reports\AllReports\

but I need the result as -

Actual Path :

C:\Users\s57893\softwares\apache-tomcat-7.0.27\Medic\src\main\reports\AllReports\

Please send me one example?


Solution

  • Because of the way appendReplacement() works, you'll need to escape backslashes that you find in the environment variable. From the Javadocs:

    Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

    I would use:

    m.appendReplacement(sb, 
        null == envVarValue ? "" : Matcher.quoteReplacement(envVarValue));