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