TemplatingServiceImpl.java
/*
* Copyright 2020 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gringlobal.service.impl;
import java.io.StringReader;
import java.io.StringWriter;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import lombok.extern.slf4j.Slf4j;
import com.vladsch.flexmark.ext.gfm.strikethrough.StrikethroughExtension;
import com.vladsch.flexmark.ext.tables.TablesExtension;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.util.ast.KeepType;
import com.vladsch.flexmark.util.ast.Node;
import com.vladsch.flexmark.util.data.MutableDataHolder;
import com.vladsch.flexmark.util.data.MutableDataSet;
import org.genesys.blocks.util.StringToJavaTimeConverter;
import org.gringlobal.service.TemplatingService;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriUtils;
import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;
import com.google.common.base.Charsets;
/**
* The TemplatingServiceImpl using Mustache https://github.com/spullara/mustache.java
*
* See http://mustache.github.io/mustache.5.html for manual.
*
* - All variables are HTML escaped by default. If you want to return unescaped HTML, use the triple mustache: {{{name}}}.
*/
@Service
@Slf4j
public class TemplatingServiceImpl implements TemplatingService {
/** The Constant flexmark OPTIONS. */
private static final MutableDataHolder OPTIONS = new MutableDataSet()
.set(Parser.REFERENCES_KEEP, KeepType.LAST)
.set(Parser.HTML_BLOCK_PARSER, false)
// .set(Parser.HTML_BLOCK_DEEP_PARSER, true)
// .set(Parser.HTML_BLOCK_START_ONLY_ON_BLOCK_TAGS, true)
.set(HtmlRenderer.INDENT_SIZE, 2)
.set(HtmlRenderer.PERCENT_ENCODE_URLS, true)
// .set(HtmlRenderer.ESCAPE_HTML, false)
// for full GFM table compatibility add the following table extension options:
.set(TablesExtension.COLUMN_SPANS, false)
.set(TablesExtension.APPEND_MISSING_COLUMNS, true)
.set(TablesExtension.DISCARD_EXTRA_COLUMNS, true)
.set(TablesExtension.HEADER_SEPARATOR_COLUMN_MATCH, true)
.set(Parser.EXTENSIONS, List.of(
TablesExtension.create(),
StrikethroughExtension.create()
));
private static final Parser parser = Parser.builder(OPTIONS).build();
private static final HtmlRenderer renderer = HtmlRenderer.builder(OPTIONS).build();
/**
* Extra functions available in templates:
*
* - <code>URL</code>: URL encode the string
* - <code>URLPATH</code>: URL encodes path
* - <code>MARKDOWN</code> converts Markdown input to HTML
*/
private static final Map<String, Object> templateFunctions = Map.of(
// URL encode
"_url", (Function<String, String>) (input) -> UriUtils.encode(input, Charsets.UTF_8),
"URL", (Function<String, String>) (input) -> UriUtils.encode(input, Charsets.UTF_8),
"_urlpath", (Function<String, String>) (input) -> UriUtils.encodePath(input, Charsets.UTF_8),
"URLPATH", (Function<String, String>) (input) -> UriUtils.encodePath(input, Charsets.UTF_8),
"year", (Function<String, String>) TemplatingServiceImpl::formatToYear,
"YEAR", (Function<String, String>) TemplatingServiceImpl::formatToYear,
"formatDate", (Function<String, String>) TemplatingServiceImpl::formatDate,
"FORMATDATE", (Function<String, String>) TemplatingServiceImpl::formatDate,
"MARKDOWN", (Function<String, String>) TemplatingServiceImpl::formatMarkdown
);
@Override
public String fillTemplate(String template, Map<String, Object> params) {
return fillTemplate(compileTemplate(template), params);
}
@Override
public String fillTemplate(Mustache mustache, Map<String, Object> params) {
StringWriter swOut = new StringWriter();
var paramsPlus = new HashMap<>(params);
paramsPlus.putAll(templateFunctions);
mustache.execute(swOut, paramsPlus);
if (log.isTraceEnabled()) {
log.trace(swOut.toString());
}
return swOut.toString();
}
@Override
public Mustache compileTemplate(String template) {
MustacheFactory mf = new DefaultMustacheFactory();
return mf.compile(new StringReader(template), null);
}
private static String formatToYear(String input) {
var instant = StringToJavaTimeConverter.StringToInstantConverter.INSTANCE.convert(input);
return String.valueOf(instant.atOffset(ZoneOffset.UTC).getYear());
}
private static String formatDate(String input) {
String[] inputParts = input.split(" ");
if (inputParts.length != 2) {
throw new IllegalArgumentException("Can't parse input: ".concat(input));
}
String pattern = inputParts[0];
String date = inputParts[1];
var instant = StringToJavaTimeConverter.StringToInstantConverter.INSTANCE.convert(date);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern).withZone(ZoneOffset.UTC);
return formatter.format(instant);
}
private static String formatMarkdown(String input) {
final Node document = parser.parse(input);
return renderer.render(document);
}
}