Add more tests of sone inserter.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / SoneInserter.java
1 /*
2  * Sone - SoneInserter.java - Copyright © 2010–2013 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 static com.google.common.base.Preconditions.checkArgument;
21 import static java.lang.System.currentTimeMillis;
22 import static net.pterodactylus.sone.data.Album.NOT_EMPTY;
23
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;
30 import java.util.Map;
31 import java.util.concurrent.atomic.AtomicInteger;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
34
35 import net.pterodactylus.sone.core.Options.Option;
36 import net.pterodactylus.sone.core.Options.OptionWatcher;
37 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
38 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
39 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
40 import net.pterodactylus.sone.data.Album;
41 import net.pterodactylus.sone.data.Post;
42 import net.pterodactylus.sone.data.Reply;
43 import net.pterodactylus.sone.data.Sone;
44 import net.pterodactylus.sone.data.Sone.SoneStatus;
45 import net.pterodactylus.sone.freenet.StringBucket;
46 import net.pterodactylus.sone.main.SonePlugin;
47 import net.pterodactylus.util.io.Closer;
48 import net.pterodactylus.util.logging.Logging;
49 import net.pterodactylus.util.service.AbstractService;
50 import net.pterodactylus.util.template.HtmlFilter;
51 import net.pterodactylus.util.template.ReflectionAccessor;
52 import net.pterodactylus.util.template.Template;
53 import net.pterodactylus.util.template.TemplateContext;
54 import net.pterodactylus.util.template.TemplateContextFactory;
55 import net.pterodactylus.util.template.TemplateException;
56 import net.pterodactylus.util.template.TemplateParser;
57 import net.pterodactylus.util.template.XmlFilter;
58
59 import com.google.common.annotations.VisibleForTesting;
60 import com.google.common.collect.FluentIterable;
61 import com.google.common.collect.Ordering;
62 import com.google.common.eventbus.EventBus;
63
64 import freenet.client.async.ManifestElement;
65 import freenet.keys.FreenetURI;
66
67 /**
68  * A Sone inserter is responsible for inserting a Sone if it has changed.
69  *
70  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
71  */
72 public class SoneInserter extends AbstractService {
73
74         /** The logger. */
75         private static final Logger logger = Logging.getLogger(SoneInserter.class);
76
77         /** The insertion delay (in seconds). */
78         private static final AtomicInteger insertionDelay = new AtomicInteger(60);
79
80         /** The template factory used to create the templates. */
81         private static final TemplateContextFactory templateContextFactory = new TemplateContextFactory();
82
83         static {
84                 templateContextFactory.addAccessor(Object.class, new ReflectionAccessor());
85                 templateContextFactory.addFilter("xml", new XmlFilter());
86                 templateContextFactory.addFilter("html", new HtmlFilter());
87         }
88
89         /** The UTF-8 charset. */
90         private static final Charset utf8Charset = Charset.forName("UTF-8");
91
92         /** The core. */
93         private final Core core;
94
95         /** The event bus. */
96         private final EventBus eventBus;
97
98         /** The Freenet interface. */
99         private final FreenetInterface freenetInterface;
100
101         private final SoneModificationDetector soneModificationDetector;
102
103         /** The Sone to insert. */
104         private volatile Sone sone;
105
106         /**
107          * Creates a new Sone inserter.
108          *
109          * @param core
110          *            The core
111          * @param eventBus
112          *            The event bus
113          * @param freenetInterface
114          *            The freenet interface
115          * @param sone
116          *            The Sone to insert
117          */
118         public SoneInserter(Core core, EventBus eventBus, FreenetInterface freenetInterface, Sone sone) {
119                 this(core, eventBus, freenetInterface, sone, new SoneModificationDetector(core, sone, insertionDelay));
120         }
121
122         @VisibleForTesting
123         SoneInserter(Core core, EventBus eventBus, FreenetInterface freenetInterface, Sone sone, SoneModificationDetector soneModificationDetector) {
124                 super("Sone Inserter for “" + sone.getName() + "”", false);
125                 this.core = core;
126                 this.eventBus = eventBus;
127                 this.freenetInterface = freenetInterface;
128                 this.sone = sone;
129                 this.soneModificationDetector = soneModificationDetector;
130         }
131
132         //
133         // ACCESSORS
134         //
135
136         /**
137          * Sets the Sone to insert.
138          *
139          * @param sone
140          *              The Sone to insert
141          * @return This Sone inserter
142          */
143         public SoneInserter setSone(Sone sone) {
144                 checkArgument(sone.equals(this.sone), "Sone to insert can not be set to a different Sone");
145                 this.sone = sone;
146                 return this;
147         }
148
149         @VisibleForTesting
150         static AtomicInteger getInsertionDelay() {
151                 return insertionDelay;
152         }
153
154         /**
155          * Changes the insertion delay, i.e. the time the Sone inserter waits after it
156          * has noticed a Sone modification before it starts the insert.
157          *
158          * @param insertionDelay
159          *            The insertion delay (in seconds)
160          */
161         public static void setInsertionDelay(int insertionDelay) {
162                 SoneInserter.insertionDelay.set(insertionDelay);
163         }
164
165         /**
166          * Returns the fingerprint of the last insert.
167          *
168          * @return The fingerprint of the last insert
169          */
170         public String getLastInsertFingerprint() {
171                 return soneModificationDetector.getOriginalFingerprint();
172         }
173
174         /**
175          * Sets the fingerprint of the last insert.
176          *
177          * @param lastInsertFingerprint
178          *            The fingerprint of the last insert
179          */
180         public void setLastInsertFingerprint(String lastInsertFingerprint) {
181                 soneModificationDetector.setFingerprint(lastInsertFingerprint);
182         }
183
184         /**
185          * Returns whether the Sone inserter has detected a modification of the
186          * Sone.
187          *
188          * @return {@code true} if the Sone has been modified, {@code false}
189          *         otherwise
190          */
191         public boolean isModified() {
192                 return soneModificationDetector.isModified();
193         }
194
195         //
196         // SERVICE METHODS
197         //
198
199         /**
200          * {@inheritDoc}
201          */
202         @Override
203         protected void serviceRun() {
204                 while (!shouldStop()) {
205                         try {
206                                 /* check every second. */
207                                 sleep(1000);
208
209                                 if (soneModificationDetector.isEligibleForInsert()) {
210                                         InsertInformation insertInformation = new InsertInformation(sone);
211                                         logger.log(Level.INFO, String.format("Inserting Sone “%s”…", sone.getName()));
212
213                                         boolean success = false;
214                                         try {
215                                                 sone.setStatus(SoneStatus.inserting);
216                                                 long insertTime = currentTimeMillis();
217                                                 eventBus.post(new SoneInsertingEvent(sone));
218                                                 FreenetURI finalUri = freenetInterface.insertDirectory(insertInformation.getInsertUri(), insertInformation.generateManifestEntries(), "index.html");
219                                                 eventBus.post(new SoneInsertedEvent(sone, currentTimeMillis() - insertTime));
220                                                 /* at this point we might already be stopped. */
221                                                 if (shouldStop()) {
222                                                         /* if so, bail out, don’t change anything. */
223                                                         break;
224                                                 }
225                                                 sone.setTime(insertTime);
226                                                 sone.setLatestEdition(finalUri.getEdition());
227                                                 core.touchConfiguration();
228                                                 success = true;
229                                                 logger.log(Level.INFO, String.format("Inserted Sone “%s” at %s.", sone.getName(), finalUri));
230                                         } catch (SoneException se1) {
231                                                 eventBus.post(new SoneInsertAbortedEvent(sone, se1));
232                                                 logger.log(Level.WARNING, String.format("Could not insert Sone “%s”!", sone.getName()), se1);
233                                         } finally {
234                                                 sone.setStatus(SoneStatus.idle);
235                                         }
236
237                                         /*
238                                          * reset modification counter if Sone has not been modified
239                                          * while it was inserted.
240                                          */
241                                         if (success) {
242                                                 synchronized (sone) {
243                                                         if (insertInformation.getFingerprint().equals(sone.getFingerprint())) {
244                                                                 logger.log(Level.FINE, String.format("Sone “%s” was not modified further, resetting counter…", sone));
245                                                                 soneModificationDetector.setFingerprint(insertInformation.getFingerprint());
246                                                                 core.touchConfiguration();
247                                                         }
248                                                 }
249                                         }
250                                 }
251                         } catch (Throwable t1) {
252                                 logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
253                         }
254                 }
255         }
256
257         static class SetInsertionDelay implements OptionWatcher<Integer> {
258
259                 @Override
260                 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
261                         setInsertionDelay(newValue);
262                 }
263
264         }
265
266         /**
267          * Container for information that are required to insert a Sone. This
268          * container merely exists to copy all relevant data without holding a lock
269          * on the {@link Sone} object for too long.
270          *
271          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
272          */
273         @VisibleForTesting
274         class InsertInformation {
275
276                 private final String fingerprint;
277
278                 /** All properties of the Sone, copied for thread safety. */
279                 private final Map<String, Object> soneProperties = new HashMap<String, Object>();
280
281                 /**
282                  * Creates a new insert information container.
283                  *
284                  * @param sone
285                  *            The sone to insert
286                  */
287                 public InsertInformation(Sone sone) {
288                         this.fingerprint = sone.getFingerprint();
289                         soneProperties.put("id", sone.getId());
290                         soneProperties.put("name", sone.getName());
291                         soneProperties.put("time", currentTimeMillis());
292                         soneProperties.put("requestUri", sone.getRequestUri());
293                         soneProperties.put("insertUri", sone.getInsertUri());
294                         soneProperties.put("profile", sone.getProfile());
295                         soneProperties.put("posts", Ordering.from(Post.TIME_COMPARATOR).sortedCopy(sone.getPosts()));
296                         soneProperties.put("replies", Ordering.from(Reply.TIME_COMPARATOR).reverse().sortedCopy(sone.getReplies()));
297                         soneProperties.put("likedPostIds", new HashSet<String>(sone.getLikedPostIds()));
298                         soneProperties.put("likedReplyIds", new HashSet<String>(sone.getLikedReplyIds()));
299                         soneProperties.put("albums", FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).filter(NOT_EMPTY).toList());
300                 }
301
302                 //
303                 // ACCESSORS
304                 //
305
306                 @VisibleForTesting
307                 String getFingerprint() {
308                         return fingerprint;
309                 }
310
311                 /**
312                  * Returns the insert URI of the Sone.
313                  *
314                  * @return The insert URI of the Sone
315                  */
316                 public FreenetURI getInsertUri() {
317                         return (FreenetURI) soneProperties.get("insertUri");
318                 }
319
320                 //
321                 // ACTIONS
322                 //
323
324                 /**
325                  * Generates all manifest entries required to insert this Sone.
326                  *
327                  * @return The manifest entries for the Sone insert
328                  */
329                 public HashMap<String, Object> generateManifestEntries() {
330                         HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
331
332                         /* first, create an index.html. */
333                         manifestEntries.put("index.html", createManifestElement("index.html", "text/html; charset=utf-8", "/templates/insert/index.html"));
334
335                         /* now, store the sone. */
336                         manifestEntries.put("sone.xml", createManifestElement("sone.xml", "text/xml; charset=utf-8", "/templates/insert/sone.xml"));
337
338                         return manifestEntries;
339                 }
340
341                 //
342                 // PRIVATE METHODS
343                 //
344
345                 /**
346                  * Creates a new manifest element.
347                  *
348                  * @param name
349                  *            The name of the file
350                  * @param contentType
351                  *            The content type of the file
352                  * @param templateName
353                  *            The name of the template to render
354                  * @return The manifest element
355                  */
356                 @SuppressWarnings("synthetic-access")
357                 private ManifestElement createManifestElement(String name, String contentType, String templateName) {
358                         InputStreamReader templateInputStreamReader = null;
359                         InputStream templateInputStream = null;
360                         Template template;
361                         try {
362                                 templateInputStream = getClass().getResourceAsStream(templateName);
363                                 templateInputStreamReader = new InputStreamReader(templateInputStream, utf8Charset);
364                                 template = TemplateParser.parse(templateInputStreamReader);
365                         } catch (TemplateException te1) {
366                                 logger.log(Level.SEVERE, String.format("Could not parse template “%s”!", templateName), te1);
367                                 return null;
368                         } finally {
369                                 Closer.close(templateInputStreamReader);
370                                 Closer.close(templateInputStream);
371                         }
372
373                         TemplateContext templateContext = templateContextFactory.createTemplateContext();
374                         templateContext.set("core", core);
375                         templateContext.set("currentSone", soneProperties);
376                         templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
377                         templateContext.set("version", SonePlugin.VERSION);
378                         StringWriter writer = new StringWriter();
379                         StringBucket bucket = null;
380                         try {
381                                 template.render(templateContext, writer);
382                                 bucket = new StringBucket(writer.toString(), utf8Charset);
383                                 return new ManifestElement(name, bucket, contentType, bucket.size());
384                         } catch (TemplateException te1) {
385                                 logger.log(Level.SEVERE, String.format("Could not render template “%s”!", templateName), te1);
386                                 return null;
387                         } finally {
388                                 Closer.close(writer);
389                                 if (bucket != null) {
390                                         bucket.free();
391                                 }
392                         }
393                 }
394
395         }
396
397 }