Add XML filter to the correct template factory.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / SoneInserter.java
1 /*
2  * FreenetSone - SoneInserter.java - Copyright © 2010 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.core;
19
20 import java.io.InputStreamReader;
21 import java.io.StringWriter;
22 import java.nio.charset.Charset;
23 import java.util.HashMap;
24 import java.util.logging.Level;
25 import java.util.logging.Logger;
26
27 import net.pterodactylus.sone.data.Sone;
28 import net.pterodactylus.sone.freenet.StringBucket;
29 import net.pterodactylus.util.io.Closer;
30 import net.pterodactylus.util.logging.Logging;
31 import net.pterodactylus.util.service.AbstractService;
32 import net.pterodactylus.util.template.DefaultTemplateFactory;
33 import net.pterodactylus.util.template.ReflectionAccessor;
34 import net.pterodactylus.util.template.Template;
35 import net.pterodactylus.util.template.TemplateException;
36 import net.pterodactylus.util.template.XmlFilter;
37 import freenet.client.async.ManifestElement;
38 import freenet.keys.FreenetURI;
39
40 /**
41  * A Sone inserter is responsible for inserting a Sone if it has changed.
42  *
43  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
44  */
45 public class SoneInserter extends AbstractService {
46
47         /** The logger. */
48         private static final Logger logger = Logging.getLogger(SoneInserter.class);
49
50         /** The template factory used to create the templates. */
51         private static final DefaultTemplateFactory templateFactory = new DefaultTemplateFactory();
52
53         static {
54                 templateFactory.addAccessor(Object.class, new ReflectionAccessor());
55                 templateFactory.addFilter("xml", new XmlFilter());
56         }
57
58         /** The UTF-8 charset. */
59         private static final Charset utf8Charset = Charset.forName("UTF-8");
60
61         /** The Freenet interface. */
62         private final FreenetInterface freenetInterface;
63
64         /** The Sone to insert. */
65         private final Sone sone;
66
67         /**
68          * Creates a new Sone inserter.
69          *
70          * @param freenetInterface
71          *            The freenet interface
72          * @param sone
73          *            The Sone to insert
74          */
75         public SoneInserter(FreenetInterface freenetInterface, Sone sone) {
76                 super("Sone Inserter for “" + sone.getName() + "”");
77                 this.freenetInterface = freenetInterface;
78                 this.sone = sone;
79         }
80
81         //
82         // SERVICE METHODS
83         //
84
85         /**
86          * {@inheritDoc}
87          */
88         @Override
89         protected void serviceRun() {
90                 long modificationCounter = 0;
91                 boolean restartNow = true;
92                 while (!shouldStop()) {
93                         if (!restartNow) {
94                                 logger.log(Level.FINEST, "Waiting 60 seconds before checking Sone “" + sone.getName() + "”.");
95                                 sleep(60 * 1000);
96                         }
97                         restartNow = false;
98                         InsertInformation insertInformation = null;
99                         synchronized (sone) {
100                                 modificationCounter = sone.getModificationCounter();
101                                 if (modificationCounter > 0) {
102                                         insertInformation = new InsertInformation(sone.getRequestUri(), sone.getInsertUri());
103                                 }
104                         }
105                         if (insertInformation != null) {
106                                 logger.log(Level.INFO, "Inserting Sone “%s”…", new Object[] { sone.getName() });
107
108                                 boolean success = false;
109                                 try {
110                                         FreenetURI finalUri = freenetInterface.insertDirectory(insertInformation.getInsertUri().setKeyType("USK").setDocName("Sone-" + sone.getName()).setSuggestedEdition(0), insertInformation.generateManifestEntries(), "index.html");
111                                         sone.updateUris(finalUri);
112                                         success = true;
113                                         logger.log(Level.INFO, "Inserted Sone “%s” at %s.", new Object[] { sone.getName(), finalUri });
114                                 } catch (SoneException se1) {
115                                         logger.log(Level.WARNING, "Could not insert Sone “" + sone.getName() + "”!", se1);
116                                 }
117
118                                 /*
119                                  * reset modification counter if Sone has not been modified
120                                  * while it was inserted.
121                                  */
122                                 if (success) {
123                                         synchronized (sone) {
124                                                 if (sone.getModificationCounter() == modificationCounter) {
125                                                         logger.log(Level.FINE, "Sone “%s” was not modified further, resetting counter…", new Object[] { sone });
126                                                         sone.setModificationCounter(0);
127                                                 } else {
128                                                         logger.log(Level.FINE, "Sone “%s” was modified since the insert started, starting another insert…", new Object[] { sone });
129                                                         restartNow = true;
130                                                 }
131                                         }
132                                 }
133                         }
134                 }
135         }
136
137         /**
138          * Container for information that are required to insert a Sone. This
139          * container merely exists to copy all relevant data without holding a lock
140          * on the {@link Sone} object for too long.
141          *
142          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
143          */
144         private class InsertInformation {
145
146                 /** The request URI of the Sone. */
147                 private final FreenetURI requestUri;
148
149                 /** The insert URI of the Sone. */
150                 private final FreenetURI insertUri;
151
152                 /**
153                  * Creates a new insert information container.
154                  *
155                  * @param requestUri
156                  *            The request URI of the Sone
157                  * @param insertUri
158                  *            The insert URI of the Sone
159                  */
160                 public InsertInformation(FreenetURI requestUri, FreenetURI insertUri) {
161                         this.requestUri = requestUri;
162                         this.insertUri = insertUri;
163                 }
164
165                 //
166                 // ACCESSORS
167                 //
168
169                 /**
170                  * Returns the request URI of the Sone.
171                  *
172                  * @return The request URI of the Sone
173                  */
174                 @SuppressWarnings("unused")
175                 public FreenetURI getRequestUri() {
176                         return requestUri;
177                 }
178
179                 /**
180                  * Returns the insert URI of the Sone.
181                  *
182                  * @return The insert URI of the Sone
183                  */
184                 public FreenetURI getInsertUri() {
185                         return insertUri;
186                 }
187
188                 //
189                 // ACTIONS
190                 //
191
192                 /**
193                  * Generates all manifest entries required to insert this Sone.
194                  *
195                  * @return The manifest entries for the Sone insert
196                  */
197                 public HashMap<String, Object> generateManifestEntries() {
198                         HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
199
200                         /* first, create an index.html. */
201                         manifestEntries.put("index.html", createManifestElement("index.html", "text/html; charset=utf-8", "/templates/insert/index.html"));
202
203                         /* now, store the sone. */
204                         manifestEntries.put("sone.xml", createManifestElement("sone.xml", "text/xml; charset=utf-8", "/templates/insert/sone.xml"));
205
206                         return manifestEntries;
207                 }
208
209                 //
210                 // PRIVATE METHODS
211                 //
212
213                 /**
214                  * Creates a new manifest element.
215                  *
216                  * @param name
217                  *            The name of the file
218                  * @param contentType
219                  *            The content type of the file
220                  * @param templateName
221                  *            The name of the template to render
222                  * @return The manifest element
223                  */
224                 @SuppressWarnings("synthetic-access")
225                 private ManifestElement createManifestElement(String name, String contentType, String templateName) {
226                         InputStreamReader templateInputStreamReader;
227                         Template template = templateFactory.createTemplate(templateInputStreamReader = new InputStreamReader(getClass().getResourceAsStream(templateName), utf8Charset));
228                         try {
229                                 template.parse();
230                         } catch (TemplateException te1) {
231                                 logger.log(Level.SEVERE, "Could not parse template “" + templateName + "”!", te1);
232                                 return null;
233                         } finally {
234                                 Closer.close(templateInputStreamReader);
235                         }
236                         template.set("currentSone", sone);
237                         StringWriter writer = new StringWriter();
238                         StringBucket bucket = null;
239                         try {
240                                 template.render(writer);
241                                 bucket = new StringBucket(writer.toString(), utf8Charset);
242                                 return new ManifestElement(name, bucket, contentType, bucket.size());
243                         } catch (TemplateException te1) {
244                                 logger.log(Level.SEVERE, "Could not render template “" + templateName + "”!", te1);
245                                 return null;
246                         } finally {
247                                 Closer.close(writer);
248                                 if (bucket != null) {
249                                         bucket.free();
250                                 }
251                         }
252                 }
253
254         }
255
256 }