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.freenet.StringBucket;
48 import net.pterodactylus.sone.main.SonePlugin;
49 import net.pterodactylus.util.io.Closer;
50 import net.pterodactylus.util.service.AbstractService;
51 import net.pterodactylus.util.template.HtmlFilter;
52 import net.pterodactylus.util.template.ReflectionAccessor;
53 import net.pterodactylus.util.template.Template;
54 import net.pterodactylus.util.template.TemplateContext;
55 import net.pterodactylus.util.template.TemplateContextFactory;
56 import net.pterodactylus.util.template.TemplateException;
57 import net.pterodactylus.util.template.TemplateParser;
58 import net.pterodactylus.util.template.XmlFilter;
60 import com.google.common.annotations.VisibleForTesting;
61 import com.google.common.base.Optional;
62 import com.google.common.collect.FluentIterable;
63 import com.google.common.collect.Ordering;
64 import com.google.common.eventbus.EventBus;
65 import com.google.common.eventbus.Subscribe;
67 import freenet.client.async.ManifestElement;
68 import freenet.keys.FreenetURI;
71 * A Sone inserter is responsible for inserting a Sone if it has changed.
73 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
75 public class SoneInserter extends AbstractService {
78 private static final Logger logger = getLogger("Sone.Inserter");
80 /** The insertion delay (in seconds). */
81 private static final AtomicInteger insertionDelay = new AtomicInteger(60);
83 /** The template factory used to create the templates. */
84 private static final TemplateContextFactory templateContextFactory = new TemplateContextFactory();
87 templateContextFactory.addAccessor(Object.class, new ReflectionAccessor());
88 templateContextFactory.addFilter("xml", new XmlFilter());
89 templateContextFactory.addFilter("html", new HtmlFilter());
92 /** The UTF-8 charset. */
93 private static final Charset utf8Charset = Charset.forName("UTF-8");
96 private final Core core;
99 private final EventBus eventBus;
101 /** The Freenet interface. */
102 private final FreenetInterface freenetInterface;
104 private final SoneModificationDetector soneModificationDetector;
105 private final long delay;
106 private final String soneId;
109 * Creates a new Sone inserter.
115 * @param freenetInterface
116 * The freenet interface
118 * The ID of the Sone to insert
120 public SoneInserter(final Core core, EventBus eventBus, FreenetInterface freenetInterface, final String soneId) {
121 this(core, eventBus, freenetInterface, soneId, new SoneModificationDetector(new LockableFingerprintProvider() {
123 public boolean isLocked() {
124 final Optional<LocalSone> sone = core.getLocalSone(soneId);
125 if (!sone.isPresent()) {
128 return core.isLocked(sone.get());
132 public String getFingerprint() {
133 final Optional<Sone> sone = core.getSone(soneId);
134 if (!sone.isPresent()) {
137 return sone.get().getFingerprint();
139 }, insertionDelay), 1000);
143 SoneInserter(Core core, EventBus eventBus, FreenetInterface freenetInterface, String soneId, SoneModificationDetector soneModificationDetector, long delay) {
144 super("Sone Inserter for “" + soneId + "”", false);
146 this.eventBus = eventBus;
147 this.freenetInterface = freenetInterface;
148 this.soneId = soneId;
149 this.soneModificationDetector = soneModificationDetector;
158 static AtomicInteger getInsertionDelay() {
159 return insertionDelay;
163 * Changes the insertion delay, i.e. the time the Sone inserter waits after it
164 * has noticed a Sone modification before it starts the insert.
166 * @param insertionDelay
167 * The insertion delay (in seconds)
169 private static void setInsertionDelay(int insertionDelay) {
170 SoneInserter.insertionDelay.set(insertionDelay);
174 * Returns the fingerprint of the last insert.
176 * @return The fingerprint of the last insert
178 public String getLastInsertFingerprint() {
179 return soneModificationDetector.getOriginalFingerprint();
183 * Sets the fingerprint of the last insert.
185 * @param lastInsertFingerprint
186 * The fingerprint of the last insert
188 public void setLastInsertFingerprint(String lastInsertFingerprint) {
189 soneModificationDetector.setFingerprint(lastInsertFingerprint);
193 * Returns whether the Sone inserter has detected a modification of the
196 * @return {@code true} if the Sone has been modified, {@code false}
199 public boolean isModified() {
200 return soneModificationDetector.isModified();
211 protected void serviceRun() {
212 while (!shouldStop()) {
214 /* check every second. */
217 if (soneModificationDetector.isEligibleForInsert()) {
218 Optional<Sone> soneOptional = core.getSone(soneId);
219 if (!soneOptional.isPresent()) {
220 logger.log(Level.WARNING, format("Sone %s has disappeared, exiting inserter.", soneId));
223 Sone sone = soneOptional.get();
224 InsertInformation insertInformation = new InsertInformation(sone);
225 logger.log(Level.INFO, String.format("Inserting Sone “%s”…", sone.getName()));
227 boolean success = false;
229 sone.setStatus(SoneStatus.inserting);
230 long insertTime = currentTimeMillis();
231 eventBus.post(new SoneInsertingEvent(sone));
232 FreenetURI finalUri = freenetInterface.insertDirectory(sone.getInsertUri(), insertInformation.generateManifestEntries(), "index.html");
233 eventBus.post(new SoneInsertedEvent(sone, currentTimeMillis() - insertTime, insertInformation.getFingerprint()));
234 /* at this point we might already be stopped. */
236 /* if so, bail out, don’t change anything. */
239 sone.setTime(insertTime);
240 sone.setLatestEdition(finalUri.getEdition());
241 core.touchConfiguration();
243 logger.log(Level.INFO, String.format("Inserted Sone “%s” at %s.", sone.getName(), finalUri));
244 } catch (SoneException se1) {
245 eventBus.post(new SoneInsertAbortedEvent(sone, se1));
246 logger.log(Level.WARNING, String.format("Could not insert Sone “%s”!", sone.getName()), se1);
248 sone.setStatus(SoneStatus.idle);
252 * reset modification counter if Sone has not been modified
253 * while it was inserted.
256 synchronized (sone) {
257 if (insertInformation.getFingerprint().equals(sone.getFingerprint())) {
258 logger.log(Level.FINE, String.format("Sone “%s” was not modified further, resetting counter…", sone));
259 soneModificationDetector.setFingerprint(insertInformation.getFingerprint());
260 core.touchConfiguration();
265 } catch (Throwable t1) {
266 logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
272 public void insertionDelayChanged(InsertionDelayChangedEvent insertionDelayChangedEvent) {
273 setInsertionDelay(insertionDelayChangedEvent.getInsertionDelay());
277 * Container for information that are required to insert a Sone. This
278 * container merely exists to copy all relevant data without holding a lock
279 * on the {@link Sone} object for too long.
281 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
284 class InsertInformation {
286 private final String fingerprint;
287 private final ManifestCreator manifestCreator;
290 * Creates a new insert information container.
295 public InsertInformation(Sone sone) {
296 this.fingerprint = sone.getFingerprint();
297 Map<String, Object> soneProperties = new HashMap<String, Object>();
298 soneProperties.put("id", sone.getId());
299 soneProperties.put("name", sone.getName());
300 soneProperties.put("time", currentTimeMillis());
301 soneProperties.put("requestUri", sone.getRequestUri());
302 soneProperties.put("profile", sone.getProfile());
303 soneProperties.put("posts", Ordering.from(Post.TIME_COMPARATOR).sortedCopy(sone.getPosts()));
304 soneProperties.put("replies", Ordering.from(Reply.TIME_COMPARATOR).reverse().sortedCopy(sone.getReplies()));
305 soneProperties.put("likedPostIds", new HashSet<String>(sone.getLikedPostIds()));
306 soneProperties.put("likedReplyIds", new HashSet<String>(sone.getLikedReplyIds()));
307 soneProperties.put("albums", FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).filter(NOT_EMPTY).toList());
308 manifestCreator = new ManifestCreator(core, soneProperties);
316 String getFingerprint() {
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", manifestCreator.createManifestElement(
334 "index.html", "text/html; charset=utf-8",
335 "/templates/insert/index.html"));
337 /* now, store the sone. */
338 manifestEntries.put("sone.xml", manifestCreator.createManifestElement(
339 "sone.xml", "text/xml; charset=utf-8",
340 "/templates/insert/sone.xml"));
342 return manifestEntries;
348 * Creates manifest elements for an insert by rendering a template.
350 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
353 static class ManifestCreator {
355 private final Core core;
356 private final Map<String, Object> soneProperties;
358 ManifestCreator(Core core, Map<String, Object> soneProperties) {
360 this.soneProperties = soneProperties;
363 public ManifestElement createManifestElement(String name, String contentType, String templateName) {
364 InputStreamReader templateInputStreamReader = null;
365 InputStream templateInputStream = null;
368 templateInputStream = getClass().getResourceAsStream(templateName);
369 templateInputStreamReader = new InputStreamReader(templateInputStream, utf8Charset);
370 template = TemplateParser.parse(templateInputStreamReader);
371 } catch (TemplateException te1) {
372 logger.log(Level.SEVERE, String.format("Could not parse template “%s”!", templateName), te1);
375 Closer.close(templateInputStreamReader);
376 Closer.close(templateInputStream);
379 TemplateContext templateContext = templateContextFactory.createTemplateContext();
380 templateContext.set("core", core);
381 templateContext.set("currentSone", soneProperties);
382 templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
383 templateContext.set("version", SonePlugin.VERSION);
384 StringWriter writer = new StringWriter();
385 StringBucket bucket = null;
387 template.render(templateContext, writer);
388 bucket = new StringBucket(writer.toString(), utf8Charset);
389 return new ManifestElement(name, bucket, contentType, bucket.size());
390 } catch (TemplateException te1) {
391 logger.log(Level.SEVERE, String.format("Could not render template “%s”!", templateName), te1);
394 Closer.close(writer);
395 if (bucket != null) {