From: David ‘Bombe’ Roden Date: Tue, 21 Jun 2011 07:11:49 +0000 (+0200) Subject: Add length parameter to text parser. X-Git-Tag: 0.6.6^2~67 X-Git-Url: https://git.pterodactylus.net/?a=commitdiff_plain;h=7755990dfedede27bb6422de66e27b484255a1ad;p=Sone.git Add length parameter to text parser. --- diff --git a/src/main/java/net/pterodactylus/sone/template/ParserFilter.java b/src/main/java/net/pterodactylus/sone/template/ParserFilter.java index 26afe2e..5f6fd3e 100644 --- a/src/main/java/net/pterodactylus/sone/template/ParserFilter.java +++ b/src/main/java/net/pterodactylus/sone/template/ParserFilter.java @@ -21,6 +21,8 @@ import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; +import java.util.ArrayList; +import java.util.List; import java.util.Map; import net.pterodactylus.sone.core.Core; @@ -85,6 +87,12 @@ public class ParserFilter implements Filter { @Override public Object format(TemplateContext templateContext, Object data, Map parameters) { String text = String.valueOf(data); + int length = -1; + try { + length = Integer.parseInt(parameters.get("length")); + } catch (NumberFormatException nfe1) { + /* ignore. */ + } String soneKey = parameters.get("sone"); if (soneKey == null) { soneKey = "sone"; @@ -97,7 +105,31 @@ public class ParserFilter implements Filter { SoneTextParserContext context = new SoneTextParserContext(request, sone); StringWriter parsedTextWriter = new StringWriter(); try { - render(parsedTextWriter, soneTextParser.parse(context, new StringReader(text))); + Iterable parts = soneTextParser.parse(context, new StringReader(text)); + if (length > -1) { + List shortenedParts = new ArrayList(); + for (Part part : parts) { + if (part instanceof PlainTextPart) { + String longText = ((PlainTextPart) part).getText(); + if (length >= longText.length()) { + shortenedParts.add(part); + } else { + shortenedParts.add(new PlainTextPart(longText.substring(0, length))); + } + length -= longText.length(); + } else if (part instanceof LinkPart) { + shortenedParts.add(part); + length -= ((LinkPart) part).getText().length(); + } else { + shortenedParts.add(part); + } + if (length <= 0) { + break; + } + } + parts = shortenedParts; + } + render(parsedTextWriter, parts); } catch (IOException ioe1) { /* no exceptions in a StringReader or StringWriter, ignore. */ }