com.greenpepper.runner.dialect.MarkdownDialect Maven / Gradle / Ivy
package com.greenpepper.runner.dialect;
import static com.greenpepper.shaded.org.apache.commons.lang3.StringUtils.isBlank;
import java.io.IOException;
import java.io.StringReader;
import java.util.Collections;
import com.greenpepper.shaded.org.jsoup.Jsoup;
import com.greenpepper.shaded.org.jsoup.nodes.Document;
import com.greenpepper.shaded.org.slf4j.Logger;
import com.greenpepper.shaded.org.slf4j.LoggerFactory;
import com.greenpepper.dialect.SpecificationDialect;
import com.greenpepper.dialect.SpecificationDialectException;
import com.greenpepper.shaded.com.vladsch.flexmark.ast.Node;
import com.greenpepper.shaded.com.vladsch.flexmark.ext.tables.TablesExtension;
import com.greenpepper.shaded.com.vladsch.flexmark.html.HtmlRenderer;
import com.greenpepper.shaded.com.vladsch.flexmark.parser.Parser;
import com.greenpepper.shaded.com.vladsch.flexmark.util.options.MutableDataSet;
public class MarkdownDialect implements SpecificationDialect {
private static final Logger LOGGER = LoggerFactory.getLogger(MarkdownDialect.class);
private static final String EMPTY_STRING = "";
private final Parser parser;
private final HtmlRenderer renderer;
public MarkdownDialect() {
MutableDataSet options = new MutableDataSet()
.set(Parser.EXTENSIONS, Collections.singletonList(TablesExtension.create()));
parser = Parser.builder(options).build();
renderer = HtmlRenderer.builder(options).build();
}
@Override
public String convert(String input) throws SpecificationDialectException {
try {
if (isBlank(input)) {
return EMPTY_STRING;
}
Node document = parser.parseReader(new StringReader(input));
String render = renderer.render(document);
// Ensure the result starts with html tags
Document jsoupDoc = Jsoup.parse(render);
LOGGER.debug("converted HTML:\n {}", jsoupDoc);
return jsoupDoc.toString();
} catch (IOException e) {
throw new SpecificationDialectException("Can't parse the input.", e);
}
}
}