Remove warning about parameter assignment.
[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          * Removes the given Sone from the downloader.
93          *
94          * @param sone
95          *            The Sone to stop watching
96          */
97         public void removeSone(Sone sone) {
98                 if (sones.remove(sone)) {
99                         freenetInterface.unregisterUsk(sone);
100                 }
101         }
102
103         /**
104          * Fetches the updated Sone. This method is a callback method for
105          * {@link FreenetInterface#registerUsk(Sone, SoneDownloader)}.
106          *
107          * @param sone
108          *            The Sone to fetch
109          */
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                 parseSone(sone, fetchResult);
115         }
116
117         /**
118          * Parses a Sone from a fetch result.
119          *
120          * @param originalSone
121          *            The sone to parse, or {@code null} if the Sone is yet unknown
122          * @param fetchResult
123          *            The fetch result
124          * @return The parsed Sone, or {@code null} if the Sone could not be parsed
125          */
126         public Sone parseSone(Sone originalSone, FetchResult fetchResult) {
127                 logger.log(Level.FINEST, "Persing FetchResult (%d bytes, %s) for %s…", new Object[] { fetchResult.size(), fetchResult.getMimeType(), originalSone });
128                 /* TODO - impose a size limit? */
129                 InputStream xmlInputStream = null;
130                 Bucket xmlBucket = null;
131                 Sone sone;
132                 try {
133                         xmlBucket = fetchResult.asBucket();
134                         xmlInputStream = xmlBucket.getInputStream();
135                         Document document = XML.transformToDocument(xmlInputStream);
136                         SimpleXML soneXml;
137                         try {
138                                 soneXml = SimpleXML.fromDocument(document);
139                         } catch (NullPointerException npe1) {
140                                 /* for some reason, invalid XML can cause NPEs. */
141                                 logger.log(Level.WARNING, "XML for Sone " + originalSone + " can not be parsed!", npe1);
142                                 return null;
143                         }
144
145                         /* check ID. */
146                         String soneId = soneXml.getValue("id", null);
147                         if ((originalSone != null) && !originalSone.getId().equals(soneId)) {
148                                 /* TODO - mark Sone as bad. */
149                                 logger.log(Level.WARNING, "Downloaded ID for Sone %s (%s) does not match known ID (%s)!", new Object[] { originalSone, originalSone.getId(), soneId });
150                                 return null;
151                         }
152
153                         /* load Sone from core. */
154                         sone = originalSone;
155                         if (sone == null) {
156                                 sone = core.getSone(soneId);
157                         }
158
159                         String soneName = soneXml.getValue("name", null);
160                         if (soneName == null) {
161                                 /* TODO - mark Sone as bad. */
162                                 logger.log(Level.WARNING, "Downloaded name for Sone %s was null!", new Object[] { sone });
163                                 return null;
164                         }
165
166                         SimpleXML profileXml = soneXml.getNode("profile");
167                         if (profileXml == null) {
168                                 /* TODO - mark Sone as bad. */
169                                 logger.log(Level.WARNING, "Downloaded Sone %s has no profile!", new Object[] { sone });
170                                 return null;
171                         }
172
173                         /* parse profile. */
174                         String profileFirstName = profileXml.getValue("first-name", null);
175                         String profileMiddleName = profileXml.getValue("middle-name", null);
176                         String profileLastName = profileXml.getValue("last-name", null);
177                         Profile profile = new Profile().setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName);
178
179                         /* parse posts. */
180                         SimpleXML postsXml = soneXml.getNode("posts");
181                         if (postsXml == null) {
182                                 /* TODO - mark Sone as bad. */
183                                 logger.log(Level.WARNING, "Downloaded Sone %s has no posts!", new Object[] { sone });
184                                 return null;
185                         }
186
187                         Set<Post> posts = new HashSet<Post>();
188                         for (SimpleXML postXml : postsXml.getNodes("post")) {
189                                 String postId = postXml.getValue("id", null);
190                                 String postTime = postXml.getValue("time", null);
191                                 String postText = postXml.getValue("text", null);
192                                 if ((postId == null) || (postTime == null) || (postText == null)) {
193                                         /* TODO - mark Sone as bad. */
194                                         logger.log(Level.WARNING, "Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", new Object[] { sone, postId, postTime, postText });
195                                         return null;
196                                 }
197                                 try {
198                                         posts.add(core.getPost(postId).setSone(sone).setTime(Long.parseLong(postTime)).setText(postText));
199                                 } catch (NumberFormatException nfe1) {
200                                         /* TODO - mark Sone as bad. */
201                                         logger.log(Level.WARNING, "Downloaded post for Sone %s with invalid time: %s", new Object[] { sone, postTime });
202                                         return null;
203                                 }
204                         }
205
206                         /* parse replies. */
207                         SimpleXML repliesXml = soneXml.getNode("replies");
208                         if (repliesXml == null) {
209                                 /* TODO - mark Sone as bad. */
210                                 logger.log(Level.WARNING, "Downloaded Sone %s has no replies!", new Object[] { sone });
211                                 return null;
212                         }
213
214                         Set<Reply> replies = new HashSet<Reply>();
215                         for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
216                                 String replyId = replyXml.getValue("id", null);
217                                 String replyPostId = replyXml.getValue("post-id", null);
218                                 String replyTime = replyXml.getValue("time", null);
219                                 String replyText = replyXml.getValue("text", null);
220                                 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
221                                         /* TODO - mark Sone as bad. */
222                                         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 });
223                                         return null;
224                                 }
225                                 try {
226                                         replies.add(core.getReply(replyId).setSone(sone).setPost(core.getPost(replyPostId)).setTime(Long.parseLong(replyTime)).setText(replyText));
227                                 } catch (NumberFormatException nfe1) {
228                                         /* TODO - mark Sone as bad. */
229                                         logger.log(Level.WARNING, "Downloaded reply for Sone %s with invalid time: %s", new Object[] { sone, replyTime });
230                                         return null;
231                                 }
232                         }
233
234                         /* okay, apparently everything was parsed correctly. Now import. */
235                         /* atomic setter operation on the Sone. */
236                         synchronized (sone) {
237                                 sone.setProfile(profile);
238                                 sone.setPosts(posts);
239                                 sone.setReplies(replies);
240                                 sone.setModificationCounter(0);
241                         }
242                 } catch (IOException ioe1) {
243                         logger.log(Level.WARNING, "Could not read XML file from " + originalSone + "!", ioe1);
244                         return null;
245                 } finally {
246                         if (xmlBucket != null) {
247                                 xmlBucket.free();
248                         }
249                         Closer.close(xmlInputStream);
250                 }
251                 return sone;
252         }
253
254         //
255         // SERVICE METHODS
256         //
257
258         /**
259          * {@inheritDoc}
260          */
261         @Override
262         protected void serviceStop() {
263                 for (Sone sone : sones) {
264                         freenetInterface.unregisterUsk(sone);
265                 }
266         }
267
268 }