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

org.joinedworkz.common.helper.VariableHelper Maven / Gradle / Ivy

There is a newer version: 1.3.51
Show newest version
package org.joinedworkz.common.helper;

import java.util.function.UnaryOperator;
import java.util.regex.Pattern;

import javax.inject.Singleton;

@Singleton
public class VariableHelper {

	    private static Pattern variablePattern = Pattern.compile("\\$\\{(.+?)\\}");

	    public String replaceVariables(final String template, final UnaryOperator variableValueProvider) {
	        if (template != null) {
	            final var matcher = variablePattern.matcher(template);
	            final var builder = new StringBuilder();
	            var i = 0;
	            while (matcher.find()) {
	                builder.append(template.substring(i, matcher.start()));
	                final var variableOccurence = matcher.group(1);
	                final var replacement = determineReplacement(variableValueProvider, variableOccurence);
	                if (replacement != null) {
	                	builder.append(replacement);
	                }
	                i = matcher.end();
	            }
	            builder.append(template.substring(i, template.length()));
	            return builder.toString();
	        }
	        return null;
	    }

	    protected String determineReplacement(final UnaryOperator variableValueProvider, final String variableOccurence) {
	        final var firstColonIndex = variableOccurence.indexOf(':');
	        String variableName;
	        String defaultValue = null;
	        if (firstColonIndex > 0) {
	            variableName = variableOccurence.substring(0, firstColonIndex).trim();
	            if (variableName.isEmpty()) {
	                throw new RuntimeException("Variable occurrence in template results in empty variable name: '" + variableOccurence + "'");
	            }
	            if (firstColonIndex < variableOccurence.length() -1 ) {
	                defaultValue = variableOccurence.substring(firstColonIndex + 1).trim();
	            }
	        } else {
	            variableName = variableOccurence.trim();
	        }
	        final var replacement = variableValueProvider.apply(variableName);
	        if (replacement == null && defaultValue != null) {
	            return defaultValue;
	        }
	        return replacement;
	    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy