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 java.lang.System.currentTimeMillis;
22 import static net.pterodactylus.sone.data.Album.NOT_EMPTY;
24 import java.io.InputStream;
25 import java.io.InputStreamReader;
26 import java.io.StringWriter;
27 import java.nio.charset.Charset;
28 import java.util.HashMap;
29 import java.util.HashSet;
31 import java.util.concurrent.atomic.AtomicInteger;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
35 import net.pterodactylus.sone.core.Options.Option;
36 import net.pterodactylus.sone.core.Options.OptionWatcher;
37 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
38 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
39 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
40 import net.pterodactylus.sone.data.Album;
41 import net.pterodactylus.sone.data.Post;
42 import net.pterodactylus.sone.data.Reply;
43 import net.pterodactylus.sone.data.Sone;
44 import net.pterodactylus.sone.data.Sone.SoneStatus;
45 import net.pterodactylus.sone.freenet.StringBucket;
46 import net.pterodactylus.sone.main.SonePlugin;
47 import net.pterodactylus.util.io.Closer;
48 import net.pterodactylus.util.logging.Logging;
49 import net.pterodactylus.util.service.AbstractService;
50 import net.pterodactylus.util.template.HtmlFilter;
51 import net.pterodactylus.util.template.ReflectionAccessor;
52 import net.pterodactylus.util.template.Template;
53 import net.pterodactylus.util.template.TemplateContext;
54 import net.pterodactylus.util.template.TemplateContextFactory;
55 import net.pterodactylus.util.template.TemplateException;
56 import net.pterodactylus.util.template.TemplateParser;
57 import net.pterodactylus.util.template.XmlFilter;
59 import com.google.common.annotations.VisibleForTesting;
60 import com.google.common.collect.FluentIterable;
61 import com.google.common.collect.Ordering;
62 import com.google.common.eventbus.EventBus;
64 import freenet.client.async.ManifestElement;
65 import freenet.keys.FreenetURI;
68 * A Sone inserter is responsible for inserting a Sone if it has changed.
70 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
72 public class SoneInserter extends AbstractService {
75 private static final Logger logger = Logging.getLogger(SoneInserter.class);
77 /** The insertion delay (in seconds). */
78 private static final AtomicInteger insertionDelay = new AtomicInteger(60);
80 /** The template factory used to create the templates. */
81 private static final TemplateContextFactory templateContextFactory = new TemplateContextFactory();
84 templateContextFactory.addAccessor(Object.class, new ReflectionAccessor());
85 templateContextFactory.addFilter("xml", new XmlFilter());
86 templateContextFactory.addFilter("html", new HtmlFilter());
89 /** The UTF-8 charset. */
90 private static final Charset utf8Charset = Charset.forName("UTF-8");
93 private final Core core;
96 private final EventBus eventBus;
98 /** The Freenet interface. */
99 private final FreenetInterface freenetInterface;
101 private final SoneModificationDetector soneModificationDetector;
102 private final long delay;
104 /** The Sone to insert. */
105 private volatile Sone sone;
108 * Creates a new Sone inserter.
114 * @param freenetInterface
115 * The freenet interface
119 public SoneInserter(Core core, EventBus eventBus, FreenetInterface freenetInterface, Sone sone) {
120 this(core, eventBus, freenetInterface, sone, new SoneModificationDetector(core, sone, insertionDelay), 1000);
124 SoneInserter(Core core, EventBus eventBus, FreenetInterface freenetInterface, Sone sone, SoneModificationDetector soneModificationDetector, long delay) {
125 super("Sone Inserter for “" + sone.getName() + "”", false);
127 this.eventBus = eventBus;
128 this.freenetInterface = freenetInterface;
130 this.soneModificationDetector = soneModificationDetector;
139 * Sets the Sone to insert.
143 * @return This Sone inserter
145 public SoneInserter setSone(Sone sone) {
146 checkArgument(sone.equals(this.sone), "Sone to insert can not be set to a different Sone");
152 static AtomicInteger getInsertionDelay() {
153 return insertionDelay;
157 * Changes the insertion delay, i.e. the time the Sone inserter waits after it
158 * has noticed a Sone modification before it starts the insert.
160 * @param insertionDelay
161 * The insertion delay (in seconds)
163 public static void setInsertionDelay(int insertionDelay) {
164 SoneInserter.insertionDelay.set(insertionDelay);
168 * Returns the fingerprint of the last insert.
170 * @return The fingerprint of the last insert
172 public String getLastInsertFingerprint() {
173 return soneModificationDetector.getOriginalFingerprint();
177 * Sets the fingerprint of the last insert.
179 * @param lastInsertFingerprint
180 * The fingerprint of the last insert
182 public void setLastInsertFingerprint(String lastInsertFingerprint) {
183 soneModificationDetector.setFingerprint(lastInsertFingerprint);
187 * Returns whether the Sone inserter has detected a modification of the
190 * @return {@code true} if the Sone has been modified, {@code false}
193 public boolean isModified() {
194 return soneModificationDetector.isModified();
205 protected void serviceRun() {
206 while (!shouldStop()) {
208 /* check every second. */
211 if (soneModificationDetector.isEligibleForInsert()) {
212 InsertInformation insertInformation = new InsertInformation(sone);
213 logger.log(Level.INFO, String.format("Inserting Sone “%s”…", sone.getName()));
215 boolean success = false;
217 sone.setStatus(SoneStatus.inserting);
218 long insertTime = currentTimeMillis();
219 eventBus.post(new SoneInsertingEvent(sone));
220 FreenetURI finalUri = freenetInterface.insertDirectory(insertInformation.getInsertUri(), insertInformation.generateManifestEntries(), "index.html");
221 eventBus.post(new SoneInsertedEvent(sone, currentTimeMillis() - insertTime));
222 /* at this point we might already be stopped. */
224 /* if so, bail out, don’t change anything. */
227 sone.setTime(insertTime);
228 sone.setLatestEdition(finalUri.getEdition());
229 core.touchConfiguration();
231 logger.log(Level.INFO, String.format("Inserted Sone “%s” at %s.", sone.getName(), finalUri));
232 } catch (SoneException se1) {
233 eventBus.post(new SoneInsertAbortedEvent(sone, se1));
234 logger.log(Level.WARNING, String.format("Could not insert Sone “%s”!", sone.getName()), se1);
236 sone.setStatus(SoneStatus.idle);
240 * reset modification counter if Sone has not been modified
241 * while it was inserted.
244 synchronized (sone) {
245 if (insertInformation.getFingerprint().equals(sone.getFingerprint())) {
246 logger.log(Level.FINE, String.format("Sone “%s” was not modified further, resetting counter…", sone));
247 soneModificationDetector.setFingerprint(insertInformation.getFingerprint());
248 core.touchConfiguration();
253 } catch (Throwable t1) {
254 logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
259 static class SetInsertionDelay implements OptionWatcher<Integer> {
262 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
263 setInsertionDelay(newValue);
269 * Container for information that are required to insert a Sone. This
270 * container merely exists to copy all relevant data without holding a lock
271 * on the {@link Sone} object for too long.
273 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
276 class InsertInformation {
278 private final String fingerprint;
280 /** All properties of the Sone, copied for thread safety. */
281 private final Map<String, Object> soneProperties = new HashMap<String, Object>();
284 * Creates a new insert information container.
289 public InsertInformation(Sone sone) {
290 this.fingerprint = sone.getFingerprint();
291 soneProperties.put("id", sone.getId());
292 soneProperties.put("name", sone.getName());
293 soneProperties.put("time", currentTimeMillis());
294 soneProperties.put("requestUri", sone.getRequestUri());
295 soneProperties.put("insertUri", sone.getInsertUri());
296 soneProperties.put("profile", sone.getProfile());
297 soneProperties.put("posts", Ordering.from(Post.TIME_COMPARATOR).sortedCopy(sone.getPosts()));
298 soneProperties.put("replies", Ordering.from(Reply.TIME_COMPARATOR).reverse().sortedCopy(sone.getReplies()));
299 soneProperties.put("likedPostIds", new HashSet<String>(sone.getLikedPostIds()));
300 soneProperties.put("likedReplyIds", new HashSet<String>(sone.getLikedReplyIds()));
301 soneProperties.put("albums", FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).filter(NOT_EMPTY).toList());
309 String getFingerprint() {
314 * Returns the insert URI of the Sone.
316 * @return The insert URI of the Sone
318 public FreenetURI getInsertUri() {
319 return (FreenetURI) soneProperties.get("insertUri");
327 * Generates all manifest entries required to insert this Sone.
329 * @return The manifest entries for the Sone insert
331 public HashMap<String, Object> generateManifestEntries() {
332 HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
334 /* first, create an index.html. */
335 manifestEntries.put("index.html", createManifestElement("index.html", "text/html; charset=utf-8", "/templates/insert/index.html"));
337 /* now, store the sone. */
338 manifestEntries.put("sone.xml", createManifestElement("sone.xml", "text/xml; charset=utf-8", "/templates/insert/sone.xml"));
340 return manifestEntries;
348 * Creates a new manifest element.
351 * The name of the file
353 * The content type of the file
354 * @param templateName
355 * The name of the template to render
356 * @return The manifest element
358 @SuppressWarnings("synthetic-access")
359 private ManifestElement createManifestElement(String name, String contentType, String templateName) {
360 InputStreamReader templateInputStreamReader = null;
361 InputStream templateInputStream = null;
364 templateInputStream = getClass().getResourceAsStream(templateName);
365 templateInputStreamReader = new InputStreamReader(templateInputStream, utf8Charset);
366 template = TemplateParser.parse(templateInputStreamReader);
367 } catch (TemplateException te1) {
368 logger.log(Level.SEVERE, String.format("Could not parse template “%s”!", templateName), te1);
371 Closer.close(templateInputStreamReader);
372 Closer.close(templateInputStream);
375 TemplateContext templateContext = templateContextFactory.createTemplateContext();
376 templateContext.set("core", core);
377 templateContext.set("currentSone", soneProperties);
378 templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
379 templateContext.set("version", SonePlugin.VERSION);
380 StringWriter writer = new StringWriter();
381 StringBucket bucket = null;
383 template.render(templateContext, writer);
384 bucket = new StringBucket(writer.toString(), utf8Charset);
385 return new ManifestElement(name, bucket, contentType, bucket.size());
386 } catch (TemplateException te1) {
387 logger.log(Level.SEVERE, String.format("Could not render template “%s”!", templateName), te1);
390 Closer.close(writer);
391 if (bucket != null) {