Use new template engine.
[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.ArrayList;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.Map;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
29
30 import net.pterodactylus.sone.core.Core.SoneStatus;
31 import net.pterodactylus.sone.data.Post;
32 import net.pterodactylus.sone.data.Reply;
33 import net.pterodactylus.sone.data.Sone;
34 import net.pterodactylus.sone.freenet.StringBucket;
35 import net.pterodactylus.sone.main.SonePlugin;
36 import net.pterodactylus.util.io.Closer;
37 import net.pterodactylus.util.logging.Logging;
38 import net.pterodactylus.util.service.AbstractService;
39 import net.pterodactylus.util.template.ReflectionAccessor;
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.TemplateException;
44 import net.pterodactylus.util.template.TemplateParser;
45 import net.pterodactylus.util.template.XmlFilter;
46 import freenet.client.async.ManifestElement;
47 import freenet.keys.FreenetURI;
48
49 /**
50  * A Sone inserter is responsible for inserting a Sone if it has changed.
51  *
52  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
53  */
54 public class SoneInserter extends AbstractService {
55
56         /** The logger. */
57         private static final Logger logger = Logging.getLogger(SoneInserter.class);
58
59         /** The insertion delay (in seconds). */
60         private static volatile int insertionDelay = 60;
61
62         /** The template factory used to create the templates. */
63         private static final TemplateContextFactory templateContextFactory = new TemplateContextFactory();
64
65         static {
66                 templateContextFactory.addAccessor(Object.class, new ReflectionAccessor());
67                 templateContextFactory.addFilter("xml", new XmlFilter());
68         }
69
70         /** The UTF-8 charset. */
71         private static final Charset utf8Charset = Charset.forName("UTF-8");
72
73         /** The core. */
74         private final Core core;
75
76         /** The Freenet interface. */
77         private final FreenetInterface freenetInterface;
78
79         /** The Sone to insert. */
80         private final Sone sone;
81
82         /** Whether a modification has been detected. */
83         private volatile boolean modified = false;
84
85         /** The fingerprint of the last insert. */
86         private volatile String lastInsertFingerprint;
87
88         /**
89          * Creates a new Sone inserter.
90          *
91          * @param core
92          *            The core
93          * @param freenetInterface
94          *            The freenet interface
95          * @param sone
96          *            The Sone to insert
97          */
98         public SoneInserter(Core core, FreenetInterface freenetInterface, Sone sone) {
99                 super("Sone Inserter for “" + sone.getName() + "”", false);
100                 this.core = core;
101                 this.freenetInterface = freenetInterface;
102                 this.sone = sone;
103         }
104
105         //
106         // ACCESSORS
107         //
108
109         /**
110          * Changes the insertion delay, i.e. the time the Sone inserter waits after
111          * it has noticed a Sone modification before it starts the insert.
112          *
113          * @param insertionDelay
114          *            The insertion delay (in seconds)
115          */
116         public static void setInsertionDelay(int insertionDelay) {
117                 SoneInserter.insertionDelay = insertionDelay;
118         }
119
120         /**
121          * Returns the fingerprint of the last insert.
122          *
123          * @return The fingerprint of the last insert
124          */
125         public String getLastInsertFingerprint() {
126                 return lastInsertFingerprint;
127         }
128
129         /**
130          * Sets the fingerprint of the last insert.
131          *
132          * @param lastInsertFingerprint
133          *            The fingerprint of the last insert
134          */
135         public void setLastInsertFingerprint(String lastInsertFingerprint) {
136                 this.lastInsertFingerprint = lastInsertFingerprint;
137         }
138
139         /**
140          * Returns whether the Sone inserter has detected a modification of the
141          * Sone.
142          *
143          * @return {@code true} if the Sone has been modified, {@code false}
144          *         otherwise
145          */
146         public boolean isModified() {
147                 return modified;
148         }
149
150         //
151         // SERVICE METHODS
152         //
153
154         /**
155          * {@inheritDoc}
156          */
157         @Override
158         protected void serviceRun() {
159                 long lastModificationTime = 0;
160                 String lastFingerprint = "";
161                 while (!shouldStop()) {
162                         /* check every seconds. */
163                         sleep(1000);
164
165                         /* don’t insert locked Sones. */
166                         if (core.isLocked(sone)) {
167                                 /* trigger redetection when the Sone is unlocked. */
168                                 synchronized (sone) {
169                                         modified = !sone.getFingerprint().equals(lastInsertFingerprint);
170                                 }
171                                 lastFingerprint = "";
172                                 lastModificationTime = 0;
173                                 continue;
174                         }
175
176                         InsertInformation insertInformation = null;
177                         synchronized (sone) {
178                                 String fingerprint = sone.getFingerprint();
179                                 if (!fingerprint.equals(lastFingerprint)) {
180                                         if (fingerprint.equals(lastInsertFingerprint)) {
181                                                 modified = false;
182                                                 lastModificationTime = 0;
183                                                 logger.log(Level.FINE, "Sone %s has been reverted to last insert state.", sone);
184                                         } else {
185                                                 lastModificationTime = System.currentTimeMillis();
186                                                 modified = true;
187                                                 logger.log(Level.FINE, "Sone %s has been modified, waiting %d seconds before inserting.", new Object[] { sone.getName(), insertionDelay });
188                                         }
189                                         lastFingerprint = fingerprint;
190                                 }
191                                 if (modified && (lastModificationTime > 0) && ((System.currentTimeMillis() - lastModificationTime) > (insertionDelay * 1000))) {
192                                         lastInsertFingerprint = fingerprint;
193                                         insertInformation = new InsertInformation(sone);
194                                 }
195                         }
196
197                         if (insertInformation != null) {
198                                 logger.log(Level.INFO, "Inserting Sone “%s”…", new Object[] { sone.getName() });
199
200                                 boolean success = false;
201                                 try {
202                                         core.setSoneStatus(sone, SoneStatus.inserting);
203                                         long insertTime = System.currentTimeMillis();
204                                         insertInformation.setTime(insertTime);
205                                         FreenetURI finalUri = freenetInterface.insertDirectory(insertInformation.getInsertUri().setKeyType("USK").setSuggestedEdition(0), insertInformation.generateManifestEntries(), "index.html");
206                                         /* at this point we might already be stopped. */
207                                         if (shouldStop()) {
208                                                 /* if so, bail out, don’t change anything. */
209                                                 break;
210                                         }
211                                         sone.setTime(insertTime);
212                                         sone.setLatestEdition(finalUri.getEdition());
213                                         success = true;
214                                         logger.log(Level.INFO, "Inserted Sone “%s” at %s.", new Object[] { sone.getName(), finalUri });
215                                 } catch (SoneException se1) {
216                                         logger.log(Level.WARNING, "Could not insert Sone “" + sone.getName() + "”!", se1);
217                                 } finally {
218                                         core.setSoneStatus(sone, SoneStatus.idle);
219                                 }
220
221                                 /*
222                                  * reset modification counter if Sone has not been modified
223                                  * while it was inserted.
224                                  */
225                                 if (success) {
226                                         synchronized (sone) {
227                                                 if (lastInsertFingerprint.equals(sone.getFingerprint())) {
228                                                         logger.log(Level.FINE, "Sone “%s” was not modified further, resetting counter…", new Object[] { sone });
229                                                         core.saveSone(sone);
230                                                         lastModificationTime = 0;
231                                                         modified = false;
232                                                 }
233                                         }
234                                 }
235                         }
236                 }
237         }
238
239         /**
240          * Container for information that are required to insert a Sone. This
241          * container merely exists to copy all relevant data without holding a lock
242          * on the {@link Sone} object for too long.
243          *
244          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
245          */
246         private class InsertInformation {
247
248                 /** All properties of the Sone, copied for thread safety. */
249                 private final Map<String, Object> soneProperties = new HashMap<String, Object>();
250
251                 /**
252                  * Creates a new insert information container.
253                  *
254                  * @param sone
255                  *            The sone to insert
256                  */
257                 public InsertInformation(Sone sone) {
258                         soneProperties.put("id", sone.getId());
259                         soneProperties.put("name", sone.getName());
260                         soneProperties.put("time", sone.getTime());
261                         soneProperties.put("requestUri", sone.getRequestUri());
262                         soneProperties.put("insertUri", sone.getInsertUri());
263                         soneProperties.put("profile", sone.getProfile());
264                         soneProperties.put("posts", new ArrayList<Post>(sone.getPosts()));
265                         soneProperties.put("replies", new HashSet<Reply>(sone.getReplies()));
266                         soneProperties.put("likedPostIds", new HashSet<String>(sone.getLikedPostIds()));
267                         soneProperties.put("likedReplyIds", new HashSet<String>(sone.getLikedReplyIds()));
268                 }
269
270                 //
271                 // ACCESSORS
272                 //
273
274                 /**
275                  * Returns the insert URI of the Sone.
276                  *
277                  * @return The insert URI of the Sone
278                  */
279                 public FreenetURI getInsertUri() {
280                         return (FreenetURI) soneProperties.get("insertUri");
281                 }
282
283                 /**
284                  * Sets the time of the Sone at the time of the insert.
285                  *
286                  * @param time
287                  *            The time of the Sone
288                  */
289                 public void setTime(long time) {
290                         soneProperties.put("time", time);
291                 }
292
293                 //
294                 // ACTIONS
295                 //
296
297                 /**
298                  * Generates all manifest entries required to insert this Sone.
299                  *
300                  * @return The manifest entries for the Sone insert
301                  */
302                 public HashMap<String, Object> generateManifestEntries() {
303                         HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
304
305                         /* first, create an index.html. */
306                         manifestEntries.put("index.html", createManifestElement("index.html", "text/html; charset=utf-8", "/templates/insert/index.html"));
307
308                         /* now, store the sone. */
309                         manifestEntries.put("sone.xml", createManifestElement("sone.xml", "text/xml; charset=utf-8", "/templates/insert/sone.xml"));
310
311                         return manifestEntries;
312                 }
313
314                 //
315                 // PRIVATE METHODS
316                 //
317
318                 /**
319                  * Creates a new manifest element.
320                  *
321                  * @param name
322                  *            The name of the file
323                  * @param contentType
324                  *            The content type of the file
325                  * @param templateName
326                  *            The name of the template to render
327                  * @return The manifest element
328                  */
329                 @SuppressWarnings("synthetic-access")
330                 private ManifestElement createManifestElement(String name, String contentType, String templateName) {
331                         InputStreamReader templateInputStreamReader = null;
332                         Template template;
333                         try {
334                                 templateInputStreamReader = new InputStreamReader(getClass().getResourceAsStream(templateName), utf8Charset);
335                                 template = TemplateParser.parse(templateInputStreamReader);
336                         } catch (TemplateException te1) {
337                                 logger.log(Level.SEVERE, "Could not parse template “" + templateName + "”!", te1);
338                                 return null;
339                         } finally {
340                                 Closer.close(templateInputStreamReader);
341                         }
342
343                         TemplateContext templateContext = templateContextFactory.createTemplateContext();
344                         templateContext.set("currentSone", soneProperties);
345                         templateContext.set("version", SonePlugin.VERSION);
346                         StringWriter writer = new StringWriter();
347                         StringBucket bucket = null;
348                         try {
349                                 template.render(templateContext, writer);
350                                 bucket = new StringBucket(writer.toString(), utf8Charset);
351                                 return new ManifestElement(name, bucket, contentType, bucket.size());
352                         } catch (TemplateException te1) {
353                                 logger.log(Level.SEVERE, "Could not render template “" + templateName + "”!", te1);
354                                 return null;
355                         } finally {
356                                 Closer.close(writer);
357                                 if (bucket != null) {
358                                         bucket.free();
359                                 }
360                         }
361                 }
362
363         }
364
365 }