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 this(core, eventBus, freenetInterface, sone, new SoneModificationDetector(core, sone, insertionDelay));
123 SoneInserter(Core core, EventBus eventBus, FreenetInterface freenetInterface, Sone sone, SoneModificationDetector soneModificationDetector) {
124 super("Sone Inserter for “" + sone.getName() + "”", false);
126 this.eventBus = eventBus;
127 this.freenetInterface = freenetInterface;
129 this.soneModificationDetector = soneModificationDetector;
137 * Sets the Sone to insert.
141 * @return This Sone inserter
143 public SoneInserter setSone(Sone sone) {
144 checkArgument(sone.equals(this.sone), "Sone to insert can not be set to a different Sone");
150 static AtomicInteger getInsertionDelay() {
151 return insertionDelay;
155 * Changes the insertion delay, i.e. the time the Sone inserter waits after it
156 * has noticed a Sone modification before it starts the insert.
158 * @param insertionDelay
159 * The insertion delay (in seconds)
161 public static void setInsertionDelay(int insertionDelay) {
162 SoneInserter.insertionDelay.set(insertionDelay);
166 * Returns the fingerprint of the last insert.
168 * @return The fingerprint of the last insert
170 public String getLastInsertFingerprint() {
171 return soneModificationDetector.getOriginalFingerprint();
175 * Sets the fingerprint of the last insert.
177 * @param lastInsertFingerprint
178 * The fingerprint of the last insert
180 public void setLastInsertFingerprint(String lastInsertFingerprint) {
181 soneModificationDetector.setFingerprint(lastInsertFingerprint);
185 * Returns whether the Sone inserter has detected a modification of the
188 * @return {@code true} if the Sone has been modified, {@code false}
191 public boolean isModified() {
192 return soneModificationDetector.isModified();
203 protected void serviceRun() {
204 while (!shouldStop()) {
206 /* check every second. */
209 if (soneModificationDetector.isEligibleForInsert()) {
210 InsertInformation insertInformation = new InsertInformation(sone);
211 logger.log(Level.INFO, String.format("Inserting Sone “%s”…", sone.getName()));
213 boolean success = false;
215 sone.setStatus(SoneStatus.inserting);
216 long insertTime = currentTimeMillis();
217 eventBus.post(new SoneInsertingEvent(sone));
218 FreenetURI finalUri = freenetInterface.insertDirectory(insertInformation.getInsertUri(), insertInformation.generateManifestEntries(), "index.html");
219 eventBus.post(new SoneInsertedEvent(sone, currentTimeMillis() - insertTime));
220 /* at this point we might already be stopped. */
222 /* if so, bail out, don’t change anything. */
225 sone.setTime(insertTime);
226 sone.setLatestEdition(finalUri.getEdition());
227 core.touchConfiguration();
229 logger.log(Level.INFO, String.format("Inserted Sone “%s” at %s.", sone.getName(), finalUri));
230 } catch (SoneException se1) {
231 eventBus.post(new SoneInsertAbortedEvent(sone, se1));
232 logger.log(Level.WARNING, String.format("Could not insert Sone “%s”!", sone.getName()), se1);
234 sone.setStatus(SoneStatus.idle);
238 * reset modification counter if Sone has not been modified
239 * while it was inserted.
242 synchronized (sone) {
243 if (insertInformation.getFingerprint().equals(sone.getFingerprint())) {
244 logger.log(Level.FINE, String.format("Sone “%s” was not modified further, resetting counter…", sone));
245 soneModificationDetector.setFingerprint(insertInformation.getFingerprint());
246 core.touchConfiguration();
251 } catch (Throwable t1) {
252 logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
257 static class SetInsertionDelay implements OptionWatcher<Integer> {
260 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
261 setInsertionDelay(newValue);
267 * Container for information that are required to insert a Sone. This
268 * container merely exists to copy all relevant data without holding a lock
269 * on the {@link Sone} object for too long.
271 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
274 class InsertInformation {
276 private final String fingerprint;
278 /** All properties of the Sone, copied for thread safety. */
279 private final Map<String, Object> soneProperties = new HashMap<String, Object>();
282 * Creates a new insert information container.
287 public InsertInformation(Sone sone) {
288 this.fingerprint = sone.getFingerprint();
289 soneProperties.put("id", sone.getId());
290 soneProperties.put("name", sone.getName());
291 soneProperties.put("time", currentTimeMillis());
292 soneProperties.put("requestUri", sone.getRequestUri());
293 soneProperties.put("insertUri", sone.getInsertUri());
294 soneProperties.put("profile", sone.getProfile());
295 soneProperties.put("posts", Ordering.from(Post.TIME_COMPARATOR).sortedCopy(sone.getPosts()));
296 soneProperties.put("replies", Ordering.from(Reply.TIME_COMPARATOR).reverse().sortedCopy(sone.getReplies()));
297 soneProperties.put("likedPostIds", new HashSet<String>(sone.getLikedPostIds()));
298 soneProperties.put("likedReplyIds", new HashSet<String>(sone.getLikedReplyIds()));
299 soneProperties.put("albums", FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).filter(NOT_EMPTY).toList());
307 String getFingerprint() {
312 * Returns the insert URI of the Sone.
314 * @return The insert URI of the Sone
316 public FreenetURI getInsertUri() {
317 return (FreenetURI) soneProperties.get("insertUri");
325 * Generates all manifest entries required to insert this Sone.
327 * @return The manifest entries for the Sone insert
329 public HashMap<String, Object> generateManifestEntries() {
330 HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
332 /* first, create an index.html. */
333 manifestEntries.put("index.html", createManifestElement("index.html", "text/html; charset=utf-8", "/templates/insert/index.html"));
335 /* now, store the sone. */
336 manifestEntries.put("sone.xml", createManifestElement("sone.xml", "text/xml; charset=utf-8", "/templates/insert/sone.xml"));
338 return manifestEntries;
346 * Creates a new manifest element.
349 * The name of the file
351 * The content type of the file
352 * @param templateName
353 * The name of the template to render
354 * @return The manifest element
356 @SuppressWarnings("synthetic-access")
357 private ManifestElement createManifestElement(String name, String contentType, String templateName) {
358 InputStreamReader templateInputStreamReader = null;
359 InputStream templateInputStream = null;
362 templateInputStream = getClass().getResourceAsStream(templateName);
363 templateInputStreamReader = new InputStreamReader(templateInputStream, utf8Charset);
364 template = TemplateParser.parse(templateInputStreamReader);
365 } catch (TemplateException te1) {
366 logger.log(Level.SEVERE, String.format("Could not parse template “%s”!", templateName), te1);
369 Closer.close(templateInputStreamReader);
370 Closer.close(templateInputStream);
373 TemplateContext templateContext = templateContextFactory.createTemplateContext();
374 templateContext.set("core", core);
375 templateContext.set("currentSone", soneProperties);
376 templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
377 templateContext.set("version", SonePlugin.VERSION);
378 StringWriter writer = new StringWriter();
379 StringBucket bucket = null;
381 template.render(templateContext, writer);
382 bucket = new StringBucket(writer.toString(), utf8Charset);
383 return new ManifestElement(name, bucket, contentType, bucket.size());
384 } catch (TemplateException te1) {
385 logger.log(Level.SEVERE, String.format("Could not render template “%s”!", templateName), te1);
388 Closer.close(writer);
389 if (bucket != null) {