Store the insert URI in the information used for inserting.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / SoneParser.java
index 7900a10..38b21e3 100644 (file)
 
 package net.pterodactylus.sone.core;
 
+import static com.google.common.base.Optional.absent;
+import static com.google.common.base.Optional.fromNullable;
+import static com.google.common.base.Optional.of;
+
 import java.io.InputStream;
-import java.net.MalformedURLException;
 import java.util.HashSet;
 import java.util.Map;
 import java.util.Set;
@@ -33,20 +36,20 @@ import net.pterodactylus.sone.data.PostReply;
 import net.pterodactylus.sone.data.Profile;
 import net.pterodactylus.sone.data.Sone;
 import net.pterodactylus.sone.data.impl.DefaultSone;
+import net.pterodactylus.sone.database.Database;
 import net.pterodactylus.sone.database.ImageBuilder.ImageCreated;
 import net.pterodactylus.sone.database.PostBuilder;
 import net.pterodactylus.sone.database.PostBuilder.PostCreated;
 import net.pterodactylus.sone.database.PostReplyBuilder;
 import net.pterodactylus.sone.database.PostReplyBuilder.PostReplyCreated;
-import net.pterodactylus.sone.database.memory.MemoryDatabase;
 import net.pterodactylus.util.number.Numbers;
 import net.pterodactylus.util.xml.SimpleXML;
 import net.pterodactylus.util.xml.XML;
 
-import freenet.keys.FreenetURI;
-
 import com.google.common.base.Optional;
 import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import com.google.common.primitives.Ints;
 import org.w3c.dom.Document;
 
 /**
@@ -58,11 +61,6 @@ public class SoneParser {
 
        private static final Logger logger = Logger.getLogger(SoneParser.class.getName());
        private static final int MAX_PROTOCOL_VERSION = 0;
-       private final Core core;
-
-       public SoneParser(Core core) {
-               this.core = core;
-       }
 
        /**
         * Parses a Sone from the given input stream and creates a new Sone from the
@@ -73,10 +71,8 @@ public class SoneParser {
         * @param soneInputStream
         *              The input stream to parse the Sone from
         * @return The parsed Sone
-        * @throws SoneException
-        *              if a parse error occurs, or the protocol is invalid
         */
-       public Sone parseSone(Sone originalSone, InputStream soneInputStream) throws SoneException {
+       public Sone parseSone(Database database, Sone originalSone, InputStream soneInputStream) {
                /* TODO - impose a size limit? */
 
                Document document;
@@ -86,73 +82,78 @@ public class SoneParser {
                }
                if (document == null) {
                        /* TODO - mark Sone as bad. */
-                       logger.log(Level.WARNING, String.format("Could not parse XML for Sone %s!", originalSone));
-                       return null;
-               }
-
-               SimpleXML soneXml;
-               try {
-                       soneXml = SimpleXML.fromDocument(document);
-               } catch (NullPointerException npe1) {
-                       /* for some reason, invalid XML can cause NPEs. */
-                       logger.log(Level.WARNING, String.format("XML for Sone %s can not be parsed!", originalSone), npe1);
-                       return null;
-               }
-
-               SimpleXML clientXml = soneXml.getNode("client");
-               Client soneClient = originalSone.getClient();
-               if (clientXml != null) {
-                       String clientName = clientXml.getValue("name", null);
-                       String clientVersion = clientXml.getValue("version", null);
-                       if ((clientName == null) || (clientVersion == null)) {
-                               logger.log(Level.WARNING, String.format("Download Sone %s with client XML but missing name or version!", originalSone));
-                               return null;
-                       }
-                       soneClient = new Client(clientName, clientVersion);
+                       logger.log(Level.WARNING, String.format("Could not parse XML for Sone %s!", originalSone.getId()));
+                       throw new InvalidXml();
                }
 
-               Sone sone = new DefaultSone(new MemoryDatabase(null), originalSone.getId(), originalSone.isLocal(), soneClient);
-
-               Integer protocolVersion = null;
-               String soneProtocolVersion = soneXml.getValue("protocol-version", null);
-               if (soneProtocolVersion != null) {
-                       protocolVersion = Numbers.safeParseInteger(soneProtocolVersion);
-               }
-               if (protocolVersion == null) {
-                       logger.log(Level.INFO, "No protocol version found, assuming 0.");
-                       protocolVersion = 0;
-               }
+               SimpleXML soneXml = SimpleXML.fromDocument(document);
+               Optional<Client> parsedClient = parseClient(originalSone, soneXml);
+               Sone sone = new DefaultSone(database, originalSone.getId(), originalSone.isLocal(), parsedClient.or(originalSone.getClient()));
 
-               if (protocolVersion < 0) {
-                       logger.log(Level.WARNING, String.format("Invalid protocol version: %d! Not parsing Sone.", protocolVersion));
-                       return null;
-               }
+               verifyProtocolVersion(soneXml);
 
-               /* check for valid versions. */
-               if (protocolVersion > MAX_PROTOCOL_VERSION) {
-                       logger.log(Level.WARNING, String.format("Unknown protocol version: %d! Not parsing Sone.", protocolVersion));
-                       return null;
-               }
-
-               String soneTime = soneXml.getValue("time", null);
-               if (soneTime == null) {
-                       /* TODO - mark Sone as bad. */
-                       logger.log(Level.WARNING, String.format("Downloaded time for Sone %s was null!", sone));
-                       return null;
-               }
-               try {
-                       sone.setTime(Long.parseLong(soneTime));
-               } catch (NumberFormatException nfe1) {
-                       /* TODO - mark Sone as bad. */
-                       logger.log(Level.WARNING, String.format("Downloaded Sone %s with invalid time: %s", sone, soneTime));
-                       return null;
-               }
+               parseTime(soneXml, sone);
 
                SimpleXML profileXml = soneXml.getNode("profile");
                if (profileXml == null) {
                        /* TODO - mark Sone as bad. */
                        logger.log(Level.WARNING, String.format("Downloaded Sone %s has no profile!", sone));
-                       return null;
+                       throw new MalformedXml();
+               }
+
+               /* parse albums. */
+               SimpleXML albumsXml = soneXml.getNode("albums");
+               Map<String, Album> albums = Maps.newHashMap();
+               Set<String> images = Sets.newHashSet();
+               if (albumsXml != null) {
+                       for (SimpleXML albumXml : albumsXml.getNodes("album")) {
+                               String id = albumXml.getValue("id", null);
+                               String parentId = albumXml.getValue("parent", null);
+                               String title = albumXml.getValue("title", null);
+                               String description = albumXml.getValue("description", "");
+                               String albumImageId = albumXml.getValue("album-image", null);
+                               if ((id == null) || (title == null) || (description == null)) {
+                                       logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid album!", sone));
+                                       throw new MalformedXml();
+                               }
+                               Album parent = sone.getRootAlbum();
+                               if (parentId != null) {
+                                       parent = albums.get(parentId);
+                                       if (parent == null) {
+                                               logger.log(Level.WARNING, String.format("Downloaded Sone %s has album with invalid parent!", sone));
+                                               throw new InvalidParentAlbum();
+                                       }
+                               }
+                               Album album = parent.newAlbumBuilder().withId(id).build().modify().setTitle(title).setDescription(description).update();
+                               albums.put(album.getId(), album);
+                               SimpleXML imagesXml = albumXml.getNode("images");
+                               if (imagesXml != null) {
+                                       for (SimpleXML imageXml : imagesXml.getNodes("image")) {
+                                               String imageId = imageXml.getValue("id", null);
+                                               String imageCreationTimeString = imageXml.getValue("creation-time", null);
+                                               String imageKey = imageXml.getValue("key", null);
+                                               String imageTitle = imageXml.getValue("title", null);
+                                               String imageDescription = imageXml.getValue("description", "");
+                                               String imageWidthString = imageXml.getValue("width", null);
+                                               String imageHeightString = imageXml.getValue("height", null);
+                                               if ((imageId == null) || (imageCreationTimeString == null) || (imageKey == null) || (imageTitle == null) || (imageWidthString == null) || (imageHeightString == null)) {
+                                                       logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid images!", sone));
+                                                       throw new MalformedXml();
+                                               }
+                                               long creationTime = Numbers.safeParseLong(imageCreationTimeString, 0L);
+                                               int imageWidth = Numbers.safeParseInteger(imageWidthString, 0);
+                                               int imageHeight = Numbers.safeParseInteger(imageHeightString, 0);
+                                               if ((imageWidth < 1) || (imageHeight < 1)) {
+                                                       logger.log(Level.WARNING, String.format("Downloaded Sone %s contains image %s with invalid dimensions (%s, %s)!", sone, imageId, imageWidthString, imageHeightString));
+                                                       throw new MalformedDimension();
+                                               }
+                                               Image image = album.newImageBuilder().withId(imageId).at(imageKey).created(creationTime).sized(imageWidth, imageHeight).build(Optional.<ImageCreated>absent());
+                                               image.modify().setTitle(imageTitle).setDescription(imageDescription).update();
+                                               images.add(imageId);
+                                       }
+                               }
+                               album.modify().setAlbumImage(albumImageId).update();
+                       }
                }
 
                /* parse profile. */
@@ -164,8 +165,13 @@ public class SoneParser {
                Integer profileBirthYear = Numbers.safeParseInteger(profileXml.getValue("birth-year", null));
                Profile profile = new Profile(sone).modify().setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName).update();
                profile.modify().setBirthDay(profileBirthDay).setBirthMonth(profileBirthMonth).setBirthYear(profileBirthYear).update();
+
                /* avatar is processed after images are loaded. */
                String avatarId = profileXml.getValue("avatar", null);
+               if ((avatarId != null) && !images.contains(avatarId)) {
+                       throw new InvalidAvatarId();
+               }
+               profile.setAvatar(fromNullable(avatarId));
 
                /* parse profile fields. */
                SimpleXML profileFieldsXml = profileXml.getNode("fields");
@@ -175,13 +181,13 @@ public class SoneParser {
                                String fieldValue = fieldXml.getValue("field-value", "");
                                if (fieldName == null) {
                                        logger.log(Level.WARNING, String.format("Downloaded profile field for Sone %s with missing data! Name: %s, Value: %s", sone, fieldName, fieldValue));
-                                       return null;
+                                       throw new MalformedXml();
                                }
                                try {
-                                       profile.addField(fieldName).setValue(fieldValue);
+                                       profile.setField(profile.addField(fieldName), fieldValue);
                                } catch (IllegalArgumentException iae1) {
                                        logger.log(Level.WARNING, String.format("Duplicate field: %s", fieldName), iae1);
-                                       return null;
+                                       throw new DuplicateField();
                                }
                        }
                }
@@ -201,20 +207,20 @@ public class SoneParser {
                                if ((postId == null) || (postTime == null) || (postText == null)) {
                                        /* TODO - mark Sone as bad. */
                                        logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", sone, postId, postTime, postText));
-                                       return null;
+                                       throw new MalformedXml();
                                }
                                try {
                                        PostBuilder postBuilder = sone.newPostBuilder();
                                        /* TODO - parse time correctly. */
                                        postBuilder.withId(postId).withTime(Long.parseLong(postTime)).withText(postText);
                                        if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
-                                               postBuilder.to(Optional.of(postRecipientId));
+                                               postBuilder.to(of(postRecipientId));
                                        }
                                        posts.add(postBuilder.build(Optional.<PostCreated>absent()));
                                } catch (NumberFormatException nfe1) {
                                        /* TODO - mark Sone as bad. */
                                        logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with invalid time: %s", sone, postTime));
-                                       return null;
+                                       throw new MalformedTime();
                                }
                        }
                }
@@ -234,7 +240,7 @@ public class SoneParser {
                                if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
                                        /* TODO - mark Sone as bad. */
                                        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));
-                                       return null;
+                                       throw new MalformedXml();
                                }
                                try {
                                        /* TODO - parse time correctly. */
@@ -243,7 +249,7 @@ public class SoneParser {
                                } catch (NumberFormatException nfe1) {
                                        /* TODO - mark Sone as bad. */
                                        logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with invalid time: %s", sone, replyTime));
-                                       return null;
+                                       throw new MalformedTime();
                                }
                        }
                }
@@ -274,64 +280,6 @@ public class SoneParser {
                        }
                }
 
-               /* parse albums. */
-               SimpleXML albumsXml = soneXml.getNode("albums");
-               Map<String, Album> albums = Maps.newHashMap();
-               if (albumsXml != null) {
-                       for (SimpleXML albumXml : albumsXml.getNodes("album")) {
-                               String id = albumXml.getValue("id", null);
-                               String parentId = albumXml.getValue("parent", null);
-                               String title = albumXml.getValue("title", null);
-                               String description = albumXml.getValue("description", "");
-                               String albumImageId = albumXml.getValue("album-image", null);
-                               if ((id == null) || (title == null) || (description == null)) {
-                                       logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid album!", sone));
-                                       return null;
-                               }
-                               Album parent = sone.getRootAlbum();
-                               if (parentId != null) {
-                                       parent = albums.get(parentId);
-                                       if (parent == null) {
-                                               logger.log(Level.WARNING, String.format("Downloaded Sone %s has album with invalid parent!", sone));
-                                               return null;
-                                       }
-                               }
-                               Album album = parent.newAlbumBuilder().withId(id).build().modify().setTitle(title).setDescription(description).update();
-                               albums.put(album.getId(), album);
-                               SimpleXML imagesXml = albumXml.getNode("images");
-                               if (imagesXml != null) {
-                                       for (SimpleXML imageXml : imagesXml.getNodes("image")) {
-                                               String imageId = imageXml.getValue("id", null);
-                                               String imageCreationTimeString = imageXml.getValue("creation-time", null);
-                                               String imageKey = imageXml.getValue("key", null);
-                                               String imageTitle = imageXml.getValue("title", null);
-                                               String imageDescription = imageXml.getValue("description", "");
-                                               String imageWidthString = imageXml.getValue("width", null);
-                                               String imageHeightString = imageXml.getValue("height", null);
-                                               if ((imageId == null) || (imageCreationTimeString == null) || (imageKey == null) || (imageTitle == null) || (imageWidthString == null) || (imageHeightString == null)) {
-                                                       logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid images!", sone));
-                                                       return null;
-                                               }
-                                               long creationTime = Numbers.safeParseLong(imageCreationTimeString, 0L);
-                                               int imageWidth = Numbers.safeParseInteger(imageWidthString, 0);
-                                               int imageHeight = Numbers.safeParseInteger(imageHeightString, 0);
-                                               if ((imageWidth < 1) || (imageHeight < 1)) {
-                                                       logger.log(Level.WARNING, String.format("Downloaded Sone %s contains image %s with invalid dimensions (%s, %s)!", sone, imageId, imageWidthString, imageHeightString));
-                                                       return null;
-                                               }
-                                               Image image = album.newImageBuilder().withId(imageId).at(imageKey).created(creationTime).sized(imageWidth, imageHeight).build(Optional.<ImageCreated>absent());
-                                               image = image.modify().setTitle(imageTitle).setDescription(imageDescription).update();
-                                       }
-                               }
-                               album.modify().setAlbumImage(albumImageId).update();
-                       }
-               }
-
-               /* process avatar. */
-               if (avatarId != null) {
-                       profile.setAvatar(core.getImage(avatarId).orNull());
-               }
-
                /* okay, apparently everything was parsed correctly. Now import. */
                sone.setProfile(profile);
                sone.setPosts(posts);
