Allow method chaining in Profile.
[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.Sone;
28 import net.pterodactylus.util.io.Closer;
29 import net.pterodactylus.util.logging.Logging;
30 import net.pterodactylus.util.service.AbstractService;
31 import net.pterodactylus.util.xml.SimpleXML;
32 import net.pterodactylus.util.xml.XML;
33
34 import org.w3c.dom.Document;
35
36 import freenet.client.FetchResult;
37 import freenet.support.api.Bucket;
38
39 /**
40  * The Sone downloader is responsible for download Sones as they are updated.
41  *
42  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
43  */
44 public class SoneDownloader extends AbstractService {
45
46         /** The logger. */
47         private static final Logger logger = Logging.getLogger(SoneDownloader.class);
48
49         /** The Freenet interface. */
50         private final FreenetInterface freenetInterface;
51
52         /** The sones to update. */
53         private final Set<Sone> sones = new HashSet<Sone>();
54
55         /**
56          * Creates a new Sone downloader.
57          *
58          * @param freenetInterface
59          *            The Freenet interface
60          */
61         public SoneDownloader(FreenetInterface freenetInterface) {
62                 super("Sone Downloader");
63                 this.freenetInterface = freenetInterface;
64         }
65
66         //
67         // ACTIONS
68         //
69
70         /**
71          * Adds the given Sone to the set of Sones that will be watched for updates.
72          *
73          * @param sone
74          *            The Sone to add
75          */
76         public void addSone(Sone sone) {
77                 if (sones.add(sone)) {
78                         freenetInterface.registerUsk(sone, this);
79                 }
80         }
81
82         /**
83          * Fetches the updated Sone. This method is a callback method for
84          * {@link FreenetInterface#registerUsk(Sone, SoneDownloader)}.
85          *
86          * @param sone
87          *            The Sone to fetch
88          */
89         public void fetchSone(Sone sone) {
90                 logger.log(Level.FINE, "Starting fetch for Sone “%s” from %s…", new Object[] { sone, sone.getRequestUri().setMetaString(new String[] { "sone.xml" }) });
91                 FetchResult fetchResult = freenetInterface.fetchUri(sone.getRequestUri().setMetaString(new String[] { "sone.xml" }));
92                 logger.log(Level.FINEST, "Got %d bytes back.", fetchResult.size());
93                 updateSoneFromXml(sone, fetchResult);
94         }
95
96         //
97         // SERVICE METHODS
98         //
99
100         /**
101          * {@inheritDoc}
102          */
103         @Override
104         protected void serviceStop() {
105                 for (Sone sone : sones) {
106                         freenetInterface.unregisterUsk(sone);
107                 }
108         }
109
110         //
111         // PRIVATE METHODS
112         //
113
114         /**
115          * Updates the contents of the given Sone from the given fetch result.
116          *
117          * @param sone
118          *            The Sone to update
119          * @param fetchResult
120          *            The fetch result
121          */
122         private void updateSoneFromXml(Sone sone, FetchResult fetchResult) {
123                 logger.log(Level.FINEST, "Persing FetchResult (%d bytes, %s) for %s…", new Object[] { fetchResult.size(), fetchResult.getMimeType(), sone });
124                 /* TODO - impose a size limit? */
125                 InputStream xmlInputStream = null;
126                 Bucket xmlBucket = null;
127                 try {
128                         xmlBucket = fetchResult.asBucket();
129                         xmlInputStream = xmlBucket.getInputStream();
130                         Document document = XML.transformToDocument(xmlInputStream);
131                         SimpleXML soneXml = SimpleXML.fromDocument(document);
132
133                         /* check ID. */
134                         String soneId = soneXml.getValue("id", null);
135                         if (!sone.getId().equals(soneId)) {
136                                 /* TODO - mark Sone as bad. */
137                                 logger.log(Level.WARNING, "Downloaded ID for Sone %s (%s) does not match known ID (%s)!", new Object[] { sone, sone.getId(), soneId });
138                                 return;
139                         }
140
141                         String soneName = soneXml.getValue("name", null);
142                         if (soneName == null) {
143                                 /* TODO - mark Sone as bad. */
144                                 logger.log(Level.WARNING, "Downloaded name for Sone %s was null!", new Object[] { sone });
145                                 return;
146                         }
147
148                         SimpleXML profileXml = soneXml.getNode("profile");
149                         if (profileXml == null) {
150                                 /* TODO - mark Sone as bad. */
151                                 logger.log(Level.WARNING, "Downloaded Sone %s has no profile!", new Object[] { sone });
152                                 return;
153                         }
154
155                         /* parse profile. */
156
157                 } catch (IOException ioe1) {
158                         logger.log(Level.WARNING, "Could not read XML file from " + sone + "!", ioe1);
159                 } finally {
160                         if (xmlBucket != null) {
161                                 xmlBucket.free();
162                         }
163                         Closer.close(xmlInputStream);
164                 }
165         }
166
167 }