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.Collection;
25 import java.util.HashMap;
26 import java.util.HashSet;
29 import java.util.logging.Level;
30 import java.util.logging.Logger;
32 import net.pterodactylus.sone.core.Core.SoneStatus;
33 import net.pterodactylus.sone.data.Post;
34 import net.pterodactylus.sone.data.Reply;
35 import net.pterodactylus.sone.data.Sone;
36 import net.pterodactylus.sone.freenet.StringBucket;
37 import net.pterodactylus.util.filter.Filter;
38 import net.pterodactylus.util.filter.Filters;
39 import net.pterodactylus.util.io.Closer;
40 import net.pterodactylus.util.logging.Logging;
41 import net.pterodactylus.util.service.AbstractService;
42 import net.pterodactylus.util.template.DefaultTemplateFactory;
43 import net.pterodactylus.util.template.ReflectionAccessor;
44 import net.pterodactylus.util.template.Template;
45 import net.pterodactylus.util.template.TemplateException;
46 import net.pterodactylus.util.template.XmlFilter;
47 import freenet.client.async.ManifestElement;
48 import freenet.keys.FreenetURI;
51 * A Sone inserter is responsible for inserting a Sone if it has changed.
53 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
55 public class SoneInserter extends AbstractService {
58 private static final Logger logger = Logging.getLogger(SoneInserter.class);
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;
81 * Creates a new Sone inserter.
85 * @param freenetInterface
86 * The freenet interface
90 public SoneInserter(Core core, FreenetInterface freenetInterface, Sone sone) {
91 super("Sone Inserter for “" + sone.getName() + "”", false);
93 this.freenetInterface = freenetInterface;
105 protected void serviceRun() {
106 long modificationCounter = 0;
107 boolean restartNow = true;
108 while (!shouldStop()) {
110 logger.log(Level.FINEST, "Waiting 60 seconds before checking Sone “" + sone.getName() + "”.");
114 InsertInformation insertInformation = null;
115 synchronized (sone) {
116 modificationCounter = sone.getModificationCounter();
117 if (modificationCounter > 0) {
118 sone.setTime(System.currentTimeMillis());
119 insertInformation = new InsertInformation(sone);
122 if (insertInformation != null) {
123 logger.log(Level.INFO, "Inserting Sone “%s”…", new Object[] { sone.getName() });
125 boolean success = false;
127 core.setSoneStatus(sone, SoneStatus.inserting);
128 FreenetURI finalUri = freenetInterface.insertDirectory(insertInformation.getInsertUri().setKeyType("USK").setDocName("Sone-" + sone.getName()).setSuggestedEdition(0), insertInformation.generateManifestEntries(), "index.html");
129 sone.updateUris(finalUri);
131 logger.log(Level.INFO, "Inserted Sone “%s” at %s.", new Object[] { sone.getName(), finalUri });
132 } catch (SoneException se1) {
133 logger.log(Level.WARNING, "Could not insert Sone “" + sone.getName() + "”!", se1);
135 core.setSoneStatus(sone, SoneStatus.idle);
139 * reset modification counter if Sone has not been modified
140 * while it was inserted.
143 synchronized (sone) {
144 if (sone.getModificationCounter() == modificationCounter) {
145 logger.log(Level.FINE, "Sone “%s” was not modified further, resetting counter…", new Object[] { sone });
146 sone.setModificationCounter(0);
148 logger.log(Level.FINE, "Sone “%s” was modified since the insert started, starting another insert…", new Object[] { sone });
158 * Container for information that are required to insert a Sone. This
159 * container merely exists to copy all relevant data without holding a lock
160 * on the {@link Sone} object for too long.
162 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
164 private class InsertInformation {
166 /** All properties of the Sone, copied for thread safety. */
167 private final Map<String, Object> soneProperties = new HashMap<String, Object>();
170 * Creates a new insert information container.
175 public InsertInformation(Sone sone) {
176 soneProperties.put("id", sone.getId());
177 soneProperties.put("name", sone.getName());
178 soneProperties.put("time", sone.getTime());
179 soneProperties.put("requestUri", sone.getRequestUri());
180 soneProperties.put("insertUri", sone.getInsertUri());
181 soneProperties.put("profile", sone.getProfile());
182 soneProperties.put("posts", new ArrayList<Post>(sone.getPosts()));
183 soneProperties.put("replies", new HashSet<Reply>(sone.getReplies()));
184 soneProperties.put("friends", new HashSet<Sone>(sone.getFriends()));
185 soneProperties.put("blockedSoneIds", new HashSet<String>(sone.getBlockedSoneIds()));
193 * Returns the insert URI of the Sone.
195 * @return The insert URI of the Sone
197 public FreenetURI getInsertUri() {
198 return (FreenetURI) soneProperties.get("insertUri");
206 * Generates all manifest entries required to insert this Sone.
208 * @return The manifest entries for the Sone insert
210 public HashMap<String, Object> generateManifestEntries() {
211 HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
213 /* first, create an index.html. */
214 manifestEntries.put("index.html", createManifestElement("index.html", "text/html; charset=utf-8", "/templates/insert/index.html"));
216 /* now, store the sone. */
217 manifestEntries.put("sone.xml", createManifestElement("sone.xml", "text/xml; charset=utf-8", "/templates/insert/sone.xml"));
219 return manifestEntries;
227 * Creates a new manifest element.
230 * The name of the file
232 * The content type of the file
233 * @param templateName
234 * The name of the template to render
235 * @return The manifest element
237 @SuppressWarnings("synthetic-access")
238 private ManifestElement createManifestElement(String name, String contentType, String templateName) {
239 InputStreamReader templateInputStreamReader;
240 Template template = templateFactory.createTemplate(templateInputStreamReader = new InputStreamReader(getClass().getResourceAsStream(templateName), utf8Charset));
243 } catch (TemplateException te1) {
244 logger.log(Level.SEVERE, "Could not parse template “" + templateName + "”!", te1);
247 Closer.close(templateInputStreamReader);
249 @SuppressWarnings("unchecked")
250 final Set<String> blockedSoneIds = (Set<String>) soneProperties.get("blockedSoneIds");
251 Collection<Sone> knownSones = Filters.filteredCollection(core.getKnownSones(), new Filter<Sone>() {
257 public boolean filterObject(Sone object) {
258 return !blockedSoneIds.contains(object.getId()) && !object.getId().equals(soneProperties.get("id"));
262 template.set("currentSone", soneProperties);
263 template.set("knownSones", knownSones);
264 StringWriter writer = new StringWriter();
265 StringBucket bucket = null;
267 template.render(writer);
268 bucket = new StringBucket(writer.toString(), utf8Charset);
269 return new ManifestElement(name, bucket, contentType, bucket.size());
270 } catch (TemplateException te1) {
271 logger.log(Level.SEVERE, "Could not render template “" + templateName + "”!", te1);
274 Closer.close(writer);
275 if (bucket != null) {