Make the insertion delay configurable.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / SoneInserter.java
1 /*
2  * FreenetSone - SoneInserter.java - Copyright © 2010 David Roden
3  *
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.pterodactylus.sone.core;
19
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;
27 import java.util.Map;
28 import java.util.Set;
29 import java.util.logging.Level;
30 import java.util.logging.Logger;
31
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;
49
50 /**
51  * A Sone inserter is responsible for inserting a Sone if it has changed.
52  *
53  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
54  */
55 public class SoneInserter extends AbstractService {
56
57         /** The logger. */
58         private static final Logger logger = Logging.getLogger(SoneInserter.class);
59
60         /** The insertion delay (in seconds). */
61         private static volatile int insertionDelay = 60;
62
63         /** The template factory used to create the templates. */
64         private static final DefaultTemplateFactory templateFactory = new DefaultTemplateFactory();
65
66         static {
67                 templateFactory.addAccessor(Object.class, new ReflectionAccessor());
68                 templateFactory.addFilter("xml", new XmlFilter());
69         }
70
71         /** The UTF-8 charset. */
72         private static final Charset utf8Charset = Charset.forName("UTF-8");
73
74         /** The core. */
75         private final Core core;
76
77         /** The Freenet interface. */
78         private final FreenetInterface freenetInterface;
79
80         /** The Sone to insert. */
81         private final Sone sone;
82
83         /**
84          * Creates a new Sone inserter.
85          *
86          * @param core
87          *            The core
88          * @param freenetInterface
89          *            The freenet interface
90          * @param sone
91          *            The Sone to insert
92          */
93         public SoneInserter(Core core, FreenetInterface freenetInterface, Sone sone) {
94                 super("Sone Inserter for “" + sone.getName() + "”", false);
95                 this.core = core;
96                 this.freenetInterface = freenetInterface;
97                 this.sone = sone;
98         }
99
100         //
101         // ACCESSORS
102         //
103
104         /**
105          * Changes the insertion delay, i.e. the time the Sone inserter waits after
106          * it has noticed a Sone modification before it starts the insert.
107          *
108          * @param insertionDelay
109          *            The insertion delay (in seconds)
110          */
111         public static void setInsertionDelay(int insertionDelay) {
112                 SoneInserter.insertionDelay = insertionDelay;
113         }
114
115         //
116         // SERVICE METHODS
117         //
118
119         /**
120          * {@inheritDoc}
121          */
122         @Override
123         protected void serviceRun() {
124                 long modificationCounter = 0;
125                 long lastModificationTime = 0;
126                 while (!shouldStop()) {
127                         /* check every seconds. */
128                         sleep(1000);
129
130                         InsertInformation insertInformation = null;
131                         synchronized (sone) {
132                                 if (sone.getModificationCounter() > modificationCounter) {
133                                         modificationCounter = sone.getModificationCounter();
134                                         lastModificationTime = System.currentTimeMillis();
135                                         sone.setTime(lastModificationTime);
136                                         logger.log(Level.FINE, "Sone %s has been modified, waiting %d seconds before inserting.", new Object[] { sone.getName(), insertionDelay });
137                                 }
138                                 if ((lastModificationTime > 0) && ((System.currentTimeMillis() - lastModificationTime) > (insertionDelay * 1000))) {
139                                         insertInformation = new InsertInformation(sone);
140                                 }
141                         }
142
143                         if (insertInformation != null) {
144                                 logger.log(Level.INFO, "Inserting Sone “%s”…", new Object[] { sone.getName() });
145
146                                 boolean success = false;
147                                 try {
148                                         core.setSoneStatus(sone, SoneStatus.inserting);
149                                         FreenetURI finalUri = freenetInterface.insertDirectory(insertInformation.getInsertUri().setKeyType("USK").setSuggestedEdition(0), insertInformation.generateManifestEntries(), "index.html");
150                                         sone.updateUris(finalUri);
151                                         success = true;
152                                         logger.log(Level.INFO, "Inserted Sone “%s” at %s.", new Object[] { sone.getName(), finalUri });
153                                 } catch (SoneException se1) {
154                                         logger.log(Level.WARNING, "Could not insert Sone “" + sone.getName() + "”!", se1);
155                                 } finally {
156                                         core.setSoneStatus(sone, SoneStatus.idle);
157                                 }
158
159                                 /*
160                                  * reset modification counter if Sone has not been modified
161                                  * while it was inserted.
162                                  */
163                                 if (success) {
164                                         synchronized (sone) {
165                                                 if (sone.getModificationCounter() == modificationCounter) {
166                                                         logger.log(Level.FINE, "Sone “%s” was not modified further, resetting counter…", new Object[] { sone });
167                                                         sone.setModificationCounter(0);
168                                                         modificationCounter = 0;
169                                                         lastModificationTime = 0;
170                                                 }
171                                         }
172                                 }
173                         }
174                 }
175         }
176
177         /**
178          * Container for information that are required to insert a Sone. This
179          * container merely exists to copy all relevant data without holding a lock
180          * on the {@link Sone} object for too long.
181          *
182          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
183          */
184         private class InsertInformation {
185
186                 /** All properties of the Sone, copied for thread safety. */
187                 private final Map<String, Object> soneProperties = new HashMap<String, Object>();
188
189                 /**
190                  * Creates a new insert information container.
191                  *
192                  * @param sone
193                  *            The sone to insert
194                  */
195                 public InsertInformation(Sone sone) {
196                         soneProperties.put("id", sone.getId());
197                         soneProperties.put("name", sone.getName());
198                         soneProperties.put("time", sone.getTime());
199                         soneProperties.put("requestUri", sone.getRequestUri());
200                         soneProperties.put("insertUri", sone.getInsertUri());
201                         soneProperties.put("profile", sone.getProfile());
202                         soneProperties.put("posts", new ArrayList<Post>(sone.getPosts()));
203                         soneProperties.put("replies", new HashSet<Reply>(sone.getReplies()));
204                         soneProperties.put("blockedSoneIds", new HashSet<String>(sone.getBlockedSoneIds()));
205                         soneProperties.put("likedPostIds", new HashSet<String>(sone.getLikedPostIds()));
206                         soneProperties.put("likeReplyIds", new HashSet<String>(sone.getLikedReplyIds()));
207                 }
208
209                 //
210                 // ACCESSORS
211                 //
212
213                 /**
214                  * Returns the insert URI of the Sone.
215                  *
216                  * @return The insert URI of the Sone
217                  */
218                 public FreenetURI getInsertUri() {
219                         return (FreenetURI) soneProperties.get("insertUri");
220                 }
221
222                 //
223                 // ACTIONS
224                 //
225
226                 /**
227                  * Generates all manifest entries required to insert this Sone.
228                  *
229                  * @return The manifest entries for the Sone insert
230                  */
231                 public HashMap<String, Object> generateManifestEntries() {
232                         HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
233
234                         /* first, create an index.html. */
235                         manifestEntries.put("index.html", createManifestElement("index.html", "text/html; charset=utf-8", "/templates/insert/index.html"));
236
237                         /* now, store the sone. */
238                         manifestEntries.put("sone.xml", createManifestElement("sone.xml", "text/xml; charset=utf-8", "/templates/insert/sone.xml"));
239
240                         return manifestEntries;
241                 }
242
243                 //
244                 // PRIVATE METHODS
245                 //
246
247                 /**
248                  * Creates a new manifest element.
249                  *
250                  * @param name
251                  *            The name of the file
252                  * @param contentType
253                  *            The content type of the file
254                  * @param templateName
255                  *            The name of the template to render
256                  * @return The manifest element
257                  */
258                 @SuppressWarnings("synthetic-access")
259                 private ManifestElement createManifestElement(String name, String contentType, String templateName) {
260                         InputStreamReader templateInputStreamReader;
261                         Template template = templateFactory.createTemplate(templateInputStreamReader = new InputStreamReader(getClass().getResourceAsStream(templateName), utf8Charset));
262                         try {
263                                 template.parse();
264                         } catch (TemplateException te1) {
265                                 logger.log(Level.SEVERE, "Could not parse template “" + templateName + "”!", te1);
266                                 return null;
267                         } finally {
268                                 Closer.close(templateInputStreamReader);
269                         }
270                         @SuppressWarnings("unchecked")
271                         final Set<String> blockedSoneIds = (Set<String>) soneProperties.get("blockedSoneIds");
272                         Collection<Sone> knownSones = Filters.filteredCollection(core.getKnownSones(), new Filter<Sone>() {
273
274                                 /**
275                                  * {@inheritDoc}
276                                  */
277                                 @Override
278                                 public boolean filterObject(Sone object) {
279                                         return !blockedSoneIds.contains(object.getId()) && !object.getId().equals(soneProperties.get("id"));
280                                 }
281                         });
282
283                         template.set("currentSone", soneProperties);
284                         template.set("knownSones", knownSones);
285                         StringWriter writer = new StringWriter();
286                         StringBucket bucket = null;
287                         try {
288                                 template.render(writer);
289                                 bucket = new StringBucket(writer.toString(), utf8Charset);
290                                 return new ManifestElement(name, bucket, contentType, bucket.size());
291                         } catch (TemplateException te1) {
292                                 logger.log(Level.SEVERE, "Could not render template “" + templateName + "”!", te1);
293                                 return null;
294                         } finally {
295                                 Closer.close(writer);
296                                 if (bucket != null) {
297                                         bucket.free();
298                                 }
299                         }
300                 }
301
302         }
303
304 }