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.util.io.Closer;
36 import net.pterodactylus.util.logging.Logging;
37 import net.pterodactylus.util.service.AbstractService;
38 import net.pterodactylus.util.template.DefaultTemplateFactory;
39 import net.pterodactylus.util.template.ReflectionAccessor;
40 import net.pterodactylus.util.template.Template;
41 import net.pterodactylus.util.template.TemplateException;
42 import net.pterodactylus.util.template.XmlFilter;
43 import freenet.client.async.ManifestElement;
44 import freenet.keys.FreenetURI;
47 * A Sone inserter is responsible for inserting a Sone if it has changed.
49 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
51 public class SoneInserter extends AbstractService {
54 private static final Logger logger = Logging.getLogger(SoneInserter.class);
56 /** The insertion delay (in seconds). */
57 private static volatile int insertionDelay = 60;
59 /** The template factory used to create the templates. */
60 private static final DefaultTemplateFactory templateFactory = new DefaultTemplateFactory();
63 templateFactory.addAccessor(Object.class, new ReflectionAccessor());
64 templateFactory.addFilter("xml", new XmlFilter());
67 /** The UTF-8 charset. */
68 private static final Charset utf8Charset = Charset.forName("UTF-8");
71 private final Core core;
73 /** The Freenet interface. */
74 private final FreenetInterface freenetInterface;
76 /** The Sone to insert. */
77 private final Sone sone;
80 * Creates a new Sone inserter.
84 * @param freenetInterface
85 * The freenet interface
89 public SoneInserter(Core core, FreenetInterface freenetInterface, Sone sone) {
90 super("Sone Inserter for “" + sone.getName() + "”", false);
92 this.freenetInterface = freenetInterface;
101 * Changes the insertion delay, i.e. the time the Sone inserter waits after
102 * it has noticed a Sone modification before it starts the insert.
104 * @param insertionDelay
105 * The insertion delay (in seconds)
107 public static void setInsertionDelay(int insertionDelay) {
108 SoneInserter.insertionDelay = insertionDelay;
119 protected void serviceRun() {
120 long modificationCounter = 0;
121 long lastModificationTime = 0;
122 while (!shouldStop()) {
123 /* check every seconds. */
126 InsertInformation insertInformation = null;
127 synchronized (sone) {
128 if (sone.getModificationCounter() > modificationCounter) {
129 modificationCounter = sone.getModificationCounter();
130 lastModificationTime = System.currentTimeMillis();
131 sone.setTime(lastModificationTime);
132 logger.log(Level.FINE, "Sone %s has been modified, waiting %d seconds before inserting.", new Object[] { sone.getName(), insertionDelay });
134 if ((lastModificationTime > 0) && ((System.currentTimeMillis() - lastModificationTime) > (insertionDelay * 1000))) {
135 insertInformation = new InsertInformation(sone);
139 if (insertInformation != null) {
140 logger.log(Level.INFO, "Inserting Sone “%s”…", new Object[] { sone.getName() });
142 boolean success = false;
144 core.setSoneStatus(sone, SoneStatus.inserting);
145 FreenetURI finalUri = freenetInterface.insertDirectory(insertInformation.getInsertUri().setKeyType("USK").setSuggestedEdition(0), insertInformation.generateManifestEntries(), "index.html");
146 /* at this point we might already be stopped. */
148 /* if so, bail out, don’t change anything. */
151 sone.setLatestEdition(finalUri.getEdition());
153 logger.log(Level.INFO, "Inserted Sone “%s” at %s.", new Object[] { sone.getName(), finalUri });
154 } catch (SoneException se1) {
155 logger.log(Level.WARNING, "Could not insert Sone “" + sone.getName() + "”!", se1);
157 core.setSoneStatus(sone, SoneStatus.idle);
161 * reset modification counter if Sone has not been modified
162 * while it was inserted.
165 synchronized (sone) {
166 if (sone.getModificationCounter() == modificationCounter) {
167 logger.log(Level.FINE, "Sone “%s” was not modified further, resetting counter…", new Object[] { sone });
168 sone.setModificationCounter(0);
170 modificationCounter = 0;
171 lastModificationTime = 0;
180 * Container for information that are required to insert a Sone. This
181 * container merely exists to copy all relevant data without holding a lock
182 * on the {@link Sone} object for too long.
184 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
186 private class InsertInformation {
188 /** All properties of the Sone, copied for thread safety. */
189 private final Map<String, Object> soneProperties = new HashMap<String, Object>();
192 * Creates a new insert information container.
197 public InsertInformation(Sone sone) {
198 soneProperties.put("id", sone.getId());
199 soneProperties.put("name", sone.getName());
200 soneProperties.put("time", sone.getTime());
201 soneProperties.put("requestUri", sone.getRequestUri());
202 soneProperties.put("insertUri", sone.getInsertUri());
203 soneProperties.put("profile", sone.getProfile());
204 soneProperties.put("posts", new ArrayList<Post>(sone.getPosts()));
205 soneProperties.put("replies", new HashSet<Reply>(sone.getReplies()));
206 soneProperties.put("likedPostIds", new HashSet<String>(sone.getLikedPostIds()));
207 soneProperties.put("likeReplyIds", new HashSet<String>(sone.getLikedReplyIds()));
215 * Returns the insert URI of the Sone.
217 * @return The insert URI of the Sone
219 public FreenetURI getInsertUri() {
220 return (FreenetURI) soneProperties.get("insertUri");
228 * Generates all manifest entries required to insert this Sone.
230 * @return The manifest entries for the Sone insert
232 public HashMap<String, Object> generateManifestEntries() {
233 HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
235 /* first, create an index.html. */
236 manifestEntries.put("index.html", createManifestElement("index.html", "text/html; charset=utf-8", "/templates/insert/index.html"));
238 /* now, store the sone. */
239 manifestEntries.put("sone.xml", createManifestElement("sone.xml", "text/xml; charset=utf-8", "/templates/insert/sone.xml"));
241 return manifestEntries;
249 * Creates a new manifest element.
252 * The name of the file
254 * The content type of the file
255 * @param templateName
256 * The name of the template to render
257 * @return The manifest element
259 @SuppressWarnings("synthetic-access")
260 private ManifestElement createManifestElement(String name, String contentType, String templateName) {
261 InputStreamReader templateInputStreamReader;
262 Template template = templateFactory.createTemplate(templateInputStreamReader = new InputStreamReader(getClass().getResourceAsStream(templateName), utf8Charset));
265 } catch (TemplateException te1) {
266 logger.log(Level.SEVERE, "Could not parse template “" + templateName + "”!", te1);
269 Closer.close(templateInputStreamReader);
272 template.set("currentSone", soneProperties);
273 StringWriter writer = new StringWriter();
274 StringBucket bucket = null;
276 template.render(writer);
277 bucket = new StringBucket(writer.toString(), utf8Charset);
278 return new ManifestElement(name, bucket, contentType, bucket.size());
279 } catch (TemplateException te1) {
280 logger.log(Level.SEVERE, "Could not render template “" + templateName + "”!", te1);
283 Closer.close(writer);
284 if (bucket != null) {