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