XML parsing is not thread-safe, synchronize on Sone downloader.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / SoneDownloader.java
1 /*
2  * Sone - SoneDownloader.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.IOException;
21 import java.io.InputStream;
22 import java.net.MalformedURLException;
23 import java.util.HashSet;
24 import java.util.Set;
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.Post;
30 import net.pterodactylus.sone.data.Profile;
31 import net.pterodactylus.sone.data.Reply;
32 import net.pterodactylus.sone.data.Sone;
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.xml.SimpleXML;
37 import net.pterodactylus.util.xml.XML;
38
39 import org.w3c.dom.Document;
40
41 import freenet.client.FetchResult;
42 import freenet.keys.FreenetURI;
43 import freenet.support.api.Bucket;
44
45 /**
46  * The Sone downloader is responsible for download Sones as they are updated.
47  *
48  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
49  */
50 public class SoneDownloader extends AbstractService {
51
52         /** The logger. */
53         private static final Logger logger = Logging.getLogger(SoneDownloader.class);
54
55         /** The core. */
56         private final Core core;
57
58         /** The Freenet interface. */
59         private final FreenetInterface freenetInterface;
60
61         /** The sones to update. */
62         private final Set<Sone> sones = new HashSet<Sone>();
63
64         /**
65          * Creates a new Sone downloader.
66          *
67          * @param core
68          *            The core
69          * @param freenetInterface
70          *            The Freenet interface
71          */
72         public SoneDownloader(Core core, FreenetInterface freenetInterface) {
73                 super("Sone Downloader", false);
74                 this.core = core;
75                 this.freenetInterface = freenetInterface;
76         }
77
78         //
79         // ACTIONS
80         //
81
82         /**
83          * Adds the given Sone to the set of Sones that will be watched for updates.
84          *
85          * @param sone
86          *            The Sone to add
87          */
88         public void addSone(Sone sone) {
89                 if (sones.add(sone)) {
90                         freenetInterface.registerUsk(sone, this);
91                 }
92         }
93
94         /**
95          * Removes the given Sone from the downloader.
96          *
97          * @param sone
98          *            The Sone to stop watching
99          */
100         public void removeSone(Sone sone) {
101                 if (sones.remove(sone)) {
102                         freenetInterface.unregisterUsk(sone);
103                 }
104         }
105
106         /**
107          * Fetches the updated Sone. This method is a callback method for
108          * {@link FreenetInterface#registerUsk(Sone, SoneDownloader)}.
109          *
110          * @param sone
111          *            The Sone to fetch
112          */
113         public void fetchSone(Sone sone) {
114                 logger.log(Level.FINE, "Starting fetch for Sone “%s” from %s…", new Object[] { sone, sone.getRequestUri().setMetaString(new String[] { "sone.xml" }) });
115                 FreenetURI requestUri = sone.getRequestUri().setMetaString(new String[] { "sone.xml" });
116                 core.setSoneStatus(sone, SoneStatus.downloading);
117                 try {
118                         FetchResult fetchResult = freenetInterface.fetchUri(requestUri);
119                         if (fetchResult == null) {
120                                 /* TODO - mark Sone as bad. */
121                                 return;
122                         }
123                         logger.log(Level.FINEST, "Got %d bytes back.", fetchResult.size());
124                         Sone parsedSone = parseSone(sone, fetchResult, requestUri);
125                         if (parsedSone != null) {
126                                 core.addSone(parsedSone);
127                         }
128                 } finally {
129                         core.setSoneStatus(sone, (sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
130                 }
131         }
132
133         /**
134          * Parses a Sone from a fetch result.
135          *
136          * @param originalSone
137          *            The sone to parse, or {@code null} if the Sone is yet unknown
138          * @param fetchResult
139          *            The fetch result
140          * @param requestUri
141          *            The requested URI
142          * @return The parsed Sone, or {@code null} if the Sone could not be parsed
143          */
144         public Sone parseSone(Sone originalSone, FetchResult fetchResult, FreenetURI requestUri) {
145                 logger.log(Level.FINEST, "Persing FetchResult (%d bytes, %s) for %s…", new Object[] { fetchResult.size(), fetchResult.getMimeType(), originalSone });
146                 /* TODO - impose a size limit? */
147                 InputStream xmlInputStream = null;
148                 Bucket xmlBucket = null;
149                 Sone sone;
150                 try {
151                         xmlBucket = fetchResult.asBucket();
152                         xmlInputStream = xmlBucket.getInputStream();
153                         Document document;
154                         /* XML parsing is not thread-safe. */
155                         synchronized (this) {
156                                 document = XML.transformToDocument(xmlInputStream);
157                         }
158                         if (document == null) {
159                                 /* TODO - mark Sone as bad. */
160                                 logger.log(Level.WARNING, "Could not parse XML for Sone %s at %s!", new Object[] { originalSone, requestUri });
161                                 return null;
162                         }
163                         SimpleXML soneXml;
164                         try {
165                                 soneXml = SimpleXML.fromDocument(document);
166                         } catch (NullPointerException npe1) {
167                                 /* for some reason, invalid XML can cause NPEs. */
168                                 logger.log(Level.WARNING, "XML for Sone " + originalSone + " can not be parsed!", npe1);
169                                 return null;
170                         }
171
172                         /* check ID. */
173                         String soneId = soneXml.getValue("id", null);
174                         if ((originalSone != null) && !originalSone.getId().equals(soneId)) {
175                                 /* TODO - mark Sone as bad. */
176                                 logger.log(Level.WARNING, "Downloaded ID for Sone %s (%s) does not match known ID (%s)!", new Object[] { originalSone, originalSone.getId(), soneId });
177                                 return null;
178                         }
179
180                         /* load Sone from core. */
181                         sone = originalSone;
182                         if (sone == null) {
183                                 sone = core.getSone(soneId).setRequestUri(requestUri.setMetaString(new String[] {}));
184                         }
185
186                         String soneName = soneXml.getValue("name", null);
187                         if (soneName == null) {
188                                 /* TODO - mark Sone as bad. */
189                                 logger.log(Level.WARNING, "Downloaded name for Sone %s was null!", new Object[] { sone });
190                                 return null;
191                         }
192                         sone.setName(soneName);
193
194                         String soneTime = soneXml.getValue("time", null);
195                         if (soneTime == null) {
196                                 /* TODO - mark Sone as bad. */
197                                 logger.log(Level.WARNING, "Downloaded time for Sone %s was null!", new Object[] { sone });
198                                 return null;
199                         }
200                         try {
201                                 sone.setTime(Long.parseLong(soneTime));
202                         } catch (NumberFormatException nfe1) {
203                                 /* TODO - mark Sone as bad. */
204                                 logger.log(Level.WARNING, "Downloaded Sone %s with invalid time: %s", new Object[] { sone, soneTime });
205                                 return null;
206                         }
207
208                         SimpleXML profileXml = soneXml.getNode("profile");
209                         if (profileXml == null) {
210                                 /* TODO - mark Sone as bad. */
211                                 logger.log(Level.WARNING, "Downloaded Sone %s has no profile!", new Object[] { sone });
212                                 return null;
213                         }
214
215                         /* parse profile. */
216                         String profileFirstName = profileXml.getValue("first-name", null);
217                         String profileMiddleName = profileXml.getValue("middle-name", null);
218                         String profileLastName = profileXml.getValue("last-name", null);
219                         Profile profile = new Profile().setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName);
220
221                         /* parse posts. */
222                         SimpleXML postsXml = soneXml.getNode("posts");
223                         if (postsXml == null) {
224                                 /* TODO - mark Sone as bad. */
225                                 logger.log(Level.WARNING, "Downloaded Sone %s has no posts!", new Object[] { sone });
226                                 return null;
227                         }
228
229                         Set<Post> posts = new HashSet<Post>();
230                         for (SimpleXML postXml : postsXml.getNodes("post")) {
231                                 String postId = postXml.getValue("id", null);
232                                 String postTime = postXml.getValue("time", null);
233                                 String postText = postXml.getValue("text", null);
234                                 if ((postId == null) || (postTime == null) || (postText == null)) {
235                                         /* TODO - mark Sone as bad. */
236                                         logger.log(Level.WARNING, "Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", new Object[] { sone, postId, postTime, postText });
237                                         return null;
238                                 }
239                                 try {
240                                         posts.add(core.getPost(postId).setSone(sone).setTime(Long.parseLong(postTime)).setText(postText));
241                                 } catch (NumberFormatException nfe1) {
242                                         /* TODO - mark Sone as bad. */
243                                         logger.log(Level.WARNING, "Downloaded post for Sone %s with invalid time: %s", new Object[] { sone, postTime });
244                                         return null;
245                                 }
246                         }
247
248                         /* parse replies. */
249                         SimpleXML repliesXml = soneXml.getNode("replies");
250                         if (repliesXml == null) {
251                                 /* TODO - mark Sone as bad. */
252                                 logger.log(Level.WARNING, "Downloaded Sone %s has no replies!", new Object[] { sone });
253                                 return null;
254                         }
255
256                         Set<Reply> replies = new HashSet<Reply>();
257                         for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
258                                 String replyId = replyXml.getValue("id", null);
259                                 String replyPostId = replyXml.getValue("post-id", null);
260                                 String replyTime = replyXml.getValue("time", null);
261                                 String replyText = replyXml.getValue("text", null);
262                                 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
263                                         /* TODO - mark Sone as bad. */
264                                         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 });
265                                         return null;
266                                 }
267                                 try {
268                                         replies.add(core.getReply(replyId).setSone(sone).setPost(core.getPost(replyPostId)).setTime(Long.parseLong(replyTime)).setText(replyText));
269                                 } catch (NumberFormatException nfe1) {
270                                         /* TODO - mark Sone as bad. */
271                                         logger.log(Level.WARNING, "Downloaded reply for Sone %s with invalid time: %s", new Object[] { sone, replyTime });
272                                         return null;
273                                 }
274                         }
275
276                         /* parse friends. */
277                         SimpleXML friendsXml = soneXml.getNode("friends");
278                         if (friendsXml == null) {
279                                 /* TODO - mark Sone as bad. */
280                                 logger.log(Level.WARNING, "Downloaded Sone %s has no friends!", new Object[] { sone });
281                                 return null;
282                         }
283
284                         Set<Sone> friends = new HashSet<Sone>();
285                         for (SimpleXML friendXml : friendsXml.getNodes("friend")) {
286                                 String friendId = friendXml.getValue("sone-id", null);
287                                 String friendKey = friendXml.getValue("sone-key", null);
288                                 String friendName = friendXml.getValue("sone-name", null);
289                                 if ((friendId == null) || (friendKey == null) || (friendName == null)) {
290                                         /* TODO - mark Sone as bad. */
291                                         logger.log(Level.WARNING, "Downloaded friend for Sone %s with missing data! ID: %s, Key: %s, Name: %s", new Object[] { sone, friendId, friendKey, friendName });
292                                         return null;
293                                 }
294                                 try {
295                                         friends.add(core.getSone(friendId).setRequestUri(new FreenetURI(friendKey)).setName(friendName));
296                                 } catch (MalformedURLException mue1) {
297                                         /* TODO - mark Sone as bad. */
298                                         logger.log(Level.WARNING, "Downloaded friend for Sone %s with invalid key: %s", new Object[] { sone, friendKey });
299                                         return null;
300                                 }
301                         }
302
303                         Set<Sone> knownSones = new HashSet<Sone>();
304                         for (SimpleXML friendXml : friendsXml.getNodes("friend")) {
305                                 String knownSoneId = friendXml.getValue("sone-id", null);
306                                 String knownSoneKey = friendXml.getValue("sone-key", null);
307                                 String knownSoneName = friendXml.getValue("sone-name", null);
308                                 if ((knownSoneId == null) || (knownSoneKey == null) || (knownSoneName == null)) {
309                                         /* TODO - mark Sone as bad. */
310                                         logger.log(Level.WARNING, "Downloaded known Sone for Sone %s with missing data! ID: %s, Key: %s, Name: %s", new Object[] { sone, knownSoneId, knownSoneKey, knownSoneName });
311                                         return null;
312                                 }
313                                 try {
314                                         knownSones.add(core.getSone(knownSoneId).setRequestUri(new FreenetURI(knownSoneKey)).setName(knownSoneName));
315                                 } catch (MalformedURLException mue1) {
316                                         /* TODO - mark Sone as bad. */
317                                         logger.log(Level.WARNING, "Downloaded known Sone for Sone %s with invalid key: %s", new Object[] { sone, knownSoneKey });
318                                         return null;
319                                 }
320                         }
321
322                         /* okay, apparently everything was parsed correctly. Now import. */
323                         /* atomic setter operation on the Sone. */
324                         synchronized (sone) {
325                                 sone.setProfile(profile);
326                                 sone.setPosts(posts);
327                                 sone.setReplies(replies);
328                                 sone.setFriends(friends);
329                                 sone.setModificationCounter(0);
330                         }
331
332                         /* add all known Sones to core for downloading. */
333                         for (Sone knownSone : knownSones) {
334                                 core.addSone(knownSone);
335                         }
336
337                 } catch (IOException ioe1) {
338                         logger.log(Level.WARNING, "Could not read XML file from " + originalSone + "!", ioe1);
339                         return null;
340                 } finally {
341                         if (xmlBucket != null) {
342                                 xmlBucket.free();
343                         }
344                         Closer.close(xmlInputStream);
345                 }
346                 return sone;
347         }
348
349         //
350         // SERVICE METHODS
351         //
352
353         /**
354          * {@inheritDoc}
355          */
356         @Override
357         protected void serviceStop() {
358                 for (Sone sone : sones) {
359                         freenetInterface.unregisterUsk(sone);
360                 }
361         }
362
363 }