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