All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.databasesandlife.util.PlaintextParameterReplacer Maven / Gradle / Ivy

The newest version!
package com.databasesandlife.util;

import com.databasesandlife.util.gwtsafe.ConfigurationException;

import java.util.Collection;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static java.util.regex.Matcher.quoteReplacement;

public class PlaintextParameterReplacer {

    /** Replaces variables such as ${XYZ} in the template. Variables which are not found remain in their original unreplaced form. */
    public static String replacePlainTextParameters(String template, Map parameters) {
        var result = new StringBuilder();
        var matcher = Pattern.compile("\\$\\{(.+?)}").matcher(template);
        while (matcher.find()) {
            var name = matcher.group(1);
            var replacement = parameters.get(name);
            if (replacement == null) replacement = matcher.group();
            matcher.appendReplacement(result, quoteReplacement(replacement));
        }
        matcher.appendTail(result);
        return result.toString();
    }

    public static String replacePlainTextParametersWithBlanks(String template) {
        return template.replaceAll("\\$\\{.+?}", "");
    }

    public static void assertParametersSuffice(Collection params, CharSequence template, String msg) throws ConfigurationException {
        if (template == null) return;
        var m = Pattern.compile("\\$\\{(.+?)}").matcher(template);
        while (m.find())
            if ( ! params.contains(m.group(1)))
                throw new ConfigurationException(msg+": Pattern '"+template+"' contains parameter ${"+m.group(1)+"} but it is not available; "
                    + "available parameters are "+params.stream().map(p -> "${"+p+"}").collect(Collectors.joining(", ")));
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy