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.sone.database.memory.MemoryDatabase;
46 import net.pterodactylus.util.number.Numbers;
47 import net.pterodactylus.util.xml.SimpleXML;
48 import net.pterodactylus.util.xml.XML;
50 import com.google.common.base.Optional;
51 import com.google.common.collect.Maps;
52 import com.google.common.primitives.Ints;
53 import org.w3c.dom.Document;
56 * Parses the inserted XML representation of a {@link Sone} into a Sone.
58 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
60 public class SoneParser {
62 private static final Logger logger = Logger.getLogger(SoneParser.class.getName());
63 private static final int MAX_PROTOCOL_VERSION = 0;
66 * Parses a Sone from the given input stream and creates a new Sone from the
71 * @param soneInputStream
72 * The input stream to parse the Sone from
73 * @return The parsed Sone
74 * @throws SoneException
75 * if a parse error occurs, or the protocol is invalid
77 public Sone parseSone(Database database, Sone originalSone, InputStream soneInputStream) throws SoneException {
78 /* TODO - impose a size limit? */
81 /* XML parsing is not thread-safe. */
83 document = XML.transformToDocument(soneInputStream);
85 if (document == null) {
86 /* TODO - mark Sone as bad. */
87 logger.log(Level.WARNING, String.format("Could not parse XML for Sone %s!", originalSone));
91 Optional<SimpleXML> soneXml = parseXml(originalSone, document);
92 if (!soneXml.isPresent()) {
93 logger.log(Level.WARNING, String.format("XML for Sone %s can not be parsed!", originalSone));
97 Optional<Client> parsedClient = parseClient(originalSone, soneXml.get());
98 Sone sone = new DefaultSone(database, originalSone.getId(), originalSone.isLocal(), parsedClient.or(originalSone.getClient()));
100 Optional<Integer> protocolVersion = parseProtocolVersion(soneXml.get());
101 if (protocolVersion.isPresent()) {
102 if (protocolVersion.get() < 0) {
103 logger.log(Level.WARNING, String.format("Invalid protocol version: %d! Not parsing Sone.", protocolVersion));
106 if (protocolVersion.get() > MAX_PROTOCOL_VERSION) {
107 logger.log(Level.WARNING, String.format("Unknown protocol version: %d! Not parsing Sone.", protocolVersion));
112 String soneTime = soneXml.get().getValue("time", null);
113 if (soneTime == null) {
114 /* TODO - mark Sone as bad. */
115 logger.log(Level.WARNING, String.format("Downloaded time for Sone %s was null!", sone));
119 sone.setTime(Long.parseLong(soneTime));
120 } catch (NumberFormatException nfe1) {
121 /* TODO - mark Sone as bad. */
122 logger.log(Level.WARNING, String.format("Downloaded Sone %s with invalid time: %s", sone, soneTime));
126 SimpleXML profileXml = soneXml.get().getNode("profile");
127 if (profileXml == null) {
128 /* TODO - mark Sone as bad. */
129 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no profile!", sone));
134 String profileFirstName = profileXml.getValue("first-name", null);
135 String profileMiddleName = profileXml.getValue("middle-name", null);
136 String profileLastName = profileXml.getValue("last-name", null);
137 Integer profileBirthDay = Numbers.safeParseInteger(profileXml.getValue("birth-day", null));
138 Integer profileBirthMonth = Numbers.safeParseInteger(profileXml.getValue("birth-month", null));
139 Integer profileBirthYear = Numbers.safeParseInteger(profileXml.getValue("birth-year", null));
140 Profile profile = new Profile(sone).modify().setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName).update();
141 profile.modify().setBirthDay(profileBirthDay).setBirthMonth(profileBirthMonth).setBirthYear(profileBirthYear).update();
142 /* avatar is processed after images are loaded. */
143 String avatarId = profileXml.getValue("avatar", null);
145 /* parse profile fields. */
146 SimpleXML profileFieldsXml = profileXml.getNode("fields");
147 if (profileFieldsXml != null) {
148 for (SimpleXML fieldXml : profileFieldsXml.getNodes("field")) {
149 String fieldName = fieldXml.getValue("field-name", null);
150 String fieldValue = fieldXml.getValue("field-value", "");
151 if (fieldName == null) {
152 logger.log(Level.WARNING, String.format("Downloaded profile field for Sone %s with missing data! Name: %s, Value: %s", sone, fieldName, fieldValue));
156 profile.addField(fieldName).setValue(fieldValue);
157 } catch (IllegalArgumentException iae1) {
158 logger.log(Level.WARNING, String.format("Duplicate field: %s", fieldName), iae1);
165 SimpleXML postsXml = soneXml.get().getNode("posts");
166 Set<Post> posts = new HashSet<Post>();
167 if (postsXml == null) {
168 /* TODO - mark Sone as bad. */
169 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no posts!", sone));
171 for (SimpleXML postXml : postsXml.getNodes("post")) {
172 String postId = postXml.getValue("id", null);
173 String postRecipientId = postXml.getValue("recipient", null);
174 String postTime = postXml.getValue("time", null);
175 String postText = postXml.getValue("text", null);
176 if ((postId == null) || (postTime == null) || (postText == null)) {
177 /* TODO - mark Sone as bad. */
178 logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", sone, postId, postTime, postText));
182 PostBuilder postBuilder = sone.newPostBuilder();
183 /* TODO - parse time correctly. */
184 postBuilder.withId(postId).withTime(Long.parseLong(postTime)).withText(postText);
185 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
186 postBuilder.to(of(postRecipientId));
188 posts.add(postBuilder.build(Optional.<PostCreated>absent()));
189 } catch (NumberFormatException nfe1) {
190 /* TODO - mark Sone as bad. */
191 logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with invalid time: %s", sone, postTime));
198 SimpleXML repliesXml = soneXml.get().getNode("replies");
199 Set<PostReply> replies = new HashSet<PostReply>();
200 if (repliesXml == null) {
201 /* TODO - mark Sone as bad. */
202 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no replies!", sone));
204 for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
205 String replyId = replyXml.getValue("id", null);
206 String replyPostId = replyXml.getValue("post-id", null);
207 String replyTime = replyXml.getValue("time", null);
208 String replyText = replyXml.getValue("text", null);
209 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
210 /* TODO - mark Sone as bad. */
211 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));
215 /* TODO - parse time correctly. */
216 PostReplyBuilder postReplyBuilder = sone.newPostReplyBuilder(replyPostId).withId(replyId).withTime(Long.parseLong(replyTime)).withText(replyText);
217 replies.add(postReplyBuilder.build(Optional.<PostReplyCreated>absent()));
218 } catch (NumberFormatException nfe1) {
219 /* TODO - mark Sone as bad. */
220 logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with invalid time: %s", sone, replyTime));
226 /* parse liked post IDs. */
227 SimpleXML likePostIdsXml = soneXml.get().getNode("post-likes");
228 Set<String> likedPostIds = new HashSet<String>();
229 if (likePostIdsXml == null) {
230 /* TODO - mark Sone as bad. */
231 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no post likes!", sone));
233 for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) {
234 String postId = likedPostIdXml.getValue();
235 likedPostIds.add(postId);
239 /* parse liked reply IDs. */
240 SimpleXML likeReplyIdsXml = soneXml.get().getNode("reply-likes");
241 Set<String> likedReplyIds = new HashSet<String>();
242 if (likeReplyIdsXml == null) {
243 /* TODO - mark Sone as bad. */
244 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no reply likes!", sone));
246 for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) {
247 String replyId = likedReplyIdXml.getValue();
248 likedReplyIds.add(replyId);
253 SimpleXML albumsXml = soneXml.get().getNode("albums");
254 Map<String, Album> albums = Maps.newHashMap();
255 if (albumsXml != null) {
256 for (SimpleXML albumXml : albumsXml.getNodes("album")) {
257 String id = albumXml.getValue("id", null);
258 String parentId = albumXml.getValue("parent", null);
259 String title = albumXml.getValue("title", null);
260 String description = albumXml.getValue("description", "");
261 String albumImageId = albumXml.getValue("album-image", null);
262 if ((id == null) || (title == null) || (description == null)) {
263 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid album!", sone));
266 Album parent = sone.getRootAlbum();
267 if (parentId != null) {
268 parent = albums.get(parentId);
269 if (parent == null) {
270 logger.log(Level.WARNING, String.format("Downloaded Sone %s has album with invalid parent!", sone));
274 Album album = parent.newAlbumBuilder().withId(id).build().modify().setTitle(title).setDescription(description).update();
275 albums.put(album.getId(), album);
276 SimpleXML imagesXml = albumXml.getNode("images");
277 if (imagesXml != null) {
278 for (SimpleXML imageXml : imagesXml.getNodes("image")) {
279 String imageId = imageXml.getValue("id", null);
280 String imageCreationTimeString = imageXml.getValue("creation-time", null);
281 String imageKey = imageXml.getValue("key", null);
282 String imageTitle = imageXml.getValue("title", null);
283 String imageDescription = imageXml.getValue("description", "");
284 String imageWidthString = imageXml.getValue("width", null);
285 String imageHeightString = imageXml.getValue("height", null);
286 if ((imageId == null) || (imageCreationTimeString == null) || (imageKey == null) || (imageTitle == null) || (imageWidthString == null) || (imageHeightString == null)) {
287 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid images!", sone));
290 long creationTime = Numbers.safeParseLong(imageCreationTimeString, 0L);
291 int imageWidth = Numbers.safeParseInteger(imageWidthString, 0);
292 int imageHeight = Numbers.safeParseInteger(imageHeightString, 0);
293 if ((imageWidth < 1) || (imageHeight < 1)) {
294 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains image %s with invalid dimensions (%s, %s)!", sone, imageId, imageWidthString, imageHeightString));
297 Image image = album.newImageBuilder().withId(imageId).at(imageKey).created(creationTime).sized(imageWidth, imageHeight).build(Optional.<ImageCreated>absent());
298 image = image.modify().setTitle(imageTitle).setDescription(imageDescription).update();
301 album.modify().setAlbumImage(albumImageId).update();
305 /* process avatar. */
306 profile.setAvatar(fromNullable(avatarId));
308 /* okay, apparently everything was parsed correctly. Now import. */
309 sone.setProfile(profile);
310 sone.setPosts(posts);
311 sone.setReplies(replies);
312 sone.setLikePostIds(likedPostIds);
313 sone.setLikeReplyIds(likedReplyIds);
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<SimpleXML> parseXml(Sone originalSone, Document document) {
329 return fromNullable(SimpleXML.fromDocument(document));
330 } catch (NullPointerException npe1) {
331 /* for some reason, invalid XML can cause NPEs. */
336 private Optional<Client> parseClient(Sone sone, SimpleXML soneXml) {
337 SimpleXML clientXml = soneXml.getNode("client");
338 if (clientXml == null) {
341 String clientName = clientXml.getValue("name", null);
342 String clientVersion = clientXml.getValue("version", null);
343 if ((clientName == null) || (clientVersion == null)) {
344 logger.log(Level.WARNING, String.format("Download Sone %s with client XML but missing name or version!", sone));
347 return of(new Client(clientName, clientVersion));