How to use StrSubstitutor

StrSubstitutor is a class available in the commons-lang package which is used to Substitutes variables within a string by values.

In this post, we are going to see how we can use this StrSubstitutor with few examples.

Assume that you have a string like this “LANG: ${LANG}”. Now you want to replace ${LANG} by env variable value.

You can simply call the System.getenv method for this key and get the value and replace it in this string content. But what happens if we want to do the same kind of substitutions for many string expressions. During that time the class StrSubstitutor class comes in handy.

In the below example, I have created an instance of StrSubstitutor class and passing an instance of EnvLookUp which is a subclass of StrLookup class. The StrLookup class is used to lookup a String key to a String value. Here in this, we want to look up the value from the environmental variables. Hence, I have created a class which extends the StrLookup and override the lookup method with my own implementation.

So when we call the “replace” method of StrSubstitutor(envPropertyResolver) with the sample string, then it will go and look up the env variables and find the value, then substitute the value in the string expression.

StrSubstitutorMain.java



import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.StrLookup;
import org.apache.commons.lang3.text.StrSubstitutor;

public class StrSubstitutorMain {

    private static final StrSubstitutor envPropertyResolver = new StrSubstitutor(new EnvLookUp());

    public static void main(String[] args) {

        String sample = "LANG: ${LANG}";
        //LANG: en_US.UTF-8
        System.out.println(envPropertyResolver.replace(sample));

    }

    private static class EnvLookUp extends StrLookup {

        @Override
        public String lookup(String key) {
            String value = System.getenv(key);
            if (StringUtils.isBlank(value)) {
                throw new IllegalArgumentException("key" + key + "is not found in the env variables");
            }
            return value;
        }
    }
}


Tne above one is a very simple example, Now let’s see how we can use this to substitute the variables found in a property file.

Here is our properties file.

test-prop.properties


java.home=${JAVA_HOME}
java.version=${java.version}
os.name=${os.name}

Now, We have to modify our code to read the above properties file and substitute the variables with the env variables.

Refer below the updated code. Once we load the properties, then we have to call the replaceAll method of Properties class and use our StrSubstitutor (envPropertyResolver) over there. So for each key/value pair, the StrSubstitutor’s replace method would be called and the corresponding value would be passed and it will replace all the variables found in property value.

StrPropertySubstitutor.java



import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.StrLookup;
import org.apache.commons.lang3.text.StrSubstitutor;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class StrPropertySubstitutor {

    private static final StrSubstitutor envPropertyResolver = new StrSubstitutor(new EnvLookUp());

    public static void main(String[] args) {

        Properties properties = new Properties();;
        try (InputStream is =
                StrPropertySubstitutor.class.getClassLoader().getResourceAsStream("test-prop.properties")) {
            properties.load(is);
            properties.replaceAll((k, v) -> envPropertyResolver.replace((String) v));
        }
        catch (IOException io) {
            io.printStackTrace();
        }

        properties.forEach( (k, v) -> System.out.println("key:: " + k + " value: "+v));

    }

    private static class EnvLookUp extends StrLookup {

        @Override
        public String lookup(String key) {
            String value = System.getenv(key);
            if (StringUtils.isBlank(value)) {
                throw new IllegalArgumentException("key " + key + " is not found in the env variables");
            }
            return value;
        }
    }

}


Output:

The output will be like below,


key::os.name value: Linux
key::java.home value: /usr/lib/jvm/java-8-oracle
key::java.version value: 1.8.0_144

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s