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;
103 /** The Sone to insert. */
104 private volatile Sone sone;
107 * Creates a new Sone inserter.
113 * @param freenetInterface
114 * The freenet interface
118 public SoneInserter(Core core, EventBus eventBus, FreenetInterface freenetInterface, Sone sone) {
119 super("Sone Inserter for “" + sone.getName() + "”", false);
121 this.eventBus = eventBus;
122 this.freenetInterface = freenetInterface;
124 this.soneModificationDetector = new SoneModificationDetector(core, sone, insertionDelay);
132 * Sets the Sone to insert.
136 * @return This Sone inserter
138 public SoneInserter setSone(Sone sone) {
139 checkArgument((this.sone == null) || sone.equals(this.sone), "Sone to insert can not be set to a different Sone");
145 static AtomicInteger getInsertionDelay() {
146 return insertionDelay;
150 * Changes the insertion delay, i.e. the time the Sone inserter waits after it
151 * has noticed a Sone modification before it starts the insert.
153 * @param insertionDelay
154 * The insertion delay (in seconds)
156 public static void setInsertionDelay(int insertionDelay) {
157 SoneInserter.insertionDelay.set(insertionDelay);
161 * Returns the fingerprint of the last insert.
163 * @return The fingerprint of the last insert
165 public String getLastInsertFingerprint() {
166 return soneModificationDetector.getOriginalFingerprint();
170 * Sets the fingerprint of the last insert.
172 * @param lastInsertFingerprint
173 * The fingerprint of the last insert
175 public void setLastInsertFingerprint(String lastInsertFingerprint) {
176 soneModificationDetector.setFingerprint(lastInsertFingerprint);
180 * Returns whether the Sone inserter has detected a modification of the
183 * @return {@code true} if the Sone has been modified, {@code false}
186 public boolean isModified() {
187 return soneModificationDetector.isModified();
198 protected void serviceRun() {
199 while (!shouldStop()) {
201 /* check every second. */
204 if (soneModificationDetector.isEligibleForInsert()) {
205 InsertInformation insertInformation = new InsertInformation(sone);
206 logger.log(Level.INFO, String.format("Inserting Sone “%s”…", sone.getName()));
208 boolean success = false;
210 sone.setStatus(SoneStatus.inserting);
211 long insertTime = currentTimeMillis();
212 eventBus.post(new SoneInsertingEvent(sone));
213 FreenetURI finalUri = freenetInterface.insertDirectory(insertInformation.getInsertUri(), insertInformation.generateManifestEntries(), "index.html");
214 eventBus.post(new SoneInsertedEvent(sone, currentTimeMillis() - insertTime));
215 /* at this point we might already be stopped. */
217 /* if so, bail out, don’t change anything. */
220 sone.setTime(insertTime);
221 sone.setLatestEdition(finalUri.getEdition());
222 core.touchConfiguration();
224 logger.log(Level.INFO, String.format("Inserted Sone “%s” at %s.", sone.getName(), finalUri));
225 } catch (SoneException se1) {
226 eventBus.post(new SoneInsertAbortedEvent(sone, se1));
227 logger.log(Level.WARNING, String.format("Could not insert Sone “%s”!", sone.getName()), se1);
229 sone.setStatus(SoneStatus.idle);
233 * reset modification counter if Sone has not been modified
234 * while it was inserted.
237 synchronized (sone) {
238 if (insertInformation.getFingerprint().equals(sone.getFingerprint())) {
239 logger.log(Level.FINE, String.format("Sone “%s” was not modified further, resetting counter…", sone));
240 soneModificationDetector.setFingerprint(insertInformation.getFingerprint());
241 core.touchConfiguration();
246 } catch (Throwable t1) {
247 logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
252 static class SetInsertionDelay implements OptionWatcher<Integer> {
255 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
256 setInsertionDelay(newValue);
262 * Container for information that are required to insert a Sone. This
263 * container merely exists to copy all relevant data without holding a lock
264 * on the {@link Sone} object for too long.
266 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
268 private class InsertInformation {
270 private final String fingerprint;
272 /** All properties of the Sone, copied for thread safety. */
273 private final Map<String, Object> soneProperties = new HashMap<String, Object>();
276 * Creates a new insert information container.
281 public InsertInformation(Sone sone) {
282 this.fingerprint = sone.getFingerprint();
283 soneProperties.put("id", sone.getId());
284 soneProperties.put("name", sone.getName());
285 soneProperties.put("time", currentTimeMillis());
286 soneProperties.put("requestUri", sone.getRequestUri());
287 soneProperties.put("insertUri", sone.getInsertUri());
288 soneProperties.put("profile", sone.getProfile());
289 soneProperties.put("posts", Ordering.from(Post.TIME_COMPARATOR).sortedCopy(sone.getPosts()));
290 soneProperties.put("replies", Ordering.from(Reply.TIME_COMPARATOR).reverse().sortedCopy(sone.getReplies()));
291 soneProperties.put("likedPostIds", new HashSet<String>(sone.getLikedPostIds()));
292 soneProperties.put("likedReplyIds", new HashSet<String>(sone.getLikedReplyIds()));
293 soneProperties.put("albums", FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).filter(NOT_EMPTY).toList());
300 private String getFingerprint() {
305 * Returns the insert URI of the Sone.
307 * @return The insert URI of the Sone
309 public FreenetURI getInsertUri() {
310 return (FreenetURI) soneProperties.get("insertUri");
318 * Generates all manifest entries required to insert this Sone.
320 * @return The manifest entries for the Sone insert
322 public HashMap<String, Object> generateManifestEntries() {
323 HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
325 /* first, create an index.html. */
326 manifestEntries.put("index.html", createManifestElement("index.html", "text/html; charset=utf-8", "/templates/insert/index.html"));
328 /* now, store the sone. */
329 manifestEntries.put("sone.xml", createManifestElement("sone.xml", "text/xml; charset=utf-8", "/templates/insert/sone.xml"));
331 return manifestEntries;
339 * Creates a new manifest element.
342 * The name of the file
344 * The content type of the file
345 * @param templateName
346 * The name of the template to render
347 * @return The manifest element
349 @SuppressWarnings("synthetic-access")
350 private ManifestElement createManifestElement(String name, String contentType, String templateName) {
351 InputStreamReader templateInputStreamReader = null;
352 InputStream templateInputStream = null;
355 templateInputStream = getClass().getResourceAsStream(templateName);
356 templateInputStreamReader = new InputStreamReader(templateInputStream, utf8Charset);
357 template = TemplateParser.parse(templateInputStreamReader);
358 } catch (TemplateException te1) {
359 logger.log(Level.SEVERE, String.format("Could not parse template “%s”!", templateName), te1);
362 Closer.close(templateInputStreamReader);
363 Closer.close(templateInputStream);
366 TemplateContext templateContext = templateContextFactory.createTemplateContext();
367 templateContext.set("core", core);
368 templateContext.set("currentSone", soneProperties);
369 templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
370 templateContext.set("version", SonePlugin.VERSION);
371 StringWriter writer = new StringWriter();
372 StringBucket bucket = null;
374 template.render(templateContext, writer);
375 bucket = new StringBucket(writer.toString(), utf8Charset);
376 return new ManifestElement(name, bucket, contentType, bucket.size());
377 } catch (TemplateException te1) {
378 logger.log(Level.SEVERE, String.format("Could not render template “%s”!", templateName), te1);
381 Closer.close(writer);
382 if (bucket != null) {