2 * Sone - ParserFilter.java - Copyright © 2011–2013 David Roden
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.
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.
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/>.
18 package net.pterodactylus.sone.template;
20 import static java.lang.String.valueOf;
22 import java.io.IOException;
23 import java.io.StringReader;
24 import java.util.Collections;
27 import net.pterodactylus.sone.core.Core;
28 import net.pterodactylus.sone.data.Sone;
29 import net.pterodactylus.sone.text.Part;
30 import net.pterodactylus.sone.text.SoneTextParser;
31 import net.pterodactylus.sone.text.SoneTextParserContext;
32 import net.pterodactylus.sone.web.page.FreenetRequest;
33 import net.pterodactylus.util.template.Filter;
34 import net.pterodactylus.util.template.TemplateContext;
37 * Filter that filters a given text through a {@link SoneTextParser} and returns the parsed {@link Part}s.
39 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
41 public class ParserFilter implements Filter {
43 private final Core core;
44 private final SoneTextParser soneTextParser;
46 public ParserFilter(Core core, SoneTextParser soneTextParser) {
48 this.soneTextParser = soneTextParser;
55 public Object format(TemplateContext templateContext, Object data, Map<String, Object> parameters) {
56 String text = valueOf(data);
57 Object sone = parameters.get("sone");
58 if (sone instanceof String) {
59 sone = core.getSone((String) sone).orNull();
61 FreenetRequest request = (FreenetRequest) templateContext.get("request");
62 SoneTextParserContext context = new SoneTextParserContext(request, (Sone) sone);
64 return soneTextParser.parse(context, new StringReader(text));
65 } catch (IOException ioe1) {
66 /* no exceptions in a StringReader, ignore. */
67 return Collections.<Part>emptyList();