Don’t crash on parsing incorrect XML.
[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.util.HashSet;
23 import java.util.Set;
24 import java.util.logging.Level;
25 import java.util.logging.Logger;
26
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;
36
37 import org.w3c.dom.Document;
38
39 import freenet.client.FetchResult;
40 import freenet.support.api.Bucket;
41
42 /**
43  * The Sone downloader is responsible for download Sones as they are updated.
44  *
45  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
46  */
47 public class SoneDownloader extends AbstractService {
48
49         /** The logger. */
50         private static final Logger logger = Logging.getLogger(SoneDownloader.class);
51
52         /** The core. */
53         private final Core core;
54
55         /** The Freenet interface. */
56         private final FreenetInterface freenetInterface;
57
58         /** The sones to update. */
59         private final Set<Sone> sones = new HashSet<Sone>();
60
61         /**
62          * Creates a new Sone downloader.
63          *
64          * @param core
65          *            The core
66          * @param freenetInterface
67          *            The Freenet interface
68          */
69         public SoneDownloader(Core core, FreenetInterface freenetInterface) {
70                 super("Sone Downloader");
71                 this.core = core;
72                 this.freenetInterface = freenetInterface;
73         }
74
75         //
76         // ACTIONS
77         //
78
79         /**
80          * Adds the given Sone to the set of Sones that will be watched for updates.
81          *
82          * @param sone
83          *            The Sone to add
84          */
85         public void addSone(Sone sone) {
86                 if (sones.add(sone)) {
87                         freenetInterface.registerUsk(sone, this);
88                 }
89         }
90
91         /**
92          * Fetches the updated Sone. This method is a callback method for
93          * {@link FreenetInterface#registerUsk(Sone, SoneDownloader)}.
94          *
95          * @param sone
96          *            The Sone to fetch
97          */
98         public void fetchSone(Sone sone) {
99                 logger.log(Level.FINE, "Starting fetch for Sone “%s” from %s…", new Object[] { sone, sone.getRequestUri().setMetaString(new String[] { "sone.xml" }) });
100                 FetchResult fetchResult = freenetInterface.fetchUri(sone.getRequestUri().setMetaString(new String[] { "sone.xml" }));
101                 logger.log(Level.FINEST, "Got %d bytes back.", fetchResult.size());
102                 updateSoneFromXml(sone, fetchResult);
103         }
104
105         //
106         // SERVICE METHODS
107         //
108
109         /**
110          * {@inheritDoc}
111          */
112         @Override
113         protected void serviceStop() {
114                 for (Sone sone : sones) {
115                         freenetInterface.unregisterUsk(sone);
116                 }
117         }
118
119         //
120         // PRIVATE METHODS
121         //
122
123         /**
124          * Updates the contents of the given Sone from the given fetch result.
125          *
126          * @param sone
127          *            The Sone to update
128          * @param fetchResult
129          *            The fetch result
130          */
131         private void updateSoneFromXml(Sone sone, FetchResult fetchResult) {
132                 logger.log(Level.FINEST, "Persing FetchResult (%d bytes, %s) for %s…", new Object[] { fetchResult.size(), fetchResult.getMimeType(), sone });
133                 /* TODO - impose a size limit? */
134                 InputStream xmlInputStream = null;
135                 Bucket xmlBucket = null;
136                 try {
137                         xmlBucket = fetchResult.asBucket();
138                         xmlInputStream = xmlBucket.getInputStream();
139                         Document document = XML.transformToDocument(xmlInputStream);
140                         SimpleXML soneXml;
141                         try {
142                                 soneXml = SimpleXML.fromDocument(document);
143                         } catch (NullPointerException npe1) {
144                                 /* for some reason, invalid XML can cause NPEs. */
145                                 logger.log(Level.WARNING, "XML for Sone " + sone + " can not be parsed!", npe1);
146                                 return;
147                         }
148
149                         /* check ID. */
150                         String soneId = soneXml.getValue("id", null);
151                         if (!sone.getId().equals(soneId)) {
152                                 /* TODO - mark Sone as bad. */
153                                 logger.log(Level.WARNING, "Downloaded ID for Sone %s (%s) does not match known ID (%s)!", new Object[] { sone, sone.getId(), soneId });
154                                 return;
155                         }
156
157                         String soneName = soneXml.getValue("name", null);
158                         if (soneName == null) {
159                                 /* TODO - mark Sone as bad. */
160                                 logger.log(Level.WARNING, "Downloaded name for Sone %s was null!", new Object[] { sone });
161                                 return;
162                         }
163
164                         SimpleXML profileXml = soneXml.getNode("profile");
165                         if (profileXml == null) {
166                                 /* TODO - mark Sone as bad. */
167                                 logger.log(Level.WARNING, "Downloaded Sone %s has no profile!", new Object[] { sone });
168                                 return;
169                         }
170
171                         /* parse profile. */
172                         String profileFirstName = profileXml.getValue("first-name", null);
173                         String profileMiddleName = profileXml.getValue("middle-name", null);
174                         String profileLastName = profileXml.getValue("last-name", null);
175                         Profile profile = new Profile().setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName);
176
177                         /* parse posts. */
178                         SimpleXML postsXml = soneXml.getNode("posts");
179                         if (postsXml == null) {
180                                 /* TODO - mark Sone as bad. */
181                                 logger.log(Level.WARNING, "Downloaded Sone %s has no posts!", new Object[] { sone });
182                                 return;
183                         }
184
185                         Set<Post> posts = new HashSet<Post>();
186                         for (SimpleXML postXml : postsXml.getNodes("post")) {
187                                 String postId = postXml.getValue("id", null);
188                                 String postTime = postXml.getValue("time", null);
189                                 String postText = postXml.getValue("text", null);
190                                 if ((postId == null) || (postTime == null) || (postText == null)) {
191                                         /* TODO - mark Sone as bad. */
192                                         logger.log(Level.WARNING, "Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", new Object[] { sone, postId, postTime, postText });
193                                         return;
194                                 }
195                                 try {
196                                         posts.add(core.getPost(postId).setSone(sone).setTime(Long.parseLong(postTime)).setText(postText));
197                                 } catch (NumberFormatException nfe1) {
198                                         /* TODO - mark Sone as bad. */
199                                         logger.log(Level.WARNING, "Downloaded post for Sone %s with invalid time: %s", new Object[] { sone, postTime });
200                                         return;
201                                 }
202                         }
203
204                         /* parse replies. */
205                         SimpleXML repliesXml = soneXml.getNode("replies");
206                         if (repliesXml == null) {
207                                 /* TODO - mark Sone as bad. */
208                                 logger.log(Level.WARNING, "Downloaded Sone %s has no replies!", new Object[] { sone });
209                                 return;
210                         }
211
212                         Set<Reply> replies = new HashSet<Reply>();
213                         for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
214                                 String replyId = replyXml.getValue("id", null);
215                                 String replyPostId = replyXml.getValue("post-id", null);
216                                 String replyTime = replyXml.getValue("time", null);
217                                 String replyText = replyXml.getValue("text", null);
218                                 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
219                                         /* TODO - mark Sone as bad. */
220                                         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 });
221                                         return;
222                                 }
223                                 try {
224                                         replies.add(core.getReply(replyId).setSone(sone).setPost(core.getPost(replyPostId)).setTime(Long.parseLong(replyTime)).setText(replyText));
225                                 } catch (NumberFormatException nfe1) {
226                                         /* TODO - mark Sone as bad. */
227                                         logger.log(Level.WARNING, "Downloaded reply for Sone %s with invalid time: %s", new Object[] { sone, replyTime });
228                                         return;
229                                 }
230                         }
231
232                         /* okay, apparently everything was parsed correctly. Now import. */
233                         /* atomic setter operation on the Sone. */
234                         synchronized (sone) {
235                                 sone.setProfile(profile);
236                         }
237                 } catch (IOException ioe1) {
238                         logger.log(Level.WARNING, "Could not read XML file from " + sone + "!", ioe1);
239                 } finally {
240                         if (xmlBucket != null) {
241                                 xmlBucket.free();
242                         }
243                         Closer.close(xmlInputStream);
244                 }
245         }
246
247 }