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 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.InputStream;
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.concurrent.atomic.AtomicInteger;
33 import java.util.logging.Level;
34 import java.util.logging.Logger;
36 import net.pterodactylus.sone.core.SoneModificationDetector.LockableFingerprintProvider;
37 import net.pterodactylus.sone.core.event.InsertionDelayChangedEvent;
38 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
39 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
40 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
41 import net.pterodactylus.sone.data.Album;
42 import net.pterodactylus.sone.data.Post;
43 import net.pterodactylus.sone.data.Reply;
44 import net.pterodactylus.sone.data.Sone;
45 import net.pterodactylus.sone.data.Sone.SoneStatus;
46 import net.pterodactylus.sone.freenet.StringBucket;
47 import net.pterodactylus.sone.main.SonePlugin;
48 import net.pterodactylus.util.io.Closer;
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.base.Optional;
61 import com.google.common.collect.FluentIterable;
62 import com.google.common.collect.Ordering;
63 import com.google.common.eventbus.EventBus;
64 import com.google.common.eventbus.Subscribe;
66 import freenet.client.async.ManifestElement;
67 import freenet.keys.FreenetURI;
70 * A Sone inserter is responsible for inserting a Sone if it has changed.
72 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
74 public class SoneInserter extends AbstractService {
77 private static final Logger logger = getLogger("Sone.Inserter");
79 /** The insertion delay (in seconds). */
80 private static final AtomicInteger insertionDelay = new AtomicInteger(60);
82 /** The template factory used to create the templates. */
83 private static final TemplateContextFactory templateContextFactory = new TemplateContextFactory();
86 templateContextFactory.addAccessor(Object.class, new ReflectionAccessor());
87 templateContextFactory.addFilter("xml", new XmlFilter());
88 templateContextFactory.addFilter("html", new HtmlFilter());
91 /** The UTF-8 charset. */
92 private static final Charset utf8Charset = Charset.forName("UTF-8");
95 private final Core core;
98 private final EventBus eventBus;
100 /** The Freenet interface. */
101 private final FreenetInterface freenetInterface;
103 private final SoneModificationDetector soneModificationDetector;
104 private final long delay;
105 private final String soneId;
108 * Creates a new Sone inserter.
114 * @param freenetInterface
115 * The freenet interface
117 * The ID of the Sone to insert
119 public SoneInserter(final Core core, EventBus eventBus, FreenetInterface freenetInterface, final String soneId) {
120 this(core, eventBus, freenetInterface, soneId, new SoneModificationDetector(new LockableFingerprintProvider() {
122 public boolean isLocked() {
123 final Optional<Sone> sone = core.getSone(soneId);
124 if (!sone.isPresent()) {
127 return core.isLocked(sone.get());
131 public String getFingerprint() {
132 final Optional<Sone> sone = core.getSone(soneId);
133 if (!sone.isPresent()) {
136 return sone.get().getFingerprint();
138 }, insertionDelay), 1000);
142 SoneInserter(Core core, EventBus eventBus, FreenetInterface freenetInterface, String soneId, SoneModificationDetector soneModificationDetector, long delay) {
143 super("Sone Inserter for “" + soneId + "”", false);
145 this.eventBus = eventBus;
146 this.freenetInterface = freenetInterface;
147 this.soneId = soneId;
148 this.soneModificationDetector = soneModificationDetector;
157 static AtomicInteger getInsertionDelay() {
158 return insertionDelay;
162 * Changes the insertion delay, i.e. the time the Sone inserter waits after it
163 * has noticed a Sone modification before it starts the insert.
165 * @param insertionDelay
166 * The insertion delay (in seconds)
168 private static void setInsertionDelay(int insertionDelay) {
169 SoneInserter.insertionDelay.set(insertionDelay);
173 * Returns the fingerprint of the last insert.
175 * @return The fingerprint of the last insert
177 public String getLastInsertFingerprint() {
178 return soneModificationDetector.getOriginalFingerprint();
182 * Sets the fingerprint of the last insert.
184 * @param lastInsertFingerprint
185 * The fingerprint of the last insert
187 public void setLastInsertFingerprint(String lastInsertFingerprint) {
188 soneModificationDetector.setFingerprint(lastInsertFingerprint);
192 * Returns whether the Sone inserter has detected a modification of the
195 * @return {@code true} if the Sone has been modified, {@code false}
198 public boolean isModified() {
199 return soneModificationDetector.isModified();
210 protected void serviceRun() {
211 while (!shouldStop()) {
213 /* check every second. */
216 if (soneModificationDetector.isEligibleForInsert()) {
217 Optional<Sone> soneOptional = core.getSone(soneId);
218 if (!soneOptional.isPresent()) {
219 logger.log(Level.WARNING, format("Sone %s has disappeared, exiting inserter.", soneId));
222 Sone sone = soneOptional.get();
223 InsertInformation insertInformation = new InsertInformation(sone);
224 logger.log(Level.INFO, String.format("Inserting Sone “%s”…", sone.getName()));
226 boolean success = false;
228 sone.setStatus(SoneStatus.inserting);
229 long insertTime = currentTimeMillis();
230 eventBus.post(new SoneInsertingEvent(sone));
231 FreenetURI finalUri = freenetInterface.insertDirectory(sone.getInsertUri(), insertInformation.generateManifestEntries(), "index.html");
232 eventBus.post(new SoneInsertedEvent(sone, currentTimeMillis() - insertTime));
233 /* at this point we might already be stopped. */
235 /* if so, bail out, don’t change anything. */
238 sone.setTime(insertTime);
239 sone.setLatestEdition(finalUri.getEdition());
240 core.touchConfiguration();
242 logger.log(Level.INFO, String.format("Inserted Sone “%s” at %s.", sone.getName(), finalUri));
243 } catch (SoneException se1) {
244 eventBus.post(new SoneInsertAbortedEvent(sone, se1));
245 logger.log(Level.WARNING, String.format("Could not insert Sone “%s”!", sone.getName()), se1);
247 sone.setStatus(SoneStatus.idle);
251 * reset modification counter if Sone has not been modified
252 * while it was inserted.
255 synchronized (sone) {
256 if (insertInformation.getFingerprint().equals(sone.getFingerprint())) {
257 logger.log(Level.FINE, String.format("Sone “%s” was not modified further, resetting counter…", sone));
258 soneModificationDetector.setFingerprint(insertInformation.getFingerprint());
259 core.touchConfiguration();
264 } catch (Throwable t1) {
265 logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
271 public void insertionDelayChanged(InsertionDelayChangedEvent insertionDelayChangedEvent) {
272 setInsertionDelay(insertionDelayChangedEvent.getInsertionDelay());
276 * Container for information that are required to insert a Sone. This
277 * container merely exists to copy all relevant data without holding a lock
278 * on the {@link Sone} object for too long.
280 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
283 class InsertInformation {
285 private final String fingerprint;
286 private final ManifestCreator manifestCreator;
289 * Creates a new insert information container.
294 public InsertInformation(Sone sone) {
295 this.fingerprint = sone.getFingerprint();
296 Map<String, Object> soneProperties = new HashMap<String, Object>();
297 soneProperties.put("id", sone.getId());
298 soneProperties.put("name", sone.getName());
299 soneProperties.put("time", currentTimeMillis());
300 soneProperties.put("requestUri", sone.getRequestUri());
301 soneProperties.put("profile", sone.getProfile());
302 soneProperties.put("posts", Ordering.from(Post.TIME_COMPARATOR).sortedCopy(sone.getPosts()));
303 soneProperties.put("replies", Ordering.from(Reply.TIME_COMPARATOR).reverse().sortedCopy(sone.getReplies()));
304 soneProperties.put("likedPostIds", new HashSet<String>(sone.getLikedPostIds()));
305 soneProperties.put("likedReplyIds", new HashSet<String>(sone.getLikedReplyIds()));
306 soneProperties.put("albums", FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).filter(NOT_EMPTY).toList());
307 manifestCreator = new ManifestCreator(core, soneProperties);
315 String getFingerprint() {
324 * Generates all manifest entries required to insert this Sone.
326 * @return The manifest entries for the Sone insert
328 public HashMap<String, Object> generateManifestEntries() {
329 HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
331 /* first, create an index.html. */
332 manifestEntries.put("index.html", manifestCreator.createManifestElement(
333 "index.html", "text/html; charset=utf-8",
334 "/templates/insert/index.html"));
336 /* now, store the sone. */
337 manifestEntries.put("sone.xml", manifestCreator.createManifestElement(
338 "sone.xml", "text/xml; charset=utf-8",
339 "/templates/insert/sone.xml"));
341 return manifestEntries;
347 * Creates manifest elements for an insert by rendering a template.
349 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
352 static class ManifestCreator {
354 private final Core core;
355 private final Map<String, Object> soneProperties;
357 ManifestCreator(Core core, Map<String, Object> soneProperties) {
359 this.soneProperties = soneProperties;
362 public ManifestElement createManifestElement(String name, String contentType, String templateName) {
363 InputStreamReader templateInputStreamReader = null;
364 InputStream templateInputStream = null;
367 templateInputStream = getClass().getResourceAsStream(templateName);
368 templateInputStreamReader = new InputStreamReader(templateInputStream, utf8Charset);
369 template = TemplateParser.parse(templateInputStreamReader);
370 } catch (TemplateException te1) {
371 logger.log(Level.SEVERE, String.format("Could not parse template “%s”!", templateName), te1);
374 Closer.close(templateInputStreamReader);
375 Closer.close(templateInputStream);
378 TemplateContext templateContext = templateContextFactory.createTemplateContext();
379 templateContext.set("core", core);
380 templateContext.set("currentSone", soneProperties);
381 templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
382 templateContext.set("version", SonePlugin.VERSION);
383 StringWriter writer = new StringWriter();
384 StringBucket bucket = null;
386 template.render(templateContext, writer);
387 bucket = new StringBucket(writer.toString(), utf8Charset);
388 return new ManifestElement(name, bucket, contentType, bucket.size());
389 } catch (TemplateException te1) {
390 logger.log(Level.SEVERE, String.format("Could not render template “%s”!", templateName), te1);
393 Closer.close(writer);
394 if (bucket != null) {