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