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