Merge branch 'release-0.8.8' 0.8.8
authorDavid ‘Bombe’ Roden <bombe@pterodactylus.net>
Thu, 27 Feb 2014 20:38:22 +0000 (21:38 +0100)
committerDavid ‘Bombe’ Roden <bombe@pterodactylus.net>
Thu, 27 Feb 2014 20:38:22 +0000 (21:38 +0100)
43 files changed:
pom.xml
src/main/java/net/pterodactylus/sone/core/Core.java
src/main/java/net/pterodactylus/sone/core/SoneDownloader.java
src/main/java/net/pterodactylus/sone/core/UpdateChecker.java
src/main/java/net/pterodactylus/sone/data/Album.java
src/main/java/net/pterodactylus/sone/data/AlbumImpl.java [new file with mode: 0644]
src/main/java/net/pterodactylus/sone/data/Image.java
src/main/java/net/pterodactylus/sone/data/ImageImpl.java [new file with mode: 0644]
src/main/java/net/pterodactylus/sone/data/Sone.java
src/main/java/net/pterodactylus/sone/data/SoneImpl.java [new file with mode: 0644]
src/main/java/net/pterodactylus/sone/data/impl/AbstractAlbumBuilder.java [new file with mode: 0644]
src/main/java/net/pterodactylus/sone/data/impl/AbstractImageBuilder.java [new file with mode: 0644]
src/main/java/net/pterodactylus/sone/data/impl/AlbumBuilderImpl.java [new file with mode: 0644]
src/main/java/net/pterodactylus/sone/data/impl/ImageBuilderImpl.java [new file with mode: 0644]
src/main/java/net/pterodactylus/sone/database/AlbumBuilder.java [new file with mode: 0644]
src/main/java/net/pterodactylus/sone/database/AlbumBuilderFactory.java [new file with mode: 0644]
src/main/java/net/pterodactylus/sone/database/AlbumDatabase.java [new file with mode: 0644]
src/main/java/net/pterodactylus/sone/database/AlbumProvider.java [new file with mode: 0644]
src/main/java/net/pterodactylus/sone/database/AlbumStore.java [new file with mode: 0644]
src/main/java/net/pterodactylus/sone/database/Database.java
src/main/java/net/pterodactylus/sone/database/ImageBuilder.java [new file with mode: 0644]
src/main/java/net/pterodactylus/sone/database/ImageBuilderFactory.java [new file with mode: 0644]
src/main/java/net/pterodactylus/sone/database/ImageDatabase.java [new file with mode: 0644]
src/main/java/net/pterodactylus/sone/database/ImageProvider.java [new file with mode: 0644]
src/main/java/net/pterodactylus/sone/database/ImageStore.java [new file with mode: 0644]
src/main/java/net/pterodactylus/sone/database/memory/MemoryDatabase.java
src/main/java/net/pterodactylus/sone/main/SonePlugin.java
src/main/java/net/pterodactylus/sone/template/AlbumAccessor.java
src/main/java/net/pterodactylus/sone/template/SoneAccessor.java
src/main/java/net/pterodactylus/sone/text/SoneTextParser.java
src/main/java/net/pterodactylus/sone/web/CreateAlbumPage.java
src/main/java/net/pterodactylus/sone/web/EditAlbumPage.java
src/main/java/net/pterodactylus/sone/web/EditImagePage.java
src/main/java/net/pterodactylus/sone/web/EditProfilePage.java
src/main/java/net/pterodactylus/sone/web/UploadImagePage.java
src/main/java/net/pterodactylus/sone/web/ajax/EditAlbumAjaxPage.java
src/main/java/net/pterodactylus/sone/web/ajax/EditImageAjaxPage.java
src/main/resources/i18n/sone.fr.properties
src/main/resources/templates/include/soneMenu.html
src/main/resources/templates/include/viewPost.html
src/main/resources/templates/include/viewReply.html
src/test/java/net/pterodactylus/sone/database/memory/MemoryDatabaseTest.java [new file with mode: 0644]
src/test/java/net/pterodactylus/sone/text/SoneTextParserTest.java

diff --git a/pom.xml b/pom.xml
index f506a24..7286872 100644 (file)
--- a/pom.xml
+++ b/pom.xml
@@ -2,7 +2,7 @@
        <modelVersion>4.0.0</modelVersion>
        <groupId>net.pterodactylus</groupId>
        <artifactId>sone</artifactId>
-       <version>0.8.7</version>
+       <version>0.8.8</version>
        <dependencies>
                <dependency>
                        <groupId>net.pterodactylus</groupId>
@@ -87,6 +87,7 @@
                                <configuration>
                                        <source>1.6</source>
                                        <target>1.6</target>
+                                       <encoding>UTF-8</encoding>
                                </configuration>
                        </plugin>
                        <plugin>
index 5103b7d..ecb5857 100644 (file)
@@ -62,6 +62,7 @@ import net.pterodactylus.sone.data.Reply;
 import net.pterodactylus.sone.data.Sone;
 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
 import net.pterodactylus.sone.data.Sone.SoneStatus;
+import net.pterodactylus.sone.data.SoneImpl;
 import net.pterodactylus.sone.data.TemporaryImage;
 import net.pterodactylus.sone.database.Database;
 import net.pterodactylus.sone.database.DatabaseException;
@@ -187,12 +188,6 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
        /** Trusted identities, sorted by own identities. */
        private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
 
-       /** All known albums. */
-       private final Map<String, Album> albums = new HashMap<String, Album>();
-
-       /** All known images. */
-       private final Map<String, Image> images = new HashMap<String, Image>();
-
        /** All temporary images. */
        private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
 
@@ -384,11 +379,11 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                synchronized (sones) {
                        Sone sone = sones.get(id);
                        if ((sone == null) && create) {
-                               sone = new Sone(id, true);
+                               sone = new SoneImpl(id, true);
                                sones.put(id, sone);
                        }
                        if ((sone != null) && !sone.isLocal()) {
-                               sone = new Sone(id, true);
+                               sone = new SoneImpl(id, true);
                                sones.put(id, sone);
                        }
                        return sone;
@@ -425,7 +420,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                synchronized (sones) {
                        Sone sone = sones.get(id);
                        if ((sone == null) && create && (id != null) && (id.length() == 43)) {
-                               sone = new Sone(id, false);
+                               sone = new SoneImpl(id, false);
                                sones.put(id, sone);
                        }
                        return sone;
@@ -636,14 +631,16 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
         *         given ID exists and {@code create} is {@code false}
         */
        public Album getAlbum(String albumId, boolean create) {
-               synchronized (albums) {
-                       Album album = albums.get(albumId);
-                       if (create && (album == null)) {
-                               album = new Album(albumId);
-                               albums.put(albumId, album);
-                       }
-                       return album;
+               Optional<Album> album = database.getAlbum(albumId);
+               if (album.isPresent()) {
+                       return album.get();
                }
+               if (!create) {
+                       return null;
+               }
+               Album newAlbum = database.newAlbumBuilder().withId(albumId).build();
+               database.storeAlbum(newAlbum);
+               return newAlbum;
        }
 
        /**
@@ -670,14 +667,16 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
         *         none was created
         */
        public Image getImage(String imageId, boolean create) {
-               synchronized (images) {
-                       Image image = images.get(imageId);
-                       if (create && (image == null)) {
-                               image = new Image(imageId);
-                               images.put(imageId, image);
-                       }
-                       return image;
+               Optional<Image> image = database.getImage(imageId);
+               if (image.isPresent()) {
+                       return image.get();
                }
+               if (!create) {
+                       return null;
+               }
+               Image newImage = database.newImageBuilder().withId(imageId).build();
+               database.storeImage(newImage);
+               return newImage;
        }
 
        /**
@@ -1033,20 +1032,16 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                                }
                        }
                        database.storePostReplies(sone, sone.getReplies());
-                       synchronized (albums) {
-                               synchronized (images) {
-                                       for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
-                                               albums.remove(album.getId());
-                                               for (Image image : album.getImages()) {
-                                                       images.remove(image.getId());
-                                               }
-                                       }
-                                       for (Album album : sone.getRootAlbum().getAlbums()) {
-                                               albums.put(album.getId(), album);
-                                               for (Image image : album.getImages()) {
-                                                       images.put(image.getId(), image);
-                                               }
-                                       }
+                       for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
+                               database.removeAlbum(album);
+                               for (Image image : album.getImages()) {
+                                       database.removeImage(image);
+                               }
+                       }
+                       for (Album album : sone.getRootAlbum().getAlbums()) {
+                               database.storeAlbum(album);
+                               for (Image image : album.getImages()) {
+                                       database.storeImage(image);
                                }
                        }
                        synchronized (sones) {
@@ -1250,7 +1245,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                                logger.log(Level.WARNING, "Invalid album found, aborting load!");
                                return;
                        }
-                       Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
+                       Album album = getAlbum(albumId).setSone(sone).modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
                        if (albumParentId != null) {
                                Album parentAlbum = getAlbum(albumParentId, false);
                                if (parentAlbum == null) {
@@ -1289,8 +1284,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                                logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
                                return;
                        }
-                       Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
-                       image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
+                       Image image = getImage(imageId).modify().setSone(sone).setCreationTime(creationTime).setKey(key).setTitle(title).setDescription(description).setWidth(width).setHeight(height).update();
                        album.addImage(image);
                }
 
@@ -1603,10 +1597,8 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
         * @return The new album
         */
        public Album createAlbum(Sone sone, Album parent) {
-               Album album = new Album();
-               synchronized (albums) {
-                       albums.put(album.getId(), album);
-               }
+               Album album = database.newAlbumBuilder().randomId().build();
+               database.storeAlbum(album);
                album.setSone(sone);
                parent.addAlbum(album);
                return album;
@@ -1626,9 +1618,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                        return;
                }
                album.getParent().removeAlbum(album);
-               synchronized (albums) {
-                       albums.remove(album.getId());
-               }
+               database.removeAlbum(album);
                touchConfiguration();
        }
 
@@ -1649,11 +1639,9 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                checkNotNull(temporaryImage, "temporaryImage must not be null");
                checkArgument(sone.isLocal(), "sone must be a local Sone");
                checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
-               Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
+               Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
                album.addImage(image);
-               synchronized (images) {
-                       images.put(image.getId(), image);
-               }
+               database.storeImage(image);
                imageInserter.insertImage(temporaryImage, image);
                return image;
        }
@@ -1671,9 +1659,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
                deleteTemporaryImage(image.getId());
                image.getAlbum().removeImage(image);
-               synchronized (images) {
-                       images.remove(image.getId());
-               }
+               database.removeImage(image);
                touchConfiguration();
        }
 
@@ -1777,7 +1763,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                synchronized (sones) {
                        for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
                                soneInserter.getValue().stop();
-                               saveSone(soneInserter.getKey());
+                               saveSone(getLocalSone(soneInserter.getKey().getId(), false));
                        }
                }
                saveConfiguration();
@@ -2230,7 +2216,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
        @Subscribe
        public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
                logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
-               imageInsertFinishedEvent.image().setKey(imageInsertFinishedEvent.resultingUri().toString());
+               imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
                deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
                touchConfiguration();
        }
index 9af6328..53eef16 100644 (file)
@@ -35,6 +35,7 @@ import net.pterodactylus.sone.data.PostReply;
 import net.pterodactylus.sone.data.Profile;
 import net.pterodactylus.sone.data.Sone;
 import net.pterodactylus.sone.data.Sone.SoneStatus;
+import net.pterodactylus.sone.data.SoneImpl;
 import net.pterodactylus.sone.database.PostBuilder;
 import net.pterodactylus.sone.database.PostReplyBuilder;
 import net.pterodactylus.util.io.Closer;
@@ -239,7 +240,7 @@ public class SoneDownloader extends AbstractService {
                        return null;
                }
 
-               Sone sone = new Sone(originalSone.getId(), originalSone.isLocal()).setIdentity(originalSone.getIdentity());
+               Sone sone = new SoneImpl(originalSone.getId(), originalSone.isLocal()).setIdentity(originalSone.getIdentity());
 
                SimpleXML soneXml;
                try {
@@ -307,16 +308,8 @@ public class SoneDownloader extends AbstractService {
                        }
                }
 
-               String soneInsertUri = soneXml.getValue("insert-uri", null);
-               if ((soneInsertUri != null) && (sone.getInsertUri() == null)) {
-                       try {
-                               sone.setInsertUri(new FreenetURI(soneInsertUri));
-                               sone.setLatestEdition(Math.max(sone.getRequestUri().getEdition(), sone.getInsertUri().getEdition()));
-                       } catch (MalformedURLException mue1) {
-                               /* TODO - mark Sone as bad. */
-                               logger.log(Level.WARNING, String.format("Downloaded Sone %s has invalid insert URI: %s", sone, soneInsertUri), mue1);
-                               return null;
-                       }
+               if (originalSone.getInsertUri() != null) {
+                       sone.setInsertUri(originalSone.getInsertUri());
                }
 
                SimpleXML profileXml = soneXml.getNode("profile");
@@ -468,7 +461,7 @@ public class SoneDownloader extends AbstractService {
                                                return null;
                                        }
                                }
-                               Album album = core.getAlbum(id).setSone(sone).setTitle(title).setDescription(description);
+                               Album album = core.getAlbum(id).setSone(sone).modify().setTitle(title).setDescription(description).update();
                                if (parent != null) {
                                        parent.addAlbum(album);
                                } else {
@@ -495,13 +488,13 @@ public class SoneDownloader extends AbstractService {
                                                        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 = core.getImage(imageId).setSone(sone).setKey(imageKey).setCreationTime(creationTime);
-                                               image.setTitle(imageTitle).setDescription(imageDescription);
-                                               image.setWidth(imageWidth).setHeight(imageHeight);
+                                               Image image = core.getImage(imageId).modify().setSone(sone).setKey(imageKey).setCreationTime(creationTime).update();
+                                               image = image.modify().setTitle(imageTitle).setDescription(imageDescription).update();
+                                               image = image.modify().setWidth(imageWidth).setHeight(imageHeight).update();
                                                album.addImage(image);
                                        }
                                }
-                               album.setAlbumImage(albumImageId);
+                               album.modify().setAlbumImage(albumImageId).update();
                        }
                }
 
