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.keys.FreenetURI;
41 import freenet.support.api.Bucket;
44 * The Sone downloader is responsible for download Sones as they are updated.
46 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
48 public class SoneDownloader extends AbstractService {
51 private static final Logger logger = Logging.getLogger(SoneDownloader.class);
54 private final Core core;
56 /** The Freenet interface. */
57 private final FreenetInterface freenetInterface;
59 /** The sones to update. */
60 private final Set<Sone> sones = new HashSet<Sone>();
63 * Creates a new Sone downloader.
67 * @param freenetInterface
68 * The Freenet interface
70 public SoneDownloader(Core core, FreenetInterface freenetInterface) {
71 super("Sone Downloader");
73 this.freenetInterface = freenetInterface;
81 * Adds the given Sone to the set of Sones that will be watched for updates.
86 public void addSone(Sone sone) {
87 if (sones.add(sone)) {
88 freenetInterface.registerUsk(sone, this);
93 * Removes the given Sone from the downloader.
96 * The Sone to stop watching
98 public void removeSone(Sone sone) {
99 if (sones.remove(sone)) {
100 freenetInterface.unregisterUsk(sone);
105 * Fetches the updated Sone. This method is a callback method for
106 * {@link FreenetInterface#registerUsk(Sone, SoneDownloader)}.
111 public void fetchSone(Sone sone) {
112 logger.log(Level.FINE, "Starting fetch for Sone “%s” from %s…", new Object[] { sone, sone.getRequestUri().setMetaString(new String[] { "sone.xml" }) });
113 FreenetURI requestUri = sone.getRequestUri().setMetaString(new String[] { "sone.xml" });
114 FetchResult fetchResult = freenetInterface.fetchUri(requestUri);
115 logger.log(Level.FINEST, "Got %d bytes back.", fetchResult.size());
116 Sone parsedSone = parseSone(sone, fetchResult, requestUri);
117 if (parsedSone != null) {
118 core.addSone(parsedSone);
123 * Parses a Sone from a fetch result.
125 * @param originalSone
126 * The sone to parse, or {@code null} if the Sone is yet unknown
131 * @return The parsed Sone, or {@code null} if the Sone could not be parsed
133 public Sone parseSone(Sone originalSone, FetchResult fetchResult, FreenetURI requestUri) {
134 logger.log(Level.FINEST, "Persing FetchResult (%d bytes, %s) for %s…", new Object[] { fetchResult.size(), fetchResult.getMimeType(), originalSone });
135 /* TODO - impose a size limit? */
136 InputStream xmlInputStream = null;
137 Bucket xmlBucket = null;
140 xmlBucket = fetchResult.asBucket();
141 xmlInputStream = xmlBucket.getInputStream();
142 Document document = XML.transformToDocument(xmlInputStream);
145 soneXml = SimpleXML.fromDocument(document);
146 } catch (NullPointerException npe1) {
147 /* for some reason, invalid XML can cause NPEs. */
148 logger.log(Level.WARNING, "XML for Sone " + originalSone + " can not be parsed!", npe1);
153 String soneId = soneXml.getValue("id", null);
154 if ((originalSone != null) && !originalSone.getId().equals(soneId)) {
155 /* TODO - mark Sone as bad. */
156 logger.log(Level.WARNING, "Downloaded ID for Sone %s (%s) does not match known ID (%s)!", new Object[] { originalSone, originalSone.getId(), soneId });
160 /* load Sone from core. */
163 sone = core.getSone(soneId).setRequestUri(requestUri.setMetaString(new String[] {}));
166 String soneName = soneXml.getValue("name", null);
167 if (soneName == null) {
168 /* TODO - mark Sone as bad. */
169 logger.log(Level.WARNING, "Downloaded name for Sone %s was null!", new Object[] { sone });
172 sone.setName(soneName);
174 SimpleXML profileXml = soneXml.getNode("profile");
175 if (profileXml == null) {
176 /* TODO - mark Sone as bad. */
177 logger.log(Level.WARNING, "Downloaded Sone %s has no profile!", new Object[] { sone });
182 String profileFirstName = profileXml.getValue("first-name", null);
183 String profileMiddleName = profileXml.getValue("middle-name", null);
184 String profileLastName = profileXml.getValue("last-name", null);
185 Profile profile = new Profile().setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName);
188 SimpleXML postsXml = soneXml.getNode("posts");
189 if (postsXml == null) {
190 /* TODO - mark Sone as bad. */
191 logger.log(Level.WARNING, "Downloaded Sone %s has no posts!", new Object[] { sone });
195 Set<Post> posts = new HashSet<Post>();
196 for (SimpleXML postXml : postsXml.getNodes("post")) {
197 String postId = postXml.getValue("id", null);
198 String postTime = postXml.getValue("time", null);
199 String postText = postXml.getValue("text", null);
200 if ((postId == null) || (postTime == null) || (postText == null)) {
201 /* TODO - mark Sone as bad. */
202 logger.log(Level.WARNING, "Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", new Object[] { sone, postId, postTime, postText });
206 posts.add(core.getPost(postId).setSone(sone).setTime(Long.parseLong(postTime)).setText(postText));
207 } catch (NumberFormatException nfe1) {
208 /* TODO - mark Sone as bad. */
209 logger.log(Level.WARNING, "Downloaded post for Sone %s with invalid time: %s", new Object[] { sone, postTime });
215 SimpleXML repliesXml = soneXml.getNode("replies");
216 if (repliesXml == null) {
217 /* TODO - mark Sone as bad. */
218 logger.log(Level.WARNING, "Downloaded Sone %s has no replies!", new Object[] { sone });
222 Set<Reply> replies = new HashSet<Reply>();
223 for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
224 String replyId = replyXml.getValue("id", null);
225 String replyPostId = replyXml.getValue("post-id", null);
226 String replyTime = replyXml.getValue("time", null);
227 String replyText = replyXml.getValue("text", null);
228 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
229 /* TODO - mark Sone as bad. */
230 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 });
234 replies.add(core.getReply(replyId).setSone(sone).setPost(core.getPost(replyPostId)).setTime(Long.parseLong(replyTime)).setText(replyText));
235 } catch (NumberFormatException nfe1) {
236 /* TODO - mark Sone as bad. */
237 logger.log(Level.WARNING, "Downloaded reply for Sone %s with invalid time: %s", new Object[] { sone, replyTime });
242 /* okay, apparently everything was parsed correctly. Now import. */
243 /* atomic setter operation on the Sone. */
244 synchronized (sone) {
245 sone.setProfile(profile);
246 sone.setPosts(posts);
247 sone.setReplies(replies);
248 sone.setModificationCounter(0);
250 } catch (IOException ioe1) {
251 logger.log(Level.WARNING, "Could not read XML file from " + originalSone + "!", ioe1);
254 if (xmlBucket != null) {
257 Closer.close(xmlInputStream);
270 protected void serviceStop() {
271 for (Sone sone : sones) {
272 freenetInterface.unregisterUsk(sone);