2 * Sone - SoneInserter.java - Copyright © 2010–2016 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 java.lang.String.format;
21 import static java.lang.System.currentTimeMillis;
22 import static java.util.logging.Logger.getLogger;
23 import static net.pterodactylus.sone.data.Album.NOT_EMPTY;
25 import java.io.Closeable;
26 import java.io.InputStream;
27 import java.io.InputStreamReader;
28 import java.io.StringWriter;
29 import java.nio.charset.Charset;
30 import java.util.HashMap;
31 import java.util.HashSet;
34 import java.util.concurrent.atomic.AtomicInteger;
35 import java.util.logging.Level;
36 import java.util.logging.Logger;
38 import net.pterodactylus.sone.core.SoneModificationDetector.LockableFingerprintProvider;
39 import net.pterodactylus.sone.core.event.InsertionDelayChangedEvent;
40 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
41 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
42 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
43 import net.pterodactylus.sone.data.Album;
44 import net.pterodactylus.sone.data.Post;
45 import net.pterodactylus.sone.data.Reply;
46 import net.pterodactylus.sone.data.Sone;
47 import net.pterodactylus.sone.data.Sone.SoneStatus;
48 import net.pterodactylus.sone.main.SonePlugin;
49 import net.pterodactylus.util.io.Closer;
50 import net.pterodactylus.util.service.AbstractService;
51 import net.pterodactylus.util.template.HtmlFilter;
52 import net.pterodactylus.util.template.ReflectionAccessor;
53 import net.pterodactylus.util.template.Template;
54 import net.pterodactylus.util.template.TemplateContext;
55 import net.pterodactylus.util.template.TemplateContextFactory;
56 import net.pterodactylus.util.template.TemplateException;
57 import net.pterodactylus.util.template.TemplateParser;
58 import net.pterodactylus.util.template.XmlFilter;
60 import com.google.common.annotations.VisibleForTesting;
61 import com.google.common.base.Charsets;
62 import com.google.common.collect.FluentIterable;
63 import com.google.common.collect.Ordering;
64 import com.google.common.eventbus.EventBus;
65 import com.google.common.eventbus.Subscribe;
67 import freenet.keys.FreenetURI;
68 import freenet.support.api.Bucket;
69 import freenet.support.api.ManifestElement;
70 import freenet.support.api.RandomAccessBucket;
71 import freenet.support.io.ArrayBucket;
74 * A Sone inserter is responsible for inserting a Sone if it has changed.
76 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
78 public class SoneInserter extends AbstractService {
81 private static final Logger logger = getLogger(SoneInserter.class.getName());
83 /** The insertion delay (in seconds). */
84 private static final AtomicInteger insertionDelay = new AtomicInteger(60);
86 /** The template factory used to create the templates. */
87 private static final TemplateContextFactory templateContextFactory = new TemplateContextFactory();
90 templateContextFactory.addAccessor(Object.class, new ReflectionAccessor());
91 templateContextFactory.addFilter("xml", new XmlFilter());
92 templateContextFactory.addFilter("html", new HtmlFilter());
95 /** The UTF-8 charset. */
96 private static final Charset utf8Charset = Charset.forName("UTF-8");
99 private final Core core;
101 /** The event bus. */
102 private final EventBus eventBus;
104 /** The Freenet interface. */
105 private final FreenetInterface freenetInterface;
107 private final SoneModificationDetector soneModificationDetector;
108 private final long delay;
109 private final String soneId;
112 * Creates a new Sone inserter.
118 * @param freenetInterface
119 * The freenet interface
121 * The ID of the Sone to insert
123 public SoneInserter(final Core core, EventBus eventBus, FreenetInterface freenetInterface, final String soneId) {
124 this(core, eventBus, freenetInterface, soneId, new SoneModificationDetector(new LockableFingerprintProvider() {
126 public boolean isLocked() {
127 Sone sone = core.getSone(soneId);
131 return core.isLocked(sone);
135 public String getFingerprint() {
136 Sone sone = core.getSone(soneId);
140 return sone.getFingerprint();
142 }, insertionDelay), 1000);
146 SoneInserter(Core core, EventBus eventBus, FreenetInterface freenetInterface, String soneId, SoneModificationDetector soneModificationDetector, long delay) {
147 super("Sone Inserter for “" + soneId + "”", false);
149 this.eventBus = eventBus;
150 this.freenetInterface = freenetInterface;
151 this.soneId = soneId;
152 this.soneModificationDetector = soneModificationDetector;
161 static AtomicInteger getInsertionDelay() {
162 return insertionDelay;
166 * Changes the insertion delay, i.e. the time the Sone inserter waits after it
167 * has noticed a Sone modification before it starts the insert.
169 * @param insertionDelay
170 * The insertion delay (in seconds)
172 private static void setInsertionDelay(int insertionDelay) {
173 SoneInserter.insertionDelay.set(insertionDelay);
177 * Returns the fingerprint of the last insert.
179 * @return The fingerprint of the last insert
181 public String getLastInsertFingerprint() {
182 return soneModificationDetector.getLastInsertFingerprint();
186 * Sets the fingerprint of the last insert.
188 * @param lastInsertFingerprint
189 * The fingerprint of the last insert
191 public void setLastInsertFingerprint(String lastInsertFingerprint) {
192 soneModificationDetector.setFingerprint(lastInsertFingerprint);
196 * Returns whether the Sone inserter has detected a modification of the
199 * @return {@code true} if the Sone has been modified, {@code false}
202 public boolean isModified() {
203 return soneModificationDetector.isModified();
214 protected void serviceRun() {
215 while (!shouldStop()) {
217 /* check every second. */
220 if (soneModificationDetector.isEligibleForInsert()) {
221 Sone sone = core.getSone(soneId);
223 logger.log(Level.WARNING, format("Sone %s has disappeared, exiting inserter.", soneId));
226 InsertInformation insertInformation = new InsertInformation(sone);
227 logger.log(Level.INFO, String.format("Inserting Sone “%s”…", sone.getName()));
229 boolean success = false;
231 sone.setStatus(SoneStatus.inserting);
232 long insertTime = currentTimeMillis();
233 eventBus.post(new SoneInsertingEvent(sone));
234 FreenetURI finalUri = freenetInterface.insertDirectory(sone.getInsertUri(), insertInformation.generateManifestEntries(), "index.html");
235 eventBus.post(new SoneInsertedEvent(sone, currentTimeMillis() - insertTime, insertInformation.getFingerprint()));
236 /* at this point we might already be stopped. */
238 /* if so, bail out, don’t change anything. */
241 sone.setTime(insertTime);
242 sone.setLatestEdition(finalUri.getEdition());
243 core.touchConfiguration();
245 logger.log(Level.INFO, String.format("Inserted Sone “%s” at %s.", sone.getName(), finalUri));
246 } catch (SoneException se1) {
247 eventBus.post(new SoneInsertAbortedEvent(sone, se1));
248 logger.log(Level.WARNING, String.format("Could not insert Sone “%s”!", sone.getName()), se1);
250 insertInformation.close();
251 sone.setStatus(SoneStatus.idle);
255 * reset modification counter if Sone has not been modified
256 * while it was inserted.
259 synchronized (sone) {
260 if (insertInformation.getFingerprint().equals(sone.getFingerprint())) {
261 logger.log(Level.FINE, String.format("Sone “%s” was not modified further, resetting counter…", sone));
262 soneModificationDetector.setFingerprint(insertInformation.getFingerprint());
263 core.touchConfiguration();
268 } catch (Throwable t1) {
269 logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
275 public void insertionDelayChanged(InsertionDelayChangedEvent insertionDelayChangedEvent) {
276 setInsertionDelay(insertionDelayChangedEvent.getInsertionDelay());
280 * Container for information that are required to insert a Sone. This
281 * container merely exists to copy all relevant data without holding a lock
282 * on the {@link Sone} object for too long.
284 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
287 class InsertInformation implements Closeable {
289 /** All properties of the Sone, copied for thread safety. */
290 private final Map<String, Object> soneProperties = new HashMap<String, Object>();
291 private final String fingerprint;
292 private final ManifestCreator manifestCreator;
295 * Creates a new insert information container.
300 public InsertInformation(Sone sone) {
301 this.fingerprint = sone.getFingerprint();
302 Map<String, Object> soneProperties = new HashMap<String, Object>();
303 soneProperties.put("id", sone.getId());
304 soneProperties.put("name", sone.getName());
305 soneProperties.put("time", currentTimeMillis());
306 soneProperties.put("requestUri", sone.getRequestUri());
307 soneProperties.put("profile", sone.getProfile());
308 soneProperties.put("posts", Ordering.from(Post.NEWEST_FIRST).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());
313 manifestCreator = new ManifestCreator(core, soneProperties);
321 String getFingerprint() {
330 * Generates all manifest entries required to insert this Sone.
332 * @return The manifest entries for the Sone insert
334 public HashMap<String, Object> generateManifestEntries() {
335 HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
337 /* first, create an index.html. */
338 manifestEntries.put("index.html", manifestCreator.createManifestElement(
339 "index.html", "text/html; charset=utf-8",
340 "/templates/insert/index.html"));
342 /* now, store the sone. */
343 manifestEntries.put("sone.xml", manifestCreator.createManifestElement(
344 "sone.xml", "text/xml; charset=utf-8",
345 "/templates/insert/sone.xml"));
347 return manifestEntries;
351 public void close() {
352 manifestCreator.close();
358 * Creates manifest elements for an insert by rendering a template.
360 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
363 static class ManifestCreator implements Closeable {
365 private final Core core;
366 private final Map<String, Object> soneProperties;
367 private final Set<Bucket> buckets = new HashSet<Bucket>();
369 ManifestCreator(Core core, Map<String, Object> soneProperties) {
371 this.soneProperties = soneProperties;
374 public ManifestElement createManifestElement(String name, String contentType, String templateName) {
375 InputStreamReader templateInputStreamReader = null;
376 InputStream templateInputStream = null;
379 templateInputStream = getClass().getResourceAsStream(templateName);
380 templateInputStreamReader = new InputStreamReader(templateInputStream, utf8Charset);
381 template = TemplateParser.parse(templateInputStreamReader);
382 } catch (TemplateException te1) {
383 logger.log(Level.SEVERE, String.format("Could not parse template “%s”!", templateName), te1);
386 Closer.close(templateInputStreamReader);
387 Closer.close(templateInputStream);
390 TemplateContext templateContext = templateContextFactory.createTemplateContext();
391 templateContext.set("core", core);
392 templateContext.set("currentSone", soneProperties);
393 templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
394 templateContext.set("version", SonePlugin.getPluginVersion());
395 StringWriter writer = new StringWriter();
397 template.render(templateContext, writer);
398 RandomAccessBucket bucket = new ArrayBucket(writer.toString().getBytes(Charsets.UTF_8));
400 return new ManifestElement(name, bucket, contentType, bucket.size());
401 } catch (TemplateException te1) {
402 logger.log(Level.SEVERE, String.format("Could not render template “%s”!", templateName), te1);
405 Closer.close(writer);
409 public void close() {
410 for (Bucket bucket : buckets) {