2 * Sone - SoneParser.java - Copyright © 2010–2013 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 static com.google.common.base.Optional.absent;
21 import static com.google.common.base.Optional.fromNullable;
22 import static com.google.common.base.Optional.of;
24 import java.io.InputStream;
25 import java.util.HashSet;
28 import java.util.logging.Level;
29 import java.util.logging.Logger;
31 import net.pterodactylus.sone.data.Album;
32 import net.pterodactylus.sone.data.Client;
33 import net.pterodactylus.sone.data.Image;
34 import net.pterodactylus.sone.data.Post;
35 import net.pterodactylus.sone.data.PostReply;
36 import net.pterodactylus.sone.data.Profile;
37 import net.pterodactylus.sone.data.Sone;
38 import net.pterodactylus.sone.data.impl.DefaultSone;
39 import net.pterodactylus.sone.database.Database;
40 import net.pterodactylus.sone.database.ImageBuilder.ImageCreated;
41 import net.pterodactylus.sone.database.PostBuilder;
42 import net.pterodactylus.sone.database.PostBuilder.PostCreated;
43 import net.pterodactylus.sone.database.PostReplyBuilder;
44 import net.pterodactylus.sone.database.PostReplyBuilder.PostReplyCreated;
45 import net.pterodactylus.util.number.Numbers;
46 import net.pterodactylus.util.xml.SimpleXML;
47 import net.pterodactylus.util.xml.XML;
49 import com.google.common.base.Optional;
50 import com.google.common.collect.Maps;
51 import com.google.common.primitives.Ints;
52 import org.w3c.dom.Document;
55 * Parses the inserted XML representation of a {@link Sone} into a Sone.
57 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
59 public class SoneParser {
61 private static final Logger logger = Logger.getLogger(SoneParser.class.getName());
62 private static final int MAX_PROTOCOL_VERSION = 0;
65 * Parses a Sone from the given input stream and creates a new Sone from the
70 * @param soneInputStream
71 * The input stream to parse the Sone from
72 * @return The parsed Sone
74 public Sone parseSone(Database database, Sone originalSone, InputStream soneInputStream) {
75 /* TODO - impose a size limit? */
78 /* XML parsing is not thread-safe. */
80 document = XML.transformToDocument(soneInputStream);
82 if (document == null) {
83 /* TODO - mark Sone as bad. */
84 logger.log(Level.WARNING, String.format("Could not parse XML for Sone %s!", originalSone.getId()));
85 throw new InvalidXml();
88 SimpleXML soneXml = SimpleXML.fromDocument(document);
89 Optional<Client> parsedClient = parseClient(originalSone, soneXml);
90 Sone sone = new DefaultSone(database, originalSone.getId(), originalSone.isLocal(), parsedClient.or(originalSone.getClient()));
92 verifyProtocolVersion(soneXml);
94 parseTime(soneXml, sone);
96 SimpleXML profileXml = soneXml.getNode("profile");
97 if (profileXml == null) {
98 /* TODO - mark Sone as bad. */
99 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no profile!", sone));
100 throw new MalformedXml();
104 String profileFirstName = profileXml.getValue("first-name", null);
105 String profileMiddleName = profileXml.getValue("middle-name", null);
106 String profileLastName = profileXml.getValue("last-name", null);
107 Integer profileBirthDay = Numbers.safeParseInteger(profileXml.getValue("birth-day", null));
108 Integer profileBirthMonth = Numbers.safeParseInteger(profileXml.getValue("birth-month", null));
109 Integer profileBirthYear = Numbers.safeParseInteger(profileXml.getValue("birth-year", null));
110 Profile profile = new Profile(sone).modify().setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName).update();
111 profile.modify().setBirthDay(profileBirthDay).setBirthMonth(profileBirthMonth).setBirthYear(profileBirthYear).update();
112 /* avatar is processed after images are loaded. */
113 String avatarId = profileXml.getValue("avatar", null);
115 /* parse profile fields. */
116 SimpleXML profileFieldsXml = profileXml.getNode("fields");
117 if (profileFieldsXml != null) {
118 for (SimpleXML fieldXml : profileFieldsXml.getNodes("field")) {
119 String fieldName = fieldXml.getValue("field-name", null);
120 String fieldValue = fieldXml.getValue("field-value", "");
121 if (fieldName == null) {
122 logger.log(Level.WARNING, String.format("Downloaded profile field for Sone %s with missing data! Name: %s, Value: %s", sone, fieldName, fieldValue));
123 throw new MalformedXml();
126 profile.setField(profile.addField(fieldName), fieldValue);
127 } catch (IllegalArgumentException iae1) {
128 logger.log(Level.WARNING, String.format("Duplicate field: %s", fieldName), iae1);
129 throw new DuplicateField();
135 SimpleXML postsXml = soneXml.getNode("posts");
136 Set<Post> posts = new HashSet<Post>();
137 if (postsXml == null) {
138 /* TODO - mark Sone as bad. */
139 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no posts!", sone));
141 for (SimpleXML postXml : postsXml.getNodes("post")) {
142 String postId = postXml.getValue("id", null);
143 String postRecipientId = postXml.getValue("recipient", null);
144 String postTime = postXml.getValue("time", null);
145 String postText = postXml.getValue("text", null);
146 if ((postId == null) || (postTime == null) || (postText == null)) {
147 /* TODO - mark Sone as bad. */
148 logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", sone, postId, postTime, postText));
149 throw new MalformedXml();
152 PostBuilder postBuilder = sone.newPostBuilder();
153 /* TODO - parse time correctly. */
154 postBuilder.withId(postId).withTime(Long.parseLong(postTime)).withText(postText);
155 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
156 postBuilder.to(of(postRecipientId));
158 posts.add(postBuilder.build(Optional.<PostCreated>absent()));
159 } catch (NumberFormatException nfe1) {
160 /* TODO - mark Sone as bad. */
161 logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with invalid time: %s", sone, postTime));
162 throw new MalformedTime();
168 SimpleXML repliesXml = soneXml.getNode("replies");
169 Set<PostReply> replies = new HashSet<PostReply>();
170 if (repliesXml == null) {
171 /* TODO - mark Sone as bad. */
172 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no replies!", sone));
174 for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
175 String replyId = replyXml.getValue("id", null);
176 String replyPostId = replyXml.getValue("post-id", null);
177 String replyTime = replyXml.getValue("time", null);
178 String replyText = replyXml.getValue("text", null);
179 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
180 /* TODO - mark Sone as bad. */
181 logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with missing data! ID: %s, Post: %s, Time: %s, Text: %s", sone, replyId, replyPostId, replyTime, replyText));
182 throw new MalformedXml();
185 /* TODO - parse time correctly. */
186 PostReplyBuilder postReplyBuilder = sone.newPostReplyBuilder(replyPostId).withId(replyId).withTime(Long.parseLong(replyTime)).withText(replyText);
187 replies.add(postReplyBuilder.build(Optional.<PostReplyCreated>absent()));
188 } catch (NumberFormatException nfe1) {
189 /* TODO - mark Sone as bad. */
190 logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with invalid time: %s", sone, replyTime));
191 throw new MalformedTime();
196 /* parse liked post IDs. */
197 SimpleXML likePostIdsXml = soneXml.getNode("post-likes");
198 Set<String> likedPostIds = new HashSet<String>();
199 if (likePostIdsXml == null) {
200 /* TODO - mark Sone as bad. */
201 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no post likes!", sone));
203 for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) {
204 String postId = likedPostIdXml.getValue();
205 likedPostIds.add(postId);
209 /* parse liked reply IDs. */
210 SimpleXML likeReplyIdsXml = soneXml.getNode("reply-likes");
211 Set<String> likedReplyIds = new HashSet<String>();
212 if (likeReplyIdsXml == null) {
213 /* TODO - mark Sone as bad. */
214 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no reply likes!", sone));
216 for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) {
217 String replyId = likedReplyIdXml.getValue();
218 likedReplyIds.add(replyId);
223 SimpleXML albumsXml = soneXml.getNode("albums");
224 Map<String, Album> albums = Maps.newHashMap();
225 if (albumsXml != null) {
226 for (SimpleXML albumXml : albumsXml.getNodes("album")) {
227 String id = albumXml.getValue("id", null);
228 String parentId = albumXml.getValue("parent", null);
229 String title = albumXml.getValue("title", null);
230 String description = albumXml.getValue("description", "");
231 String albumImageId = albumXml.getValue("album-image", null);
232 if ((id == null) || (title == null) || (description == null)) {
233 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid album!", sone));
234 throw new MalformedXml();
236 Album parent = sone.getRootAlbum();
237 if (parentId != null) {
238 parent = albums.get(parentId);
239 if (parent == null) {
240 logger.log(Level.WARNING, String.format("Downloaded Sone %s has album with invalid parent!", sone));
241 throw new InvalidParentAlbum();
244 Album album = parent.newAlbumBuilder().withId(id).build().modify().setTitle(title).setDescription(description).update();
245 albums.put(album.getId(), album);
246 SimpleXML imagesXml = albumXml.getNode("images");
247 if (imagesXml != null) {
248 for (SimpleXML imageXml : imagesXml.getNodes("image")) {
249 String imageId = imageXml.getValue("id", null);
250 String imageCreationTimeString = imageXml.getValue("creation-time", null);
251 String imageKey = imageXml.getValue("key", null);
252 String imageTitle = imageXml.getValue("title", null);
253 String imageDescription = imageXml.getValue("description", "");
254 String imageWidthString = imageXml.getValue("width", null);
255 String imageHeightString = imageXml.getValue("height", null);
256 if ((imageId == null) || (imageCreationTimeString == null) || (imageKey == null) || (imageTitle == null) || (imageWidthString == null) || (imageHeightString == null)) {
257 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid images!", sone));
258 throw new MalformedXml();
260 long creationTime = Numbers.safeParseLong(imageCreationTimeString, 0L);
261 int imageWidth = Numbers.safeParseInteger(imageWidthString, 0);
262 int imageHeight = Numbers.safeParseInteger(imageHeightString, 0);
263 if ((imageWidth < 1) || (imageHeight < 1)) {
264 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains image %s with invalid dimensions (%s, %s)!", sone, imageId, imageWidthString, imageHeightString));
265 throw new MalformedDimension();
267 Image image = album.newImageBuilder().withId(imageId).at(imageKey).created(creationTime).sized(imageWidth, imageHeight).build(Optional.<ImageCreated>absent());
268 image = image.modify().setTitle(imageTitle).setDescription(imageDescription).update();
271 album.modify().setAlbumImage(albumImageId).update();
275 /* process avatar. */
276 profile.setAvatar(fromNullable(avatarId));
278 /* okay, apparently everything was parsed correctly. Now import. */
279 sone.setProfile(profile);
280 sone.setPosts(posts);
281 sone.setReplies(replies);
282 sone.setLikePostIds(likedPostIds);
283 sone.setLikeReplyIds(likedReplyIds);
288 private void parseTime(SimpleXML soneXml, Sone sone) {
289 String soneTime = soneXml.getValue("time", null);
290 if (soneTime == null) {
291 /* TODO - mark Sone as bad. */
292 logger.log(Level.WARNING, String.format("Downloaded time for Sone %s was null!", sone));
293 throw new MalformedXml();
296 sone.setTime(Long.parseLong(soneTime));
297 } catch (NumberFormatException nfe1) {
298 /* TODO - mark Sone as bad. */
299 logger.log(Level.WARNING, String.format("Downloaded Sone %s with invalid time: %s", sone, soneTime));
300 throw new MalformedTime();
304 private void verifyProtocolVersion(SimpleXML soneXml) {
305 Optional<Integer> protocolVersion = parseProtocolVersion(soneXml);
306 if (protocolVersion.isPresent()) {
307 if (protocolVersion.get() < 0) {
308 logger.log(Level.WARNING, String.format("Invalid protocol version: %d! Not parsing Sone.", protocolVersion.get()));
309 throw new InvalidProtocolVersion();
311 if (protocolVersion.get() > MAX_PROTOCOL_VERSION) {
312 logger.log(Level.WARNING, String.format("Unknown protocol version: %d! Not parsing Sone.", protocolVersion.get()));
313 throw new SoneTooNew();
318 private Optional<Integer> parseProtocolVersion(SimpleXML soneXml) {
319 String soneProtocolVersion = soneXml.getValue("protocol-version", null);
320 if (soneProtocolVersion == null) {
321 logger.log(Level.INFO, "No protocol version found, assuming 0.");
324 return fromNullable(Ints.tryParse(soneProtocolVersion));
327 private Optional<Client> parseClient(Sone sone, SimpleXML soneXml) {
328 SimpleXML clientXml = soneXml.getNode("client");
329 if (clientXml == null) {
332 String clientName = clientXml.getValue("name", null);
333 String clientVersion = clientXml.getValue("version", null);
334 if ((clientName == null) || (clientVersion == null)) {
335 logger.log(Level.WARNING, String.format("Download Sone %s with client XML but missing name or version!", sone));
338 return of(new Client(clientName, clientVersion));
341 public static class InvalidXml extends RuntimeException {
345 public static class InvalidProtocolVersion extends RuntimeException {
349 public static class SoneTooNew extends RuntimeException {
353 public static class MalformedXml extends RuntimeException {
357 public static class DuplicateField extends RuntimeException {
361 public static class MalformedTime extends RuntimeException {
365 public static class InvalidParentAlbum extends RuntimeException {
369 public static class MalformedDimension extends RuntimeException {