RFE: StringTemplate interpolation with custom function

Rob Spoor openjdk at icemanx.nl
Thu Oct 26 20:25:12 UTC 2023


Because if you URL encode the entire interpolated string the : and / 
inside the URL will also be encoded (to %3A and %2F respectively).

Likewise, the CSV escaping will escape all of the double quotes incorrectly.


On 26/10/2023 22:05, Jim Laskey wrote:
> I think I’m missing something. Why wouldn’t you just;
> 
> import java.lang.StringTemplate.Processor;
> 
> Processor<URL, RuntimeException> urlEncode = template -> URLEncoder.encode(template.interpolate(), UTF_8));
> 
> Processor<String, RuntimeException> CSV = template -> StringEscapeUtils.escapeCsv<https://commons.apache.org/proper/commons-lang/apidocs/src-html/org/apache/commons/lang3/StringEscapeUtils.html#line.768>(template.interpolate());
> 
> 
> On Oct 26, 2023, at 4:47 PM, Rob Spoor <openjdk at icemanx.nl> wrote:
> 
> I've been reading up on string templates, and I think it's a very cool feature. However, writing a custom processor can be a lot of copy-paste work if you want STR but with some extra translation applied. For instance, if I'd want to have a URL encoding processor I would have to write everything from scratch.
> 
> I think it would be useful to overload interpolate (both static and non-static) with a custom Function<Object, String> as additional arguments. This would work like STR if that provided String::valueOf as function.
> 
> With this method, creating a URL encoding processor would be as simple as this:
> 
>     var urlEncode = template -> template.interpolate(o ->
>             URLEncoder.encode(String.valueOf(o), UTF_8));
> 
>     var url = urlEncode."https://host/path/\{id}?param=\{value\}";
> 
> 
> Likewise, a processor backed by Apache Commons Text's StringEscapeUtils would now be just as simple:
> 
>     var CSV = template -> template.interpolate(o ->
>             StringEscapeUtils.ESCAPE_CSV.translate(String.valueOf(o));
> 
>     var csv = CSV."""
>             Header1, Header2, Header3
>             "\{value1}", "\{value2}", "\{value3}"
>             """;
> 
> 
> If the JVM allows it, the existing interpolate method can even delegate to the new overload providing String::valueOf.
> 



More information about the core-libs-dev mailing list