Make SoneInserter thread-safe.
[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 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() + "”");
91                 this.core = core;
92                 this.freenetInterface = freenetInterface;
93                 this.sone = sone;
94         }
95
96         //
97         // SERVICE METHODS
98         //
99
100         /**
101          * {@inheritDoc}
102          */
103         @Override
104         protected void serviceRun() {
105                 long modificationCounter = 0;
106                 boolean restartNow = true;
107                 while (!shouldStop()) {
108                         if (!restartNow) {
109                                 logger.log(Level.FINEST, "Waiting 60 seconds before checking Sone “" + sone.getName() + "”.");
110                                 sleep(60 * 1000);
111                         }
112                         restartNow = false;
113                         InsertInformation insertInformation = null;
114                         synchronized (sone) {
115                                 modificationCounter = sone.getModificationCounter();
116                                 if (modificationCounter > 0) {
117                                         sone.setTime(System.currentTimeMillis());
118                                         insertInformation = new InsertInformation(sone);
119                                 }
120                         }
121                         if (insertInformation != null) {
122                                 logger.log(Level.INFO, "Inserting Sone “%s”…", new Object[] { sone.getName() });
123
124                                 boolean success = false;
125                                 try {
126                                         core.setSoneStatus(sone, SoneStatus.inserting);
127                                         FreenetURI finalUri = freenetInterface.insertDirectory(insertInformation.getInsertUri().setKeyType("USK").setDocName("Sone-" + sone.getName()).setSuggestedEdition(0), insertInformation.generateManifestEntries(), "index.html");
128                                         sone.updateUris(finalUri);
129                                         success = true;
130                                         logger.log(Level.INFO, "Inserted Sone “%s” at %s.", new Object[] { sone.getName(), finalUri });
131                                 } catch (SoneException se1) {
132                                         logger.log(Level.WARNING, "Could not insert Sone “" + sone.getName() + "”!", se1);
133                                 } finally {
134                                         core.setSoneStatus(sone, SoneStatus.idle);
135                                 }
136
137                                 /*
138                                  * reset modification counter if Sone has not been modified
139                                  * while it was inserted.
140                                  */
141                                 if (success) {
142                                         synchronized (sone) {
143                                                 if (sone.getModificationCounter() == modificationCounter) {
144                                                         logger.log(Level.FINE, "Sone “%s” was not modified further, resetting counter…", new Object[] { sone });
145                                                         sone.setModificationCounter(0);
146                                                 } else {
147                                                         logger.log(Level.FINE, "Sone “%s” was modified since the insert started, starting another insert…", new Object[] { sone });
148                                                         restartNow = true;
149                                                 }
150                                         }
151                                 }
152                         }
153                 }
154         }
155
156         /**
157          * Container for information that are required to insert a Sone. This
158          * container merely exists to copy all relevant data without holding a lock
159          * on the {@link Sone} object for too long.
160          *
161          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
162          */
163         private class InsertInformation {
164
165                 /** All properties of the Sone, copied for thread safety. */
166                 private final Map<String, Object> soneProperties = new HashMap<String, Object>();
167
168                 /**
169                  * Creates a new insert information container.
170                  *
171                  * @param sone
172                  *            The sone to insert
173                  */
174                 public InsertInformation(Sone sone) {
175                         soneProperties.put("id", sone.getId());
176                         soneProperties.put("name", sone.getName());
177                         soneProperties.put("time", sone.getTime());
178                         soneProperties.put("requestUri", sone.getRequestUri());
179                         soneProperties.put("insertUri", sone.getInsertUri());
180                         soneProperties.put("profile", sone.getProfile());
181                         soneProperties.put("posts", new ArrayList<Post>(sone.getPosts()));
182                         soneProperties.put("replies", new HashSet<Reply>(sone.getReplies()));
183                         soneProperties.put("friends", new HashSet<Sone>(sone.getFriends()));
184                         soneProperties.put("blockedSoneIds", new HashSet<String>(sone.getBlockedSoneIds()));
185                 }
186
187                 //
188                 // ACCESSORS
189                 //
190
191                 /**
192                  * Returns the insert URI of the Sone.
193                  *
194                  * @return The insert URI of the Sone
195                  */
196                 public FreenetURI getInsertUri() {
197                         return (FreenetURI) soneProperties.get("insertUri");
198                 }
199
200                 //
201                 // ACTIONS
202                 //
203
204                 /**
205                  * Generates all manifest entries required to insert this Sone.
206                  *
207                  * @return The manifest entries for the Sone insert
208                  */
209                 public HashMap<String, Object> generateManifestEntries() {
210                         HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
211
212                         /* first, create an index.html. */
213                         manifestEntries.put("index.html", createManifestElement("index.html", "text/html; charset=utf-8", "/templates/insert/index.html"));
214
215                         /* now, store the sone. */
216                         manifestEntries.put("sone.xml", createManifestElement("sone.xml", "text/xml; charset=utf-8", "/templates/insert/sone.xml"));
217
218                         return manifestEntries;
219                 }
220
221                 //
222                 // PRIVATE METHODS
223                 //
224
225                 /**
226                  * Creates a new manifest element.
227                  *
228                  * @param name
229                  *            The name of the file
230                  * @param contentType
231                  *            The content type of the file
232                  * @param templateName
233                  *            The name of the template to render
234                  * @return The manifest element
235                  */
236                 @SuppressWarnings("synthetic-access")
237                 private ManifestElement createManifestElement(String name, String contentType, String templateName) {
238                         InputStreamReader templateInputStreamReader;
239                         Template template = templateFactory.createTemplate(templateInputStreamReader = new InputStreamReader(getClass().getResourceAsStream(templateName), utf8Charset));
240                         try {
241                                 template.parse();
242                         } catch (TemplateException te1) {
243                                 logger.log(Level.SEVERE, "Could not parse template “" + templateName + "”!", te1);
244                                 return null;
245                         } finally {
246                                 Closer.close(templateInputStreamReader);
247                         }
248                         Collection<Sone> knownSones = Filters.filteredCollection(core.getKnownSones(), new Filter<Sone>() {
249
250                                 /**
251                                  * {@inheritDoc}
252                                  */
253                                 @Override
254                                 public boolean filterObject(Sone object) {
255                                         return !soneProperties.containsKey(object.getId()) && !object.getId().equals(soneProperties.get("id"));
256                                 }
257                         });
258
259                         template.set("currentSone", soneProperties);
260                         template.set("knownSones", knownSones);
261                         StringWriter writer = new StringWriter();
262                         StringBucket bucket = null;
263                         try {
264                                 template.render(writer);
265                                 bucket = new StringBucket(writer.toString(), utf8Charset);
266                                 return new ManifestElement(name, bucket, contentType, bucket.size());
267                         } catch (TemplateException te1) {
268                                 logger.log(Level.SEVERE, "Could not render template “" + templateName + "”!", te1);
269                                 return null;
270                         } finally {
271                                 Closer.close(writer);
272                                 if (bucket != null) {
273                                         bucket.free();
274                                 }
275                         }
276                 }
277
278         }
279
280 }