Prevent NPE when no length is given.
[Sone.git] / src / main / java / net / pterodactylus / sone / template / ParserFilter.java
1 /*
2  * Sone - ParserFilter.java - Copyright © 2011 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sone.template;
19
20 import java.io.IOException;
21 import java.io.StringReader;
22 import java.io.StringWriter;
23 import java.io.Writer;
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.Map;
27
28 import net.pterodactylus.sone.core.Core;
29 import net.pterodactylus.sone.data.Sone;
30 import net.pterodactylus.sone.text.FreenetLinkPart;
31 import net.pterodactylus.sone.text.LinkPart;
32 import net.pterodactylus.sone.text.Part;
33 import net.pterodactylus.sone.text.PlainTextPart;
34 import net.pterodactylus.sone.text.PostPart;
35 import net.pterodactylus.sone.text.SonePart;
36 import net.pterodactylus.sone.text.SoneTextParser;
37 import net.pterodactylus.sone.text.SoneTextParserContext;
38 import net.pterodactylus.sone.web.page.Page.Request;
39 import net.pterodactylus.util.template.Filter;
40 import net.pterodactylus.util.template.Template;
41 import net.pterodactylus.util.template.TemplateContext;
42 import net.pterodactylus.util.template.TemplateContextFactory;
43 import net.pterodactylus.util.template.TemplateParser;
44
45 /**
46  * Filter that filters a given text through a {@link SoneTextParser}.
47  *
48  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
49  */
50 public class ParserFilter implements Filter {
51
52         /** The core. */
53         private final Core core;
54
55         /** The link parser. */
56         private final SoneTextParser soneTextParser;
57
58         /** The template context factory. */
59         private final TemplateContextFactory templateContextFactory;
60
61         /** The template for {@link PlainTextPart}s. */
62         private final Template plainTextTemplate = TemplateParser.parse(new StringReader("<%text|html>"));
63
64         /** The template for {@link FreenetLinkPart}s. */
65         private final Template linkTemplate = TemplateParser.parse(new StringReader("<a class=\"<%cssClass|html>\" href=\"<%link|html>\" title=\"<%title|html>\"><%text|html></a>"));
66
67         /**
68          * Creates a new filter that runs its input through a {@link SoneTextParser}
69          * .
70          *
71          * @param core
72          *            The core
73          * @param templateContextFactory
74          *            The context factory for rendering the parts
75          * @param soneTextParser
76          *            The Sone text parser
77          */
78         public ParserFilter(Core core, TemplateContextFactory templateContextFactory, SoneTextParser soneTextParser) {
79                 this.core = core;
80                 this.templateContextFactory = templateContextFactory;
81                 this.soneTextParser = soneTextParser;
82         }
83
84         /**
85          * {@inheritDoc}
86          */
87         @Override
88         public Object format(TemplateContext templateContext, Object data, Map<String, String> parameters) {
89                 String text = String.valueOf(data);
90                 int length = -1;
91                 try {
92                         length = Integer.parseInt(parameters.get("length"));
93                 } catch (NumberFormatException nfe1) {
94                         /* ignore. */
95                 }
96                 if ((length == -1) && (parameters.get("length") != null)) {
97                         try {
98                                 length = Integer.parseInt(String.valueOf(templateContext.get(parameters.get("length"))));
99                         } catch (NumberFormatException nfe1) {
100                                 /* ignore. */
101                         }
102                 }
103                 String soneKey = parameters.get("sone");
104                 if (soneKey == null) {
105                         soneKey = "sone";
106                 }
107                 Sone sone = (Sone) templateContext.get(soneKey);
108                 if (sone == null) {
109                         sone = core.getSone(soneKey, false);
110                 }
111                 Request request = (Request) templateContext.get("request");
112                 SoneTextParserContext context = new SoneTextParserContext(request, sone);
113                 StringWriter parsedTextWriter = new StringWriter();
114                 try {
115                         Iterable<Part> parts = soneTextParser.parse(context, new StringReader(text));
116                         if (length > -1) {
117                                 List<Part> shortenedParts = new ArrayList<Part>();
118                                 for (Part part : parts) {
119                                         if (part instanceof PlainTextPart) {
120                                                 String longText = ((PlainTextPart) part).getText();
121                                                 if (length >= longText.length()) {
122                                                         shortenedParts.add(part);
123                                                 } else {
124                                                         shortenedParts.add(new PlainTextPart(longText.substring(0, length) + "…"));
125                                                 }
126                                                 length -= longText.length();
127                                         } else if (part instanceof LinkPart) {
128                                                 shortenedParts.add(part);
129                                                 length -= ((LinkPart) part).getText().length();
130                                         } else {
131                                                 shortenedParts.add(part);
132                                         }
133                                         if (length <= 0) {
134                                                 break;
135                                         }
136                                 }
137                                 parts = shortenedParts;
138                         }
139                         render(parsedTextWriter, parts);
140                 } catch (IOException ioe1) {
141                         /* no exceptions in a StringReader or StringWriter, ignore. */
142                 }
143                 return parsedTextWriter.toString();
144         }
145
146         //
147         // PRIVATE METHODS
148         //
149
150         /**
151          * Renders the given parts.
152          *
153          * @param writer
154          *            The writer to render the parts to
155          * @param parts
156          *            The parts to render
157          */
158         private void render(Writer writer, Iterable<Part> parts) {
159                 for (Part part : parts) {
160                         render(writer, part);
161                 }
162         }
163
164         /**
165          * Renders the given part.
166          *
167          * @param writer
168          *            The writer to render the part to
169          * @param part
170          *            The part to render
171          */
172         @SuppressWarnings("unchecked")
173         private void render(Writer writer, Part part) {
174                 if (part instanceof PlainTextPart) {
175                         render(writer, (PlainTextPart) part);
176                 } else if (part instanceof FreenetLinkPart) {
177                         render(writer, (FreenetLinkPart) part);
178                 } else if (part instanceof LinkPart) {
179                         render(writer, (LinkPart) part);
180                 } else if (part instanceof SonePart) {
181                         render(writer, (SonePart) part);
182                 } else if (part instanceof PostPart) {
183                         render(writer, (PostPart) part);
184                 } else if (part instanceof Iterable<?>) {
185                         render(writer, (Iterable<Part>) part);
186                 }
187         }
188
189         /**
190          * Renders the given plain-text part.
191          *
192          * @param writer
193          *            The writer to render the part to
194          * @param plainTextPart
195          *            The part to render
196          */
197         private void render(Writer writer, PlainTextPart plainTextPart) {
198                 TemplateContext templateContext = templateContextFactory.createTemplateContext();
199                 templateContext.set("text", plainTextPart.getText());
200                 plainTextTemplate.render(templateContext, writer);
201         }
202
203         /**
204          * Renders the given freenet link part.
205          *
206          * @param writer
207          *            The writer to render the part to
208          * @param freenetLinkPart
209          *            The part to render
210          */
211         private void render(Writer writer, FreenetLinkPart freenetLinkPart) {
212                 renderLink(writer, "/" + freenetLinkPart.getLink(), freenetLinkPart.getText(), freenetLinkPart.getTitle(), freenetLinkPart.isTrusted() ? "freenet-trusted" : "freenet");
213         }
214
215         /**
216          * Renders the given link part.
217          *
218          * @param writer
219          *            The writer to render the part to
220          * @param linkPart
221          *            The part to render
222          */
223         private void render(Writer writer, LinkPart linkPart) {
224                 renderLink(writer, "/?_CHECKED_HTTP_=" + linkPart.getLink(), linkPart.getText(), linkPart.getTitle(), "internet");
225         }
226
227         /**
228          * Renders the given Sone part.
229          *
230          * @param writer
231          *            The writer to render the part to
232          * @param sonePart
233          *            The part to render
234          */
235         private void render(Writer writer, SonePart sonePart) {
236                 renderLink(writer, "viewSone.html?sone=" + sonePart.getSone().getId(), SoneAccessor.getNiceName(sonePart.getSone()), SoneAccessor.getNiceName(sonePart.getSone()), "in-sone");
237         }
238
239         /**
240          * Renders the given post part.
241          *
242          * @param writer
243          *            The writer to render the part to
244          * @param postPart
245          *            The part to render
246          */
247         private void render(Writer writer, PostPart postPart) {
248                 renderLink(writer, "viewPost.html?post=" + postPart.getPost().getId(), getExcerpt(postPart.getPost().getText(), 20), SoneAccessor.getNiceName(postPart.getPost().getSone()), "in-sone");
249         }
250
251         /**
252          * Renders the given link.
253          *
254          * @param writer
255          *            The writer to render the link to
256          * @param link
257          *            The link to render
258          * @param text
259          *            The text of the link
260          * @param title
261          *            The title of the link
262          * @param cssClass
263          *            The CSS class of the link
264          */
265         private void renderLink(Writer writer, String link, String text, String title, String cssClass) {
266                 TemplateContext templateContext = templateContextFactory.createTemplateContext();
267                 templateContext.set("cssClass", cssClass);
268                 templateContext.set("link", link);
269                 templateContext.set("text", text);
270                 templateContext.set("title", title);
271                 linkTemplate.render(templateContext, writer);
272         }
273
274         //
275         // STATIC METHODS
276         //
277
278         /**
279          * Returns up to {@code length} characters from the given text, appending
280          * “…” if the text is longer.
281          *
282          * @param text
283          *            The text to get an excerpt from
284          * @param length
285          *            The maximum length of the excerpt (without the ellipsis)
286          * @return The excerpt of the text
287          */
288         private static String getExcerpt(String text, int length) {
289                 if (text.length() > length) {
290                         return text.substring(0, length) + "…";
291                 }
292                 return text;
293         }
294
295 }