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