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.LocalSone;
43 import net.pterodactylus.sone.data.Post;
44 import net.pterodactylus.sone.data.Reply;
45 import net.pterodactylus.sone.data.Sone;
46 import net.pterodactylus.sone.data.Sone.SoneStatus;
47 import net.pterodactylus.sone.database.Database;
48 import net.pterodactylus.sone.freenet.StringBucket;
49 import net.pterodactylus.sone.main.SonePlugin;
50 import net.pterodactylus.util.io.Closer;
51 import net.pterodactylus.util.service.AbstractService;
52 import net.pterodactylus.util.template.HtmlFilter;
53 import net.pterodactylus.util.template.ReflectionAccessor;
54 import net.pterodactylus.util.template.Template;
55 import net.pterodactylus.util.template.TemplateContext;
56 import net.pterodactylus.util.template.TemplateContextFactory;
57 import net.pterodactylus.util.template.TemplateException;
58 import net.pterodactylus.util.template.TemplateParser;
59 import net.pterodactylus.util.template.XmlFilter;
61 import com.google.common.annotations.VisibleForTesting;
62 import com.google.common.base.Optional;
63 import com.google.common.collect.FluentIterable;
64 import com.google.common.collect.Ordering;
65 import com.google.common.eventbus.EventBus;
66 import com.google.common.eventbus.Subscribe;
68 import freenet.client.async.ManifestElement;
69 import freenet.keys.FreenetURI;
72 * A Sone inserter is responsible for inserting a Sone if it has changed.
74 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
76 public class SoneInserter extends AbstractService {
79 private static final Logger logger = getLogger("Sone.Inserter");
81 /** The insertion delay (in seconds). */
82 private static final AtomicInteger insertionDelay = new AtomicInteger(60);
84 /** The template factory used to create the templates. */
85 private static final TemplateContextFactory templateContextFactory = new TemplateContextFactory();
88 templateContextFactory.addAccessor(Object.class, new ReflectionAccessor());
89 templateContextFactory.addFilter("xml", new XmlFilter());
90 templateContextFactory.addFilter("html", new HtmlFilter());
93 /** The UTF-8 charset. */
94 private static final Charset utf8Charset = Charset.forName("UTF-8");
97 private final Core core;
100 private final EventBus eventBus;
102 /** The Freenet interface. */
103 private final FreenetInterface freenetInterface;
104 private final Database database;
105 private final SoneModificationDetector soneModificationDetector;
106 private final long delay;
107 private final String soneId;
110 * Creates a new Sone inserter.
116 * @param freenetInterface
117 * The freenet interface
119 * The ID of the Sone to insert
121 public SoneInserter(final Core core, EventBus eventBus, FreenetInterface freenetInterface, Database database, final String soneId) {
122 this(core, eventBus, freenetInterface, database, soneId, new SoneModificationDetector(new LockableFingerprintProvider() {
124 public boolean isLocked() {
125 final Optional<LocalSone> sone = core.getLocalSone(soneId);
126 if (!sone.isPresent()) {
129 return core.isLocked(sone.get());
133 public String getFingerprint() {
134 final Optional<Sone> sone = core.getSone(soneId);
135 if (!sone.isPresent()) {
138 return sone.get().getFingerprint();
140 }, insertionDelay), 1000);
144 SoneInserter(Core core, EventBus eventBus, FreenetInterface freenetInterface, Database database, String soneId, SoneModificationDetector soneModificationDetector, long delay) {
145 super("Sone Inserter for “" + soneId + "”", false);
147 this.eventBus = eventBus;
148 this.freenetInterface = freenetInterface;
149 this.database = database;
150 this.soneId = soneId;
151 this.soneModificationDetector = soneModificationDetector;
160 static AtomicInteger getInsertionDelay() {
161 return insertionDelay;
165 * Changes the insertion delay, i.e. the time the Sone inserter waits after it
166 * has noticed a Sone modification before it starts the insert.
168 * @param insertionDelay
169 * The insertion delay (in seconds)
171 private static void setInsertionDelay(int insertionDelay) {
172 SoneInserter.insertionDelay.set(insertionDelay);
176 * Returns the fingerprint of the last insert.
178 * @return The fingerprint of the last insert
180 public String getLastInsertFingerprint() {
181 return soneModificationDetector.getOriginalFingerprint();
185 * Sets the fingerprint of the last insert.
187 * @param lastInsertFingerprint
188 * The fingerprint of the last insert
190 public void setLastInsertFingerprint(String lastInsertFingerprint) {
191 soneModificationDetector.setFingerprint(lastInsertFingerprint);
195 * Returns whether the Sone inserter has detected a modification of the
198 * @return {@code true} if the Sone has been modified, {@code false}
201 public boolean isModified() {
202 return soneModificationDetector.isModified();
213 protected void serviceRun() {
214 while (!shouldStop()) {
216 /* check every second. */
219 if (soneModificationDetector.isEligibleForInsert()) {
220 Optional<LocalSone> soneOptional = core.getLocalSone(soneId);
221 if (!soneOptional.isPresent()) {
222 logger.log(Level.WARNING, format("Sone %s has disappeared, exiting inserter.", soneId));
225 LocalSone sone = soneOptional.get();
226 InsertInformation insertInformation = new InsertInformation(sone);
227 logger.log(Level.INFO, String.format("Inserting Sone “%s”…", sone.getName()));
229 boolean success = false;
231 sone.setStatus(SoneStatus.inserting);
232 long insertTime = currentTimeMillis();
233 eventBus.post(new SoneInsertingEvent(sone));
234 FreenetURI finalUri = freenetInterface.insertDirectory(sone.getInsertUri(), insertInformation.generateManifestEntries(), "index.html");
235 eventBus.post(new SoneInsertedEvent(sone, currentTimeMillis() - insertTime, insertInformation.getFingerprint()));
236 /* at this point we might already be stopped. */
238 /* if so, bail out, don’t change anything. */
241 database.updateSoneTime(sone, insertTime);
242 sone.setLatestEdition(finalUri.getEdition());
243 core.touchConfiguration();
245 logger.log(Level.INFO, String.format("Inserted Sone “%s” at %s.", sone.getName(), finalUri));
246 } catch (SoneException se1) {
247 eventBus.post(new SoneInsertAbortedEvent(sone, se1));
248 logger.log(Level.WARNING, String.format("Could not insert Sone “%s”!", sone.getName()), se1);
250 sone.setStatus(SoneStatus.idle);
254 * reset modification counter if Sone has not been modified
255 * while it was inserted.
258 synchronized (sone) {
259 if (insertInformation.getFingerprint().equals(sone.getFingerprint())) {
260 logger.log(Level.FINE, String.format("Sone “%s” was not modified further, resetting counter…", sone));
261 soneModificationDetector.setFingerprint(insertInformation.getFingerprint());
262 core.touchConfiguration();
267 } catch (Throwable t1) {
268 logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
274 public void insertionDelayChanged(InsertionDelayChangedEvent insertionDelayChangedEvent) {
275 setInsertionDelay(insertionDelayChangedEvent.getInsertionDelay());
279 * Container for information that are required to insert a Sone. This
280 * container merely exists to copy all relevant data without holding a lock
281 * on the {@link Sone} object for too long.
283 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
286 class InsertInformation {
288 private final String fingerprint;
289 private final ManifestCreator manifestCreator;
292 * Creates a new insert information container.
297 public InsertInformation(Sone sone) {
298 this.fingerprint = sone.getFingerprint();
299 Map<String, Object> soneProperties = new HashMap<String, Object>();
300 soneProperties.put("id", sone.getId());
301 soneProperties.put("name", sone.getName());
302 soneProperties.put("time", currentTimeMillis());
303 soneProperties.put("requestUri", sone.getRequestUri());
304 soneProperties.put("profile", sone.getProfile());
305 soneProperties.put("posts", Ordering.from(Post.TIME_COMPARATOR).sortedCopy(sone.getPosts()));
306 soneProperties.put("replies", Ordering.from(Reply.TIME_COMPARATOR).reverse().sortedCopy(sone.getReplies()));
307 soneProperties.put("likedPostIds", new HashSet<String>(sone.getLikedPostIds()));
308 soneProperties.put("likedReplyIds", new HashSet<String>(sone.getLikedReplyIds()));
309 soneProperties.put("albums", FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).filter(NOT_EMPTY).toList());
310 manifestCreator = new ManifestCreator(core, soneProperties);
318 String getFingerprint() {
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", manifestCreator.createManifestElement(
336 "index.html", "text/html; charset=utf-8",
337 "/templates/insert/index.html"));
339 /* now, store the sone. */
340 manifestEntries.put("sone.xml", manifestCreator.createManifestElement(
341 "sone.xml", "text/xml; charset=utf-8",
342 "/templates/insert/sone.xml"));
344 return manifestEntries;
350 * Creates manifest elements for an insert by rendering a template.
352 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
355 static class ManifestCreator {
357 private final Core core;
358 private final Map<String, Object> soneProperties;
360 ManifestCreator(Core core, Map<String, Object> soneProperties) {
362 this.soneProperties = soneProperties;
365 public ManifestElement createManifestElement(String name, String contentType, String templateName) {
366 InputStreamReader templateInputStreamReader = null;
367 InputStream templateInputStream = null;
370 templateInputStream = getClass().getResourceAsStream(templateName);
371 templateInputStreamReader = new InputStreamReader(templateInputStream, utf8Charset);
372 template = TemplateParser.parse(templateInputStreamReader);
373 } catch (TemplateException te1) {
374 logger.log(Level.SEVERE, String.format("Could not parse template “%s”!", templateName), te1);
377 Closer.close(templateInputStreamReader);
378 Closer.close(templateInputStream);
381 TemplateContext templateContext = templateContextFactory.createTemplateContext();
382 templateContext.set("core", core);
383 templateContext.set("currentSone", soneProperties);
384 templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
385 templateContext.set("version", SonePlugin.VERSION);
386 StringWriter writer = new StringWriter();
387 StringBucket bucket = null;
389 template.render(templateContext, writer);
390 bucket = new StringBucket(writer.toString(), utf8Charset);
391 return new ManifestElement(name, bucket, contentType, bucket.size());
392 } catch (TemplateException te1) {
393 logger.log(Level.SEVERE, String.format("Could not render template “%s”!", templateName), te1);
396 Closer.close(writer);
397 if (bucket != null) {