SubstituteCtrl.java

package org.docascode.office;

import org.docascode.utils.DocAsCodeException;
import java.io.File;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SubstituteCtrl {
    /**
     * @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, HashMap<String,String> dict) throws DocAsCodeException {
        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("Cannot find property "+key+" in dictionnary.");
            }
            result = m.replaceFirst(dict.get(key));
            m = p.matcher(result);
        }
        return result;
    }

    public static String substitute(String string, File file) throws DocAsCodeException {
        String result;
        if (string.contains("@")){
            try{
                result=substitute(string, Dictionnaries.getInstance().get(file));
            } catch (DocAsCodeException e){
                throw new DocAsCodeException("Cannot substitute string "+string+" with properties given in "+file.getAbsolutePath(),e);
            }
        } else {
            result  = string;
        }
        return result;
    }
}