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.String.format;
22 import static java.lang.System.currentTimeMillis;
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.Options.Option;
37 import net.pterodactylus.sone.core.Options.OptionWatcher;
38 import net.pterodactylus.sone.core.SoneModificationDetector.LockableFingerprintProvider;
39 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
40 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
41 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
42 import net.pterodactylus.sone.data.Album;
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.logging.Logging;
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;
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 = Logging.getLogger(SoneInserter.class);
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<Sone> sone = core.getSone(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 public 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(insertInformation.getInsertUri(), insertInformation.generateManifestEntries(), "index.html");
233 eventBus.post(new SoneInsertedEvent(sone, currentTimeMillis() - insertTime));
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);
271 static class SetInsertionDelay implements OptionWatcher<Integer> {
274 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
275 setInsertionDelay(newValue);
281 * Container for information that are required to insert a Sone. This
282 * container merely exists to copy all relevant data without holding a lock
283 * on the {@link Sone} object for too long.
285 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
288 class InsertInformation {
290 private final String fingerprint;
292 /** All properties of the Sone, copied for thread safety. */
293 private final Map<String, Object> soneProperties = new HashMap<String, Object>();
296 * Creates a new insert information container.
301 public InsertInformation(Sone sone) {
302 this.fingerprint = sone.getFingerprint();
303 soneProperties.put("id", sone.getId());
304 soneProperties.put("name", sone.getName());
305 soneProperties.put("time", currentTimeMillis());
306 soneProperties.put("requestUri", sone.getRequestUri());
307 soneProperties.put("insertUri", sone.getInsertUri());
308 soneProperties.put("profile", sone.getProfile());
309 soneProperties.put("posts", Ordering.from(Post.TIME_COMPARATOR).sortedCopy(sone.getPosts()));
310 soneProperties.put("replies", Ordering.from(Reply.TIME_COMPARATOR).reverse().sortedCopy(sone.getReplies()));
311 soneProperties.put("likedPostIds", new HashSet<String>(sone.getLikedPostIds()));
312 soneProperties.put("likedReplyIds", new HashSet<String>(sone.getLikedReplyIds()));
313 soneProperties.put("albums", FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).filter(NOT_EMPTY).toList());
321 String getFingerprint() {
326 * Returns the insert URI of the Sone.
328 * @return The insert URI of the Sone
330 public FreenetURI getInsertUri() {
331 return (FreenetURI) soneProperties.get("insertUri");
339 * Generates all manifest entries required to insert this Sone.
341 * @return The manifest entries for the Sone insert
343 public HashMap<String, Object> generateManifestEntries() {
344 HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
346 /* first, create an index.html. */
347 manifestEntries.put("index.html", createManifestElement("index.html", "text/html; charset=utf-8", "/templates/insert/index.html"));
349 /* now, store the sone. */
350 manifestEntries.put("sone.xml", createManifestElement("sone.xml", "text/xml; charset=utf-8", "/templates/insert/sone.xml"));
352 return manifestEntries;
360 * Creates a new manifest element.
363 * The name of the file
365 * The content type of the file
366 * @param templateName
367 * The name of the template to render
368 * @return The manifest element
370 @SuppressWarnings("synthetic-access")
371 private ManifestElement createManifestElement(String name, String contentType, String templateName) {
372 InputStreamReader templateInputStreamReader = null;
373 InputStream templateInputStream = null;
376 templateInputStream = getClass().getResourceAsStream(templateName);
377 templateInputStreamReader = new InputStreamReader(templateInputStream, utf8Charset);
378 template = TemplateParser.parse(templateInputStreamReader);
379 } catch (TemplateException te1) {
380 logger.log(Level.SEVERE, String.format("Could not parse template “%s”!", templateName), te1);
383 Closer.close(templateInputStreamReader);
384 Closer.close(templateInputStream);
387 TemplateContext templateContext = templateContextFactory.createTemplateContext();
388 templateContext.set("core", core);
389 templateContext.set("currentSone", soneProperties);
390 templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
391 templateContext.set("version", SonePlugin.VERSION);
392 StringWriter writer = new StringWriter();
393 StringBucket bucket = null;
395 template.render(templateContext, writer);
396 bucket = new StringBucket(writer.toString(), utf8Charset);
397 return new ManifestElement(name, bucket, contentType, bucket.size());
398 } catch (TemplateException te1) {
399 logger.log(Level.SEVERE, String.format("Could not render template “%s”!", templateName), te1);
402 Closer.close(writer);
403 if (bucket != null) {