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