
in.ashwanthkumar.utils.template.TemplateParser Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of my-java-utils Show documentation
Show all versions of my-java-utils Show documentation
My personal set of utils that I take along with my java projects.
The newest version!
package in.ashwanthkumar.utils.template;
import in.ashwanthkumar.utils.collections.Lists;
import in.ashwanthkumar.utils.collections.Maps;
import in.ashwanthkumar.utils.func.Function;
import in.ashwanthkumar.utils.func.Functions;
import in.ashwanthkumar.utils.lang.tuple.Tuple2;
import in.ashwanthkumar.utils.parser.Parser;
import in.ashwanthkumar.utils.parser.Parsers;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* TemplateParser build using {@link in.ashwanthkumar.utils.parser.Parser}
*
* It supports the following type of rendering
*
* - {@code #{variable}} type substitution
* - {@code #{variable?default}} type substitution. Here if the {@code variable} value is not passed, it would assign the {@code default} value
*
*/
public class TemplateParser {
private Map variables;
public TemplateParser(Map variables) {
this.variables = variables;
}
public String render(String input) {
Parser baseParser = templateParser();
return Parsers.Sequence(baseParser)
.parse(input)
.map(new Function, String>() {
@Override
public String apply(List input) {
return Lists.mkString(input, "");
}
})
.get();
}
private Parser templateParser() {
Parser variableName = Parsers.Regex(Pattern.compile("[a-zA-Z0-9]+")).named("variable name regex");
Parser defaultValue = Parsers.Regex(Pattern.compile("[a-zA-Z0-9_$.]+")).named("default value regex");
Parser withDefault = Parsers.Literal("#{")
.thenR(variableName)
.thenL(Parsers.Literal("?"))
.then(defaultValue)
.thenL(Parsers.Literal("}"))
.map(new Function, State>() {
@Override
public State apply(Tuple2 input) {
return new State(input._1(), input._2());
}
});
Parser variableNameParser = Parsers.Literal("#{")
.thenR(variableName)
.thenL(Parsers.Literal("}"))
.map(new Function() {
@Override
public State apply(String input) {
return new State(input);
}
});
return withDefault
.or(variableNameParser)
.map(new Function() {
@Override
public String apply(State input) {
return String.valueOf(Maps.getOrElse(variables, input.variableName, input.defaultValue));
}
})
.or(Parsers.Regex(Pattern.compile(".")).named("match all"))
.map(Functions.identity());
}
static class State {
String variableName;
String defaultValue;
public State(String variableName) {
this.variableName = variableName;
}
public State(String variableName, String defaultValue) {
this.variableName = variableName;
this.defaultValue = defaultValue;
}
@Override
public String toString() {
return "State{" +
"variableName='" + variableName + '\'' +
", defaultValue='" + defaultValue + '\'' +
'}';
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy