2 * FreenetSone - SoneInserter.java - Copyright © 2010 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 java.io.InputStreamReader;
21 import java.io.StringWriter;
22 import java.nio.charset.Charset;
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.HashSet;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
30 import net.pterodactylus.sone.core.Core.SoneStatus;
31 import net.pterodactylus.sone.data.Post;
32 import net.pterodactylus.sone.data.Reply;
33 import net.pterodactylus.sone.data.Sone;
34 import net.pterodactylus.sone.freenet.StringBucket;
35 import net.pterodactylus.sone.main.SonePlugin;
36 import net.pterodactylus.util.io.Closer;
37 import net.pterodactylus.util.logging.Logging;
38 import net.pterodactylus.util.service.AbstractService;
39 import net.pterodactylus.util.template.DefaultTemplateFactory;
40 import net.pterodactylus.util.template.ReflectionAccessor;
41 import net.pterodactylus.util.template.Template;
42 import net.pterodactylus.util.template.TemplateException;
43 import net.pterodactylus.util.template.XmlFilter;
44 import freenet.client.async.ManifestElement;
45 import freenet.keys.FreenetURI;
48 * A Sone inserter is responsible for inserting a Sone if it has changed.
50 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
52 public class SoneInserter extends AbstractService {
55 private static final Logger logger = Logging.getLogger(SoneInserter.class);
57 /** The insertion delay (in seconds). */
58 private static volatile int insertionDelay = 60;
60 /** The template factory used to create the templates. */
61 private static final DefaultTemplateFactory templateFactory = new DefaultTemplateFactory();
64 templateFactory.addAccessor(Object.class, new ReflectionAccessor());
65 templateFactory.addFilter("xml", new XmlFilter());
68 /** The UTF-8 charset. */
69 private static final Charset utf8Charset = Charset.forName("UTF-8");
72 private final Core core;
74 /** The Freenet interface. */
75 private final FreenetInterface freenetInterface;
77 /** The Sone to insert. */
78 private final Sone sone;
80 /** Whether a modification has been detected. */
81 private volatile boolean modified = false;
83 /** The fingerprint of the last insert. */
84 private volatile String lastInsertFingerprint;
87 * Creates a new Sone inserter.
91 * @param freenetInterface
92 * The freenet interface
96 public SoneInserter(Core core, FreenetInterface freenetInterface, Sone sone) {
97 super("Sone Inserter for “" + sone.getName() + "”", false);
99 this.freenetInterface = freenetInterface;
108 * Changes the insertion delay, i.e. the time the Sone inserter waits after
109 * it has noticed a Sone modification before it starts the insert.
111 * @param insertionDelay
112 * The insertion delay (in seconds)
114 public static void setInsertionDelay(int insertionDelay) {
115 SoneInserter.insertionDelay = insertionDelay;
119 * Returns the fingerprint of the last insert.
121 * @return The fingerprint of the last insert
123 public String getLastInsertFingerprint() {
124 return lastInsertFingerprint;
128 * Sets the fingerprint of the last insert.
130 * @param lastInsertFingerprint
131 * The fingerprint of the last insert
133 public void setLastInsertFingerprint(String lastInsertFingerprint) {
134 this.lastInsertFingerprint = lastInsertFingerprint;
138 * Returns whether the Sone inserter has detected a modification of the
141 * @return {@code true} if the Sone has been modified, {@code false}
144 public boolean isModified() {
156 protected void serviceRun() {
157 long lastModificationTime = 0;
158 String lastFingerprint = "";
159 while (!shouldStop()) {
160 /* check every seconds. */
163 InsertInformation insertInformation = null;
164 synchronized (sone) {
165 String fingerprint = sone.getFingerprint();
166 if (!fingerprint.equals(lastFingerprint)) {
167 if (fingerprint.equals(lastInsertFingerprint)) {
169 lastModificationTime = 0;
170 logger.log(Level.FINE, "Sone %s has been reverted to last insert state.", sone);
172 lastModificationTime = System.currentTimeMillis();
174 sone.setTime(lastModificationTime);
175 logger.log(Level.FINE, "Sone %s has been modified, waiting %d seconds before inserting.", new Object[] { sone.getName(), insertionDelay });
177 lastFingerprint = fingerprint;
179 if (modified && (lastModificationTime > 0) && ((System.currentTimeMillis() - lastModificationTime) > (insertionDelay * 1000))) {
180 lastInsertFingerprint = fingerprint;
181 insertInformation = new InsertInformation(sone);
185 if (insertInformation != null) {
186 logger.log(Level.INFO, "Inserting Sone “%s”…", new Object[] { sone.getName() });
188 boolean success = false;
190 core.setSoneStatus(sone, SoneStatus.inserting);
191 FreenetURI finalUri = freenetInterface.insertDirectory(insertInformation.getInsertUri().setKeyType("USK").setSuggestedEdition(0), insertInformation.generateManifestEntries(), "index.html");
192 /* at this point we might already be stopped. */
194 /* if so, bail out, don’t change anything. */
197 sone.setLatestEdition(finalUri.getEdition());
199 logger.log(Level.INFO, "Inserted Sone “%s” at %s.", new Object[] { sone.getName(), finalUri });
200 } catch (SoneException se1) {
201 logger.log(Level.WARNING, "Could not insert Sone “" + sone.getName() + "”!", se1);
203 core.setSoneStatus(sone, SoneStatus.idle);
207 * reset modification counter if Sone has not been modified
208 * while it was inserted.
211 synchronized (sone) {
212 if (lastInsertFingerprint.equals(sone.getFingerprint())) {
213 logger.log(Level.FINE, "Sone “%s” was not modified further, resetting counter…", new Object[] { sone });
215 lastModificationTime = 0;
225 * Container for information that are required to insert a Sone. This
226 * container merely exists to copy all relevant data without holding a lock
227 * on the {@link Sone} object for too long.
229 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
231 private class InsertInformation {
233 /** All properties of the Sone, copied for thread safety. */
234 private final Map<String, Object> soneProperties = new HashMap<String, Object>();
237 * Creates a new insert information container.
242 public InsertInformation(Sone sone) {
243 soneProperties.put("id", sone.getId());
244 soneProperties.put("name", sone.getName());
245 soneProperties.put("time", sone.getTime());
246 soneProperties.put("requestUri", sone.getRequestUri());
247 soneProperties.put("insertUri", sone.getInsertUri());
248 soneProperties.put("profile", sone.getProfile());
249 soneProperties.put("posts", new ArrayList<Post>(sone.getPosts()));
250 soneProperties.put("replies", new HashSet<Reply>(sone.getReplies()));
251 soneProperties.put("likedPostIds", new HashSet<String>(sone.getLikedPostIds()));
252 soneProperties.put("likeReplyIds", new HashSet<String>(sone.getLikedReplyIds()));
260 * Returns the insert URI of the Sone.
262 * @return The insert URI of the Sone
264 public FreenetURI getInsertUri() {
265 return (FreenetURI) soneProperties.get("insertUri");
273 * Generates all manifest entries required to insert this Sone.
275 * @return The manifest entries for the Sone insert
277 public HashMap<String, Object> generateManifestEntries() {
278 HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
280 /* first, create an index.html. */
281 manifestEntries.put("index.html", createManifestElement("index.html", "text/html; charset=utf-8", "/templates/insert/index.html"));
283 /* now, store the sone. */
284 manifestEntries.put("sone.xml", createManifestElement("sone.xml", "text/xml; charset=utf-8", "/templates/insert/sone.xml"));
286 return manifestEntries;
294 * Creates a new manifest element.
297 * The name of the file
299 * The content type of the file
300 * @param templateName
301 * The name of the template to render
302 * @return The manifest element
304 @SuppressWarnings("synthetic-access")
305 private ManifestElement createManifestElement(String name, String contentType, String templateName) {
306 InputStreamReader templateInputStreamReader;
307 Template template = templateFactory.createTemplate(templateInputStreamReader = new InputStreamReader(getClass().getResourceAsStream(templateName), utf8Charset));
310 } catch (TemplateException te1) {
311 logger.log(Level.SEVERE, "Could not parse template “" + templateName + "”!", te1);
314 Closer.close(templateInputStreamReader);
317 template.set("currentSone", soneProperties);
318 template.set("version", SonePlugin.VERSION);
319 StringWriter writer = new StringWriter();
320 StringBucket bucket = null;
322 template.render(writer);
323 bucket = new StringBucket(writer.toString(), utf8Charset);
324 return new ManifestElement(name, bucket, contentType, bucket.size());
325 } catch (TemplateException te1) {
326 logger.log(Level.SEVERE, "Could not render template “" + templateName + "”!", te1);
329 Closer.close(writer);
330 if (bucket != null) {