@@ -341,4 +289,94 @@ public class SoneParser {
 
                return sone;
        }
+
+       private void parseTime(SimpleXML soneXml, Sone sone) {
+               String soneTime = soneXml.getValue("time", null);
+               if (soneTime == null) {
+                       /* TODO - mark Sone as bad. */
+                       logger.log(Level.WARNING, String.format("Downloaded time for Sone %s was null!", sone));
+                       throw new MalformedXml();
+               }
+               try {
+                       sone.setTime(Long.parseLong(soneTime));
+               } catch (NumberFormatException nfe1) {
+                       /* TODO - mark Sone as bad. */
+                       logger.log(Level.WARNING, String.format("Downloaded Sone %s with invalid time: %s", sone, soneTime));
+                       throw new MalformedTime();
+               }
+       }
+
+       private void verifyProtocolVersion(SimpleXML soneXml) {
+               Optional<Integer> protocolVersion = parseProtocolVersion(soneXml);
+               if (protocolVersion.isPresent()) {
+                       if (protocolVersion.get() < 0) {
+                               logger.log(Level.WARNING, String.format("Invalid protocol version: %d! Not parsing Sone.", protocolVersion.get()));
+                               throw new InvalidProtocolVersion();
+                       }
+                       if (protocolVersion.get() > MAX_PROTOCOL_VERSION) {
+                               logger.log(Level.WARNING, String.format("Unknown protocol version: %d! Not parsing Sone.", protocolVersion.get()));
+                               throw new SoneTooNew();
+                       }
+               }
+       }
+
+       private Optional<Integer> parseProtocolVersion(SimpleXML soneXml) {
+               String soneProtocolVersion = soneXml.getValue("protocol-version", null);
+               if (soneProtocolVersion == null) {
+                       logger.log(Level.INFO, "No protocol version found, assuming 0.");
+                       return absent();
+               }
+               return fromNullable(Ints.tryParse(soneProtocolVersion));
+       }
+
+       private Optional<Client> parseClient(Sone sone, SimpleXML soneXml) {
+               SimpleXML clientXml = soneXml.getNode("client");
+               if (clientXml == null) {
+                       return absent();
+               }
+               String clientName = clientXml.getValue("name", null);
+               String clientVersion = clientXml.getValue("version", null);
+               if ((clientName == null) || (clientVersion == null)) {
+                       logger.log(Level.WARNING, String.format("Download Sone %s with client XML but missing name or version!", sone));
+                       return absent();
+               }
+               return of(new Client(clientName, clientVersion));
+       }
+
+       public static class InvalidXml extends RuntimeException {
+
+       }
+
+       public static class InvalidProtocolVersion extends RuntimeException {
+
+       }
+
+       public static class SoneTooNew extends RuntimeException {
+
+       }
+
+       public static class MalformedXml extends RuntimeException {
+
+       }
+
+       public static class InvalidAvatarId extends RuntimeException {
+
+       }
+
+       public static class DuplicateField extends RuntimeException {
+
+       }
+
+       public static class MalformedTime extends RuntimeException {
+
+       }
+
+       public static class InvalidParentAlbum extends RuntimeException {
+
+       }
+
+       public static class MalformedDimension extends RuntimeException {
+
+       }
+
 }