2 * Sone - SoneDownloader.java - Copyright © 2010 David Roden
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.
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.
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/>.
18 package net.pterodactylus.sone.core;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.util.HashSet;
24 import java.util.logging.Level;
25 import java.util.logging.Logger;
27 import net.pterodactylus.sone.data.Post;
28 import net.pterodactylus.sone.data.Profile;
29 import net.pterodactylus.sone.data.Reply;
30 import net.pterodactylus.sone.data.Sone;
31 import net.pterodactylus.util.io.Closer;
32 import net.pterodactylus.util.logging.Logging;
33 import net.pterodactylus.util.service.AbstractService;
34 import net.pterodactylus.util.xml.SimpleXML;
35 import net.pterodactylus.util.xml.XML;
37 import org.w3c.dom.Document;
39 import freenet.client.FetchResult;
40 import freenet.support.api.Bucket;
43 * The Sone downloader is responsible for download Sones as they are updated.
45 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
47 public class SoneDownloader extends AbstractService {
50 private static final Logger logger = Logging.getLogger(SoneDownloader.class);
53 private final Core core;
55 /** The Freenet interface. */
56 private final FreenetInterface freenetInterface;
58 /** The sones to update. */
59 private final Set<Sone> sones = new HashSet<Sone>();
62 * Creates a new Sone downloader.
66 * @param freenetInterface
67 * The Freenet interface
69 public SoneDownloader(Core core, FreenetInterface freenetInterface) {
70 super("Sone Downloader");
72 this.freenetInterface = freenetInterface;
80 * Adds the given Sone to the set of Sones that will be watched for updates.
85 public void addSone(Sone sone) {
86 if (sones.add(sone)) {
87 freenetInterface.registerUsk(sone, this);
92 * Removes the given Sone from the downloader.
95 * The Sone to stop watching
97 public void removeSone(Sone sone) {
98 if (sones.remove(sone)) {
99 freenetInterface.unregisterUsk(sone);
104 * Fetches the updated Sone. This method is a callback method for
105 * {@link FreenetInterface#registerUsk(Sone, SoneDownloader)}.
110 public void fetchSone(Sone sone) {
111 logger.log(Level.FINE, "Starting fetch for Sone “%s” from %s…", new Object[] { sone, sone.getRequestUri().setMetaString(new String[] { "sone.xml" }) });
112 FetchResult fetchResult = freenetInterface.fetchUri(sone.getRequestUri().setMetaString(new String[] { "sone.xml" }));
113 logger.log(Level.FINEST, "Got %d bytes back.", fetchResult.size());
114 Sone parsedSone = parseSone(sone, fetchResult);
115 if (parsedSone != null) {
116 core.addSone(parsedSone);
121 * Parses a Sone from a fetch result.
123 * @param originalSone
124 * The sone to parse, or {@code null} if the Sone is yet unknown
127 * @return The parsed Sone, or {@code null} if the Sone could not be parsed
129 public Sone parseSone(Sone originalSone, FetchResult fetchResult) {
130 logger.log(Level.FINEST, "Persing FetchResult (%d bytes, %s) for %s…", new Object[] { fetchResult.size(), fetchResult.getMimeType(), originalSone });
131 /* TODO - impose a size limit? */
132 InputStream xmlInputStream = null;
133 Bucket xmlBucket = null;
136 xmlBucket = fetchResult.asBucket();
137 xmlInputStream = xmlBucket.getInputStream();
138 Document document = XML.transformToDocument(xmlInputStream);
141 soneXml = SimpleXML.fromDocument(document);
142 } catch (NullPointerException npe1) {
143 /* for some reason, invalid XML can cause NPEs. */
144 logger.log(Level.WARNING, "XML for Sone " + originalSone + " can not be parsed!", npe1);
149 String soneId = soneXml.getValue("id", null);
150 if ((originalSone != null) && !originalSone.getId().equals(soneId)) {
151 /* TODO - mark Sone as bad. */
152 logger.log(Level.WARNING, "Downloaded ID for Sone %s (%s) does not match known ID (%s)!", new Object[] { originalSone, originalSone.getId(), soneId });
156 /* load Sone from core. */
159 sone = core.getSone(soneId);
162 String soneName = soneXml.getValue("name", null);
163 if (soneName == null) {
164 /* TODO - mark Sone as bad. */
165 logger.log(Level.WARNING, "Downloaded name for Sone %s was null!", new Object[] { sone });
169 SimpleXML profileXml = soneXml.getNode("profile");
170 if (profileXml == null) {
171 /* TODO - mark Sone as bad. */
172 logger.log(Level.WARNING, "Downloaded Sone %s has no profile!", new Object[] { sone });
177 String profileFirstName = profileXml.getValue("first-name", null);
178 String profileMiddleName = profileXml.getValue("middle-name", null);
179 String profileLastName = profileXml.getValue("last-name", null);
180 Profile profile = new Profile().setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName);
183 SimpleXML postsXml = soneXml.getNode("posts");
184 if (postsXml == null) {
185 /* TODO - mark Sone as bad. */
186 logger.log(Level.WARNING, "Downloaded Sone %s has no posts!", new Object[] { sone });
190 Set<Post> posts = new HashSet<Post>();
191 for (SimpleXML postXml : postsXml.getNodes("post")) {
192 String postId = postXml.getValue("id", null);
193 String postTime = postXml.getValue("time", null);
194 String postText = postXml.getValue("text", null);
195 if ((postId == null) || (postTime == null) || (postText == null)) {
196 /* TODO - mark Sone as bad. */
197 logger.log(Level.WARNING, "Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", new Object[] { sone, postId, postTime, postText });
201 posts.add(core.getPost(postId).setSone(sone).setTime(Long.parseLong(postTime)).setText(postText));
202 } catch (NumberFormatException nfe1) {
203 /* TODO - mark Sone as bad. */
204 logger.log(Level.WARNING, "Downloaded post for Sone %s with invalid time: %s", new Object[] { sone, postTime });
210 SimpleXML repliesXml = soneXml.getNode("replies");
211 if (repliesXml == null) {
212 /* TODO - mark Sone as bad. */
213 logger.log(Level.WARNING, "Downloaded Sone %s has no replies!", new Object[] { sone });
217 Set<Reply> replies = new HashSet<Reply>();
218 for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
219 String replyId = replyXml.getValue("id", null);
220 String replyPostId = replyXml.getValue("post-id", null);
221 String replyTime = replyXml.getValue("time", null);
222 String replyText = replyXml.getValue("text", null);
223 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
224 /* TODO - mark Sone as bad. */
225 logger.log(Level.WARNING, "Downloaded reply for Sone %s with missing data! ID: %s, Post: %s, Time: %s, Text: %s", new Object[] { sone, replyId, replyPostId, replyTime, replyText });
229 replies.add(core.getReply(replyId).setSone(sone).setPost(core.getPost(replyPostId)).setTime(Long.parseLong(replyTime)).setText(replyText));
230 } catch (NumberFormatException nfe1) {
231 /* TODO - mark Sone as bad. */
232 logger.log(Level.WARNING, "Downloaded reply for Sone %s with invalid time: %s", new Object[] { sone, replyTime });
237 /* okay, apparently everything was parsed correctly. Now import. */
238 /* atomic setter operation on the Sone. */
239 synchronized (sone) {
240 sone.setProfile(profile);
241 sone.setPosts(posts);
242 sone.setReplies(replies);
243 sone.setModificationCounter(0);
245 } catch (IOException ioe1) {
246 logger.log(Level.WARNING, "Could not read XML file from " + originalSone + "!", ioe1);
249 if (xmlBucket != null) {
252 Closer.close(xmlInputStream);
265 protected void serviceStop() {
266 for (Sone sone : sones) {
267 freenetInterface.unregisterUsk(sone);