From 7755990dfedede27bb6422de66e27b484255a1ad Mon Sep 17 00:00:00 2001 From: =?utf8?q?David=20=E2=80=98Bombe=E2=80=99=20Roden?= Date: Tue, 21 Jun 2011 09:11:49 +0200 Subject: [PATCH] Add length parameter to text parser. --- .../pterodactylus/sone/template/ParserFilter.java | 34 +++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) 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. */ } -- 2.7.4