Text formatter feature holds formatters for different text formats allowing to generate (X)HTML code from various source types.


Central class for text processing is pl.wrzasq.commons.text.TextFormatter - it aggregates multiple format handlers. You can use it’s instance to format source text in any registred format:

Formatter formatter = new Formatter();
formatter.registerFormatter("plain", new PlainTextFormatter());
formatter.registerFormatter("html", new HtmlFormatter());
formatter.registerFormatter("markdown", new MarkdownFormatter());

// formats using plain text
String plainText = formatter.format("plain", "<foo bar>");

// formats using HTML
String html = formatter.format("html", "<p>foo</p>");

// formats using Markdown
String markdown = formatter.format("markdown", "**foo**");

// throws exception because of unknown format
String unknown = formatter.format("unknown", "foo");

Supported formats

Plain text

Handled by pl.wrzasq.commons.text.formatter.PlainTextFormatter. It returns HTML snippet that with all HTML special characters replaced by entities to avoid their interpretation. Also replaces new line characters with <br/> to map all lines.

FormatterInterface formatHandler = new PlainTextFormatter();

// generates "foo &lt;bar&gt;<br/>baz"
formatHandler.transform("foo <bar>\nbaz");


Handled by pl.wrzasq.commons.text.formatter.HtmlFormatter. Since we operate in (X)HTML by default this formatter does literally nothing - returns input text untouched.

FormatterInterface formatHandler = new HtmlFormatter();

// returns same input text
formatHandler.transform("foo <bar>\nbaz");


Handled by pl.wrzasq.commons.text.formatter.MarkdownFormatter. Formats Markdown into HTML. It uses Pegdown with all available extensions.

FormatterInterface formatHandler = new MarkdownFormatter();

// genrates "<p><strong>foo</strong> <em>bar</em></p>"
formatHandler.transform("**foo** _bar_");

Custom implementation

Apart from existing formatters there is an interface pl.wrzasq.commons.text.formatter.FormatterInterface. It can be used for implementing any custom format handler:

class MyTextFormatter implements FormatterInterface
    public String transform(String text)
        return "<p>" + text.replaceAll("\n", "</p><p>") + "</p>";