index e18c6d4..c9d07c3 100644 (file)
@@ -53,7 +53,7 @@ public class UpdateChecker {
        private static final String SONE_HOMEPAGE = "USK@nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI,DuQSUZiI~agF8c-6tjsFFGuZ8eICrzWCILB60nT8KKo,AQACAAE/sone/";
 
        /** The current latest known edition. */
-       private static final int LATEST_EDITION = 60;
+       private static final int LATEST_EDITION = 61;
 
        /** The event bus. */
        private final EventBus eventBus;
index 70478f3..09a7da4 100644 (file)
 
 package net.pterodactylus.sone.data;
 
-import static com.google.common.base.Preconditions.checkArgument;
-import static com.google.common.base.Preconditions.checkNotNull;
-import static com.google.common.base.Preconditions.checkState;
 import static java.util.Arrays.asList;
 import static java.util.Collections.emptyList;
 
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Comparator;
-import java.util.HashMap;
 import java.util.List;
-import java.util.Map;
-import java.util.UUID;
 import javax.annotation.Nonnull;
 
 import com.google.common.base.Function;
-import com.google.common.base.Optional;
 import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
-import com.google.common.collect.Collections2;
 import com.google.common.collect.FluentIterable;
 import com.google.common.collect.ImmutableList;
-import com.google.common.hash.Hasher;
-import com.google.common.hash.Hashing;
 
 /**
  * Container for images that can also contain nested {@link Album}s.
  *
  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
  */
-public class Album implements Identified, Fingerprintable {
+public interface Album extends Identified, Fingerprintable {
 
        /** Compares two {@link Album}s by {@link #getTitle()}. */
-       public static final Comparator<Album> TITLE_COMPARATOR = new Comparator<Album>() {
+       Comparator<Album> TITLE_COMPARATOR = new Comparator<Album>() {
 
                @Override
                public int compare(Album leftAlbum, Album rightAlbum) {
@@ -59,7 +48,7 @@ public class Album implements Identified, Fingerprintable {
        };
 
        /** Function that flattens the given album and all albums beneath it. */
-       public static final Function<Album, List<Album>> FLATTENER = new Function<Album, List<Album>>() {
+       Function<Album, List<Album>> FLATTENER = new Function<Album, List<Album>>() {
 
                @Override
                @Nonnull
@@ -77,7 +66,7 @@ public class Album implements Identified, Fingerprintable {
        };
 
        /** Function that transforms an album into the images it contains. */
-       public static final Function<Album, List<Image>> IMAGES = new Function<Album, List<Image>>() {
+       Function<Album, List<Image>> IMAGES = new Function<Album, List<Image>>() {
 
                @Override
                @Nonnull
@@ -90,7 +79,7 @@ public class Album implements Identified, Fingerprintable {
         * Filter that removes all albums that do not have any images in any album
         * below it.
         */
-       public static final Predicate<Album> NOT_EMPTY = new Predicate<Album>() {
+       Predicate<Album> NOT_EMPTY = new Predicate<Album>() {
 
                @Override
                public boolean apply(Album album) {
@@ -112,308 +101,134 @@ public class Album implements Identified, Fingerprintable {
                }
        };
 
-       /** The ID of this album. */
-       private final String id;
-
-       /** The Sone this album belongs to. */
-       private Sone sone;
-
-       /** Nested albums. */
-       private final List<Album> albums = new ArrayList<Album>();
-
-       /** The image IDs in order. */
-       private final List<String> imageIds = new ArrayList<String>();
-
-       /** The images in this album. */
-       private final Map<String, Image> images = new HashMap<String, Image>();
-
-       /** The parent album. */
-       private Album parent;
-
-       /** The title of this album. */
-       private String title;
-
-       /** The description of this album. */
-       private String description;
-
-       /** The ID of the album picture. */
-       private String albumImage;
-
-       /**
-        * Creates a new album with a random ID.
-        */
-       public Album() {
-               this(UUID.randomUUID().toString());
-       }
-
-       /**
-        * Creates a new album with the given ID.
-        *
-        * @param id
-        *            The ID of the album
-        */
-       public Album(String id) {
-               this.id = checkNotNull(id, "id must not be null");
-       }
-
-       //
-       // ACCESSORS
-       //
-
        /**
         * Returns the ID of this album.
         *
         * @return The ID of this album
         */
-       public String getId() {
-               return id;
-       }
+       String getId();
 
        /**
         * Returns the Sone this album belongs to.
         *
         * @return The Sone this album belongs to
         */
-       public Sone getSone() {
-               return sone;
-       }
+       Sone getSone();
 
        /**
         * Sets the owner of the album. The owner can only be set as long as the
         * current owner is {@code null}.
         *
         * @param sone
-        *            The album owner
+        *              The album owner
         * @return This album
         */
-       public Album setSone(Sone sone) {
-               checkNotNull(sone, "sone must not be null");
-               checkState((this.sone == null) || (this.sone.equals(sone)), "album owner must not already be set to some other Sone");
-               this.sone = sone;
-               return this;
-       }
+       Album setSone(Sone sone);
 
        /**
         * Returns the nested albums.
         *
         * @return The nested albums
         */
-       public List<Album> getAlbums() {
-               return new ArrayList<Album>(albums);
-       }
+       List<Album> getAlbums();
 
        /**
         * Adds an album to this album.
         *
         * @param album
-        *            The album to add
+        *              The album to add
         */
-       public void addAlbum(Album album) {
-               checkNotNull(album, "album must not be null");
-               checkArgument(album.getSone().equals(sone), "album must belong to the same Sone as this album");
-               album.setParent(this);
-               if (!albums.contains(album)) {
-                       albums.add(album);
-               }
-       }
+       void addAlbum(Album album);
 
        /**
         * Removes an album from this album.
         *
         * @param album
-        *            The album to remove
+        *              The album to remove
         */
-       public void removeAlbum(Album album) {
-               checkNotNull(album, "album must not be null");
-               checkArgument(album.sone.equals(sone), "album must belong this album’s Sone");
-               checkArgument(equals(album.parent), "album must belong to this album");
-               albums.remove(album);
-               album.removeParent();
-       }
+       void removeAlbum(Album album);
 
        /**
-        * Moves the given album up in this album’s albums. If the album is already
-        * the first album, nothing happens.
+        * Moves the given album up in this album’s albums. If the album is already the
+        * first album, nothing happens.
         *
         * @param album
-        *            The album to move up
+        *              The album to move up
         * @return The album that the given album swapped the place with, or
         *         <code>null</code> if the album did not change its place
         */
-       public Album moveAlbumUp(Album album) {
-               checkNotNull(album, "album must not be null");
-               checkArgument(album.sone.equals(sone), "album must belong to the same Sone as this album");
-               checkArgument(equals(album.parent), "album must belong to this album");
-               int oldIndex = albums.indexOf(album);
-               if (oldIndex <= 0) {
-                       return null;
-               }
-               albums.remove(oldIndex);
-               albums.add(oldIndex - 1, album);
-               return albums.get(oldIndex);
-       }
+       Album moveAlbumUp(Album album);
 
        /**
-        * Moves the given album down in this album’s albums. If the album is
-        * already the last album, nothing happens.
+        * Moves the given album down in this album’s albums. If the album is already
+        * the last album, nothing happens.
         *
         * @param album
-        *            The album to move down
+        *              The album to move down
         * @return The album that the given album swapped the place with, or
         *         <code>null</code> if the album did not change its place
         */
-       public Album moveAlbumDown(Album album) {
-               checkNotNull(album, "album must not be null");
-               checkArgument(album.sone.equals(sone), "album must belong to the same Sone as this album");
-               checkArgument(equals(album.parent), "album must belong to this album");
-               int oldIndex = albums.indexOf(album);
-               if ((oldIndex < 0) || (oldIndex >= (albums.size() - 1))) {
-                       return null;
-               }
-               albums.remove(oldIndex);
-               albums.add(oldIndex + 1, album);
-               return albums.get(oldIndex);
-       }
+       Album moveAlbumDown(Album album);
 
        /**
         * Returns the images in this album.
         *
         * @return The images in this album
         */
-       public List<Image> getImages() {
-               return new ArrayList<Image>(Collections2.filter(Collections2.transform(imageIds, new Function<String, Image>() {
-
-                       @Override
-                       @SuppressWarnings("synthetic-access")
-                       public Image apply(String imageId) {
-                               return images.get(imageId);
-                       }
-               }), Predicates.notNull()));
-       }
+       List<Image> getImages();
 
        /**
         * Adds the given image to this album.
         *
         * @param image
-        *            The image to add
+        *              The image to add
         */
-       public void addImage(Image image) {
-               checkNotNull(image, "image must not be null");
-               checkNotNull(image.getSone(), "image must have an owner");
-               checkArgument(image.getSone().equals(sone), "image must belong to the same Sone as this album");
-               if (image.getAlbum() != null) {
-                       image.getAlbum().removeImage(image);
-               }
-               image.setAlbum(this);
-               if (imageIds.isEmpty() && (albumImage == null)) {
-                       albumImage = image.getId();
-               }
-               if (!imageIds.contains(image.getId())) {
-                       imageIds.add(image.getId());
-                       images.put(image.getId(), image);
-               }
-       }
+       void addImage(Image image);
 
        /**
         * Removes the given image from this album.
         *
         * @param image
-        *            The image to remove
+        *              The image to remove
         */
-       public void removeImage(Image image) {
-               checkNotNull(image, "image must not be null");
-               checkNotNull(image.getSone(), "image must have an owner");
-               checkArgument(image.getSone().equals(sone), "image must belong to the same Sone as this album");
-               imageIds.remove(image.getId());
-               images.remove(image.getId());
-               if (image.getId().equals(albumImage)) {
-                       if (images.isEmpty()) {
-                               albumImage = null;
-                       } else {
-                               albumImage = images.values().iterator().next().getId();
-                       }
-               }
-       }
+       void removeImage(Image image);
 
        /**
-        * Moves the given image up in this album’s images. If the image is already
-        * the first image, nothing happens.
+        * Moves the given image up in this album’s images. If the image is already the
+        * first image, nothing happens.
         *
         * @param image
-        *            The image to move up
+        *              The image to move up
         * @return The image that the given image swapped the place with, or
         *         <code>null</code> if the image did not change its place
         */
-       public Image moveImageUp(Image image) {
-               checkNotNull(image, "image must not be null");
-               checkNotNull(image.getSone(), "image must have an owner");
-               checkArgument(image.getSone().equals(sone), "image must belong to the same Sone as this album");
-               checkArgument(image.getAlbum().equals(this), "image must belong to this album");
-               int oldIndex = imageIds.indexOf(image.getId());
-               if (oldIndex <= 0) {
-                       return null;
-               }
-               imageIds.remove(image.getId());
-               imageIds.add(oldIndex - 1, image.getId());
-               return images.get(imageIds.get(oldIndex));
-       }
+       Image moveImageUp(Image image);
 
        /**
-        * Moves the given image down in this album’s images. If the image is
-        * already the last image, nothing happens.
+        * Moves the given image down in this album’s images. If the image is already
+        * the last image, nothing happens.
         *
         * @param image
-        *            The image to move down
+        *              The image to move down
         * @return The image that the given image swapped the place with, or
         *         <code>null</code> if the image did not change its place
         */
-       public Image moveImageDown(Image image) {
-               checkNotNull(image, "image must not be null");
-               checkNotNull(image.getSone(), "image must have an owner");
-               checkArgument(image.getSone().equals(sone), "image must belong to the same Sone as this album");
-               checkArgument(image.getAlbum().equals(this), "image must belong to this album");
-               int oldIndex = imageIds.indexOf(image.getId());
-               if ((oldIndex == -1) || (oldIndex >= (imageIds.size() - 1))) {
-                       return null;
-               }
-               imageIds.remove(image.getId());
-               imageIds.add(oldIndex + 1, image.getId());
-               return images.get(imageIds.get(oldIndex));
-       }
+       Image moveImageDown(Image image);
 
        /**
-        * Returns the album image of this album, or {@code null} if no album image
-        * has been set.
+        * Returns the album image of this album, or {@code null} if no album image has
+        * been set.
         *
         * @return The image to show when this album is listed
         */
-       public Image getAlbumImage() {
-               if (albumImage == null) {
-                       return null;
-               }
-               return Optional.fromNullable(images.get(albumImage)).or(images.values().iterator().next());
-       }
-
-       /**
-        * Sets the ID of the album image.
-        *
-        * @param id
-        *            The ID of the album image
-        * @return This album
-        */
-       public Album setAlbumImage(String id) {
-               this.albumImage = id;
-               return this;
-       }
+       Image getAlbumImage();
 
        /**
         * Returns whether this album contains any other albums or images.
         *
         * @return {@code true} if this album is empty, {@code false} otherwise
         */
-       public boolean isEmpty() {
-               return albums.isEmpty() && images.isEmpty();
-       }
+       boolean isEmpty();
 
        /**
         * Returns whether this album is an identitiy’s root album.
@@ -421,144 +236,72 @@ public class Album implements Identified, Fingerprintable {
         * @return {@code true} if this album is an identity’s root album, {@code
         *         false} otherwise
         */
-       public boolean isRoot() {
-               return parent == null;
-       }
+       boolean isRoot();
 
        /**
         * Returns the parent album of this album.
         *
-        * @return The parent album of this album, or {@code null} if this album
-        *         does not have a parent
+        * @return The parent album of this album, or {@code null} if this album does
+        *         not have a parent
         */
-       public Album getParent() {
-               return parent;
-       }
+       Album getParent();
 
        /**
         * Sets the parent album of this album.
         *
         * @param parent
-        *            The new parent album of this album
+        *              The new parent album of this album
         * @return This album
         */
-       protected Album setParent(Album parent) {
-               this.parent = checkNotNull(parent, "parent must not be null");
-               return this;
-       }
+       Album setParent(Album parent);
 
        /**
         * Removes the parent album of this album.
         *
         * @return This album
         */
-       protected Album removeParent() {
-               this.parent = null;
-               return this;
-       }
+       Album removeParent();
 
        /**
         * Returns the title of this album.
         *
         * @return The title of this album
         */
-       public String getTitle() {
-               return title;
-       }
-
-       /**
-        * Sets the title of this album.
-        *
-        * @param title
-        *            The title of this album
-        * @return This album
-        */
-       public Album setTitle(String title) {
-               this.title = checkNotNull(title, "title must not be null");
-               return this;
-       }
+       String getTitle();
 
        /**
         * Returns the description of this album.
         *
         * @return The description of this album
         */
-       public String getDescription() {
-               return description;
-       }
+       String getDescription();
 
        /**
-        * Sets the description of this album.
+        * Returns a modifier for this album.
         *
-        * @param description
-        *            The description of this album
-        * @return This album
+        * @return A modifier for this album
+        * @throws IllegalStateException
+        *              if this album can not be modified
         */
-       public Album setDescription(String description) {
-               this.description = checkNotNull(description, "description must not be null");
-               return this;
-       }
-
-       //
-       // FINGERPRINTABLE METHODS
-       //
+       Modifier modify() throws IllegalStateException;
 
        /**
-        * {@inheritDoc}
+        * Allows modifying an album. Modifications are only performed once {@link
+        * #update()} has succesfully returned a new album with the modifications
+        * made.
+        *
+        * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
         */
-       @Override
-       public String getFingerprint() {
-               Hasher hash = Hashing.sha256().newHasher();
-               hash.putString("Album(");
-               hash.putString("ID(").putString(id).putString(")");
-               hash.putString("Title(").putString(title).putString(")");
-               hash.putString("Description(").putString(description).putString(")");
-               if (albumImage != null) {
-                       hash.putString("AlbumImage(").putString(albumImage).putString(")");
-               }
-
-               /* add nested albums. */
-               hash.putString("Albums(");
-               for (Album album : albums) {
-                       hash.putString(album.getFingerprint());
-               }
-               hash.putString(")");
+       interface Modifier {
 
-               /* add images. */
-               hash.putString("Images(");
-               for (Image image : getImages()) {
-                       if (image.isInserted()) {
-                               hash.putString(image.getFingerprint());
-                       }
-               }
-               hash.putString(")");
+               Modifier setTitle(String title);
 
-               hash.putString(")");
-               return hash.hash().toString();
-       }
+               Modifier setDescription(String description);
 
-       //
-       // OBJECT METHODS
-       //
+               Modifier setAlbumImage(String imageId);
 
-       /**
-        * {@inheritDoc}
-        */
-       @Override
-       public int hashCode() {
-               return id.hashCode();
-       }
+               Album update() throws IllegalStateException;
 
-       /**
-        * {@inheritDoc}
-        */
-       @Override
-       public boolean equals(Object object) {
-               if (!(object instanceof Album)) {
-                       return false;
-               }
-               Album album = (Album) object;
-               return id.equals(album.id);
        }
 
 }
diff --git a/src/main/java/net/pterodactylus/sone/data/AlbumImpl.java b/src/main/java/net/pterodactylus/sone/data/AlbumImpl.java
new file mode 100644 (file)
index 0000000..f489b0b
--- /dev/null
@@ -0,0 +1,380 @@
+/*
+ * Sone - Album.java - Copyright © 2011–2013 David Roden
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package net.pterodactylus.sone.data;
+
+import static com.google.common.base.Optional.absent;
+import static com.google.common.base.Optional.fromNullable;
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkNotNull;
+import static com.google.common.base.Preconditions.checkState;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+import com.google.common.base.Function;
+import com.google.common.base.Optional;
+import com.google.common.base.Predicates;
+import com.google.common.collect.Collections2;
+import com.google.common.hash.Hasher;
+import com.google.common.hash.Hashing;
+
+/**
+ * Container for images that can also contain nested {@link AlbumImpl}s.
+ *
+ * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+ */
+public class AlbumImpl implements Album {
+
+       /** The ID of this album. */
+       private final String id;
+
+       /** The Sone this album belongs to. */
+       private Sone sone;
+
+       /** Nested albums. */
+       private final List<Album> albums = new ArrayList<Album>();
+
+       /** The image IDs in order. */
+       private final List<String> imageIds = new ArrayList<String>();
+
+       /** The images in this album. */
+       private final Map<String, Image> images = new HashMap<String, Image>();
+
+       /** The parent album. */
+       private Album parent;
+
+       /** The title of this album. */
+       private String title;
+
+       /** The description of this album. */
+       private String description;
+
+       /** The ID of the album picture. */
+       private String albumImage;
+
+       /** Creates a new album with a random ID. */
+       public AlbumImpl() {
+               this(UUID.randomUUID().toString());
+       }
+
+       /**
+        * Creates a new album with the given ID.
+        *
+        * @param id
+        *              The ID of the album
+        */
+       public AlbumImpl(String id) {
+               this.id = checkNotNull(id, "id must not be null");
+       }
+
+       //
+       // ACCESSORS
+       //
+
+       @Override
+       public String getId() {
+               return id;
+       }
+
+       @Override
+       public Sone getSone() {
+               return sone;
+       }
+
+       @Override
+       public Album setSone(Sone sone) {
+               checkNotNull(sone, "sone must not be null");
+               checkState((this.sone == null) || (this.sone.equals(sone)), "album owner must not already be set to some other Sone");
+               this.sone = sone;
+               return this;
+       }
+
+       @Override
+       public List<Album> getAlbums() {
+               return new ArrayList<Album>(albums);
+       }
+
+       @Override
+       public void addAlbum(Album album) {
+               checkNotNull(album, "album must not be null");
+               checkArgument(album.getSone().equals(sone), "album must belong to the same Sone as this album");
+               album.setParent(this);
+               if (!albums.contains(album)) {
+                       albums.add(album);
+               }
+       }
+
+       @Override
+       public void removeAlbum(Album album) {
+               checkNotNull(album, "album must not be null");
+               checkArgument(album.getSone().equals(sone), "album must belong this album’s Sone");
+               checkArgument(equals(album.getParent()), "album must belong to this album");
+               albums.remove(album);
+               album.removeParent();
+       }
+
+       @Override
+       public Album moveAlbumUp(Album album) {
+               checkNotNull(album, "album must not be null");
+               checkArgument(album.getSone().equals(sone), "album must belong to the same Sone as this album");
+               checkArgument(equals(album.getParent()), "album must belong to this album");
+               int oldIndex = albums.indexOf(album);
+               if (oldIndex <= 0) {
+                       return null;
+               }
+               albums.remove(oldIndex);
+               albums.add(oldIndex - 1, album);
+               return albums.get(oldIndex);
+       }
+
+       @Override
+       public Album moveAlbumDown(Album album) {
+               checkNotNull(album, "album must not be null");
+               checkArgument(album.getSone().equals(sone), "album must belong to the same Sone as this album");
+               checkArgument(equals(album.getParent()), "album must belong to this album");
+               int oldIndex = albums.indexOf(album);
+               if ((oldIndex < 0) || (oldIndex >= (albums.size() - 1))) {
+                       return null;
+               }
+               albums.remove(oldIndex);
+               albums.add(oldIndex + 1, album);
+               return albums.get(oldIndex);
+       }
+
+       @Override
+       public List<Image> getImages() {
+               return new ArrayList<Image>(Collections2.filter(Collections2.transform(imageIds, new Function<String, Image>() {
+
+                       @Override
+                       @SuppressWarnings("synthetic-access")
+                       public Image apply(String imageId) {
+                               return images.get(imageId);
+                       }
+               }), Predicates.notNull()));
+       }
+
+       @Override
+       public void addImage(Image image) {
+               checkNotNull(image, "image must not be null");
+               checkNotNull(image.getSone(), "image must have an owner");
+               checkArgument(image.getSone().equals(sone), "image must belong to the same Sone as this album");
+               if (image.getAlbum() != null) {
+                       image.getAlbum().removeImage(image);
+               }
+               image.setAlbum(this);
+               if (imageIds.isEmpty() && (albumImage == null)) {
+                       albumImage = image.getId();
+               }
+               if (!imageIds.contains(image.getId())) {
+                       imageIds.add(image.getId());
+                       images.put(image.getId(), image);
+               }
+       }
+
+       @Override
+       public void removeImage(Image image) {
+               checkNotNull(image, "image must not be null");
+               checkNotNull(image.getSone(), "image must have an owner");
+               checkArgument(image.getSone().equals(sone), "image must belong to the same Sone as this album");
+               imageIds.remove(image.getId());
+               images.remove(image.getId());
+               if (image.getId().equals(albumImage)) {
+                       if (images.isEmpty()) {
+                               albumImage = null;
+                       } else {
+                               albumImage = images.values().iterator().next().getId();
+                       }
+               }
+       }
+
+       @Override
+       public Image moveImageUp(Image image) {
+               checkNotNull(image, "image must not be null");
+               checkNotNull(image.getSone(), "image must have an owner");
+               checkArgument(image.getSone().equals(sone), "image must belong to the same Sone as this album");
+               checkArgument(image.getAlbum().equals(this), "image must belong to this album");
+               int oldIndex = imageIds.indexOf(image.getId());
+               if (oldIndex <= 0) {
+                       return null;
+               }
+               imageIds.remove(image.getId());
+               imageIds.add(oldIndex - 1, image.getId());
+               return images.get(imageIds.get(oldIndex));
+       }
+
+       @Override
+       public Image moveImageDown(Image image) {
+               checkNotNull(image, "image must not be null");
+               checkNotNull(image.getSone(), "image must have an owner");
+               checkArgument(image.getSone().equals(sone), "image must belong to the same Sone as this album");
+               checkArgument(image.getAlbum().equals(this), "image must belong to this album");
+               int oldIndex = imageIds.indexOf(image.getId());
+               if ((oldIndex == -1) || (oldIndex >= (imageIds.size() - 1))) {
+                       return null;
+               }
+               imageIds.remove(image.getId());
+               imageIds.add(oldIndex + 1, image.getId());
+               return images.get(imageIds.get(oldIndex));
+       }
+
+       @Override
+       public Image getAlbumImage() {
+               if (albumImage == null) {
+                       return null;
+               }
+               return Optional.fromNullable(images.get(albumImage)).or(images.values().iterator().next());
+       }
+
+       @Override
+       public boolean isEmpty() {
+               return albums.isEmpty() && images.isEmpty();
+       }
+
+       @Override
+       public boolean isRoot() {
+               return parent == null;
+       }
+
+       @Override
+       public Album getParent() {
+               return parent;
+       }
+
+       @Override
+       public Album setParent(Album parent) {
+               this.parent = checkNotNull(parent, "parent must not be null");
+               return this;
+       }
+
+       @Override
+       public Album removeParent() {
+               this.parent = null;
+               return this;
+       }
+
+       @Override
+       public String getTitle() {
+               return title;
+       }
+
+       @Override
+       public String getDescription() {
+               return description;
+       }
+
+       @Override
+       public Modifier modify() throws IllegalStateException {
+               // TODO: reenable check for local Sones
+               return new Modifier() {
+                       private Optional<String> title = absent();
+
+                       private Optional<String> description = absent();
+
+                       private Optional<String> albumImage = absent();
+
+                       @Override
+                       public Modifier setTitle(String title) {
+                               this.title = fromNullable(title);
+                               return this;
+                       }
+
+                       @Override
+                       public Modifier setDescription(String description) {
+                               this.description = fromNullable(description);
+                               return this;
+                       }
+
+                       @Override
+                       public Modifier setAlbumImage(String imageId) {
+                               this.albumImage = fromNullable(imageId);
+                               return this;
+                       }
+
+                       @Override
+                       public Album update() throws IllegalStateException {
+                               if (title.isPresent()) {
+                                       AlbumImpl.this.title = title.get();
+                               }
+                               if (description.isPresent()) {
+                                       AlbumImpl.this.description = description.get();
+                               }
+                               if (albumImage.isPresent()) {
+                                       AlbumImpl.this.albumImage = albumImage.get();
+                               }
+                               return AlbumImpl.this;
+                       }
+               };
+       }
+
+       //
+       // FINGERPRINTABLE METHODS
+       //
+
+       @Override
+       public String getFingerprint() {
+               Hasher hash = Hashing.sha256().newHasher();
+               hash.putString("Album(");
+               hash.putString("ID(").putString(id).putString(")");
+               hash.putString("Title(").putString(title).putString(")");
+               hash.putString("Description(").putString(description).putString(")");
+               if (albumImage != null) {
+                       hash.putString("AlbumImage(").putString(albumImage).putString(")");
+               }
+
+               /* add nested albums. */
+               hash.putString("Albums(");
+               for (Album album : albums) {
+                       hash.putString(album.getFingerprint());
+               }
+               hash.putString(")");
+
+               /* add images. */
+               hash.putString("Images(");
+               for (Image image : getImages()) {
+                       if (image.isInserted()) {
+                               hash.putString(image.getFingerprint());
+                       }
+               }
+               hash.putString(")");
+
+               hash.putString(")");
+               return hash.hash().toString();
+       }
+
+       //
+       // OBJECT METHODS
+       //
+
+       @Override
+       public int hashCode() {
+               return id.hashCode();
+       }
+
+       @Override
+       public boolean equals(Object object) {
+               if (!(object instanceof AlbumImpl)) {
+                       return false;
+               }
+               AlbumImpl album = (AlbumImpl) object;
+               return id.equals(album.id);
+       }
+
+}
index d8a8ab1..e3e1b4d 100644 (file)
 
 package net.pterodactylus.sone.data;
 
-import static com.google.common.base.Preconditions.checkArgument;
-import static com.google.common.base.Preconditions.checkNotNull;
-import static com.google.common.base.Preconditions.checkState;
-
-import java.util.UUID;
-
-import com.google.common.hash.Hasher;
-import com.google.common.hash.Hashing;
-
 /**
  * Container for image metadata.
  *
- * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+ * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
  */
-public class Image implements Identified, Fingerprintable {
-
-       /** The ID of the image. */
-       private final String id;
-
-       /** The Sone the image belongs to. */
-       private Sone sone;
-
-       /** The album this image belongs to. */
-       private Album album;
-
-       /** The request key of the image. */
-       private String key;
-
-       /** The creation time of the image. */
-       private long creationTime;
-
-       /** The width of the image. */
-       private int width;
-
-       /** The height of the image. */
-       private int height;
-
-       /** The title of the image. */
-       private String title;
-
-       /** The description of the image. */
-       private String description;
-
-       /**
-        * Creates a new image with a random ID.
-        */
-       public Image() {
-               this(UUID.randomUUID().toString());
-               setCreationTime(System.currentTimeMillis());
-       }
-
-       /**
-        * Creates a new image.
-        *
-        * @param id
-        *            The ID of the image
-        */
-       public Image(String id) {
-               this.id = checkNotNull(id, "id must not be null");
-       }
-
-       //
-       // ACCESSORS
-       //
+public interface Image extends Identified, Fingerprintable {
 
        /**
         * Returns the ID of this image.
         *
         * @return The ID of this image
         */
-       public String getId() {
-               return id;
-       }
+       String getId();
 
        /**
         * Returns the Sone this image belongs to.
         *
         * @return The Sone this image belongs to
         */
-       public Sone getSone() {
-               return sone;
-       }
-
-       /**
-        * Sets the owner of this image. The owner can only be set if no owner has
-        * yet been set.
-        *
-        * @param sone
-        *            The new owner of this image
-        * @return This image
-        */
-       public Image setSone(Sone sone) {
-               checkNotNull(sone, "sone must not be null");
-               checkArgument((this.sone == null) || this.sone.equals(sone), "sone must not already be set to another sone");
-               this.sone = sone;
-               return this;
-       }
+       Sone getSone();
 
        /**
         * Returns the album this image belongs to.
         *
         * @return The album this image belongs to
         */
-       public Album getAlbum() {
-               return album;
-       }
+       Album getAlbum();
 
        /**
         * Sets the album this image belongs to. The album of an image can only be
@@ -132,36 +53,14 @@ public class Image implements Identified, Fingerprintable {
         *            The album this image belongs to
         * @return This image
         */
-       public Image setAlbum(Album album) {
-               checkNotNull(album, "album must not be null");
-               checkNotNull(album.getSone().equals(getSone()), "album must belong to the same Sone as this image");
-               this.album = album;
-               return this;
-       }
+       Image setAlbum(Album album);
 
        /**
         * Returns the request key of this image.
         *
         * @return The request key of this image
         */
-       public String getKey() {
-               return key;
-       }
-
-       /**
-        * Sets the request key of this image. The request key can only be set as
-        * long as no request key has yet been set.
-        *
-        * @param key
-        *            The new request key of this image
-        * @return This image
-        */
-       public Image setKey(String key) {
-               checkNotNull(key, "key must not be null");
-               checkState((this.key == null) || this.key.equals(key), "key must not be already set to another key");
-               this.key = key;
-               return this;
-       }
+       String getKey();
 
        /**
         * Returns whether the image has already been inserted. An image is
@@ -171,9 +70,7 @@ public class Image implements Identified, Fingerprintable {
         * @return {@code true} if there is a key for this image, {@code false}
         *         otherwise
         */
-       public boolean isInserted() {
-               return key != null;
-       }
+       boolean isInserted();
 
        /**
         * Returns the creation time of this image.
@@ -181,154 +78,62 @@ public class Image implements Identified, Fingerprintable {
         * @return The creation time of this image (in milliseconds since 1970, Jan
         *         1, UTC)
         */
-       public long getCreationTime() {
-               return creationTime;
-       }
-
-       /**
-        * Sets the new creation time of this image. The creation time can only be
-        * set as long as no creation time has been set yet.
-        *
-        * @param creationTime
-        *            The new creation time of this image
-        * @return This image
-        */
-       public Image setCreationTime(long creationTime) {
-               checkArgument(creationTime > 0, "creationTime must be > 0");
-               checkState((this.creationTime == 0) || (this.creationTime == creationTime), "creationTime must not already be set");
-               this.creationTime = creationTime;
-               return this;
-       }
+       long getCreationTime();
 
        /**
         * Returns the width of this image.
         *
         * @return The width of this image (in pixels)
         */
-       public int getWidth() {
-               return width;
-       }
-
-       /**
-        * Sets the width of this image. The width can only be set as long as no
-        * width has been set yet.
-        *
-        * @param width
-        *            The new width of this image
-        * @return This image
-        */
-       public Image setWidth(int width) {
-               checkArgument(width > 0, "width must be > 0");
-               checkState((this.width == 0) || (this.width == width), "width must not already be set to another width");
-               this.width = width;
-               return this;
-       }
+       int getWidth();
 
        /**
         * Returns the height of this image.
         *
         * @return The height of this image (in pixels)
         */
-       public int getHeight() {
-               return height;
-       }
-
-       /**
-        * Sets the new height of this image. The height can only be set as long as
-        * no height has yet been set.
-        *
-        * @param height
-        *            The new height of this image
-        * @return This image
-        */
-       public Image setHeight(int height) {
-               checkArgument(height > 0, "height must be > 0");
-               checkState((this.height == 0) || (this.height == height), "height must not already be set to another height");
-               this.height = height;
-               return this;
-       }
+       int getHeight();
 
        /**
         * Returns the title of this image.
         *
         * @return The title of this image
         */
-       public String getTitle() {
-               return title;
-       }
-
-       /**
-        * Sets the title of this image.
-        *
-        * @param title
-        *            The title of this image
-        * @return This image
-        */
-       public Image setTitle(String title) {
-               this.title = checkNotNull(title, "title must not be null");
-               return this;
-       }
+       String getTitle();
 
        /**
         * Returns the description of this image.
         *
         * @return The description of this image
         */
-       public String getDescription() {
-               return description;
-       }
-
-       /**
-        * Sets the description of this image.
-        *
-        * @param description
-        *            The description of this image
-        * @return This image
-        */
-       public Image setDescription(String description) {
-               this.description = checkNotNull(description, "description must not be null");
-               return this;
-       }
-
-       //
-       // FINGERPRINTABLE METHODS
-       //
+       String getDescription();
 
        /**
         * {@inheritDoc}
         */
        @Override
-       public String getFingerprint() {
-               Hasher hash = Hashing.sha256().newHasher();
-               hash.putString("Image(");
-               hash.putString("ID(").putString(id).putString(")");
-               hash.putString("Title(").putString(title).putString(")");
-               hash.putString("Description(").putString(description).putString(")");
-               hash.putString(")");
-               return hash.hash().toString();
-       }
+       String getFingerprint();
 
-       //
-       // OBJECT METHODS
-       //
+       Modifier modify() throws IllegalStateException;
 
-       /**
-        * {@inheritDoc}
-        */
-       @Override
-       public int hashCode() {
-               return id.hashCode();
-       }
+       interface Modifier {
+
+               Modifier setSone(Sone sone);
+
+               Modifier setCreationTime(long creationTime);
+
+               Modifier setKey(String key);
+
+               Modifier setTitle(String title);
+
+               Modifier setDescription(String description);
+
+               Modifier setWidth(int width);
+
+               Modifier setHeight(int height);
+
+               Image update() throws IllegalStateException;
 
-       /**
-        * {@inheritDoc}
-        */
-       @Override
-       public boolean equals(Object object) {
-               if (!(object instanceof Image)) {
-                       return false;
-               }
-               return ((Image) object).id.equals(id);
        }
 
 }
diff --git a/src/main/java/net/pterodactylus/sone/data/ImageImpl.java b/src/main/java/net/pterodactylus/sone/data/ImageImpl.java
new file mode 100644 (file)
index 0000000..447bb82
--- /dev/null
@@ -0,0 +1,271 @@
+/*
+ * Sone - ImageImpl.java - Copyright © 2011–2013 David Roden
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+package net.pterodactylus.sone.data;
+
+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 static com.google.common.base.Preconditions.checkNotNull;
+import static com.google.common.base.Preconditions.checkState;
+
+import java.util.UUID;
+
+import com.google.common.base.Optional;
+import com.google.common.hash.Hasher;
+import com.google.common.hash.Hashing;
+
+/**
+ * Container for image metadata.
+ *
+ * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+ */
+public class ImageImpl implements Image {
+
+       /** The ID of the image. */
+       private final String id;
+
+       /** The Sone the image belongs to. */
+       private Sone sone;
+
+       /** The album this image belongs to. */
+       private Album album;
+
+       /** The request key of the image. */
+       private String key;
+
+       /** The creation time of the image. */
+       private long creationTime;
+
+       /** The width of the image. */
+       private int width;
+
+       /** The height of the image. */
+       private int height;
+
+       /** The title of the image. */
+       private String title;
+
+       /** The description of the image. */
+       private String description;
+
+       /** Creates a new image with a random ID. */
+       public ImageImpl() {
+               this(UUID.randomUUID().toString());
+               this.creationTime = System.currentTimeMillis();
+       }
+
+       /**
+        * Creates a new image.
+        *
+        * @param id
+        *              The ID of the image
+        */
+       public ImageImpl(String id) {
+               this.id = checkNotNull(id, "id must not be null");
+       }
+
+       //
+       // ACCESSORS
+       //
+
+       @Override
+       public String getId() {
+               return id;
+       }
+
+       @Override
+       public Sone getSone() {
+               return sone;
+       }
+
+       @Override
+       public Album getAlbum() {
+               return album;
+       }
+
+       @Override
+       public Image setAlbum(Album album) {
+               checkNotNull(album, "album must not be null");
+               checkNotNull(album.getSone().equals(getSone()), "album must belong to the same Sone as this image");
+               this.album = album;
+               return this;
+       }
+
+       @Override
+       public String getKey() {
+               return key;
+       }
+
+       @Override
+       public boolean isInserted() {
+               return key != null;
+       }
+
+       @Override
+       public long getCreationTime() {
+               return creationTime;
+       }
+
+       @Override
+       public int getWidth() {
+               return width;
+       }
+
+       @Override
+       public int getHeight() {
+               return height;
+       }
+
+       @Override
+       public String getTitle() {
+               return title;
+       }
+
+       @Override
+       public String getDescription() {
+               return description;
+       }
+
+       public Modifier modify() throws IllegalStateException {
+               // TODO: reenable check for local images
+               return new Modifier() {
+                       private Optional<Sone> sone = absent();
+
+                       private Optional<Long> creationTime = absent();
+
+                       private Optional<String> key = absent();
+
+                       private Optional<String> title = absent();
+
+                       private Optional<String> description = absent();
+
+                       private Optional<Integer> width = absent();
+
+                       private Optional<Integer> height = absent();
+
+                       @Override
+                       public Modifier setSone(Sone sone) {
+                               this.sone = fromNullable(sone);
+                               return this;
+                       }
+
+                       @Override
+                       public Modifier setCreationTime(long creationTime) {
+                               this.creationTime = of(creationTime);
+                               return this;
+                       }
+
+                       @Override
+                       public Modifier setKey(String key) {
+                               this.key = fromNullable(key);
+                               return this;
+                       }
+
+                       @Override
+                       public Modifier setTitle(String title) {
+                               this.title = fromNullable(title);
+                               return this;
+                       }
+
+                       @Override
+                       public Modifier setDescription(String description) {
+                               this.description = fromNullable(description);
+                               return this;
+                       }
+
+                       @Override
+                       public Modifier setWidth(int width) {
+                               this.width = of(width);
+                               return this;
+                       }
+
+                       @Override
+                       public Modifier setHeight(int height) {
+                               this.height = of(height);
+                               return this;
+                       }
+
+                       @Override
+                       public Image update() throws IllegalStateException {
+                               checkState(!sone.isPresent() || (ImageImpl.this.sone == null) || sone.get().equals(ImageImpl.this.sone), "can not change Sone once set");
+                               checkState(!creationTime.isPresent() || ((ImageImpl.this.creationTime == 0) || (ImageImpl.this.creationTime == creationTime.get())), "can not change creation time once set");
+                               checkState(!key.isPresent() || (ImageImpl.this.key == null) || key.get().equals(ImageImpl.this.key), "can not change key once set");
+                               checkState(!width.isPresent() || (ImageImpl.this.width == 0) || width.get().equals(ImageImpl.this.width), "can not change width once set");
+                               checkState(!height.isPresent() || (ImageImpl.this.height == 0) || height.get().equals(ImageImpl.this.height), "can not change height once set");
+
+                               if (sone.isPresent()) {
+                                       ImageImpl.this.sone = sone.get();
+                               }
+                               if (creationTime.isPresent()) {
+                                       ImageImpl.this.creationTime = creationTime.get();
+                               }
+                               if (key.isPresent()) {
+                                       ImageImpl.this.key = key.get();
+                               }
+                               if (title.isPresent()) {
+                                       ImageImpl.this.title = title.get();
+                               }
+                               if (description.isPresent()) {
+                                       ImageImpl.this.description = description.get();
+                               }
+                               if (width.isPresent()) {
+                                       ImageImpl.this.width = width.get();
+                               }
+                               if (height.isPresent()) {
+                                       ImageImpl.this.height = height.get();
+                               }
+
+                               return ImageImpl.this;
+                       }
+               };
+       }
+
+       //
+       // FINGERPRINTABLE METHODS
+       //
+
+       @Override
+       public String getFingerprint() {
+               Hasher hash = Hashing.sha256().newHasher();
+               hash.putString("Image(");
+               hash.putString("ID(").putString(id).putString(")");
+               hash.putString("Title(").putString(title).putString(")");
+               hash.putString("Description(").putString(description).putString(")");
+               hash.putString(")");
+               return hash.hash().toString();
+       }
+
+       //
+       // OBJECT METHODS
+       //
+
+       /** {@inheritDoc} */
+       @Override
+       public int hashCode() {
+               return id.hashCode();
+       }
+
+       /** {@inheritDoc} */
+       @Override
+       public boolean equals(Object object) {
+               if (!(object instanceof ImageImpl)) {
+                       return false;
+               }
+               return ((ImageImpl) object).id.equals(id);
+       }
+
+}
index 31153ff..d7a7dee 100644 (file)
 
 package net.pterodactylus.sone.data;
 
-import static com.google.common.base.Preconditions.checkNotNull;
 import static com.google.common.collect.FluentIterable.from;
 import static java.util.Arrays.asList;
 import static net.pterodactylus.sone.data.Album.FLATTENER;
 import static net.pterodactylus.sone.data.Album.IMAGES;
 
-import java.util.ArrayList;
 import java.util.Collection;
-import java.util.Collections;
 import java.util.Comparator;
 import java.util.List;
 import java.util.Set;
-import java.util.concurrent.CopyOnWriteArraySet;
-import java.util.logging.Level;
-import java.util.logging.Logger;
 
 import net.pterodactylus.sone.core.Options;
 import net.pterodactylus.sone.freenet.wot.Identity;
 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
 import net.pterodactylus.sone.template.SoneAccessor;
-import net.pterodactylus.util.logging.Logging;
 
 import freenet.keys.FreenetURI;
 
 import com.google.common.base.Predicate;
-import com.google.common.hash.Hasher;
-import com.google.common.hash.Hashing;
 import com.google.common.primitives.Ints;
 
 /**
  * A Sone defines everything about a user: her profile, her status updates, her
  * replies, her likes and dislikes, etc.
- * <p/>
- * Operations that modify the Sone need to synchronize on the Sone in question.
  *
  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
  */
-public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
+public interface Sone extends Identified, Fingerprintable, Comparable<Sone> {
 
        /**
         * Enumeration for the possible states of a {@link Sone}.
@@ -178,98 +167,12 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
                }
        };
 
-       /** The logger. */
-       private static final Logger logger = Logging.getLogger(Sone.class);
-
-       /** The ID of this Sone. */
-       private final String id;
-
-       /** Whether the Sone is local. */
-       private final boolean local;
-
-       /** The identity of this Sone. */
-       private Identity identity;
-
-       /** The URI under which the Sone is stored in Freenet. */
-       private volatile FreenetURI requestUri;
-
-       /** The URI used to insert a new version of this Sone. */
-       /* This will be null for remote Sones! */
-       private volatile FreenetURI insertUri;
-
-       /** The latest edition of the Sone. */
-       private volatile long latestEdition;
-
-       /** The time of the last inserted update. */
-       private volatile long time;
-
-       /** The status of this Sone. */
-       private volatile SoneStatus status = SoneStatus.unknown;
-
-       /** The profile of this Sone. */
-       private volatile Profile profile = new Profile(this);
-
-       /** The client used by the Sone. */
-       private volatile Client client;
-
-       /** Whether this Sone is known. */
-       private volatile boolean known;
-
-       /** All friend Sones. */
-       private final Set<String> friendSones = new CopyOnWriteArraySet<String>();
-
-       /** All posts. */
-       private final Set<Post> posts = new CopyOnWriteArraySet<Post>();
-
-       /** All replies. */
-       private final Set<PostReply> replies = new CopyOnWriteArraySet<PostReply>();
-
-       /** The IDs of all liked posts. */
-       private final Set<String> likedPostIds = new CopyOnWriteArraySet<String>();
-
-       /** The IDs of all liked replies. */
-       private final Set<String> likedReplyIds = new CopyOnWriteArraySet<String>();
-
-       /** The root album containing all albums. */
-       private final Album rootAlbum = new Album().setSone(this);
-
-       /** Sone-specific options. */
-       private Options options = new Options();
-
-       /**
-        * Creates a new Sone.
-        *
-        * @param id
-        *              The ID of the Sone
-        * @param local
-        *              {@code true} if the Sone is a local Sone, {@code false} otherwise
-        */
-       public Sone(String id, boolean local) {
-               this.id = id;
-               this.local = local;
-       }
-
-       //
-       // ACCESSORS
-       //
-
-       /**
-        * Returns the identity of this Sone.
-        *
-        * @return The identity of this Sone
-        */
-       public String getId() {
-               return id;
-       }
-
        /**
         * Returns the identity of this Sone.
         *
         * @return The identity of this Sone
         */
-       public Identity getIdentity() {
-               return identity;
-       }
+       Identity getIdentity();
 
        /**
         * Sets the identity of this Sone. The {@link Identity#getId() ID} of the
@@ -281,40 +184,28 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         * @throws IllegalArgumentException
         *              if the ID of the identity does not match this Sone’s ID
         */
-       public Sone setIdentity(Identity identity) throws IllegalArgumentException {
-               if (!identity.getId().equals(id)) {
-                       throw new IllegalArgumentException("Identity’s ID does not match Sone’s ID!");
-               }
-               this.identity = identity;
-               return this;
-       }
+       Sone setIdentity(Identity identity) throws IllegalArgumentException;
 
        /**
         * Returns the name of this Sone.
         *
         * @return The name of this Sone
         */
-       public String getName() {
-               return (identity != null) ? identity.getNickname() : null;
-       }
+       String getName();
 
        /**
         * Returns whether this Sone is a local Sone.
         *
         * @return {@code true} if this Sone is a local Sone, {@code false} otherwise
         */
-       public boolean isLocal() {
-               return local;
-       }
+       boolean isLocal();
 
        /**
         * Returns the request URI of this Sone.
         *
         * @return The request URI of this Sone
         */
-       public FreenetURI getRequestUri() {
-               return (requestUri != null) ? requestUri.setSuggestedEdition(latestEdition) : null;
-       }
+       FreenetURI getRequestUri();
 
        /**
         * Sets the request URI of this Sone.
@@ -323,26 +214,14 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         *              The request URI of this Sone
         * @return This Sone (for method chaining)
         */
-       public Sone setRequestUri(FreenetURI requestUri) {
-               if (this.requestUri == null) {
-                       this.requestUri = requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
-                       return this;
-               }
-               if (!this.requestUri.equalsKeypair(requestUri)) {
-                       logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", requestUri, this.requestUri));
-                       return this;
-               }
-               return this;
-       }
+       Sone setRequestUri(FreenetURI requestUri);
 
        /**
         * Returns the insert URI of this Sone.
         *
         * @return The insert URI of this Sone
         */
-       public FreenetURI getInsertUri() {
-               return (insertUri != null) ? insertUri.setSuggestedEdition(latestEdition) : null;
-       }
+       FreenetURI getInsertUri();
 
        /**
         * Sets the insert URI of this Sone.
@@ -351,26 +230,14 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         *              The insert URI of this Sone
         * @return This Sone (for method chaining)
         */
-       public Sone setInsertUri(FreenetURI insertUri) {
-               if (this.insertUri == null) {
-                       this.insertUri = insertUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
-                       return this;
-               }
-               if (!this.insertUri.equalsKeypair(insertUri)) {
-                       logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", insertUri, this.insertUri));
-                       return this;
-               }
-               return this;
-       }
+       Sone setInsertUri(FreenetURI insertUri);
 
        /**
         * Returns the latest edition of this Sone.
         *
         * @return The latest edition of this Sone
         */
-       public long getLatestEdition() {
-               return latestEdition;
-       }
+       long getLatestEdition();
 
        /**
         * Sets the latest edition of this Sone. If the given latest edition is not
@@ -380,22 +247,14 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         * @param latestEdition
         *              The latest edition of this Sone
         */
-       public void setLatestEdition(long latestEdition) {
-               if (!(latestEdition > this.latestEdition)) {
-                       logger.log(Level.FINE, String.format("New latest edition %d is not greater than current latest edition %d!", latestEdition, this.latestEdition));
-                       return;
-               }
-               this.latestEdition = latestEdition;
-       }
+       void setLatestEdition(long latestEdition);
 
        /**
         * Return the time of the last inserted update of this Sone.
         *
         * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
         */
-       public long getTime() {
-               return time;
-       }
+       long getTime();
 
        /**
         * Sets the time of the last inserted update of this Sone.
@@ -404,19 +263,14 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         *              The time of the update (in milliseconds since Jan 1, 1970 UTC)
         * @return This Sone (for method chaining)
         */
-       public Sone setTime(long time) {
-               this.time = time;
-               return this;
-       }
+       Sone setTime(long time);
 
        /**
         * Returns the status of this Sone.
         *
         * @return The status of this Sone
         */
-       public SoneStatus getStatus() {
-               return status;
-       }
+       SoneStatus getStatus();
 
        /**
         * Sets the new status of this Sone.
@@ -427,10 +281,7 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         * @throws IllegalArgumentException
         *              if {@code status} is {@code null}
         */
-       public Sone setStatus(SoneStatus status) {
-               this.status = checkNotNull(status, "status must not be null");
-               return this;
-       }
+       Sone setStatus(SoneStatus status);
 
        /**
         * Returns a copy of the profile. If you want to update values in the profile
@@ -439,9 +290,7 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         *
         * @return A copy of the profile
         */
-       public Profile getProfile() {
-               return new Profile(profile);
-       }
+       Profile getProfile();
 
        /**
         * Sets the profile of this Sone. A copy of the given profile is stored so that
@@ -451,18 +300,14 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         * @param profile
         *              The profile to set
         */
-       public void setProfile(Profile profile) {
-               this.profile = new Profile(profile);
-       }
+       void setProfile(Profile profile);
 
        /**
         * Returns the client used by this Sone.
         *
         * @return The client used by this Sone, or {@code null}
         */
-       public Client getClient() {
-               return client;
-       }
+       Client getClient();
 
        /**
         * Sets the client used by this Sone.
@@ -471,19 +316,14 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         *              The client used by this Sone, or {@code null}
         * @return This Sone (for method chaining)
         */
-       public Sone setClient(Client client) {
-               this.client = client;
-               return this;
-       }
+       Sone setClient(Client client);
 
        /**
         * Returns whether this Sone is known.
         *
         * @return {@code true} if this Sone is known, {@code false} otherwise
         */
-       public boolean isKnown() {
-               return known;
-       }
+       boolean isKnown();
 
        /**
         * Sets whether this Sone is known.
@@ -492,20 +332,14 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         *              {@code true} if this Sone is known, {@code false} otherwise
         * @return This Sone
         */
-       public Sone setKnown(boolean known) {
-               this.known = known;
-               return this;
-       }
+       Sone setKnown(boolean known);
 
        /**
         * Returns all friend Sones of this Sone.
         *
         * @return The friend Sones of this Sone
         */
-       public List<String> getFriends() {
-               List<String> friends = new ArrayList<String>(friendSones);
-               return friends;
-       }
+       List<String> getFriends();
 
        /**
         * Returns whether this Sone has the given Sone as a friend Sone.
@@ -515,9 +349,7 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         * @return {@code true} if this Sone has the given Sone as a friend, {@code
         *         false} otherwise
         */
-       public boolean hasFriend(String friendSoneId) {
-               return friendSones.contains(friendSoneId);
-       }
+       boolean hasFriend(String friendSoneId);
 
        /**
         * Adds the given Sone as a friend Sone.
@@ -526,12 +358,7 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         *              The friend Sone to add
         * @return This Sone (for method chaining)
         */
-       public Sone addFriend(String friendSone) {
-               if (!friendSone.equals(id)) {
-                       friendSones.add(friendSone);
-               }
-               return this;
-       }
+       Sone addFriend(String friendSone);
 
        /**
         * Removes the given Sone as a friend Sone.
@@ -540,24 +367,14 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         *              The ID of the friend Sone to remove
         * @return This Sone (for method chaining)
         */
-       public Sone removeFriend(String friendSoneId) {
-               friendSones.remove(friendSoneId);
-               return this;
-       }
+       Sone removeFriend(String friendSoneId);
 
        /**
         * Returns the list of posts of this Sone, sorted by time, newest first.
         *
         * @return All posts of this Sone
         */
-       public List<Post> getPosts() {
-               List<Post> sortedPosts;
-               synchronized (this) {
-                       sortedPosts = new ArrayList<Post>(posts);
-               }
-               Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
-               return sortedPosts;
-       }
+       List<Post> getPosts();
 
        /**
         * Sets all posts of this Sone at once.
@@ -566,13 +383,7 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         *              The new (and only) posts of this Sone
         * @return This Sone (for method chaining)
         */
-       public Sone setPosts(Collection<Post> posts) {
-               synchronized (this) {
-                       this.posts.clear();
-                       this.posts.addAll(posts);
-               }
-               return this;
-       }
+       Sone setPosts(Collection<Post> posts);
 
        /**
         * Adds the given post to this Sone. The post will not be added if its {@link
@@ -581,11 +392,7 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         * @param post
         *              The post to add
         */
-       public void addPost(Post post) {
-               if (post.getSone().equals(this) && posts.add(post)) {
-                       logger.log(Level.FINEST, String.format("Adding %s to “%s”.", post, getName()));
-               }
-       }
+       void addPost(Post post);
 
        /**
         * Removes the given post from this Sone.
@@ -593,20 +400,14 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         * @param post
         *              The post to remove
         */
-       public void removePost(Post post) {
-               if (post.getSone().equals(this)) {
-                       posts.remove(post);
-               }
-       }
+       void removePost(Post post);
 
        /**
         * Returns all replies this Sone made.
         *
         * @return All replies this Sone made
         */
-       public Set<PostReply> getReplies() {
-               return Collections.unmodifiableSet(replies);
-       }
+       Set<PostReply> getReplies();
 
        /**
         * Sets all replies of this Sone at once.
@@ -615,11 +416,7 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         *              The new (and only) replies of this Sone
         * @return This Sone (for method chaining)
         */
-       public Sone setReplies(Collection<PostReply> replies) {
-               this.replies.clear();
-               this.replies.addAll(replies);
-               return this;
-       }
+       Sone setReplies(Collection<PostReply> replies);
 
        /**
         * Adds a reply to this Sone. If the given reply was not made by this Sone,
@@ -628,11 +425,7 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         * @param reply
         *              The reply to add
         */
-       public void addReply(PostReply reply) {
-               if (reply.getSone().equals(this)) {
-                       replies.add(reply);
-               }
-       }
+       void addReply(PostReply reply);
 
        /**
         * Removes a reply from this Sone.
@@ -640,20 +433,14 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         * @param reply
         *              The reply to remove
         */
-       public void removeReply(PostReply reply) {
-               if (reply.getSone().equals(this)) {
-                       replies.remove(reply);
-               }
-       }
+       void removeReply(PostReply reply);
 
        /**
         * Returns the IDs of all liked posts.
         *
         * @return All liked posts’ IDs
         */
-       public Set<String> getLikedPostIds() {
-               return Collections.unmodifiableSet(likedPostIds);
-       }
+       Set<String> getLikedPostIds();
 
        /**
         * Sets the IDs of all liked posts.
@@ -662,11 +449,7 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         *              All liked posts’ IDs
         * @return This Sone (for method chaining)
         */
-       public Sone setLikePostIds(Set<String> likedPostIds) {
-               this.likedPostIds.clear();
-               this.likedPostIds.addAll(likedPostIds);
-               return this;
-       }
+       Sone setLikePostIds(Set<String> likedPostIds);
 
        /**
         * Checks whether the given post ID is liked by this Sone.
@@ -676,9 +459,7 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         * @return {@code true} if this Sone likes the given post, {@code false}
         *         otherwise
         */
-       public boolean isLikedPostId(String postId) {
-               return likedPostIds.contains(postId);
-       }
+       boolean isLikedPostId(String postId);
 
        /**
         * Adds the given post ID to the list of posts this Sone likes.
@@ -687,10 +468,7 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         *              The ID of the post
         * @return This Sone (for method chaining)
         */
-       public Sone addLikedPostId(String postId) {
-               likedPostIds.add(postId);
-               return this;
-       }
+       Sone addLikedPostId(String postId);
 
        /**
         * Removes the given post ID from the list of posts this Sone likes.
@@ -699,19 +477,14 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         *              The ID of the post
         * @return This Sone (for method chaining)
         */
-       public Sone removeLikedPostId(String postId) {
-               likedPostIds.remove(postId);
-               return this;
-       }
+       Sone removeLikedPostId(String postId);
 
        /**
         * Returns the IDs of all liked replies.
         *
         * @return All liked replies’ IDs
         */
-       public Set<String> getLikedReplyIds() {
-               return Collections.unmodifiableSet(likedReplyIds);
-       }
+       Set<String> getLikedReplyIds();
 
        /**
         * Sets the IDs of all liked replies.
@@ -720,11 +493,7 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         *              All liked replies’ IDs
         * @return This Sone (for method chaining)
         */
-       public Sone setLikeReplyIds(Set<String> likedReplyIds) {
-               this.likedReplyIds.clear();
-               this.likedReplyIds.addAll(likedReplyIds);
-               return this;
-       }
+       Sone setLikeReplyIds(Set<String> likedReplyIds);
 
        /**
         * Checks whether the given reply ID is liked by this Sone.
@@ -734,9 +503,7 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         * @return {@code true} if this Sone likes the given reply, {@code false}
         *         otherwise
         */
-       public boolean isLikedReplyId(String replyId) {
-               return likedReplyIds.contains(replyId);
-       }
+       boolean isLikedReplyId(String replyId);
 
        /**
         * Adds the given reply ID to the list of replies this Sone likes.
@@ -745,10 +512,7 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         *              The ID of the reply
         * @return This Sone (for method chaining)
         */
-       public Sone addLikedReplyId(String replyId) {
-               likedReplyIds.add(replyId);
-               return this;
-       }
+       Sone addLikedReplyId(String replyId);
 
        /**
         * Removes the given post ID from the list of replies this Sone likes.
@@ -757,28 +521,21 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         *              The ID of the reply
         * @return This Sone (for method chaining)
         */
-       public Sone removeLikedReplyId(String replyId) {
-               likedReplyIds.remove(replyId);
-               return this;
-       }
+       Sone removeLikedReplyId(String replyId);
 
        /**
         * Returns the root album that contains all visible albums of this Sone.
         *
         * @return The root album of this Sone
         */
-       public Album getRootAlbum() {
-               return rootAlbum;
-       }
+       Album getRootAlbum();
 
        /**
         * Returns Sone-specific options.
         *
         * @return The options of this Sone
         */
-       public Options getOptions() {
-               return options;
-       }
+       Options getOptions();
 
        /**
         * Sets the options of this Sone.
@@ -787,95 +544,6 @@ public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
         *              The options of this Sone
         */
        /* TODO - remove this method again, maybe add an option provider */
-       public void setOptions(Options options) {
-               this.options = options;
-       }
-
-       //
-       // FINGERPRINTABLE METHODS
-       //
-
-       /** {@inheritDoc} */
-       @Override
-       public synchronized String getFingerprint() {
-               Hasher hash = Hashing.sha256().newHasher();
-               hash.putString(profile.getFingerprint());
-
-               hash.putString("Posts(");
-               for (Post post : getPosts()) {
-                       hash.putString("Post(").putString(post.getId()).putString(")");
-               }
-               hash.putString(")");
-
-               List<PostReply> replies = new ArrayList<PostReply>(getReplies());
-               Collections.sort(replies, Reply.TIME_COMPARATOR);
-               hash.putString("Replies(");
-               for (PostReply reply : replies) {
-                       hash.putString("Reply(").putString(reply.getId()).putString(")");
-               }
-               hash.putString(")");
-
-               List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
-               Collections.sort(likedPostIds);
-               hash.putString("LikedPosts(");
-               for (String likedPostId : likedPostIds) {
-                       hash.putString("Post(").putString(likedPostId).putString(")");
-               }
-               hash.putString(")");
-
-               List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
-               Collections.sort(likedReplyIds);
-               hash.putString("LikedReplies(");
-               for (String likedReplyId : likedReplyIds) {
-                       hash.putString("Reply(").putString(likedReplyId).putString(")");
-               }
-               hash.putString(")");
-
-               hash.putString("Albums(");
-               for (Album album : rootAlbum.getAlbums()) {
-                       if (!Album.NOT_EMPTY.apply(album)) {
-                               continue;
-                       }
-                       hash.putString(album.getFingerprint());
-               }
-               hash.putString(")");
-
-               return hash.hash().toString();
-       }
-
-       //
-       // INTERFACE Comparable<Sone>
-       //
-
-       /** {@inheritDoc} */
-       @Override
-       public int compareTo(Sone sone) {
-               return NICE_NAME_COMPARATOR.compare(this, sone);
-       }
-
-       //
-       // OBJECT METHODS
-       //
-
-       /** {@inheritDoc} */
-       @Override
-       public int hashCode() {
-               return id.hashCode();
-       }
-
-       /** {@inheritDoc} */
-       @Override
-       public boolean equals(Object object) {
-               if (!(object instanceof Sone)) {
-                       return false;
-               }
-               return ((Sone) object).id.equals(id);
-       }
-
-       /** {@inheritDoc} */
-       @Override
-       public String toString() {
-               return getClass().getName() + "[identity=" + identity + ",requestUri=" + requestUri + ",insertUri(" + String.valueOf(insertUri).length() + "),friends(" + friendSones.size() + "),posts(" + posts.size() + "),replies(" + replies.size() + "),albums(" + getRootAlbum().getAlbums().size() + ")]";
-       }
+       void setOptions(Options options);
 
 }
diff --git a/src/main/java/net/pterodactylus/sone/data/SoneImpl.java b/src/main/java/net/pterodactylus/sone/data/SoneImpl.java
new file mode 100644 (file)
index 0000000..880eb95
--- /dev/null
@@ -0,0 +1,749 @@
+/*
+ * Sone - SoneImpl.java - Copyright © 2010–2013 David Roden
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package net.pterodactylus.sone.data;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CopyOnWriteArraySet;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import net.pterodactylus.sone.core.Options;
+import net.pterodactylus.sone.freenet.wot.Identity;
+import net.pterodactylus.util.logging.Logging;
+
+import freenet.keys.FreenetURI;
+
+import com.google.common.hash.Hasher;
+import com.google.common.hash.Hashing;
+
+/**
+ * {@link Sone} implementation.
+ * <p/>
+ * Operations that modify the Sone need to synchronize on the Sone in question.
+ *
+ * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+ */
+public class SoneImpl implements Sone {
+
+       /** The logger. */
+       private static final Logger logger = Logging.getLogger(SoneImpl.class);
+
+       /** The ID of this Sone. */
+       private final String id;
+
+       /** Whether the Sone is local. */
+       private final boolean local;
+
+       /** The identity of this Sone. */
+       private Identity identity;
+
+       /** The URI under which the Sone is stored in Freenet. */
+       private volatile FreenetURI requestUri;
+
+       /** The URI used to insert a new version of this Sone. */
+       /* This will be null for remote Sones! */
+       private volatile FreenetURI insertUri;
+
+       /** The latest edition of the Sone. */
+       private volatile long latestEdition;
+
+       /** The time of the last inserted update. */
+       private volatile long time;
+
+       /** The status of this Sone. */
+       private volatile SoneStatus status = SoneStatus.unknown;
+
+       /** The profile of this Sone. */
+       private volatile Profile profile = new Profile(this);
+
+       /** The client used by the Sone. */
+       private volatile Client client;
+
+       /** Whether this Sone is known. */
+       private volatile boolean known;
+
+       /** All friend Sones. */
+       private final Set<String> friendSones = new CopyOnWriteArraySet<String>();
+
+       /** All posts. */
+       private final Set<Post> posts = new CopyOnWriteArraySet<Post>();
+
+       /** All replies. */
+       private final Set<PostReply> replies = new CopyOnWriteArraySet<PostReply>();
+
+       /** The IDs of all liked posts. */
+       private final Set<String> likedPostIds = new CopyOnWriteArraySet<String>();
+
+       /** The IDs of all liked replies. */
+       private final Set<String> likedReplyIds = new CopyOnWriteArraySet<String>();
+
+       /** The root album containing all albums. */
+       private final Album rootAlbum = new AlbumImpl().setSone(this);
+
+       /** Sone-specific options. */
+       private Options options = new Options();
+
+       /**
+        * Creates a new Sone.
+        *
+        * @param id
+        *              The ID of the Sone
+        * @param local
+        *              {@code true} if the Sone is a local Sone, {@code false} otherwise
+        */
+       public SoneImpl(String id, boolean local) {
+               this.id = id;
+               this.local = local;
+       }
+
+       //
+       // ACCESSORS
+       //
+
+       /**
+        * Returns the identity of this Sone.
+        *
+        * @return The identity of this Sone
+        */
+       public String getId() {
+               return id;
+       }
+
+       /**
+        * Returns the identity of this Sone.
+        *
+        * @return The identity of this Sone
+        */
+       public Identity getIdentity() {
+               return identity;
+       }
+
+       /**
+        * Sets the identity of this Sone. The {@link Identity#getId() ID} of the
+        * identity has to match this Sone’s {@link #getId()}.
+        *
+        * @param identity
+        *              The identity of this Sone
+        * @return This Sone (for method chaining)
+        * @throws IllegalArgumentException
+        *              if the ID of the identity does not match this Sone’s ID
+        */
+       public SoneImpl setIdentity(Identity identity) throws IllegalArgumentException {
+               if (!identity.getId().equals(id)) {
+                       throw new IllegalArgumentException("Identity’s ID does not match Sone’s ID!");
+               }
+               this.identity = identity;
+               return this;
+       }
+
+       /**
+        * Returns the name of this Sone.
+        *
+        * @return The name of this Sone
+        */
+       public String getName() {
+               return (identity != null) ? identity.getNickname() : null;
+       }
+
+       /**
+        * Returns whether this Sone is a local Sone.
+        *
+        * @return {@code true} if this Sone is a local Sone, {@code false} otherwise
+        */
+       public boolean isLocal() {
+               return local;
+       }
+
+       /**
+        * Returns the request URI of this Sone.
+        *
+        * @return The request URI of this Sone
+        */
+       public FreenetURI getRequestUri() {
+               return (requestUri != null) ? requestUri.setSuggestedEdition(latestEdition) : null;
+       }
+
+       /**
+        * Sets the request URI of this Sone.
+        *
+        * @param requestUri
+        *              The request URI of this Sone
+        * @return This Sone (for method chaining)
+        */
+       public Sone setRequestUri(FreenetURI requestUri) {
+               if (this.requestUri == null) {
+                       this.requestUri = requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
+                       return this;
+               }
+               if (!this.requestUri.equalsKeypair(requestUri)) {
+                       logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", requestUri, this.requestUri));
+                       return this;
+               }
+               return this;
+       }
+
+       /**
+        * Returns the insert URI of this Sone.
+        *
+        * @return The insert URI of this Sone
+        */
+       public FreenetURI getInsertUri() {
+               return (insertUri != null) ? insertUri.setSuggestedEdition(latestEdition) : null;
+       }
+
+       /**
+        * Sets the insert URI of this Sone.
+        *
+        * @param insertUri
+        *              The insert URI of this Sone
+        * @return This Sone (for method chaining)
+        */
+       public Sone setInsertUri(FreenetURI insertUri) {
+               if (this.insertUri == null) {
+                       this.insertUri = insertUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
+                       return this;
+               }
+               if (!this.insertUri.equalsKeypair(insertUri)) {
+                       logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", insertUri, this.insertUri));
+                       return this;
+               }
+               return this;
+       }
+
+       /**
+        * Returns the latest edition of this Sone.
+        *
+        * @return The latest edition of this Sone
+        */
+       public long getLatestEdition() {
+               return latestEdition;
+       }
+
+       /**
+        * Sets the latest edition of this Sone. If the given latest edition is not
+        * greater than the current latest edition, the latest edition of this Sone is
+        * not changed.
+        *
+        * @param latestEdition
+        *              The latest edition of this Sone
+        */
+       public void setLatestEdition(long latestEdition) {
+               if (!(latestEdition > this.latestEdition)) {
+                       logger.log(Level.FINE, String.format("New latest edition %d is not greater than current latest edition %d!", latestEdition, this.latestEdition));
+                       return;
+               }
+               this.latestEdition = latestEdition;
+       }
+
+       /**
+        * Return the time of the last inserted update of this Sone.
+        *
+        * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
+        */
+       public long getTime() {
+               return time;
+       }
+
+       /**
+        * Sets the time of the last inserted update of this Sone.
+        *
+        * @param time
+        *              The time of the update (in milliseconds since Jan 1, 1970 UTC)
+        * @return This Sone (for method chaining)
+        */
+       public Sone setTime(long time) {
+               this.time = time;
+               return this;
+       }
+
+       /**
+        * Returns the status of this Sone.
+        *
+        * @return The status of this Sone
+        */
+       public SoneStatus getStatus() {
+               return status;
+       }
+
+       /**
+        * Sets the new status of this Sone.
+        *
+        * @param status
+        *              The new status of this Sone
+        * @return This Sone
+        * @throws IllegalArgumentException
+        *              if {@code status} is {@code null}
+        */
+       public Sone setStatus(SoneStatus status) {
+               this.status = checkNotNull(status, "status must not be null");
+               return this;
+       }
+
+       /**
+        * Returns a copy of the profile. If you want to update values in the profile
+        * of this Sone, update the values in the returned {@link Profile} and use
+        * {@link #setProfile(Profile)} to change the profile in this Sone.
+        *
+        * @return A copy of the profile
+        */
+       public Profile getProfile() {
+               return new Profile(profile);
+       }
+
+       /**
+        * Sets the profile of this Sone. A copy of the given profile is stored so that
+        * subsequent modifications of the given profile are not reflected in this
+        * Sone!
+        *
+        * @param profile
+        *              The profile to set
+        */
+       public void setProfile(Profile profile) {
+               this.profile = new Profile(profile);
+       }
+
+       /**
+        * Returns the client used by this Sone.
+        *
+        * @return The client used by this Sone, or {@code null}
+        */
+       public Client getClient() {
+               return client;
+       }
+
+       /**
+        * Sets the client used by this Sone.
+        *
+        * @param client
+        *              The client used by this Sone, or {@code null}
+        * @return This Sone (for method chaining)
+        */
+       public Sone setClient(Client client) {
+               this.client = client;
+               return this;
+       }
+
+       /**
+        * Returns whether this Sone is known.
+        *
+        * @return {@code true} if this Sone is known, {@code false} otherwise
+        */
+       public boolean isKnown() {
+               return known;
+       }
+
+       /**
+        * Sets whether this Sone is known.
+        *
+        * @param known
+        *              {@code true} if this Sone is known, {@code false} otherwise
+        * @return This Sone
+        */
+       public Sone setKnown(boolean known) {
+               this.known = known;
+               return this;
+       }
+
+       /**
+        * Returns all friend Sones of this Sone.
+        *
+        * @return The friend Sones of this Sone
+        */
+       public List<String> getFriends() {
+               List<String> friends = new ArrayList<String>(friendSones);
+               return friends;
+       }
+
+       /**
+        * Returns whether this Sone has the given Sone as a friend Sone.
+        *
+        * @param friendSoneId
+        *              The ID of the Sone to check for
+        * @return {@code true} if this Sone has the given Sone as a friend, {@code
+        *         false} otherwise
+        */
+       public boolean hasFriend(String friendSoneId) {
+               return friendSones.contains(friendSoneId);
+       }
+
+       /**
+        * Adds the given Sone as a friend Sone.
+        *
+        * @param friendSone
+        *              The friend Sone to add
+        * @return This Sone (for method chaining)
+        */
+       public Sone addFriend(String friendSone) {
+               if (!friendSone.equals(id)) {
+                       friendSones.add(friendSone);
+               }
+               return this;
+       }
+
+       /**
+        * Removes the given Sone as a friend Sone.
+        *
+        * @param friendSoneId
+        *              The ID of the friend Sone to remove
+        * @return This Sone (for method chaining)
+        */
+       public Sone removeFriend(String friendSoneId) {
+               friendSones.remove(friendSoneId);
+               return this;
+       }
+
+       /**
+        * Returns the list of posts of this Sone, sorted by time, newest first.
+        *
+        * @return All posts of this Sone
+        */
+       public List<Post> getPosts() {
+               List<Post> sortedPosts;
+               synchronized (this) {
+                       sortedPosts = new ArrayList<Post>(posts);
+               }
+               Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
+               return sortedPosts;
+       }
+
+       /**
+        * Sets all posts of this Sone at once.
+        *
+        * @param posts
+        *              The new (and only) posts of this Sone
+        * @return This Sone (for method chaining)
+        */
+       public Sone setPosts(Collection<Post> posts) {
+               synchronized (this) {
+                       this.posts.clear();
+                       this.posts.addAll(posts);
+               }
+               return this;
+       }
+
+       /**
+        * Adds the given post to this Sone. The post will not be added if its {@link
+        * Post#getSone() Sone} is not this Sone.
+        *
+        * @param post
+        *              The post to add
+        */
+       public void addPost(Post post) {
+               if (post.getSone().equals(this) && posts.add(post)) {
+                       logger.log(Level.FINEST, String.format("Adding %s to “%s”.", post, getName()));
+               }
+       }
+
+       /**
+        * Removes the given post from this Sone.
+        *
+        * @param post
+        *              The post to remove
+        */
+       public void removePost(Post post) {
+               if (post.getSone().equals(this)) {
+                       posts.remove(post);
+               }
+       }
+
+       /**
+        * Returns all replies this Sone made.
+        *
+        * @return All replies this Sone made
+        */
+       public Set<PostReply> getReplies() {
+               return Collections.unmodifiableSet(replies);
+       }
+
+       /**
+        * Sets all replies of this Sone at once.
+        *
+        * @param replies
+        *              The new (and only) replies of this Sone
+        * @return This Sone (for method chaining)
+        */
+       public Sone setReplies(Collection<PostReply> replies) {
+               this.replies.clear();
+               this.replies.addAll(replies);
+               return this;
+       }
+
+       /**
+        * Adds a reply to this Sone. If the given reply was not made by this Sone,
+        * nothing is added to this Sone.
+        *
+        * @param reply
+        *              The reply to add
+        */
+       public void addReply(PostReply reply) {
+               if (reply.getSone().equals(this)) {
+                       replies.add(reply);
+               }
+       }
+
+       /**
+        * Removes a reply from this Sone.
+        *
+        * @param reply
+        *              The reply to remove
+        */
+       public void removeReply(PostReply reply) {
+               if (reply.getSone().equals(this)) {
+                       replies.remove(reply);
+               }
+       }
+
+       /**
+        * Returns the IDs of all liked posts.
+        *
+        * @return All liked posts’ IDs
+        */
+       public Set<String> getLikedPostIds() {
+               return Collections.unmodifiableSet(likedPostIds);
+       }
+
+       /**
+        * Sets the IDs of all liked posts.
+        *
+        * @param likedPostIds
+        *              All liked posts’ IDs
+        * @return This Sone (for method chaining)
+        */
+       public Sone setLikePostIds(Set<String> likedPostIds) {
+               this.likedPostIds.clear();
+               this.likedPostIds.addAll(likedPostIds);
+               return this;
+       }
+
+       /**
+        * Checks whether the given post ID is liked by this Sone.
+        *
+        * @param postId
+        *              The ID of the post
+        * @return {@code true} if this Sone likes the given post, {@code false}
+        *         otherwise
+        */
+       public boolean isLikedPostId(String postId) {
+               return likedPostIds.contains(postId);
+       }
+
+       /**
+        * Adds the given post ID to the list of posts this Sone likes.
+        *
+        * @param postId
+        *              The ID of the post
+        * @return This Sone (for method chaining)
+        */
+       public Sone addLikedPostId(String postId) {
+               likedPostIds.add(postId);
+               return this;
+       }
+
+       /**
+        * Removes the given post ID from the list of posts this Sone likes.
+        *
+        * @param postId
+        *              The ID of the post
+        * @return This Sone (for method chaining)
+        */
+       public Sone removeLikedPostId(String postId) {
+               likedPostIds.remove(postId);
+               return this;
+       }
+
+       /**
+        * Returns the IDs of all liked replies.
+        *
+        * @return All liked replies’ IDs
+        */
+       public Set<String> getLikedReplyIds() {
+               return Collections.unmodifiableSet(likedReplyIds);
+       }
+
+       /**
+        * Sets the IDs of all liked replies.
+        *
+        * @param likedReplyIds
+        *              All liked replies’ IDs
+        * @return This Sone (for method chaining)
+        */
+       public Sone setLikeReplyIds(Set<String> likedReplyIds) {
+               this.likedReplyIds.clear();
+               this.likedReplyIds.addAll(likedReplyIds);
+               return this;
+       }
+
+       /**
+        * Checks whether the given reply ID is liked by this Sone.
+        *
+        * @param replyId
+        *              The ID of the reply
+        * @return {@code true} if this Sone likes the given reply, {@code false}
+        *         otherwise
+        */
+       public boolean isLikedReplyId(String replyId) {
+               return likedReplyIds.contains(replyId);
+       }
+
+       /**
+        * Adds the given reply ID to the list of replies this Sone likes.
+        *
+        * @param replyId
+        *              The ID of the reply
+        * @return This Sone (for method chaining)
+        */
+       public Sone addLikedReplyId(String replyId) {
+               likedReplyIds.add(replyId);
+               return this;
+       }
+
+       /**
+        * Removes the given post ID from the list of replies this Sone likes.
+        *
+        * @param replyId
+        *              The ID of the reply
+        * @return This Sone (for method chaining)
+        */
+       public Sone removeLikedReplyId(String replyId) {
+               likedReplyIds.remove(replyId);
+               return this;
+       }
+
+       /**
+        * Returns the root album that contains all visible albums of this Sone.
+        *
+        * @return The root album of this Sone
+        */
+       public Album getRootAlbum() {
+               return rootAlbum;
+       }
+
+       /**
+        * Returns Sone-specific options.
+        *
+        * @return The options of this Sone
+        */
+       public Options getOptions() {
+               return options;
+       }
+
+       /**
+        * Sets the options of this Sone.
+        *
+        * @param options
+        *              The options of this Sone
+        */
+       /* TODO - remove this method again, maybe add an option provider */
+       public void setOptions(Options options) {
+               this.options = options;
+       }
+
+       //
+       // FINGERPRINTABLE METHODS
+       //
+
+       /** {@inheritDoc} */
+       @Override
+       public synchronized String getFingerprint() {
+               Hasher hash = Hashing.sha256().newHasher();
+               hash.putString(profile.getFingerprint());
+
+               hash.putString("Posts(");
+               for (Post post : getPosts()) {
+                       hash.putString("Post(").putString(post.getId()).putString(")");
+               }
+               hash.putString(")");
+
+               List<PostReply> replies = new ArrayList<PostReply>(getReplies());
+               Collections.sort(replies, Reply.TIME_COMPARATOR);
+               hash.putString("Replies(");
+               for (PostReply reply : replies) {
+                       hash.putString("Reply(").putString(reply.getId()).putString(")");
+               }
+               hash.putString(")");
+
+               List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
+               Collections.sort(likedPostIds);
+               hash.putString("LikedPosts(");
+               for (String likedPostId : likedPostIds) {
+                       hash.putString("Post(").putString(likedPostId).putString(")");
+               }
+               hash.putString(")");
+
+               List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
+               Collections.sort(likedReplyIds);
+               hash.putString("LikedReplies(");
+               for (String likedReplyId : likedReplyIds) {
+                       hash.putString("Reply(").putString(likedReplyId).putString(")");
+               }
+               hash.putString(")");
+
+               hash.putString("Albums(");
+               for (Album album : rootAlbum.getAlbums()) {
+                       if (!Album.NOT_EMPTY.apply(album)) {
+                               continue;
+                       }
+                       hash.putString(album.getFingerprint());
+               }
+               hash.putString(")");
+
+               return hash.hash().toString();
+       }
+
+       //
+       // INTERFACE Comparable<Sone>
+       //
+
+       /** {@inheritDoc} */
+       @Override
+       public int compareTo(Sone sone) {
+               return NICE_NAME_COMPARATOR.compare(this, sone);
+       }
+
+       //
+       // OBJECT METHODS
+       //
+
+       /** {@inheritDoc} */
+       @Override
+       public int hashCode() {
+               return id.hashCode();
+       }
+
+       /** {@inheritDoc} */
+       @Override
+       public boolean equals(Object object) {
+               if (!(object instanceof Sone)) {
+                       return false;
+               }
+               return ((Sone) object).getId().equals(id);
+       }
+
+       /** {@inheritDoc} */
+       @Override
+       public String toString() {
+               return getClass().getName() + "[identity=" + identity + ",requestUri=" + requestUri + ",insertUri(" + String.valueOf(insertUri).length() + "),friends(" + friendSones.size() + "),posts(" + posts.size() + "),replies(" + replies.size() + "),albums(" + getRootAlbum().getAlbums().size() + ")]";
+       }
+
+}
diff --git a/src/main/java/net/pterodactylus/sone/data/impl/AbstractAlbumBuilder.java b/src/main/java/net/pterodactylus/sone/data/impl/AbstractAlbumBuilder.java
new file mode 100644 (file)
index 0000000..312c795
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * Sone - AbstractAlbumBuilder.java - Copyright © 2013 David Roden
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package net.pterodactylus.sone.data.impl;
+
+import static com.google.common.base.Preconditions.checkState;
+
+import net.pterodactylus.sone.database.AlbumBuilder;
+
+/**
+ * Abstract {@link AlbumBuilder} implementation. It stores the state of the new
+ * album and performs validation, you only need to implement {@link #build()}.
+ *
+ * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+ */
+public abstract class AbstractAlbumBuilder implements AlbumBuilder {
+
+       /** Whether to create an album with a random ID. */
+       protected boolean randomId;
+
+       /** The ID of the album to create. */
+       protected String id;
+
+       @Override
+       public AlbumBuilder randomId() {
+               randomId = true;
+               return this;
+       }
+
+       @Override
+       public AlbumBuilder withId(String id) {
+               this.id = id;
+               return this;
+       }
+
+       //
+       // PROTECTED METHODS
+       //
+
+       /**
+        * Validates the state of this post builder.
+        *
+        * @throws IllegalStateException
+        *              if the state is not valid for building a new post
+        */
+       protected void validate() throws IllegalStateException {
+               checkState((randomId && (id == null)) || (!randomId && (id != null)), "exactly one of random ID or custom ID must be set");
+       }
+
+}
diff --git a/src/main/java/net/pterodactylus/sone/data/impl/AbstractImageBuilder.java b/src/main/java/net/pterodactylus/sone/data/impl/AbstractImageBuilder.java
new file mode 100644 (file)
index 0000000..533ba39
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ * Sone - AbstractImageBuilder.java - Copyright © 2013 David Roden
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+package net.pterodactylus.sone.data.impl;
+
+import static com.google.common.base.Preconditions.checkState;
+
+import net.pterodactylus.sone.database.ImageBuilder;
+
+/**
+ * Abstract {@link ImageBuilder} implementation. It stores the state of the new
+ * album and performs validation, you only need to implement {@link #build()}.
+ *
+ * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+ */
+public abstract class AbstractImageBuilder implements ImageBuilder {
+
+       /** Whether to create an album with a random ID. */
+       protected boolean randomId;
+
+       /** The ID of the album to create. */
+       protected String id;
+
+       @Override
+       public ImageBuilder randomId() {
+               randomId = true;
+               return this;
+       }
+
+       @Override
+       public ImageBuilder withId(String id) {
+               this.id = id;
+               return this;
+       }
+
+       //
+       // PROTECTED METHODS
+       //
+
+       /**
+        * Validates the state of this image builder.
+        *
+        * @throws IllegalStateException
+        *              if the state is not valid for building a new image
+        */
+       protected void validate() throws IllegalStateException {
+               checkState((randomId && (id == null)) || (!randomId && (id != null)), "exactly one of random ID or custom ID must be set");
+       }
+
+}
diff --git a/src/main/java/net/pterodactylus/sone/data/impl/AlbumBuilderImpl.java b/src/main/java/net/pterodactylus/sone/data/impl/AlbumBuilderImpl.java
new file mode 100644 (file)
index 0000000..3403a62
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Sone - MemoryAlbumBuilder.java - Copyright © 2013 David Roden
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package net.pterodactylus.sone.data.impl;
+
+import net.pterodactylus.sone.data.Album;
+import net.pterodactylus.sone.data.AlbumImpl;
+import net.pterodactylus.sone.database.AlbumBuilder;
+
+/**
+ * {@link AlbumBuilder} implementation that creates {@link AlbumImpl} objects.
+ *
+ * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+ */
+public class AlbumBuilderImpl extends AbstractAlbumBuilder {
+
+       @Override
+       public Album build() throws IllegalStateException {
+               validate();
+               return randomId ? new AlbumImpl() : new AlbumImpl(id);
+       }
+
+}
diff --git a/src/main/java/net/pterodactylus/sone/data/impl/ImageBuilderImpl.java b/src/main/java/net/pterodactylus/sone/data/impl/ImageBuilderImpl.java
new file mode 100644 (file)
index 0000000..870b5d7
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Sone - ImageBuilderImpl.java - Copyright © 2013 David Roden
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package net.pterodactylus.sone.data.impl;
+
+import net.pterodactylus.sone.data.Image;
+import net.pterodactylus.sone.data.ImageImpl;
+import net.pterodactylus.sone.database.ImageBuilder;
+
+/**
+ * {@link ImageBuilder} implementation that creates {@link ImageImpl} objects.
+ *
+ * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
+ */
+public class ImageBuilderImpl extends AbstractImageBuilder {
+
+       @Override
+       public Image build() throws IllegalStateException {
+               validate();
+               return randomId ? new ImageImpl() : new ImageImpl(id);
+       }
+
+}
diff --git a/src/main/java/net/pterodactylus/sone/database/AlbumBuilder.java b/src/main/java/net/pterodactylus/sone/database/AlbumBuilder.java
new file mode 100644 (file)
index 0000000..b888828
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * Sone - AlbumBuilder.java - Copyright © 2013 David Roden
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package net.pterodactylus.sone.database;
+
+import net.pterodactylus.sone.data.Album;
+
+/**
+ * Builder for {@link Album} objects.
+ *
+ * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+ */
+public interface AlbumBuilder {
+
+       /**
+        * Configures this builder to create an album with a random ID.
+        *
+        * @return This album builder
+        */
+       AlbumBuilder randomId();
+
+       /**
+        * Configures this builder to create an album with the given ID.
+        *
+        * @param id
+        *              The ID of the album
+        * @return This album builder
+        */
+       AlbumBuilder withId(String id);
+
+       /**
+        * Creates the album.
+        *
+        * @return The created album
+        * @throws IllegalStateException
+        *              if the album could not be created
+        */
+       Album build() throws IllegalStateException;
+
+}
diff --git a/src/main/java/net/pterodactylus/sone/database/AlbumBuilderFactory.java b/src/main/java/net/pterodactylus/sone/database/AlbumBuilderFactory.java
new file mode 100644 (file)
index 0000000..e7a537d
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Sone - AlbumBuilderFactory.java - Copyright © 2013 David Roden
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package net.pterodactylus.sone.database;
+
+/**
+ * Factory for {@link AlbumBuilder}s.
+ *
+ * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+ */
+public interface AlbumBuilderFactory {
+
+       /**
+        * Creates a new album builder.
+        *
+        * @return A new album builder
+        */
+       AlbumBuilder newAlbumBuilder();
+
+}
diff --git a/src/main/java/net/pterodactylus/sone/database/AlbumDatabase.java b/src/main/java/net/pterodactylus/sone/database/AlbumDatabase.java
new file mode 100644 (file)
index 0000000..01d91b6
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * Sone - AlbumDatabase.java - Copyright © 2013 David Roden
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package net.pterodactylus.sone.database;
+
+/**
+ * Combines an {@link AlbumProvider} and an {@link AlbumStore} into an album
+ * database.
+ *
+ * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+ */
+public interface AlbumDatabase extends AlbumProvider, AlbumBuilderFactory, AlbumStore {
+
+       /* nothing here. */
+
+}
diff --git a/src/main/java/net/pterodactylus/sone/database/AlbumProvider.java b/src/main/java/net/pterodactylus/sone/database/AlbumProvider.java
new file mode 100644 (file)
index 0000000..b83b179
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * Sone - AlbumProvider.java - Copyright © 2013 David Roden
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package net.pterodactylus.sone.database;
+
+import net.pterodactylus.sone.data.Album;
+
+import com.google.common.base.Optional;
+
+/**
+ * Interface for objects that can provide {@link Album}s by their ID.
+ *
+ * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+ */
+public interface AlbumProvider {
+
+       /**
+        * Returns the album with the given ID, or {@link Optional#absent()} if no such
+        * album exists.
+        *
+        * @param albumId
+        *              The ID of the album
+        * @return The album, or {@link Optional#absent()} if the album does not exist
+        */
+       Optional<Album> getAlbum(String albumId);
+
+}
diff --git a/src/main/java/net/pterodactylus/sone/database/AlbumStore.java b/src/main/java/net/pterodactylus/sone/database/AlbumStore.java
new file mode 100644 (file)
index 0000000..c625535
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Sone - AlbumStore.java - Copyright © 2013 David Roden
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package net.pterodactylus.sone.database;
+
+import net.pterodactylus.sone.data.Album;
+
+/**
+ * Interface for a store of albums.
+ *
+ * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+ */
+public interface AlbumStore {
+
+       /**
+        * Stores the given album.
+        *
+        * @param album
+        *              The album to store
+        */
+       void storeAlbum(Album album);
+
+       /**
+        * Removes the given album from the store.
+        *
+        * @param album
+        *              The album to remove
+        */
+       void removeAlbum(Album album);
+
+}
index c93c061..ee7a9af 100644 (file)
@@ -26,7 +26,7 @@ import com.google.common.util.concurrent.Service;
  *
  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
  */
-public interface Database extends Service, PostDatabase, PostReplyDatabase {
+public interface Database extends Service, PostDatabase, PostReplyDatabase, AlbumDatabase, ImageDatabase {
 
        /**
         * Saves the database.
diff --git a/src/main/java/net/pterodactylus/sone/database/ImageBuilder.java b/src/main/java/net/pterodactylus/sone/database/ImageBuilder.java
new file mode 100644 (file)
index 0000000..af405c7
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Sone - ImageBuilder.java - Copyright © 2013 David Roden
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+package net.pterodactylus.sone.database;
+
+import net.pterodactylus.sone.data.Image;
+
+/**
+ * Builder for {@link Image} objects.
+ *
+ * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
+ */
+public interface ImageBuilder {
+
+       ImageBuilder randomId();
+
+       ImageBuilder withId(String id);
+
+       Image build() throws IllegalStateException;
+
+}
diff --git a/src/main/java/net/pterodactylus/sone/database/ImageBuilderFactory.java b/src/main/java/net/pterodactylus/sone/database/ImageBuilderFactory.java
new file mode 100644 (file)
index 0000000..29b605b
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * Sone - ImageBuilderFactory.java - Copyright © 2013 David Roden
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package net.pterodactylus.sone.database;
+
+/**
+ * Factory for {@link ImageBuilder}s.
+ *
+ * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
+ */
+public interface ImageBuilderFactory {
+
+       ImageBuilder newImageBuilder();
+
+}
diff --git a/src/main/java/net/pterodactylus/sone/database/ImageDatabase.java b/src/main/java/net/pterodactylus/sone/database/ImageDatabase.java
new file mode 100644 (file)
index 0000000..b5e436d
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * Sone - ImageDatabase.java - Copyright © 2013 David Roden
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package net.pterodactylus.sone.database;
+
+/**
+ * Combines an {@link ImageProvider}, an {@link ImageBuilderFactory}, and an
+ * {@link ImageStore} into an image database.
+ *
+ * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+ */
+public interface ImageDatabase extends ImageProvider, ImageBuilderFactory, ImageStore {
+
+       /* nothing here. */
+
+}
diff --git a/src/main/java/net/pterodactylus/sone/database/ImageProvider.java b/src/main/java/net/pterodactylus/sone/database/ImageProvider.java
new file mode 100644 (file)
index 0000000..c9ad9e1
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * Sone - ImageProvider.java - Copyright © 2013 David Roden
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package net.pterodactylus.sone.database;
+
+import net.pterodactylus.sone.data.Image;
+
+import com.google.common.base.Optional;
+
+/**
+ * Provides {@link Image}.
+ *
+ * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
+ */
+public interface ImageProvider {
+
+       Optional<Image> getImage(String imageId);
+
+}
diff --git a/src/main/java/net/pterodactylus/sone/database/ImageStore.java b/src/main/java/net/pterodactylus/sone/database/ImageStore.java
new file mode 100644 (file)
index 0000000..f09eff0
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * Sone - ImageStore.java - Copyright © 2013 David Roden
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package net.pterodactylus.sone.database;
+
+import net.pterodactylus.sone.data.Image;
+
+/**
+ * Manages {@link Image} storage.
+ *
+ * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
+ */
+public interface ImageStore {
+
+       void storeImage(Image image);
+
+       void removeImage(Image image);
+
+}
index 3f30d11..8b25954 100644 (file)
@@ -17,7 +17,8 @@
 
 package net.pterodactylus.sone.database.memory;
 
-import static com.google.common.base.Preconditions.*;
+import static com.google.common.base.Optional.fromNullable;
+import static com.google.common.base.Preconditions.checkNotNull;
 
 import java.util.ArrayList;
 import java.util.Collection;
@@ -33,12 +34,18 @@ import java.util.TreeSet;
 import java.util.concurrent.locks.ReadWriteLock;
 import java.util.concurrent.locks.ReentrantReadWriteLock;
 
+import net.pterodactylus.sone.data.Album;
+import net.pterodactylus.sone.data.Image;
 import net.pterodactylus.sone.data.Post;
 import net.pterodactylus.sone.data.PostReply;
 import net.pterodactylus.sone.data.Reply;
 import net.pterodactylus.sone.data.Sone;
+import net.pterodactylus.sone.data.impl.AlbumBuilderImpl;
+import net.pterodactylus.sone.data.impl.ImageBuilderImpl;
+import net.pterodactylus.sone.database.AlbumBuilder;
 import net.pterodactylus.sone.database.Database;
 import net.pterodactylus.sone.database.DatabaseException;
+import net.pterodactylus.sone.database.ImageBuilder;
 import net.pterodactylus.sone.database.PostBuilder;
 import net.pterodactylus.sone.database.PostDatabase;
 import net.pterodactylus.sone.database.PostReplyBuilder;
@@ -98,6 +105,10 @@ public class MemoryDatabase extends AbstractService implements Database {
        /** Whether post replies are known. */
        private final Set<String> knownPostReplies = new HashSet<String>();
 
+       private final Map<String, Album> allAlbums = new HashMap<String, Album>();
+
+       private final Map<String, Image> allImages = new HashMap<String, Image>();
+
        /**
         * Creates a new memory database.
         *
@@ -160,7 +171,7 @@ public class MemoryDatabase extends AbstractService implements Database {
        public Optional<Post> getPost(String postId) {
                lock.readLock().lock();
                try {
-                       return Optional.fromNullable(allPosts.get(postId));
+                       return fromNullable(allPosts.get(postId));
                } finally {
                        lock.readLock().unlock();
                }
@@ -294,7 +305,7 @@ public class MemoryDatabase extends AbstractService implements Database {
        public Optional<PostReply> getPostReply(String id) {
                lock.readLock().lock();
                try {
-                       return Optional.fromNullable(allPostReplies.get(id));
+                       return fromNullable(allPostReplies.get(id));
                } finally {
                        lock.readLock().unlock();
                }
@@ -412,6 +423,100 @@ public class MemoryDatabase extends AbstractService implements Database {
        }
 
        //
+       // ALBUMPROVDER METHODS
+       //
+
+       @Override
+       public Optional<Album> getAlbum(String albumId) {
+               lock.readLock().lock();
+               try {
+                       return fromNullable(allAlbums.get(albumId));
+               } finally {
+                       lock.readLock().unlock();
+               }
+       }
+
+       //
+       // ALBUMBUILDERFACTORY METHODS
+       //
+
+       @Override
+       public AlbumBuilder newAlbumBuilder() {
+               return new AlbumBuilderImpl();
+       }
+
+       //
+       // ALBUMSTORE METHODS
+       //
+
+       @Override
+       public void storeAlbum(Album album) {
+               lock.writeLock().lock();
+               try {
+                       allAlbums.put(album.getId(), album);
+               } finally {
+                       lock.writeLock().unlock();
+               }
+       }
+
+       @Override
+       public void removeAlbum(Album album) {
+               lock.writeLock().lock();
+               try {
+                       allAlbums.remove(album.getId());
+               } finally {
+                       lock.writeLock().unlock();
+               }
+       }
+
+       //
+       // IMAGEPROVIDER METHODS
+       //
+
+       @Override
+       public Optional<Image> getImage(String imageId) {
+               lock.readLock().lock();
+               try {
+                       return fromNullable(allImages.get(imageId));
+               } finally {
+                       lock.readLock().unlock();
+               }
+       }
+
+       //
+       // IMAGEBUILDERFACTORY METHODS
+       //
+
+       @Override
+       public ImageBuilder newImageBuilder() {
+               return new ImageBuilderImpl();
+       }
+
+       //
+       // IMAGESTORE METHODS
+       //
+
+       @Override
+       public void storeImage(Image image) {
+               lock.writeLock().lock();
+               try {
+                       allImages.put(image.getId(), image);
+               } finally {
+                       lock.writeLock().unlock();
+               }
+       }
+
+       @Override
+       public void removeImage(Image image) {
+               lock.writeLock().lock();
+               try {
+                       allImages.remove(image.getId());
+               } finally {
+                       lock.writeLock().unlock();
+               }
+       }
+
+       //
        // PACKAGE-PRIVATE METHODS
        //
 
index e31bbf5..61095b1 100644 (file)
@@ -104,7 +104,7 @@ public class SonePlugin implements FredPlugin, FredPluginFCP, FredPluginL10n, Fr
        }
 
        /** The version. */
-       public static final Version VERSION = new Version(0, 8, 7);
+       public static final Version VERSION = new Version(0, 8, 8);
 
        /** The logger. */
        private static final Logger logger = Logging.getLogger(SonePlugin.class);
index 13b4d65..9ef168a 100644 (file)
@@ -43,7 +43,7 @@ public class AlbumAccessor extends ReflectionAccessor {
                if ("backlinks".equals(member)) {
                        List<Link> backlinks = new ArrayList<Link>();
                        Album currentAlbum = album;
-                       while (!currentAlbum.equals(album.getSone().getRootAlbum())) {
+                       while (!currentAlbum.isRoot()) {
                                backlinks.add(0, new Link("imageBrowser.html?album=" + currentAlbum.getId(), currentAlbum.getTitle()));
                                currentAlbum = currentAlbum.getParent();
                        }
index ab872d9..92be8e0 100644 (file)
@@ -118,6 +118,8 @@ public class SoneAccessor extends ReflectionAccessor {
                        return trust;
                } else if (member.equals("allImages")) {
                        return from(asList(sone.getRootAlbum())).transformAndConcat(FLATTENER).transformAndConcat(IMAGES);
+               } else if (member.equals("albums")) {
+                       return sone.getRootAlbum().getAlbums();
                }
                return super.get(templateContext, object, member);
        }
index 6d81c0d..0b1585a 100644 (file)
@@ -28,6 +28,7 @@ import java.util.regex.Pattern;
 
 import net.pterodactylus.sone.data.Post;
 import net.pterodactylus.sone.data.Sone;
+import net.pterodactylus.sone.data.SoneImpl;
 import net.pterodactylus.sone.database.PostProvider;
 import net.pterodactylus.sone.database.SoneProvider;
 import net.pterodactylus.util.io.Closer;
@@ -248,7 +249,7 @@ public class SoneTextParser implements Parser<SoneTextParserContext> {
                                                                 * don’t use create=true above, we don’t want
                                                                 * the empty shell.
                                                                 */
-                                                               sone = Optional.fromNullable(new Sone(soneId, false));
+                                                               sone = Optional.<Sone>of(new SoneImpl(soneId, false));
                                                        }
                                                        parts.add(new SonePart(sone.get()));
                                                        line = line.substring(50);
index 9e9cd9e..a8d024a 100644 (file)
@@ -68,7 +68,7 @@ public class CreateAlbumPage extends SoneTemplatePage {
                                parent = currentSone.getRootAlbum();
                        }
                        Album album = webInterface.getCore().createAlbum(currentSone, parent);
-                       album.setTitle(name).setDescription(TextFilter.filter(request.getHttpRequest().getHeader("host"), description));
+                       album.modify().setTitle(name).setDescription(TextFilter.filter(request.getHttpRequest().getHeader("host"), description)).update();
                        webInterface.getCore().touchConfiguration();
                        throw new RedirectException("imageBrowser.html?album=" + album.getId());
                }
index 3db14d5..9e4aae9 100644 (file)
@@ -18,7 +18,6 @@
 package net.pterodactylus.sone.web;
 
 import net.pterodactylus.sone.data.Album;
-import net.pterodactylus.sone.data.Sone;
 import net.pterodactylus.sone.text.TextFilter;
 import net.pterodactylus.sone.web.page.FreenetRequest;
 import net.pterodactylus.util.template.Template;
@@ -72,14 +71,14 @@ public class EditAlbumPage extends SoneTemplatePage {
                        if (webInterface.getCore().getImage(albumImageId, false) == null) {
                                albumImageId = null;
                        }
-                       album.setAlbumImage(albumImageId);
+                       album.modify().setAlbumImage(albumImageId).update();
                        String title = request.getHttpRequest().getPartAsStringFailsafe("title", 100).trim();
                        if (title.length() == 0) {
                                templateContext.set("titleMissing", true);
                                return;
                        }
                        String description = request.getHttpRequest().getPartAsStringFailsafe("description", 1000).trim();
-                       album.setTitle(title).setDescription(TextFilter.filter(request.getHttpRequest().getHeader("host"), description));
+                       album.modify().setTitle(title).setDescription(TextFilter.filter(request.getHttpRequest().getHeader("host"), description)).update();
                        webInterface.getCore().touchConfiguration();
                        throw new RedirectException("imageBrowser.html?album=" + album.getId());
                }
index 75872eb..9a29c85 100644 (file)
@@ -73,8 +73,7 @@ public class EditImagePage extends SoneTemplatePage {
                                if (title.length() == 0) {
                                        templateContext.set("titleMissing", true);
                                }
-                               image.setTitle(title);
-                               image.setDescription(TextFilter.filter(request.getHttpRequest().getHeader("host"), description));
+                               image.modify().setTitle(title).setDescription(TextFilter.filter(request.getHttpRequest().getHeader("host"), description)).update();
                        }
                        webInterface.getCore().touchConfiguration();
                        throw new RedirectException(returnPage);
index c79a1e9..d0ddb26 100644 (file)
 
 package net.pterodactylus.sone.web;
 
+import static net.pterodactylus.sone.text.TextFilter.filter;
+
 import java.util.List;
 
 import net.pterodactylus.sone.data.Profile;
 import net.pterodactylus.sone.data.Profile.Field;
 import net.pterodactylus.sone.data.Sone;
+import net.pterodactylus.sone.text.TextFilter;
 import net.pterodactylus.sone.web.page.FreenetRequest;
 import net.pterodactylus.util.number.Numbers;
 import net.pterodactylus.util.template.Template;
@@ -85,7 +88,8 @@ public class EditProfilePage extends SoneTemplatePage {
                                profile.setAvatar(webInterface.getCore().getImage(avatarId, false));
                                for (Field field : fields) {
                                        String value = request.getHttpRequest().getPartAsStringFailsafe("field-" + field.getId(), 400);
-                                       field.setValue(value);
+                                       String filteredValue = filter(request.getHttpRequest().getHeader("Host"), value);
+                                       field.setValue(filteredValue);
                                }
                                currentSone.setProfile(profile);
                                webInterface.getCore().touchConfiguration();
index 2800f29..3844082 100644 (file)
@@ -123,7 +123,7 @@ public class UploadImagePage extends SoneTemplatePage {
                                String mimeType = getMimeType(imageData);
                                TemporaryImage temporaryImage = webInterface.getCore().createTemporaryImage(mimeType, imageData);
                                image = webInterface.getCore().createImage(currentSone, parent, temporaryImage);
-                               image.setTitle(name).setDescription(TextFilter.filter(request.getHttpRequest().getHeader("host"), description)).setWidth(uploadedImage.getWidth(null)).setHeight(uploadedImage.getHeight(null));
+                               image.modify().setTitle(name).setDescription(TextFilter.filter(request.getHttpRequest().getHeader("host"), description)).setWidth(uploadedImage.getWidth(null)).setHeight(uploadedImage.getHeight(null)).update();
                        } catch (IOException ioe1) {
                                logger.log(Level.WARNING, "Could not read uploaded image!", ioe1);
                                return;
index 5d587db..74a73b8 100644 (file)
@@ -68,7 +68,7 @@ public class EditAlbumAjaxPage extends JsonPage {
                }
                String title = request.getHttpRequest().getParam("title").trim();
                String description = request.getHttpRequest().getParam("description").trim();
-               album.setTitle(title).setDescription(TextFilter.filter(request.getHttpRequest().getHeader("host"), description));
+               album.modify().setTitle(title).setDescription(TextFilter.filter(request.getHttpRequest().getHeader("host"), description)).update();
                webInterface.getCore().touchConfiguration();
                return createSuccessJsonObject().put("albumId", album.getId()).put("title", album.getTitle()).put("description", album.getDescription());
        }
index 08452ef..0c45225 100644 (file)
@@ -78,7 +78,7 @@ public class EditImageAjaxPage extends JsonPage {
                }
                String title = request.getHttpRequest().getParam("title").trim();
                String description = request.getHttpRequest().getParam("description").trim();
-               image.setTitle(title).setDescription(TextFilter.filter(request.getHttpRequest().getHeader("host"), description));
+               image.modify().setTitle(title).setDescription(TextFilter.filter(request.getHttpRequest().getHeader("host"), description)).update();
                webInterface.getCore().touchConfiguration();
                return createSuccessJsonObject().put("imageId", image.getId()).put("title", image.getTitle()).put("description", image.getDescription()).put("parsedDescription", (String) parserFilter.format(new TemplateContext(), image.getDescription(), ImmutableMap.<String, Object>builder().put("sone", image.getSone()).build()));
        }
index c55159d..94c8b0f 100644 (file)
@@ -117,8 +117,8 @@ Page.KnownSones.Filter.Followed=Montrer seulement les Sones suivis
 Page.KnownSones.Filter.NotFollowed=Cacher les Sones suivis
 Page.KnownSones.Filter.New=Montrer seulement les nouveaux Sones
 Page.KnownSones.Filter.NotNew=Cacher les nouveaux Sones
-Page.KnownSones.Filter.Own=Show only local Sones
-Page.KnownSones.Filter.NotOwn=Show only remote Sones
+Page.KnownSones.Filter.Own=Montrer les Sones locaux
+Page.KnownSones.Filter.NotOwn=Montrer les Sones distants
 Page.KnownSones.Button.Apply=Appliquer
 Page.KnownSones.Button.FollowAllSones=Suivre tous les Sones de cette page
 Page.KnownSones.Button.UnfollowAllSones=Ne plus suivre tous les Sones de cette page
@@ -378,7 +378,7 @@ View.Time.InTheFuture=dans le futur
 View.Time.AFewSecondsAgo=au cours des dernières secondes passées
 View.Time.HalfAMinuteAgo=au cours des 30 dernières secondes
 View.Time.AMinuteAgo=au cours de la dernière minute
-View.Time.XMinutesAgo=il y a environs {min} minutes
+View.Time.XMinutesAgo=il y a environs ${min} minutes
 View.Time.HalfAnHourAgo=au cours de la dernière demi heure
 View.Time.AnHourAgo=il y a environ une heure
 View.Time.XHoursAgo=Il y a environ ${hour} heures
@@ -445,7 +445,7 @@ Notification.SoneIsBeingRescued.Text=Les Sones suivants sont actuellement en cou
 Notification.SoneRescued.Text=Les Sones suivants ont été sauvés:
 Notification.SoneRescued.Text.RememberToUnlock=Veuillez vous souvenir de contrôler les messages et réponses que vous avez donnés et n'oubliez ps de déverrouiller vos Sones!
 Notification.LockedSones.Text=Les Sones suivants ont été verrouillés pour plus de 5 minutes. Veuillez vérifier si vous voulez vraiment garder ces Sones bloqués:
-Notification.NewVersion.Text=La version {version} du plugin Sone a été trouvée. Téléchargez la depuis USK@nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI,DuQSUZiI~agF8c-6tjsFFGuZ8eICrzWCILB60nT8KKo,AQACAAE/sone/{edition}​!
+Notification.NewVersion.Text=La version ${version} du plugin Sone a été trouvée. Téléchargez la depuis USK@nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI,DuQSUZiI~agF8c-6tjsFFGuZ8eICrzWCILB60nT8KKo,AQACAAE/sone/{edition}​!
 Notification.InsertingImages.Text=Les images suivantes sont en cours d'insertion:
 Notification.InsertedImages.Text=Les images suivantes ont été insérées:
 Notification.ImageInsertFailed.Text=Les images suivantes ne peuvent être insérées:
@@ -454,4 +454,4 @@ Notification.Mention.Text=Vous avez été mentionné dans les messages suivants:
 Notification.SoneIsInserting.Text=Your Sone sone://{0} is now being inserted.
 Notification.SoneIsInserted.Text=Your Sone sone://{0} has been inserted in {1,number} {1,choice,0#seconds|1#second|1<seconds}.
 Notification.SoneInsertAborted.Text=Your Sone sone://{0} could not be inserted.
-# 120-121, 454-456
+# 454-456
index f599eb4..fc51e79 100644 (file)
@@ -4,7 +4,7 @@
                <%ifnull !sone.profile.avatar>
                        <%sone.profile.avatar|image-link max-width==64 max-height==64 mode==enlarge title=sone.niceName>
                <%else>
-                       <img src="/WebOfTrust/GetIdenticon?identity=<%sone.id|html>&amp;width=64&amp;height=64" width="64" height="64" alt="Avatar Image" />
+                       <img src="/WebOfTrust/GetIdenticon?identity=<%sone.id|html>&amp;width=128&amp;height=128" width="64" height="64" alt="Avatar Image" />
                <%/if>
        </div>
        <div class="inner-menu">
index efc3d53..1c53d42 100644 (file)
@@ -9,7 +9,7 @@
                        <%ifnull !post.sone.profile.avatar>
                                <%post.sone.profile.avatar|image-link max-width==48 max-height==48 mode==enlarge title=="Avatar Image">
                        <%else>
-                               <img src="/WebOfTrust/GetIdenticon?identity=<% post.sone.id|html>&amp;width=48&amp;height=48" width="48" height="48" alt="Avatar Image" />
+                               <img src="/WebOfTrust/GetIdenticon?identity=<% post.sone.id|html>&amp;width=96&amp;height=96" width="48" height="48" alt="Avatar Image" />
                        <%/if>
                <%else>
                        <img src="images/sone-avatar.png" width="48" height="48" alt="Avatar Image" />
index 449a235..ab20441 100644 (file)
@@ -8,7 +8,7 @@
                <%ifnull !reply.sone.profile.avatar>
                        <% reply.sone.profile.avatar|image-link max-width==36 max-height==36 mode==enlarge title=="Avatar Image">
                <%else>
-                       <img src="/WebOfTrust/GetIdenticon?identity=<% reply.sone.id|html>&amp;width=36&height=36" width="36" height="36" alt="Avatar Image" />
+                       <img src="/WebOfTrust/GetIdenticon?identity=<% reply.sone.id|html>&amp;width=72&height=72" width="36" height="36" alt="Avatar Image" />
                <%/if>
        </div>
        <div class="inner-part">
diff --git a/src/test/java/net/pterodactylus/sone/database/memory/MemoryDatabaseTest.java b/src/test/java/net/pterodactylus/sone/database/memory/MemoryDatabaseTest.java
new file mode 100644 (file)
index 0000000..056a06d
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * Sone - MemoryDatabaseTest.java - Copyright © 2013 David Roden
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package net.pterodactylus.sone.database.memory;
+
+import static com.google.common.base.Optional.of;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import net.pterodactylus.sone.data.Album;
+import net.pterodactylus.sone.data.AlbumImpl;
+
+import com.google.common.base.Optional;
+import org.junit.Test;
+
+/**
+ * Tests for {@link MemoryDatabase}.
+ *
+ * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+ */
+public class MemoryDatabaseTest {
+
+       private final MemoryDatabase memoryDatabase = new MemoryDatabase(null, null);
+
+       @Test
+       public void testBasicAlbumFunctionality() {
+               Album newAlbum = new AlbumImpl();
+               assertThat(memoryDatabase.getAlbum(newAlbum.getId()), is(Optional.<Album>absent()));
+               memoryDatabase.storeAlbum(newAlbum);
+               assertThat(memoryDatabase.getAlbum(newAlbum.getId()), is(of(newAlbum)));
+               memoryDatabase.removeAlbum(newAlbum);
+               assertThat(memoryDatabase.getAlbum(newAlbum.getId()), is(Optional.<Album>absent()));
+       }
+
+}
index 7286001..2c04b23 100644 (file)
@@ -26,6 +26,7 @@ import com.google.common.base.Optional;
 
 import junit.framework.TestCase;
 import net.pterodactylus.sone.data.Sone;
+import net.pterodactylus.sone.data.SoneImpl;
 import net.pterodactylus.sone.database.SoneProvider;
 
 /**
@@ -185,7 +186,7 @@ public class SoneTextParserTest extends TestCase {
                 */
                @Override
                public Optional<Sone> getSone(final String soneId) {
-                       return Optional.<Sone> fromNullable(new Sone(soneId, false) {
+                       return Optional.<Sone>of(new SoneImpl(soneId, false) {
 
                                /**
                                 * {@inheritDoc}