Float sender selection button to the left.
[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.util.Map;
23
24 import net.pterodactylus.sone.data.Sone;
25 import net.pterodactylus.sone.text.FreenetLinkParser;
26 import net.pterodactylus.sone.text.FreenetLinkParserContext;
27 import net.pterodactylus.util.template.DataProvider;
28 import net.pterodactylus.util.template.Filter;
29 import net.pterodactylus.util.template.TemplateFactory;
30
31 /**
32  * Filter that filters a given text through a {@link FreenetLinkParser}.
33  *
34  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
35  */
36 public class ParserFilter implements Filter {
37
38         /** The link parser. */
39         private final FreenetLinkParser linkParser;
40
41         /**
42          * Creates a new parser filter.
43          *
44          * @param templateFactory
45          *            The template factory for the link parser
46          */
47         public ParserFilter(TemplateFactory templateFactory) {
48                 this.linkParser = new FreenetLinkParser(templateFactory);
49         }
50
51         /**
52          * {@inheritDoc}
53          */
54         @Override
55         public Object format(DataProvider dataProvider, Object data, Map<String, String> parameters) {
56                 String text = String.valueOf(data);
57                 String soneKey = parameters.get("sone");
58                 if (soneKey == null) {
59                         soneKey = "sone";
60                 }
61                 Sone sone = (Sone) dataProvider.get(soneKey);
62                 FreenetLinkParserContext context = new FreenetLinkParserContext(sone);
63                 try {
64                         return linkParser.parse(context, new StringReader(text));
65                 } catch (IOException ioe1) {
66                         /* no exceptions in a StringReader, ignore. */
67                 }
68                 return null;
69         }
70
71 }