A set of utility classes for working with string templates.
Class StringTemplateProcessors
can be used to easily construct string template processors that work like the default STR
template processor, except they apply a function to the template values.
For instance, using Apache Commons Text:
StringTemplate.Processor<String, RuntimeException> JSON = StringTemplateProcessors
.interpolateMapped(o -> StringEscapeUtils.ESCAPE_JSON.translate(String.valueOf(o)));
String json = JSON."""
{
"id": \{id},
"name": "\{name}"
}
""";
Or equivalent, to prevent having to call String.valueOf
explicitly:
StringTemplate.Processor<String, RuntimeException> JSON = StringTemplateProcessors
.interpolateMappedAsString(s -> StringEscapeUtils.ESCAPE_JSON.translate(s));
String json = JSON."""
{
"id": \{id},
"name": "\{name}"
}
""";
In both cases, the name
property will have a properly escaped value.
Class URLEncoderProcessor
is a string template processor that uses URLEncoder for encoding template values. This makes it safe to use to create URIs. For example, using a static import:
URI uri = encodeAsURI()."https://host/path/\{id}?url=\{url}";
If id
is id/123
and url
is https://example.org?q=1
, the result will be https://host/path/id%2F123?url=https%3A%2F%2Fexample.org%3Fq%3D1
.