Implement Sone inserting.
[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 Freenet interface. */
55         private final FreenetInterface freenetInterface;
56
57         /** The Sone to insert. */
58         private final Sone sone;
59
60         /**
61          * Creates a new Sone inserter.
62          *
63          * @param freenetInterface
64          *            The freenet interface
65          * @param sone
66          *            The Sone to insert
67          */
68         public SoneInserter(FreenetInterface freenetInterface, Sone sone) {
69                 super("Sone Inserter for “" + sone.getName() + "”");
70                 this.freenetInterface = freenetInterface;
71                 this.sone = sone;
72         }
73
74         //
75         // SERVICE METHODS
76         //
77
78         /**
79          * {@inheritDoc}
80          */
81         @Override
82         protected void serviceRun() {
83                 long modificationCounter = 0;
84                 while (!shouldStop()) {
85                         InsertInformation insertInformation = null;
86                         synchronized (sone) {
87                                 modificationCounter = sone.getModificationCounter();
88                                 if (modificationCounter > 0) {
89                                         insertInformation = new InsertInformation(sone.getRequestUri(), sone.getInsertUri());
90                                 }
91                         }
92                         if (insertInformation != null) {
93                                 logger.log(Level.INFO, "Inserting Sone “%s”…", new Object[] { sone.getName() });
94
95                                 boolean success = false;
96                                 try {
97                                         FreenetURI finalUri = freenetInterface.insertDirectory(insertInformation.getInsertUri().setKeyType("USK").setDocName("Sone-" + sone.getName()).setSuggestedEdition(0), insertInformation.generateManifestEntries(), "index.html");
98                                         success = true;
99                                         logger.log(Level.INFO, "Inserted Sone “%s” at %s.", new Object[] { sone.getName(), finalUri });
100                                 } catch (SoneException se1) {
101                                         logger.log(Level.WARNING, "Could not insert Sone “" + sone.getName() + "”!", se1);
102                                 }
103
104                                 /*
105                                  * reset modification counter if Sone has not been modified
106                                  * while it was inserted.
107                                  */
108                                 if (success) {
109                                         synchronized (sone) {
110                                                 if (sone.getModificationCounter() == modificationCounter) {
111                                                         sone.setModificationCounter(0);
112                                                 }
113                                         }
114                                 }
115                         }
116                         logger.log(Level.FINEST, "Waiting 60 seconds before checking Sone “" + sone.getName() + "” again.");
117                         sleep(60 * 1000);
118                 }
119         }
120
121         /**
122          * Container for information that are required to insert a Sone. This
123          * container merely exists to copy all relevant data without holding a lock
124          * on the {@link Sone} object for too long.
125          *
126          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
127          */
128         private class InsertInformation {
129
130                 /** The request URI of the Sone. */
131                 private final FreenetURI requestUri;
132
133                 /** The insert URI of the Sone. */
134                 private final FreenetURI insertUri;
135
136                 /**
137                  * Creates a new insert information container.
138                  *
139                  * @param requestUri
140                  *            The request URI of the Sone
141                  * @param insertUri
142                  *            The insert URI of the Sone
143                  */
144                 public InsertInformation(FreenetURI requestUri, FreenetURI insertUri) {
145                         this.requestUri = requestUri;
146                         this.insertUri = insertUri;
147                 }
148
149                 //
150                 // ACCESSORS
151                 //
152
153                 /**
154                  * Returns the request URI of the Sone.
155                  *
156                  * @return The request URI of the Sone
157                  */
158                 @SuppressWarnings("unused")
159                 public FreenetURI getRequestUri() {
160                         return requestUri;
161                 }
162
163                 /**
164                  * Returns the insert URI of the Sone.
165                  *
166                  * @return The insert URI of the Sone
167                  */
168                 public FreenetURI getInsertUri() {
169                         return insertUri;
170                 }
171
172                 //
173                 // ACTIONS
174                 //
175
176                 /**
177                  * Generates all manifest entries required to insert this Sone.
178                  *
179                  * @return The manifest entries for the Sone insert
180                  */
181                 @SuppressWarnings("synthetic-access")
182                 public HashMap<String, Object> generateManifestEntries() {
183                         HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
184
185                         Charset utf8Charset = Charset.forName("UTF-8");
186
187                         /* first, create an index.html. */
188                         Template indexTemplate = templateFactory.createTemplate(new InputStreamReader(getClass().getResourceAsStream("/templates/insert/index.html"), utf8Charset));
189                         indexTemplate.set("currentSone", sone);
190                         StringWriter indexWriter = new StringWriter();
191                         indexTemplate.render(indexWriter);
192                         StringBucket indexBucket = new StringBucket(indexWriter.toString(), utf8Charset);
193                         ManifestElement indexManifestElement = new ManifestElement("index.html", indexBucket, "text/html; charset=utf-8", indexBucket.size());
194                         manifestEntries.put("index.html", indexManifestElement);
195
196                         return manifestEntries;
197                 }
198
199                 //
200                 // PRIVATE METHODS
201                 //
202
203         }
204
205 }