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.Optional.absent;
21 import static com.google.common.base.Optional.of;
22 import static com.google.common.base.Preconditions.checkArgument;
23 import static java.lang.System.currentTimeMillis;
24 import static net.pterodactylus.sone.data.Album.NOT_EMPTY;
26 import java.io.InputStreamReader;
27 import java.io.StringWriter;
28 import java.nio.charset.Charset;
29 import java.util.HashMap;
30 import java.util.HashSet;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
35 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
36 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
37 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
38 import net.pterodactylus.sone.data.Album;
39 import net.pterodactylus.sone.data.Post;
40 import net.pterodactylus.sone.data.Reply;
41 import net.pterodactylus.sone.data.Sone;
42 import net.pterodactylus.sone.data.Sone.SoneStatus;
43 import net.pterodactylus.sone.freenet.StringBucket;
44 import net.pterodactylus.sone.main.SonePlugin;
45 import net.pterodactylus.util.io.Closer;
46 import net.pterodactylus.util.logging.Logging;
47 import net.pterodactylus.util.service.AbstractService;
48 import net.pterodactylus.util.template.HtmlFilter;
49 import net.pterodactylus.util.template.ReflectionAccessor;
50 import net.pterodactylus.util.template.Template;
51 import net.pterodactylus.util.template.TemplateContext;
52 import net.pterodactylus.util.template.TemplateContextFactory;
53 import net.pterodactylus.util.template.TemplateException;
54 import net.pterodactylus.util.template.TemplateParser;
55 import net.pterodactylus.util.template.XmlFilter;
57 import com.google.common.base.Optional;
58 import com.google.common.collect.FluentIterable;
59 import com.google.common.collect.Ordering;
60 import com.google.common.eventbus.EventBus;
62 import freenet.client.async.ManifestElement;
63 import freenet.keys.FreenetURI;
66 * A Sone inserter is responsible for inserting a Sone if it has changed.
68 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
70 public class SoneInserter extends AbstractService {
73 private static final Logger logger = Logging.getLogger(SoneInserter.class);
75 /** The insertion delay (in seconds). */
76 private static volatile int insertionDelay = 60;
78 /** The template factory used to create the templates. */
79 private static final TemplateContextFactory templateContextFactory = new TemplateContextFactory();
82 templateContextFactory.addAccessor(Object.class, new ReflectionAccessor());
83 templateContextFactory.addFilter("xml", new XmlFilter());
84 templateContextFactory.addFilter("html", new HtmlFilter());
87 /** The UTF-8 charset. */
88 private static final Charset utf8Charset = Charset.forName("UTF-8");
91 private final Core core;
94 private final EventBus eventBus;
96 /** The Freenet interface. */
97 private final FreenetInterface freenetInterface;
99 /** The Sone to insert. */
100 private volatile Sone sone;
102 /** Whether a modification has been detected. */
103 private volatile boolean modified = false;
105 /** The fingerprint of the last insert. */
106 private volatile String lastInsertFingerprint;
109 * Creates a new Sone inserter.
115 * @param freenetInterface
116 * The freenet interface
120 public SoneInserter(Core core, EventBus eventBus, FreenetInterface freenetInterface, Sone sone) {
121 super("Sone Inserter for “" + sone.getName() + "”", false);
123 this.eventBus = eventBus;
124 this.freenetInterface = freenetInterface;
133 * Sets the Sone to insert.
137 * @return This Sone inserter
139 public SoneInserter setSone(Sone sone) {
140 checkArgument((this.sone == null) || sone.equals(this.sone), "Sone to insert can not be set to a different Sone");
146 * Changes the insertion delay, i.e. the time the Sone inserter waits after it
147 * has noticed a Sone modification before it starts the insert.
149 * @param insertionDelay
150 * The insertion delay (in seconds)
152 public static void setInsertionDelay(int insertionDelay) {
153 SoneInserter.insertionDelay = insertionDelay;
157 * Returns the fingerprint of the last insert.
159 * @return The fingerprint of the last insert
161 public String getLastInsertFingerprint() {
162 return lastInsertFingerprint;
166 * Sets the fingerprint of the last insert.
168 * @param lastInsertFingerprint
169 * The fingerprint of the last insert
171 public void setLastInsertFingerprint(String lastInsertFingerprint) {
172 this.lastInsertFingerprint = lastInsertFingerprint;
176 * Returns whether the Sone inserter has detected a modification of the
179 * @return {@code true} if the Sone has been modified, {@code false}
182 public boolean isModified() {
194 protected void serviceRun() {
195 Optional<Long> lastModificationTime = absent();
196 String lastInsertedFingerprint = lastInsertFingerprint;
197 String lastFingerprint = "";
198 while (!shouldStop()) {
200 /* check every second. */
203 /* don’t insert locked Sones. */
204 Sone sone = this.sone;
205 if (core.isLocked(sone)) {
206 /* trigger redetection when the Sone is unlocked. */
207 synchronized (sone) {
208 modified = !sone.getFingerprint().equals(lastInsertedFingerprint);
210 lastFingerprint = "";
211 lastModificationTime = absent();
215 InsertInformation insertInformation = null;
216 synchronized (sone) {
217 String fingerprint = sone.getFingerprint();
218 if (!fingerprint.equals(lastFingerprint)) {
219 if (fingerprint.equals(lastInsertedFingerprint)) {
221 lastModificationTime = absent();
222 logger.log(Level.FINE, String.format("Sone %s has been reverted to last insert state.", sone));
224 lastModificationTime = of(currentTimeMillis());
226 logger.log(Level.FINE, String.format("Sone %s has been modified, waiting %d seconds before inserting.", sone.getName(), insertionDelay));
228 lastFingerprint = fingerprint;
230 if (modified && lastModificationTime.isPresent() && ((currentTimeMillis() - lastModificationTime.get()) > (insertionDelay * 1000))) {
231 lastInsertedFingerprint = fingerprint;
232 insertInformation = new InsertInformation(sone);
236 if (insertInformation != null) {
237 logger.log(Level.INFO, String.format("Inserting Sone “%s”…", sone.getName()));
239 boolean success = false;
241 sone.setStatus(SoneStatus.inserting);
242 long insertTime = currentTimeMillis();
243 insertInformation.setTime(insertTime);
244 eventBus.post(new SoneInsertingEvent(sone));
245 FreenetURI finalUri = freenetInterface.insertDirectory(insertInformation.getInsertUri(), insertInformation.generateManifestEntries(), "index.html");
246 eventBus.post(new SoneInsertedEvent(sone, currentTimeMillis() - insertTime));
247 /* at this point we might already be stopped. */
249 /* if so, bail out, don’t change anything. */
252 sone.setTime(insertTime);
253 sone.setLatestEdition(finalUri.getEdition());
254 core.touchConfiguration();
256 logger.log(Level.INFO, String.format("Inserted Sone “%s” at %s.", sone.getName(), finalUri));
257 } catch (SoneException se1) {
258 eventBus.post(new SoneInsertAbortedEvent(sone, se1));
259 logger.log(Level.WARNING, String.format("Could not insert Sone “%s”!", sone.getName()), se1);
261 sone.setStatus(SoneStatus.idle);
265 * reset modification counter if Sone has not been modified
266 * while it was inserted.
269 synchronized (sone) {
270 if (lastInsertedFingerprint.equals(sone.getFingerprint())) {
271 logger.log(Level.FINE, String.format("Sone “%s” was not modified further, resetting counter…", sone));
272 lastModificationTime = absent();
273 lastInsertFingerprint = lastInsertedFingerprint;
274 core.touchConfiguration();
280 } catch (Throwable t1) {
281 logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
287 * Container for information that are required to insert a Sone. This
288 * container merely exists to copy all relevant data without holding a lock
289 * on the {@link Sone} object for too long.
291 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
293 private class InsertInformation {
295 /** All properties of the Sone, copied for thread safety. */
296 private final Map<String, Object> soneProperties = new HashMap<String, Object>();
299 * Creates a new insert information container.
304 public InsertInformation(Sone sone) {
305 soneProperties.put("id", sone.getId());
306 soneProperties.put("name", sone.getName());
307 soneProperties.put("time", sone.getTime());
308 soneProperties.put("requestUri", sone.getRequestUri());
309 soneProperties.put("insertUri", sone.getInsertUri());
310 soneProperties.put("profile", sone.getProfile());
311 soneProperties.put("posts", Ordering.from(Post.TIME_COMPARATOR).sortedCopy(sone.getPosts()));
312 soneProperties.put("replies", Ordering.from(Reply.TIME_COMPARATOR).reverse().sortedCopy(sone.getReplies()));
313 soneProperties.put("likedPostIds", new HashSet<String>(sone.getLikedPostIds()));
314 soneProperties.put("likedReplyIds", new HashSet<String>(sone.getLikedReplyIds()));
315 soneProperties.put("albums", FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).filter(NOT_EMPTY).toList());
323 * Returns the insert URI of the Sone.
325 * @return The insert URI of the Sone
327 public FreenetURI getInsertUri() {
328 return (FreenetURI) soneProperties.get("insertUri");
332 * Sets the time of the Sone at the time of the insert.
335 * The time of the Sone
337 public void setTime(long time) {
338 soneProperties.put("time", time);
346 * Generates all manifest entries required to insert this Sone.
348 * @return The manifest entries for the Sone insert
350 public HashMap<String, Object> generateManifestEntries() {
351 HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
353 /* first, create an index.html. */
354 manifestEntries.put("index.html", createManifestElement("index.html", "text/html; charset=utf-8", "/templates/insert/index.html"));
356 /* now, store the sone. */
357 manifestEntries.put("sone.xml", createManifestElement("sone.xml", "text/xml; charset=utf-8", "/templates/insert/sone.xml"));
359 return manifestEntries;
367 * Creates a new manifest element.
370 * The name of the file
372 * The content type of the file
373 * @param templateName
374 * The name of the template to render
375 * @return The manifest element
377 @SuppressWarnings("synthetic-access")
378 private ManifestElement createManifestElement(String name, String contentType, String templateName) {
379 InputStreamReader templateInputStreamReader = null;
382 templateInputStreamReader = new InputStreamReader(getClass().getResourceAsStream(templateName), utf8Charset);
383 template = TemplateParser.parse(templateInputStreamReader);
384 } catch (TemplateException te1) {
385 logger.log(Level.SEVERE, String.format("Could not parse template “%s”!", templateName), te1);
388 Closer.close(templateInputStreamReader);
391 TemplateContext templateContext = templateContextFactory.createTemplateContext();
392 templateContext.set("core", core);
393 templateContext.set("currentSone", soneProperties);
394 templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
395 templateContext.set("version", SonePlugin.VERSION);
396 StringWriter writer = new StringWriter();
397 StringBucket bucket = null;
399 template.render(templateContext, writer);
400 bucket = new StringBucket(writer.toString(), utf8Charset);
401 return new ManifestElement(name, bucket, contentType, bucket.size());
402 } catch (TemplateException te1) {
403 logger.log(Level.SEVERE, String.format("Could not render template “%s”!", templateName), te1);
406 Closer.close(writer);
407 if (bucket != null) {