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