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 static com.google.common.base.Preconditions.checkArgument;
21 import static net.pterodactylus.sone.data.Album.NOT_EMPTY;
23 import java.io.InputStreamReader;
24 import java.io.StringWriter;
25 import java.nio.charset.Charset;
26 import java.util.HashMap;
27 import java.util.HashSet;
29 import java.util.logging.Level;
30 import java.util.logging.Logger;
32 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
33 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
34 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
35 import net.pterodactylus.sone.data.Album;
36 import net.pterodactylus.sone.data.Post;
37 import net.pterodactylus.sone.data.Reply;
38 import net.pterodactylus.sone.data.Sone;
39 import net.pterodactylus.sone.data.Sone.SoneStatus;
40 import net.pterodactylus.sone.freenet.StringBucket;
41 import net.pterodactylus.sone.main.SonePlugin;
42 import net.pterodactylus.util.io.Closer;
43 import net.pterodactylus.util.logging.Logging;
44 import net.pterodactylus.util.service.AbstractService;
45 import net.pterodactylus.util.template.HtmlFilter;
46 import net.pterodactylus.util.template.ReflectionAccessor;
47 import net.pterodactylus.util.template.Template;
48 import net.pterodactylus.util.template.TemplateContext;
49 import net.pterodactylus.util.template.TemplateContextFactory;
50 import net.pterodactylus.util.template.TemplateException;
51 import net.pterodactylus.util.template.TemplateParser;
52 import net.pterodactylus.util.template.XmlFilter;
54 import com.google.common.collect.FluentIterable;
55 import com.google.common.collect.Ordering;
56 import com.google.common.eventbus.EventBus;
58 import freenet.client.async.ManifestElement;
59 import freenet.keys.FreenetURI;
62 * A Sone inserter is responsible for inserting a Sone if it has changed.
64 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
66 public class SoneInserter extends AbstractService {
69 private static final Logger logger = Logging.getLogger(SoneInserter.class);
71 /** The insertion delay (in seconds). */
72 private static volatile int insertionDelay = 60;
74 /** The template factory used to create the templates. */
75 private static final TemplateContextFactory templateContextFactory = new TemplateContextFactory();
78 templateContextFactory.addAccessor(Object.class, new ReflectionAccessor());
79 templateContextFactory.addFilter("xml", new XmlFilter());
80 templateContextFactory.addFilter("html", new HtmlFilter());
83 /** The UTF-8 charset. */
84 private static final Charset utf8Charset = Charset.forName("UTF-8");
87 private final Core core;
90 private final EventBus eventBus;
92 /** The Freenet interface. */
93 private final FreenetInterface freenetInterface;
95 /** The Sone to insert. */
96 private volatile Sone sone;
98 /** Whether a modification has been detected. */
99 private volatile boolean modified = false;
101 /** The fingerprint of the last insert. */
102 private volatile String lastInsertFingerprint;
105 * Creates a new Sone inserter.
111 * @param freenetInterface
112 * The freenet interface
116 public SoneInserter(Core core, EventBus eventBus, FreenetInterface freenetInterface, Sone sone) {
117 super("Sone Inserter for “" + sone.getName() + "”", false);
119 this.eventBus = eventBus;
120 this.freenetInterface = freenetInterface;
129 * Sets the Sone to insert.
133 * @return This Sone inserter
135 public SoneInserter setSone(Sone sone) {
136 checkArgument((this.sone == null) || sone.equals(this.sone), "Sone to insert can not be set to a different Sone");
142 * Changes the insertion delay, i.e. the time the Sone inserter waits after it
143 * has noticed a Sone modification before it starts the insert.
145 * @param insertionDelay
146 * The insertion delay (in seconds)
148 public static void setInsertionDelay(int insertionDelay) {
149 SoneInserter.insertionDelay = insertionDelay;
153 * Returns the fingerprint of the last insert.
155 * @return The fingerprint of the last insert
157 public String getLastInsertFingerprint() {
158 return lastInsertFingerprint;
162 * Sets the fingerprint of the last insert.
164 * @param lastInsertFingerprint
165 * The fingerprint of the last insert
167 public void setLastInsertFingerprint(String lastInsertFingerprint) {
168 this.lastInsertFingerprint = lastInsertFingerprint;
172 * Returns whether the Sone inserter has detected a modification of the
175 * @return {@code true} if the Sone has been modified, {@code false}
178 public boolean isModified() {
190 protected void serviceRun() {
191 long lastModificationTime = 0;
192 String lastInsertedFingerprint = lastInsertFingerprint;
193 String lastFingerprint = "";
195 while (!shouldStop()) {
197 /* check every seconds. */
200 /* don’t insert locked Sones. */
202 if (core.isLocked(sone)) {
203 /* trigger redetection when the Sone is unlocked. */
204 synchronized (sone) {
205 modified = !sone.getFingerprint().equals(lastInsertedFingerprint);
207 lastFingerprint = "";
208 lastModificationTime = 0;
212 InsertInformation insertInformation = null;
213 synchronized (sone) {
214 String fingerprint = sone.getFingerprint();
215 if (!fingerprint.equals(lastFingerprint)) {
216 if (fingerprint.equals(lastInsertedFingerprint)) {
218 lastModificationTime = 0;
219 logger.log(Level.FINE, String.format("Sone %s has been reverted to last insert state.", sone));
221 lastModificationTime = System.currentTimeMillis();
223 logger.log(Level.FINE, String.format("Sone %s has been modified, waiting %d seconds before inserting.", sone.getName(), insertionDelay));
225 lastFingerprint = fingerprint;
227 if (modified && (lastModificationTime > 0) && ((System.currentTimeMillis() - lastModificationTime) > (insertionDelay * 1000))) {
228 lastInsertedFingerprint = fingerprint;
229 insertInformation = new InsertInformation(sone);
233 if (insertInformation != null) {
234 logger.log(Level.INFO, String.format("Inserting Sone “%s”…", sone.getName()));
236 boolean success = false;
238 sone.setStatus(SoneStatus.inserting);
239 long insertTime = System.currentTimeMillis();
240 insertInformation.setTime(insertTime);
241 eventBus.post(new SoneInsertingEvent(sone));
242 FreenetURI finalUri = freenetInterface.insertDirectory(insertInformation.getInsertUri(), insertInformation.generateManifestEntries(), "index.html");
243 eventBus.post(new SoneInsertedEvent(sone, System.currentTimeMillis() - insertTime));
244 /* at this point we might already be stopped. */
246 /* if so, bail out, don’t change anything. */
249 sone.setTime(insertTime);
250 sone.setLatestEdition(finalUri.getEdition());
251 core.touchConfiguration();
253 logger.log(Level.INFO, String.format("Inserted Sone “%s” at %s.", sone.getName(), finalUri));
254 } catch (SoneException se1) {
255 eventBus.post(new SoneInsertAbortedEvent(sone, se1));
256 logger.log(Level.WARNING, String.format("Could not insert Sone “%s”!", sone.getName()), se1);
258 sone.setStatus(SoneStatus.idle);
262 * reset modification counter if Sone has not been modified
263 * while it was inserted.
266 synchronized (sone) {
267 if (lastInsertedFingerprint.equals(sone.getFingerprint())) {
268 logger.log(Level.FINE, String.format("Sone “%s” was not modified further, resetting counter…", sone));
269 lastModificationTime = 0;
270 lastInsertFingerprint = lastInsertedFingerprint;
271 core.touchConfiguration();
277 } catch (Throwable t1) {
278 logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
284 * Container for information that are required to insert a Sone. This
285 * container merely exists to copy all relevant data without holding a lock
286 * on the {@link Sone} object for too long.
288 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
290 private class InsertInformation {
292 /** All properties of the Sone, copied for thread safety. */
293 private final Map<String, Object> soneProperties = new HashMap<String, Object>();
296 * Creates a new insert information container.
301 public InsertInformation(Sone sone) {
302 soneProperties.put("id", sone.getId());
303 soneProperties.put("name", sone.getName());
304 soneProperties.put("time", sone.getTime());
305 soneProperties.put("requestUri", sone.getRequestUri());
306 soneProperties.put("insertUri", sone.getInsertUri());
307 soneProperties.put("profile", sone.getProfile());
308 soneProperties.put("posts", Ordering.from(Post.TIME_COMPARATOR).sortedCopy(sone.getPosts()));
309 soneProperties.put("replies", Ordering.from(Reply.TIME_COMPARATOR).reverse().sortedCopy(sone.getReplies()));
310 soneProperties.put("likedPostIds", new HashSet<String>(sone.getLikedPostIds()));
311 soneProperties.put("likedReplyIds", new HashSet<String>(sone.getLikedReplyIds()));
312 soneProperties.put("albums", FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).filter(NOT_EMPTY).toList());
320 * Returns the insert URI of the Sone.
322 * @return The insert URI of the Sone
324 public FreenetURI getInsertUri() {
325 return (FreenetURI) soneProperties.get("insertUri");
329 * Sets the time of the Sone at the time of the insert.
332 * The time of the Sone
334 public void setTime(long time) {
335 soneProperties.put("time", time);
343 * Generates all manifest entries required to insert this Sone.
345 * @return The manifest entries for the Sone insert
347 public HashMap<String, Object> generateManifestEntries() {
348 HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
350 /* first, create an index.html. */
351 manifestEntries.put("index.html", createManifestElement("index.html", "text/html; charset=utf-8", "/templates/insert/index.html"));
353 /* now, store the sone. */
354 manifestEntries.put("sone.xml", createManifestElement("sone.xml", "text/xml; charset=utf-8", "/templates/insert/sone.xml"));
356 return manifestEntries;
364 * Creates a new manifest element.
367 * The name of the file
369 * The content type of the file
370 * @param templateName
371 * The name of the template to render
372 * @return The manifest element
374 @SuppressWarnings("synthetic-access")
375 private ManifestElement createManifestElement(String name, String contentType, String templateName) {
376 InputStreamReader templateInputStreamReader = null;
379 templateInputStreamReader = new InputStreamReader(getClass().getResourceAsStream(templateName), utf8Charset);
380 template = TemplateParser.parse(templateInputStreamReader);
381 } catch (TemplateException te1) {
382 logger.log(Level.SEVERE, String.format("Could not parse template “%s”!", templateName), te1);
385 Closer.close(templateInputStreamReader);
388 TemplateContext templateContext = templateContextFactory.createTemplateContext();
389 templateContext.set("core", core);
390 templateContext.set("currentSone", soneProperties);
391 templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
392 templateContext.set("version", SonePlugin.VERSION);
393 StringWriter writer = new StringWriter();
394 StringBucket bucket = null;
396 template.render(templateContext, writer);
397 bucket = new StringBucket(writer.toString(), utf8Charset);
398 return new ManifestElement(name, bucket, contentType, bucket.size());
399 } catch (TemplateException te1) {
400 logger.log(Level.SEVERE, String.format("Could not render template “%s”!", templateName), te1);
403 Closer.close(writer);
404 if (bucket != null) {