Substitute.java

package org.docascode.api.core;

import org.docascode.api.core.errors.DocAsCodeException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Substitute {
    private Substitute(){}

    /**
     * @param string The String to evaluate (e.g. @key1@-text-@key2@)
     * @param dict A dictionnary for subsitution words (e.g. dict(key1)=value1 and dict(key2)=value2)
     * @return The substituted String (e.g. value1-text-value2)
     */
    public static String substitute (String string, Map<String,String> dict) throws DocAsCodeException {
        if (string == null){
            return null;
        }
        String result = string;
        Pattern p = Pattern.compile("@(.*?)@");
        Matcher m = p.matcher(result);
        String key;
        while(m.find())
        {
            key = m.group(1);
            if (!dict.containsKey(key)){
                throw new DocAsCodeException(
                        String.format("Cannot find property '%s' in dictionnary.",key));
            }
            result = m.replaceFirst(dict.get(key));
            m = p.matcher(result);
        }
        return result;
    }

    public static Map<String,String> substitute (List<String> strings, Map<String,String> dict) throws DocAsCodeException {
        HashMap<String,String> result = new HashMap<>();
        for (String string : strings){
            result.put(string,substitute(string,dict));
        }
        return result;
    }
}