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.System.currentTimeMillis;
22 import static net.pterodactylus.sone.data.Album.NOT_EMPTY;
24 import java.io.InputStream;
25 import java.io.InputStreamReader;
26 import java.io.StringWriter;
27 import java.nio.charset.Charset;
28 import java.util.HashMap;
29 import java.util.HashSet;
31 import java.util.concurrent.atomic.AtomicInteger;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
35 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
36 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
37 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
38 import net.pterodactylus.sone.data.Album;
39 import net.pterodactylus.sone.data.Post;
40 import net.pterodactylus.sone.data.Reply;
41 import net.pterodactylus.sone.data.Sone;
42 import net.pterodactylus.sone.data.Sone.SoneStatus;
43 import net.pterodactylus.sone.freenet.StringBucket;
44 import net.pterodactylus.sone.main.SonePlugin;
45 import net.pterodactylus.util.io.Closer;
46 import net.pterodactylus.util.logging.Logging;
47 import net.pterodactylus.util.service.AbstractService;
48 import net.pterodactylus.util.template.HtmlFilter;
49 import net.pterodactylus.util.template.ReflectionAccessor;
50 import net.pterodactylus.util.template.Template;
51 import net.pterodactylus.util.template.TemplateContext;
52 import net.pterodactylus.util.template.TemplateContextFactory;
53 import net.pterodactylus.util.template.TemplateException;
54 import net.pterodactylus.util.template.TemplateParser;
55 import net.pterodactylus.util.template.XmlFilter;
57 import com.google.common.collect.FluentIterable;
58 import com.google.common.collect.Ordering;
59 import com.google.common.eventbus.EventBus;
61 import freenet.client.async.ManifestElement;
62 import freenet.keys.FreenetURI;
65 * A Sone inserter is responsible for inserting a Sone if it has changed.
67 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
69 public class SoneInserter extends AbstractService {
72 private static final Logger logger = Logging.getLogger(SoneInserter.class);
74 /** The insertion delay (in seconds). */
75 private static final AtomicInteger insertionDelay = new AtomicInteger(60);
77 /** The template factory used to create the templates. */
78 private static final TemplateContextFactory templateContextFactory = new TemplateContextFactory();
81 templateContextFactory.addAccessor(Object.class, new ReflectionAccessor());
82 templateContextFactory.addFilter("xml", new XmlFilter());
83 templateContextFactory.addFilter("html", new HtmlFilter());
86 /** The UTF-8 charset. */
87 private static final Charset utf8Charset = Charset.forName("UTF-8");
90 private final Core core;
93 private final EventBus eventBus;
95 /** The Freenet interface. */
96 private final FreenetInterface freenetInterface;
98 private final SoneModificationDetector soneModificationDetector;
100 /** The Sone to insert. */
101 private volatile Sone sone;
104 * Creates a new Sone inserter.
110 * @param freenetInterface
111 * The freenet interface
115 public SoneInserter(Core core, EventBus eventBus, FreenetInterface freenetInterface, Sone sone) {
116 super("Sone Inserter for “" + sone.getName() + "”", false);
118 this.eventBus = eventBus;
119 this.freenetInterface = freenetInterface;
121 this.soneModificationDetector = new SoneModificationDetector(core, sone, insertionDelay);
129 * Sets the Sone to insert.
133 * @return This Sone inserter
135 public SoneInserter setSone(Sone sone) {
136 checkArgument((this.sone == null) || sone.equals(this.sone), "Sone to insert can not be set to a different Sone");
142 * Changes the insertion delay, i.e. the time the Sone inserter waits after it
143 * has noticed a Sone modification before it starts the insert.
145 * @param insertionDelay
146 * The insertion delay (in seconds)
148 public static void setInsertionDelay(int insertionDelay) {
149 SoneInserter.insertionDelay.set(insertionDelay);
153 * Returns the fingerprint of the last insert.
155 * @return The fingerprint of the last insert
157 public String getLastInsertFingerprint() {
158 return soneModificationDetector.getOriginalFingerprint();
162 * Sets the fingerprint of the last insert.
164 * @param lastInsertFingerprint
165 * The fingerprint of the last insert
167 public void setLastInsertFingerprint(String lastInsertFingerprint) {
168 soneModificationDetector.setFingerprint(lastInsertFingerprint);
172 * Returns whether the Sone inserter has detected a modification of the
175 * @return {@code true} if the Sone has been modified, {@code false}
178 public boolean isModified() {
179 return soneModificationDetector.isModified();
190 protected void serviceRun() {
191 while (!shouldStop()) {
193 /* check every second. */
196 if (soneModificationDetector.isEligibleForInsert()) {
197 InsertInformation insertInformation = new InsertInformation(sone);
198 logger.log(Level.INFO, String.format("Inserting Sone “%s”…", sone.getName()));
200 boolean success = false;
202 sone.setStatus(SoneStatus.inserting);
203 long insertTime = currentTimeMillis();
204 insertInformation.setTime(insertTime);
205 eventBus.post(new SoneInsertingEvent(sone));
206 FreenetURI finalUri = freenetInterface.insertDirectory(insertInformation.getInsertUri(), insertInformation.generateManifestEntries(), "index.html");
207 eventBus.post(new SoneInsertedEvent(sone, currentTimeMillis() - insertTime));
208 /* at this point we might already be stopped. */
210 /* if so, bail out, don’t change anything. */
213 sone.setTime(insertTime);
214 sone.setLatestEdition(finalUri.getEdition());
215 core.touchConfiguration();
217 logger.log(Level.INFO, String.format("Inserted Sone “%s” at %s.", sone.getName(), finalUri));
218 } catch (SoneException se1) {
219 eventBus.post(new SoneInsertAbortedEvent(sone, se1));
220 logger.log(Level.WARNING, String.format("Could not insert Sone “%s”!", sone.getName()), se1);
222 sone.setStatus(SoneStatus.idle);
226 * reset modification counter if Sone has not been modified
227 * while it was inserted.
230 synchronized (sone) {
231 if (insertInformation.getFingerprint().equals(sone.getFingerprint())) {
232 logger.log(Level.FINE, String.format("Sone “%s” was not modified further, resetting counter…", sone));
233 soneModificationDetector.setFingerprint(insertInformation.getFingerprint());
234 core.touchConfiguration();
239 } catch (Throwable t1) {
240 logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
246 * Container for information that are required to insert a Sone. This
247 * container merely exists to copy all relevant data without holding a lock
248 * on the {@link Sone} object for too long.
250 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
252 private class InsertInformation {
254 private final String fingerprint;
256 /** All properties of the Sone, copied for thread safety. */
257 private final Map<String, Object> soneProperties = new HashMap<String, Object>();
260 * Creates a new insert information container.
265 public InsertInformation(Sone sone) {
266 this.fingerprint = sone.getFingerprint();
267 soneProperties.put("id", sone.getId());
268 soneProperties.put("name", sone.getName());
269 soneProperties.put("time", sone.getTime());
270 soneProperties.put("requestUri", sone.getRequestUri());
271 soneProperties.put("insertUri", sone.getInsertUri());
272 soneProperties.put("profile", sone.getProfile());
273 soneProperties.put("posts", Ordering.from(Post.TIME_COMPARATOR).sortedCopy(sone.getPosts()));
274 soneProperties.put("replies", Ordering.from(Reply.TIME_COMPARATOR).reverse().sortedCopy(sone.getReplies()));
275 soneProperties.put("likedPostIds", new HashSet<String>(sone.getLikedPostIds()));
276 soneProperties.put("likedReplyIds", new HashSet<String>(sone.getLikedReplyIds()));
277 soneProperties.put("albums", FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).filter(NOT_EMPTY).toList());
284 private String getFingerprint() {
289 * Returns the insert URI of the Sone.
291 * @return The insert URI of the Sone
293 public FreenetURI getInsertUri() {
294 return (FreenetURI) soneProperties.get("insertUri");
298 * Sets the time of the Sone at the time of the insert.
301 * The time of the Sone
303 public void setTime(long time) {
304 soneProperties.put("time", time);
312 * Generates all manifest entries required to insert this Sone.
314 * @return The manifest entries for the Sone insert
316 public HashMap<String, Object> generateManifestEntries() {
317 HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
319 /* first, create an index.html. */
320 manifestEntries.put("index.html", createManifestElement("index.html", "text/html; charset=utf-8", "/templates/insert/index.html"));
322 /* now, store the sone. */
323 manifestEntries.put("sone.xml", createManifestElement("sone.xml", "text/xml; charset=utf-8", "/templates/insert/sone.xml"));
325 return manifestEntries;
333 * Creates a new manifest element.
336 * The name of the file
338 * The content type of the file
339 * @param templateName
340 * The name of the template to render
341 * @return The manifest element
343 @SuppressWarnings("synthetic-access")
344 private ManifestElement createManifestElement(String name, String contentType, String templateName) {
345 InputStreamReader templateInputStreamReader = null;
346 InputStream templateInputStream = null;
349 templateInputStream = getClass().getResourceAsStream(templateName);
350 templateInputStreamReader = new InputStreamReader(templateInputStream, utf8Charset);
351 template = TemplateParser.parse(templateInputStreamReader);
352 } catch (TemplateException te1) {
353 logger.log(Level.SEVERE, String.format("Could not parse template “%s”!", templateName), te1);
356 Closer.close(templateInputStreamReader);
357 Closer.close(templateInputStream);
360 TemplateContext templateContext = templateContextFactory.createTemplateContext();
361 templateContext.set("core", core);
362 templateContext.set("currentSone", soneProperties);
363 templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
364 templateContext.set("version", SonePlugin.VERSION);
365 StringWriter writer = new StringWriter();
366 StringBucket bucket = null;
368 template.render(templateContext, writer);
369 bucket = new StringBucket(writer.toString(), utf8Charset);
370 return new ManifestElement(name, bucket, contentType, bucket.size());
371 } catch (TemplateException te1) {
372 logger.log(Level.SEVERE, String.format("Could not render template “%s”!", templateName), te1);
375 Closer.close(writer);
376 if (bucket != null) {