2 * Sone - SoneInserter.java - Copyright © 2010–2016 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.Closeable;
26 import java.io.InputStream;
27 import java.io.InputStreamReader;
28 import java.io.StringWriter;
29 import java.nio.charset.Charset;
30 import java.util.HashMap;
31 import java.util.HashSet;
34 import java.util.concurrent.atomic.AtomicInteger;
35 import java.util.logging.Level;
36 import java.util.logging.Logger;
38 import net.pterodactylus.sone.core.SoneModificationDetector.LockableFingerprintProvider;
39 import net.pterodactylus.sone.core.event.InsertionDelayChangedEvent;
40 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
41 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
42 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
43 import net.pterodactylus.sone.data.Album;
44 import net.pterodactylus.sone.data.Post;
45 import net.pterodactylus.sone.data.Reply;
46 import net.pterodactylus.sone.data.Sone;
47 import net.pterodactylus.sone.data.Sone.SoneStatus;
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.Charsets;
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.keys.FreenetURI;
68 import freenet.support.api.Bucket;
69 import freenet.support.api.ManifestElement;
70 import freenet.support.api.RandomAccessBucket;
71 import freenet.support.io.ArrayBucket;
74 * A Sone inserter is responsible for inserting a Sone if it has changed.
76 public class SoneInserter extends AbstractService {
79 private static final Logger logger = getLogger(SoneInserter.class.getName());
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;
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, final String soneId) {
122 this(core, eventBus, freenetInterface, soneId, new SoneModificationDetector(new LockableFingerprintProvider() {
124 public boolean isLocked() {
125 Sone sone = core.getSone(soneId);
129 return core.isLocked(sone);
133 public String getFingerprint() {
134 Sone sone = core.getSone(soneId);
138 return sone.getFingerprint();
140 }, insertionDelay), 1000);
144 SoneInserter(Core core, EventBus eventBus, FreenetInterface freenetInterface, String soneId, SoneModificationDetector soneModificationDetector, long delay) {
145 super("Sone Inserter for “" + soneId + "”", false);
147 this.eventBus = eventBus;
148 this.freenetInterface = freenetInterface;
149 this.soneId = soneId;
150 this.soneModificationDetector = soneModificationDetector;
159 static AtomicInteger getInsertionDelay() {
160 return insertionDelay;
164 * Changes the insertion delay, i.e. the time the Sone inserter waits after it
165 * has noticed a Sone modification before it starts the insert.
167 * @param insertionDelay
168 * The insertion delay (in seconds)
170 private static void setInsertionDelay(int insertionDelay) {
171 SoneInserter.insertionDelay.set(insertionDelay);
175 * Returns the fingerprint of the last insert.
177 * @return The fingerprint of the last insert
179 public String getLastInsertFingerprint() {
180 return soneModificationDetector.getLastInsertFingerprint();
184 * Sets the fingerprint of the last insert.
186 * @param lastInsertFingerprint
187 * The fingerprint of the last insert
189 public void setLastInsertFingerprint(String lastInsertFingerprint) {
190 soneModificationDetector.setFingerprint(lastInsertFingerprint);
194 * Returns whether the Sone inserter has detected a modification of the
197 * @return {@code true} if the Sone has been modified, {@code false}
200 public boolean isModified() {
201 return soneModificationDetector.isModified();
212 protected void serviceRun() {
213 while (!shouldStop()) {
215 /* check every second. */
218 if (soneModificationDetector.isEligibleForInsert()) {
219 Sone sone = core.getSone(soneId);
221 logger.log(Level.WARNING, format("Sone %s has disappeared, exiting inserter.", soneId));
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 insertInformation.close();
249 sone.setStatus(SoneStatus.idle);
253 * reset modification counter if Sone has not been modified
254 * while it was inserted.
257 synchronized (sone) {
258 if (insertInformation.getFingerprint().equals(sone.getFingerprint())) {
259 logger.log(Level.FINE, String.format("Sone “%s” was not modified further, resetting counter…", sone));
260 soneModificationDetector.setFingerprint(insertInformation.getFingerprint());
261 core.touchConfiguration();
266 } catch (Throwable t1) {
267 logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
273 public void insertionDelayChanged(InsertionDelayChangedEvent insertionDelayChangedEvent) {
274 setInsertionDelay(insertionDelayChangedEvent.getInsertionDelay());
278 * Container for information that are required to insert a Sone. This
279 * container merely exists to copy all relevant data without holding a lock
280 * on the {@link Sone} object for too long.
283 class InsertInformation implements Closeable {
285 /** All properties of the Sone, copied for thread safety. */
286 private final Map<String, Object> soneProperties = new HashMap<>();
287 private final String fingerprint;
288 private final ManifestCreator manifestCreator;
291 * Creates a new insert information container.
296 public InsertInformation(Sone sone) {
297 this.fingerprint = sone.getFingerprint();
298 Map<String, Object> soneProperties = new HashMap<>();
299 soneProperties.put("id", sone.getId());
300 soneProperties.put("name", sone.getName());
301 soneProperties.put("time", currentTimeMillis());
302 soneProperties.put("requestUri", sone.getRequestUri());
303 soneProperties.put("profile", sone.getProfile());
304 soneProperties.put("posts", Ordering.from(Post.NEWEST_FIRST).sortedCopy(sone.getPosts()));
305 soneProperties.put("replies", Ordering.from(Reply.TIME_COMPARATOR).reverse().sortedCopy(sone.getReplies()));
306 soneProperties.put("likedPostIds", new HashSet<>(sone.getLikedPostIds()));
307 soneProperties.put("likedReplyIds", new HashSet<>(sone.getLikedReplyIds()));
308 soneProperties.put("albums", FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).filter(NOT_EMPTY).toList());
309 manifestCreator = new ManifestCreator(core, soneProperties);
317 String getFingerprint() {
326 * Generates all manifest entries required to insert this Sone.
328 * @return The manifest entries for the Sone insert
330 public HashMap<String, Object> generateManifestEntries() {
331 HashMap<String, Object> manifestEntries = new HashMap<>();
333 /* first, create an index.html. */
334 manifestEntries.put("index.html", manifestCreator.createManifestElement(
335 "index.html", "text/html; charset=utf-8",
336 "/templates/insert/index.html"));
338 /* now, store the sone. */
339 manifestEntries.put("sone.xml", manifestCreator.createManifestElement(
340 "sone.xml", "text/xml; charset=utf-8",
341 "/templates/insert/sone.xml"));
343 return manifestEntries;
347 public void close() {
348 manifestCreator.close();
354 * Creates manifest elements for an insert by rendering a template.
357 static class ManifestCreator implements Closeable {
359 private final Core core;
360 private final Map<String, Object> soneProperties;
361 private final Set<Bucket> buckets = new HashSet<>();
363 ManifestCreator(Core core, Map<String, Object> soneProperties) {
365 this.soneProperties = soneProperties;
368 public ManifestElement createManifestElement(String name, String contentType, String templateName) {
369 InputStreamReader templateInputStreamReader = null;
370 InputStream templateInputStream = null;
373 templateInputStream = getClass().getResourceAsStream(templateName);
374 templateInputStreamReader = new InputStreamReader(templateInputStream, utf8Charset);
375 template = TemplateParser.parse(templateInputStreamReader);
376 } catch (TemplateException te1) {
377 logger.log(Level.SEVERE, String.format("Could not parse template “%s”!", templateName), te1);
380 Closer.close(templateInputStreamReader);
381 Closer.close(templateInputStream);
384 TemplateContext templateContext = templateContextFactory.createTemplateContext();
385 templateContext.set("core", core);
386 templateContext.set("currentSone", soneProperties);
387 templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
388 templateContext.set("version", SonePlugin.getPluginVersion());
389 StringWriter writer = new StringWriter();
391 template.render(templateContext, writer);
392 RandomAccessBucket bucket = new ArrayBucket(writer.toString().getBytes(Charsets.UTF_8));
394 return new ManifestElement(name, bucket, contentType, bucket.size());
395 } catch (TemplateException te1) {
396 logger.log(Level.SEVERE, String.format("Could not render template “%s”!", templateName), te1);
399 Closer.close(writer);
403 public void close() {
404 for (Bucket bucket : buckets) {