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