2 * Sone - SoneInserter.java - Copyright © 2010–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.core;
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.HashSet;
26 import java.util.logging.Level;
27 import java.util.logging.Logger;
29 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
30 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
31 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
32 import net.pterodactylus.sone.data.Album;
33 import net.pterodactylus.sone.data.Post;
34 import net.pterodactylus.sone.data.Reply;
35 import net.pterodactylus.sone.data.Sone;
36 import net.pterodactylus.sone.data.Sone.SoneStatus;
37 import net.pterodactylus.sone.freenet.StringBucket;
38 import net.pterodactylus.sone.main.SonePlugin;
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;
51 import com.google.common.collect.FluentIterable;
52 import com.google.common.collect.Ordering;
53 import com.google.common.eventbus.EventBus;
55 import freenet.client.async.ManifestElement;
56 import freenet.keys.FreenetURI;
59 * A Sone inserter is responsible for inserting a Sone if it has changed.
61 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
63 public class SoneInserter extends AbstractService {
66 private static final Logger logger = Logging.getLogger(SoneInserter.class);
68 /** The insertion delay (in seconds). */
69 private static volatile int insertionDelay = 60;
71 /** The template factory used to create the templates. */
72 private static final TemplateContextFactory templateContextFactory = new TemplateContextFactory();
75 templateContextFactory.addAccessor(Object.class, new ReflectionAccessor());
76 templateContextFactory.addFilter("xml", new XmlFilter());
77 templateContextFactory.addFilter("html", new HtmlFilter());
80 /** The UTF-8 charset. */
81 private static final Charset utf8Charset = Charset.forName("UTF-8");
84 private final Core core;
87 private final EventBus eventBus;
89 /** The Freenet interface. */
90 private final FreenetInterface freenetInterface;
92 /** The Sone to insert. */
93 private final Sone sone;
95 /** Whether a modification has been detected. */
96 private volatile boolean modified = false;
98 /** The fingerprint of the last insert. */
99 private volatile String lastInsertFingerprint;
102 * Creates a new Sone inserter.
108 * @param freenetInterface
109 * The freenet interface
113 public SoneInserter(Core core, EventBus eventBus, FreenetInterface freenetInterface, Sone sone) {
114 super("Sone Inserter for “" + sone.getName() + "”", false);
116 this.eventBus = eventBus;
117 this.freenetInterface = freenetInterface;
126 * Changes the insertion delay, i.e. the time the Sone inserter waits after
127 * it has noticed a Sone modification before it starts the insert.
129 * @param insertionDelay
130 * The insertion delay (in seconds)
132 public static void setInsertionDelay(int insertionDelay) {
133 SoneInserter.insertionDelay = insertionDelay;
137 * Returns the fingerprint of the last insert.
139 * @return The fingerprint of the last insert
141 public String getLastInsertFingerprint() {
142 return lastInsertFingerprint;
146 * Sets the fingerprint of the last insert.
148 * @param lastInsertFingerprint
149 * The fingerprint of the last insert
151 public void setLastInsertFingerprint(String lastInsertFingerprint) {
152 this.lastInsertFingerprint = lastInsertFingerprint;
156 * Returns whether the Sone inserter has detected a modification of the
159 * @return {@code true} if the Sone has been modified, {@code false}
162 public boolean isModified() {
174 protected void serviceRun() {
175 long lastModificationTime = 0;
176 String lastInsertedFingerprint = lastInsertFingerprint;
177 String lastFingerprint = "";
178 while (!shouldStop()) {
180 /* check every seconds. */
183 /* don’t insert locked Sones. */
184 if (core.isLocked(sone)) {
185 /* trigger redetection when the Sone is unlocked. */
186 synchronized (sone) {
187 modified = !sone.getFingerprint().equals(lastInsertedFingerprint);
189 lastFingerprint = "";
190 lastModificationTime = 0;
194 InsertInformation insertInformation = null;
195 synchronized (sone) {
196 String fingerprint = sone.getFingerprint();
197 if (!fingerprint.equals(lastFingerprint)) {
198 if (fingerprint.equals(lastInsertedFingerprint)) {
200 lastModificationTime = 0;
201 logger.log(Level.FINE, String.format("Sone %s has been reverted to last insert state.", sone));
203 lastModificationTime = System.currentTimeMillis();
205 logger.log(Level.FINE, String.format("Sone %s has been modified, waiting %d seconds before inserting.", sone.getName(), insertionDelay));
207 lastFingerprint = fingerprint;
209 if (modified && (lastModificationTime > 0) && ((System.currentTimeMillis() - lastModificationTime) > (insertionDelay * 1000))) {
210 lastInsertedFingerprint = fingerprint;
211 insertInformation = new InsertInformation(sone);
215 if (insertInformation != null) {
216 logger.log(Level.INFO, String.format("Inserting Sone “%s”…", sone.getName()));
218 boolean success = false;
220 sone.setStatus(SoneStatus.inserting);
221 long insertTime = System.currentTimeMillis();
222 insertInformation.setTime(insertTime);
223 eventBus.post(new SoneInsertingEvent(sone));
224 FreenetURI finalUri = freenetInterface.insertDirectory(insertInformation.getInsertUri(), insertInformation.generateManifestEntries(), "index.html");
225 eventBus.post(new SoneInsertedEvent(sone, System.currentTimeMillis() - insertTime));
226 /* at this point we might already be stopped. */
228 /* if so, bail out, don’t change anything. */
231 sone.setTime(insertTime);
232 sone.setLatestEdition(finalUri.getEdition());
233 core.touchConfiguration();
235 logger.log(Level.INFO, String.format("Inserted Sone “%s” at %s.", sone.getName(), finalUri));
236 } catch (SoneException se1) {
237 eventBus.post(new SoneInsertAbortedEvent(sone, se1));
238 logger.log(Level.WARNING, String.format("Could not insert Sone “%s”!", sone.getName()), se1);
240 sone.setStatus(SoneStatus.idle);
244 * reset modification counter if Sone has not been modified
245 * while it was inserted.
248 synchronized (sone) {
249 if (lastInsertedFingerprint.equals(sone.getFingerprint())) {
250 logger.log(Level.FINE, String.format("Sone “%s” was not modified further, resetting counter…", sone));
251 lastModificationTime = 0;
252 lastInsertFingerprint = lastInsertedFingerprint;
253 core.touchConfiguration();
259 } catch (Throwable t1) {
260 logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
266 * Container for information that are required to insert a Sone. This
267 * container merely exists to copy all relevant data without holding a lock
268 * on the {@link Sone} object for too long.
270 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
272 private class InsertInformation {
274 /** All properties of the Sone, copied for thread safety. */
275 private final Map<String, Object> soneProperties = new HashMap<String, Object>();
278 * Creates a new insert information container.
283 public InsertInformation(Sone sone) {
284 soneProperties.put("id", sone.getId());
285 soneProperties.put("name", sone.getName());
286 soneProperties.put("time", sone.getTime());
287 soneProperties.put("requestUri", sone.getRequestUri());
288 soneProperties.put("insertUri", sone.getInsertUri());
289 soneProperties.put("profile", sone.getProfile());
290 soneProperties.put("posts", Ordering.from(Post.TIME_COMPARATOR).sortedCopy(sone.getPosts()));
291 soneProperties.put("replies", Ordering.from(Reply.TIME_COMPARATOR).reverse().sortedCopy(sone.getReplies()));
292 soneProperties.put("likedPostIds", new HashSet<String>(sone.getLikedPostIds()));
293 soneProperties.put("likedReplyIds", new HashSet<String>(sone.getLikedReplyIds()));
294 soneProperties.put("albums", FluentIterable.from(sone.getAlbums()).transformAndConcat(Album.FLATTENER).toList());
302 * Returns the insert URI of the Sone.
304 * @return The insert URI of the Sone
306 public FreenetURI getInsertUri() {
307 return (FreenetURI) soneProperties.get("insertUri");
311 * Sets the time of the Sone at the time of the insert.
314 * The time of the Sone
316 public void setTime(long time) {
317 soneProperties.put("time", time);
325 * Generates all manifest entries required to insert this Sone.
327 * @return The manifest entries for the Sone insert
329 public HashMap<String, Object> generateManifestEntries() {
330 HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
332 /* first, create an index.html. */
333 manifestEntries.put("index.html", createManifestElement("index.html", "text/html; charset=utf-8", "/templates/insert/index.html"));
335 /* now, store the sone. */
336 manifestEntries.put("sone.xml", createManifestElement("sone.xml", "text/xml; charset=utf-8", "/templates/insert/sone.xml"));
338 return manifestEntries;
346 * Creates a new manifest element.
349 * The name of the file
351 * The content type of the file
352 * @param templateName
353 * The name of the template to render
354 * @return The manifest element
356 @SuppressWarnings("synthetic-access")
357 private ManifestElement createManifestElement(String name, String contentType, String templateName) {
358 InputStreamReader templateInputStreamReader = null;
361 templateInputStreamReader = new InputStreamReader(getClass().getResourceAsStream(templateName), utf8Charset);
362 template = TemplateParser.parse(templateInputStreamReader);
363 } catch (TemplateException te1) {
364 logger.log(Level.SEVERE, String.format("Could not parse template “%s”!", templateName), te1);
367 Closer.close(templateInputStreamReader);
370 TemplateContext templateContext = templateContextFactory.createTemplateContext();
371 templateContext.set("core", core);
372 templateContext.set("currentSone", soneProperties);
373 templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
374 templateContext.set("version", SonePlugin.VERSION);
375 StringWriter writer = new StringWriter();
376 StringBucket bucket = null;
378 template.render(templateContext, writer);
379 bucket = new StringBucket(writer.toString(), utf8Charset);
380 return new ManifestElement(name, bucket, contentType, bucket.size());
381 } catch (TemplateException te1) {
382 logger.log(Level.SEVERE, String.format("Could not render template “%s”!", templateName), te1);
385 Closer.close(writer);
386 if (bucket != null) {