Created
July 18, 2017 11:10
-
-
Save ukuhnhardt/c6e9bb5e55ee7bda5318fa11d4aa8bf9 to your computer and use it in GitHub Desktop.
A very simple Java String template renderer based on Java Reflection API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class StringTemplateRenderer { | |
private static final Logger log = LoggerFactory.getLogger(StringTemplateRenderer.class); | |
public String render(String templateString, RenderContext context) { | |
final List<String> expressions = getExpressions(templateString); | |
// each expression is turned into a value | |
Stream<String> values = expressions.stream() | |
.map(e -> resolve(context, getMethods(e))) | |
.map(v -> v+""); | |
String format = templateString.replaceAll("\\{.*?\\}", "%s"); | |
return String.format(format, values.toArray()); | |
} | |
private List<String> getExpressions(String subject) { | |
List<String> expressions = Lists.newArrayList(); | |
Matcher m = Pattern.compile("\\w*\\{(.*?)\\}").matcher(subject); | |
while (m.find()) { | |
String expression = m.group(1); | |
expressions.add(expression); | |
} | |
return expressions; | |
} | |
private List<String> getMethods(String expression) { | |
return Arrays.stream(expression.split("\\.")) | |
.map(m -> "get" + m.substring(0, 1).toUpperCase() + m.substring(1)) | |
.collect(Collectors.toList()); | |
} | |
private Object resolve(Object o, List<String> methods) { | |
if (methods.size() == 0) return o; | |
if (o instanceof RenderContext) { | |
String key = methods.get(0).replace("get", ""); | |
key = key.substring(0, 1).toLowerCase() + key.substring(1); | |
Object result = ((RenderContext) o).get(key); | |
methods.remove(0); | |
return resolve(result, methods); | |
} | |
Object result = null; | |
try { | |
Method m = o.getClass().getMethod(methods.get(0)); | |
result = m.invoke(o); | |
} catch (NoSuchMethodException e) { | |
log.error(e.getMessage(), e); | |
return String.format("[ERR: Method not found %s.%s]", o.getClass().getSimpleName(), methods.get(0)); | |
} catch (IllegalAccessException e) { | |
log.error(e.getMessage(), e); | |
return String.format("[ERR: %s: %s/%s]", e.getMessage(), o.getClass().getSimpleName(), methods.get(0)); | |
} catch (InvocationTargetException e) { | |
log.error(e.getMessage(), e); | |
return String.format("[ERR: %s: %s/%s]", e.getMessage(), o.getClass().getSimpleName(), methods.get(0)); | |
} | |
if (result == null) { | |
return String.format("[ERR: %s.%s is NULL]", o.getClass().getSimpleName(), methods.get(0)); | |
} | |
methods.remove(0); | |
return resolve(result, methods); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment