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