12ef439f762b3552d97c8271cf6b6b4483119df7
[Sone.git] / src / main / java / net / pterodactylus / sone / database / memory / MemoryDatabase.java
1 /*
2  * Sone - MemoryDatabase.java - Copyright © 2013 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sone.database.memory;
19
20 import static com.google.common.base.Optional.fromNullable;
21 import static com.google.common.base.Preconditions.checkNotNull;
22 import static com.google.common.base.Predicates.not;
23 import static com.google.common.collect.FluentIterable.from;
24 import static java.lang.String.format;
25 import static java.util.logging.Level.WARNING;
26 import static net.pterodactylus.sone.data.Reply.TIME_COMPARATOR;
27 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
28 import static net.pterodactylus.sone.data.Sone.toAllAlbums;
29 import static net.pterodactylus.sone.data.Sone.toAllImages;
30
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.Comparator;
34 import java.util.HashMap;
35 import java.util.HashSet;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.Set;
39 import java.util.concurrent.locks.ReadWriteLock;
40 import java.util.concurrent.locks.ReentrantReadWriteLock;
41 import java.util.logging.Level;
42 import java.util.logging.Logger;
43
44 import net.pterodactylus.sone.core.ConfigurationSoneParser;
45 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidAlbumFound;
46 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidImageFound;
47 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidParentAlbumFound;
48 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostFound;
49 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostReplyFound;
50 import net.pterodactylus.sone.data.Album;
51 import net.pterodactylus.sone.data.Client;
52 import net.pterodactylus.sone.data.Image;
53 import net.pterodactylus.sone.data.LocalSone;
54 import net.pterodactylus.sone.data.Post;
55 import net.pterodactylus.sone.data.PostReply;
56 import net.pterodactylus.sone.data.Profile;
57 import net.pterodactylus.sone.data.Profile.Field;
58 import net.pterodactylus.sone.data.Sone;
59 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
60 import net.pterodactylus.sone.data.impl.AlbumBuilderImpl;
61 import net.pterodactylus.sone.data.impl.ImageBuilderImpl;
62 import net.pterodactylus.sone.database.AlbumBuilder;
63 import net.pterodactylus.sone.database.Database;
64 import net.pterodactylus.sone.database.DatabaseException;
65 import net.pterodactylus.sone.database.ImageBuilder;
66 import net.pterodactylus.sone.database.PostBuilder;
67 import net.pterodactylus.sone.database.PostDatabase;
68 import net.pterodactylus.sone.database.PostReplyBuilder;
69 import net.pterodactylus.sone.database.SoneBuilder;
70 import net.pterodactylus.sone.database.SoneProvider;
71 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
72 import net.pterodactylus.sone.main.SonePlugin;
73 import net.pterodactylus.sone.utils.Optionals;
74 import net.pterodactylus.util.config.Configuration;
75 import net.pterodactylus.util.config.ConfigurationException;
76
77 import com.google.common.base.Function;
78 import com.google.common.base.Optional;
79 import com.google.common.base.Predicate;
80 import com.google.common.collect.FluentIterable;
81 import com.google.common.collect.HashMultimap;
82 import com.google.common.collect.Multimap;
83 import com.google.common.collect.SortedSetMultimap;
84 import com.google.common.collect.TreeMultimap;
85 import com.google.common.primitives.Longs;
86 import com.google.common.util.concurrent.AbstractService;
87 import com.google.inject.Inject;
88 import com.google.inject.Singleton;
89
90 /**
91  * Memory-based {@link PostDatabase} implementation.
92  *
93  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
94  */
95 @Singleton
96 public class MemoryDatabase extends AbstractService implements Database {
97
98         private static final Logger logger = Logger.getLogger("Sone.Database.Memory");
99         private static final String LATEST_EDITION_PROPERTY = "Sone.LatestEdition";
100         /** The lock. */
101         private final ReadWriteLock lock = new ReentrantReadWriteLock();
102
103         /** The Sone provider. */
104         private final SoneProvider soneProvider;
105
106         /** The configuration. */
107         private final Configuration configuration;
108         private final ConfigurationLoader configurationLoader;
109
110         private final Set<String> localSones = new HashSet<String>();
111         private final Map<String, Sone> allSones = new HashMap<String, Sone>();
112         private final Map<String, String> lastInsertFingerprints = new HashMap<String, String>();
113
114         /** All post replies by their ID. */
115         private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
116
117         /** Replies sorted by Sone. */
118         private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
119
120                 @Override
121                 public int compare(String leftString, String rightString) {
122                         return leftString.compareTo(rightString);
123                 }
124         }, TIME_COMPARATOR);
125
126         /** Whether post replies are known. */
127         private final Set<String> knownPostReplies = new HashSet<String>();
128
129         private final Map<String, Album> allAlbums = new HashMap<String, Album>();
130         private final Multimap<String, Album> soneAlbums = HashMultimap.create();
131
132         private final Map<String, Image> allImages = new HashMap<String, Image>();
133         private final Multimap<String, Image> soneImages = HashMultimap.create();
134
135         private final MemoryPostDatabase postDatabase;
136         private final MemoryBookmarkDatabase memoryBookmarkDatabase;
137         private final MemoryFriendDatabase memoryFriendDatabase;
138
139         /**
140          * Creates a new memory database.
141          *
142          * @param soneProvider
143          *              The Sone provider
144          * @param configuration
145          *              The configuration for loading and saving elements
146          */
147         @Inject
148         public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
149                 this.soneProvider = soneProvider;
150                 this.configuration = configuration;
151                 this.configurationLoader = new ConfigurationLoader(configuration);
152                 postDatabase = new MemoryPostDatabase(this, configurationLoader);
153                 memoryBookmarkDatabase =
154                                 new MemoryBookmarkDatabase(this, configurationLoader);
155                 memoryFriendDatabase = new MemoryFriendDatabase(configurationLoader);
156         }
157
158         //
159         // DATABASE METHODS
160         //
161
162         @Override
163         public Optional<LocalSone> getLocalSone(String localSoneId) {
164                 lock.readLock().lock();
165                 try {
166                         if (!localSones.contains(localSoneId)) {
167                                 return Optional.absent();
168                         }
169                         return Optional.of((LocalSone) allSones.get(localSoneId));
170                 } finally {
171                         lock.readLock().unlock();
172                 }
173         }
174
175         @Override
176         public Sone registerLocalSone(OwnIdentity ownIdentity) {
177                 final Sone localSone = loadLocalSone(ownIdentity);
178                 localSones.add(ownIdentity.getId());
179                 return localSone;
180         }
181
182         private Sone loadLocalSone(OwnIdentity ownIdentity) {
183                 Sone localSone = newSoneBuilder().local().from(ownIdentity).build();
184                 localSone.setLatestEdition(
185                                 Optional.fromNullable(
186                                                 Longs.tryParse(ownIdentity.getProperty(LATEST_EDITION_PROPERTY)))
187                                 .or(0L));
188                 localSone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
189                 localSone.setKnown(true);
190
191                 loadSone(localSone);
192                 return localSone;
193         }
194
195         public void loadSone(Sone sone) {
196                 long soneTime = configurationLoader.getLocalSoneTime(sone.getId());
197                 if (soneTime == -1) {
198                         return;
199                 }
200
201                 /* load profile. */
202                 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
203                 Profile profile = configurationSoneParser.parseProfile();
204
205                 /* load posts. */
206                 Collection<Post> posts;
207                 try {
208                         posts = configurationSoneParser.parsePosts(this);
209                 } catch (InvalidPostFound ipf) {
210                         logger.log(Level.WARNING, "Invalid post found, aborting load!");
211                         return;
212                 }
213
214                 /* load replies. */
215                 Collection<PostReply> postReplies;
216                 try {
217                         postReplies = configurationSoneParser.parsePostReplies(this);
218                 } catch (InvalidPostReplyFound iprf) {
219                         logger.log(Level.WARNING, "Invalid reply found, aborting load!");
220                         return;
221                 }
222
223                 /* load post likes. */
224                 Set<String> likedPostIds = configurationSoneParser.parseLikedPostIds();
225
226                 /* load reply likes. */
227                 Set<String> likedReplyIds = configurationSoneParser.parseLikedPostReplyIds();
228
229                 /* load albums. */
230                 List<Album> topLevelAlbums;
231                 try {
232                         topLevelAlbums = configurationSoneParser.parseTopLevelAlbums(this);
233                 } catch (InvalidAlbumFound iaf) {
234                         logger.log(Level.WARNING, "Invalid album found, aborting load!");
235                         return;
236                 } catch (InvalidParentAlbumFound ipaf) {
237                         logger.log(Level.WARNING,
238                                         format("Invalid parent album ID: %s", ipaf.getAlbumParentId()));
239                         return;
240                 }
241
242                 /* load images. */
243                 try {
244                         configurationSoneParser.parseImages(this);
245                 } catch (InvalidImageFound iif) {
246                         logger.log(WARNING, "Invalid image found, aborting load!");
247                         return;
248                 } catch (InvalidParentAlbumFound ipaf) {
249                         logger.log(Level.WARNING,
250                                         format("Invalid album image (%s) encountered, aborting load!",
251                                                         ipaf.getAlbumParentId()));
252                         return;
253                 }
254
255                 /* load avatar. */
256                 String sonePrefix = "Sone/" + sone.getId();
257                 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
258                 if (avatarId != null) {
259                         final Map<String, Image> images = configurationSoneParser.getImages();
260                         profile.setAvatar(images.get(avatarId));
261                 }
262
263                 /* load options. */
264                 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
265                 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
266                 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
267                 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
268                 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
269                 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(
270                                 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars")
271                                                 .getValue(ShowCustomAvatars.NEVER.name())));
272
273                 /* if we’re still here, Sone was loaded successfully. */
274                 lock.writeLock().lock();
275                 try {
276                         sone.setTime(soneTime);
277                         sone.setProfile(profile);
278                         sone.setLikePostIds(likedPostIds);
279                         sone.setLikeReplyIds(likedReplyIds);
280
281                         String lastInsertFingerprint = configurationLoader.getLastInsertFingerprint(sone.getId());
282                         lastInsertFingerprints.put(sone.getId(), lastInsertFingerprint);
283
284                         allSones.put(sone.getId(), sone);
285                         storePosts(sone.getId(), posts);
286                         storePostReplies(sone.getId(), postReplies);
287                         storeAlbums(sone.getId(), topLevelAlbums);
288                         storeImages(sone.getId(), from(topLevelAlbums).transformAndConcat(Album.FLATTENER).transformAndConcat(Album.IMAGES).toList());
289                 } finally {
290                         lock.writeLock().unlock();
291                 }
292                 for (Post post : posts) {
293                         post.setKnown(true);
294                 }
295                 for (PostReply reply : postReplies) {
296                         reply.setKnown(true);
297                 }
298
299                 logger.info(String.format("Sone loaded successfully: %s", sone));
300         }
301
302         @Override
303         public String getLastInsertFingerprint(Sone sone) {
304                 lock.readLock().lock();
305                 try {
306                         if (!lastInsertFingerprints.containsKey(sone.getId())) {
307                                 return "";
308                         }
309                         return lastInsertFingerprints.get(sone.getId());
310                 } finally {
311                         lock.readLock().unlock();
312                 }
313         }
314
315         @Override
316         public void setLastInsertFingerprint(Sone sone, String lastInsertFingerprint) {
317                 lock.writeLock().lock();
318                 try {
319                         lastInsertFingerprints.put(sone.getId(), lastInsertFingerprint);
320                 } finally {
321                         lock.writeLock().unlock();
322                 }
323         }
324
325         /**
326          * Saves the database.
327          *
328          * @throws DatabaseException
329          *              if an error occurs while saving
330          */
331         @Override
332         public void save() throws DatabaseException {
333                 lock.writeLock().lock();
334                 try {
335                         saveKnownPostReplies();
336                         for (Sone localSone : from(localSones).transform(soneLoader()).transform(Optionals.<Sone>get())) {
337                                 saveSone(localSone);
338                         }
339                 } finally {
340                         lock.writeLock().unlock();
341                 }
342         }
343
344         private synchronized void saveSone(Sone sone) {
345                 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
346                 try {
347                         /* save Sone into configuration. */
348                         String sonePrefix = "Sone/" + sone.getId();
349                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
350                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(lastInsertFingerprints.get(sone.getId()));
351
352                         /* save profile. */
353                         Profile profile = sone.getProfile();
354                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
355                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
356                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
357                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
358                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
359                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
360                         configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
361
362                         /* save profile fields. */
363                         int fieldCounter = 0;
364                         for (Field profileField : profile.getFields()) {
365                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
366                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
367                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
368                         }
369                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
370
371                         /* save posts. */
372                         int postCounter = 0;
373                         for (Post post : sone.getPosts()) {
374                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
375                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
376                                 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
377                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
378                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
379                         }
380                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
381
382                         /* save replies. */
383                         int replyCounter = 0;
384                         for (PostReply reply : sone.getReplies()) {
385                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
386                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
387                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
388                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
389                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
390                         }
391                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
392
393                         /* save post likes. */
394                         int postLikeCounter = 0;
395                         for (String postId : sone.getLikedPostIds()) {
396                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
397                         }
398                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
399
400                         /* save reply likes. */
401                         int replyLikeCounter = 0;
402                         for (String replyId : sone.getLikedReplyIds()) {
403                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
404                         }
405                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
406
407                         /* save albums. first, collect in a flat structure, top-level first. */
408                         List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
409
410                         int albumCounter = 0;
411                         for (Album album : albums) {
412                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
413                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
414                                 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
415                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
416                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
417                                 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
418                         }
419                         configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
420
421                         /* save images. */
422                         int imageCounter = 0;
423                         for (Album album : albums) {
424                                 for (Image image : album.getImages()) {
425                                         if (!image.isInserted()) {
426                                                 continue;
427                                         }
428                                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
429                                         configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
430                                         configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
431                                         configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
432                                         configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
433                                         configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
434                                         configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
435                                         configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
436                                         configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
437                                 }
438                         }
439                         configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
440
441                         /* save options. */
442                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
443                         configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
444                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
445                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
446                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
447                         configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
448
449                         configuration.save();
450
451                         logger.log(Level.INFO, String.format("Sone %s saved.", sone));
452                 } catch (ConfigurationException ce1) {
453                         logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
454                 }
455         }
456
457         //
458         // SERVICE METHODS
459         //
460
461         /** {@inheritDocs} */
462         @Override
463         protected void doStart() {
464                 postDatabase.start();
465                 memoryBookmarkDatabase.start();
466                 loadKnownPostReplies();
467                 notifyStarted();
468         }
469
470         /** {@inheritDocs} */
471         @Override
472         protected void doStop() {
473                 try {
474                         postDatabase.stop();
475                         memoryBookmarkDatabase.stop();
476                         save();
477                         notifyStopped();
478                 } catch (DatabaseException de1) {
479                         notifyFailed(de1);
480                 }
481         }
482
483         @Override
484         public SoneBuilder newSoneBuilder() {
485                 return new MemorySoneBuilder(this);
486         }
487
488         @Override
489         public void storeSone(Sone sone) {
490                 lock.writeLock().lock();
491                 try {
492                         removeSone(sone);
493
494                         allSones.put(sone.getId(), sone);
495                         storePosts(sone.getId(), sone.getPosts());
496                         storePostReplies(sone.getId(), sone.getReplies());
497                         storeAlbums(sone.getId(), toAllAlbums.apply(sone));
498                         storeImages(sone.getId(), toAllImages.apply(sone));
499                 } finally {
500                         lock.writeLock().unlock();
501                 }
502         }
503
504         private void storePosts(String soneId, Collection<Post> posts) {
505                 postDatabase.storePosts(soneId, posts);
506         }
507
508         private void storePostReplies(String soneId, Collection<PostReply> postReplies) {
509                 sonePostReplies.putAll(soneId, postReplies);
510                 for (PostReply postReply : postReplies) {
511                         allPostReplies.put(postReply.getId(), postReply);
512                 }
513         }
514
515         private void storeAlbums(String soneId, Collection<Album> albums) {
516                 soneAlbums.putAll(soneId, albums);
517                 for (Album album : albums) {
518                         allAlbums.put(album.getId(), album);
519                 }
520         }
521
522         private void storeImages(String soneId, Collection<Image> images) {
523                 soneImages.putAll(soneId, images);
524                 for (Image image : images) {
525                         allImages.put(image.getId(), image);
526                 }
527         }
528
529         @Override
530         public void removeSone(Sone sone) {
531                 lock.writeLock().lock();
532                 try {
533                         allSones.remove(sone.getId());
534                         postDatabase.removePostsFor(sone.getId());
535                         Collection<PostReply> removedPostReplies =
536                                         sonePostReplies.removeAll(sone.getId());
537                         for (PostReply removedPostReply : removedPostReplies) {
538                                 allPostReplies.remove(removedPostReply.getId());
539                         }
540                         Collection<Album> removedAlbums =
541                                         soneAlbums.removeAll(sone.getId());
542                         for (Album removedAlbum : removedAlbums) {
543                                 allAlbums.remove(removedAlbum.getId());
544                         }
545                         Collection<Image> removedImages =
546                                         soneImages.removeAll(sone.getId());
547                         for (Image removedImage : removedImages) {
548                                 allImages.remove(removedImage.getId());
549                         }
550                 } finally {
551                         lock.writeLock().unlock();
552                 }
553         }
554
555         @Override
556         public Function<String, Optional<Sone>> soneLoader() {
557                 return new Function<String, Optional<Sone>>() {
558                         @Override
559                         public Optional<Sone> apply(String soneId) {
560                                 return getSone(soneId);
561                         }
562                 };
563         }
564
565         @Override
566         public Optional<Sone> getSone(String soneId) {
567                 lock.readLock().lock();
568                 try {
569                         return fromNullable(allSones.get(soneId));
570                 } finally {
571                         lock.readLock().unlock();
572                 }
573         }
574
575         @Override
576         public Collection<Sone> getSones() {
577                 lock.readLock().lock();
578                 try {
579                         return new HashSet<Sone>(allSones.values());
580                 } finally {
581                         lock.readLock().unlock();
582                 }
583         }
584
585         @Override
586         public Collection<Sone> getLocalSones() {
587                 lock.readLock().lock();
588                 try {
589                         return from(allSones.values()).filter(LOCAL_SONE_FILTER).toSet();
590                 } finally {
591                         lock.readLock().unlock();
592                 }
593         }
594
595         @Override
596         public Collection<Sone> getRemoteSones() {
597                 lock.readLock().lock();
598                 try {
599                         return from(allSones.values())
600                                         .filter(not(LOCAL_SONE_FILTER)) .toSet();
601                 } finally {
602                         lock.readLock().unlock();
603                 }
604         }
605
606         @Override
607         public Collection<String> getFriends(Sone localSone) {
608                 if (!localSone.isLocal()) {
609                         return Collections.emptySet();
610                 }
611                 return memoryFriendDatabase.getFriends(localSone.getId());
612         }
613
614         @Override
615         public boolean isFriend(Sone localSone, String friendSoneId) {
616                 if (!localSone.isLocal()) {
617                         return false;
618                 }
619                 return memoryFriendDatabase.isFriend(localSone.getId(), friendSoneId);
620         }
621
622         @Override
623         public void addFriend(Sone localSone, String friendSoneId) {
624                 if (!localSone.isLocal()) {
625                         return;
626                 }
627                 memoryFriendDatabase.addFriend(localSone.getId(), friendSoneId);
628         }
629
630         @Override
631         public void removeFriend(Sone localSone, String friendSoneId) {
632                 if (!localSone.isLocal()) {
633                         return;
634                 }
635                 memoryFriendDatabase.removeFriend(localSone.getId(), friendSoneId);
636         }
637
638         //
639         // POSTPROVIDER METHODS
640         //
641
642         /** {@inheritDocs} */
643         @Override
644         public Optional<Post> getPost(String postId) {
645                 return postDatabase.getPost(postId);
646         }
647
648         /** {@inheritDocs} */
649         @Override
650         public Collection<Post> getPosts(String soneId) {
651                 return new HashSet<Post>(getPostsFrom(soneId));
652         }
653
654         /** {@inheritDocs} */
655         @Override
656         public Collection<Post> getDirectedPosts(final String recipientId) {
657                 return postDatabase.getDirectedPosts(recipientId);
658         }
659
660         //
661         // POSTBUILDERFACTORY METHODS
662         //
663
664         /** {@inheritDocs} */
665         @Override
666         public PostBuilder newPostBuilder() {
667                 return new MemoryPostBuilder(this, soneProvider);
668         }
669
670         //
671         // POSTSTORE METHODS
672         //
673
674         /** {@inheritDocs} */
675         @Override
676         public void storePost(Post post) {
677                 checkNotNull(post, "post must not be null");
678                 postDatabase.storePost(post);
679         }
680
681         /** {@inheritDocs} */
682         @Override
683         public void removePost(Post post) {
684                 checkNotNull(post, "post must not be null");
685                 postDatabase.removePost(post.getId());
686         }
687
688         //
689         // POSTREPLYPROVIDER METHODS
690         //
691
692         /** {@inheritDocs} */
693         @Override
694         public Optional<PostReply> getPostReply(String id) {
695                 lock.readLock().lock();
696                 try {
697                         return fromNullable(allPostReplies.get(id));
698                 } finally {
699                         lock.readLock().unlock();
700                 }
701         }
702
703         /** {@inheritDocs} */
704         @Override
705         public List<PostReply> getReplies(final String postId) {
706                 lock.readLock().lock();
707                 try {
708                         return from(allPostReplies.values())
709                                         .filter(new Predicate<PostReply>() {
710                                                 @Override
711                                                 public boolean apply(PostReply postReply) {
712                                                         return postReply.getPostId().equals(postId);
713                                                 }
714                                         }).toSortedList(TIME_COMPARATOR);
715                 } finally {
716                         lock.readLock().unlock();
717                 }
718         }
719
720         //
721         // POSTREPLYBUILDERFACTORY METHODS
722         //
723
724         /** {@inheritDocs} */
725         @Override
726         public PostReplyBuilder newPostReplyBuilder() {
727                 return new MemoryPostReplyBuilder(this, soneProvider);
728         }
729
730         //
731         // POSTREPLYSTORE METHODS
732         //
733
734         /** {@inheritDocs} */
735         @Override
736         public void storePostReply(PostReply postReply) {
737                 lock.writeLock().lock();
738                 try {
739                         allPostReplies.put(postReply.getId(), postReply);
740                 } finally {
741                         lock.writeLock().unlock();
742                 }
743         }
744
745         /** {@inheritDocs} */
746         @Override
747         public void removePostReply(PostReply postReply) {
748                 lock.writeLock().lock();
749                 try {
750                         allPostReplies.remove(postReply.getId());
751                 } finally {
752                         lock.writeLock().unlock();
753                 }
754         }
755
756         //
757         // ALBUMPROVDER METHODS
758         //
759
760         @Override
761         public Optional<Album> getAlbum(String albumId) {
762                 lock.readLock().lock();
763                 try {
764                         return fromNullable(allAlbums.get(albumId));
765                 } finally {
766                         lock.readLock().unlock();
767                 }
768         }
769
770         //
771         // ALBUMBUILDERFACTORY METHODS
772         //
773
774         @Override
775         public AlbumBuilder newAlbumBuilder() {
776                 return new AlbumBuilderImpl();
777         }
778
779         //
780         // ALBUMSTORE METHODS
781         //
782
783         @Override
784         public void storeAlbum(Album album) {
785                 lock.writeLock().lock();
786                 try {
787                         allAlbums.put(album.getId(), album);
788                         soneAlbums.put(album.getSone().getId(), album);
789                 } finally {
790                         lock.writeLock().unlock();
791                 }
792         }
793
794         @Override
795         public void removeAlbum(Album album) {
796                 lock.writeLock().lock();
797                 try {
798                         allAlbums.remove(album.getId());
799                         soneAlbums.remove(album.getSone().getId(), album);
800                 } finally {
801                         lock.writeLock().unlock();
802                 }
803         }
804
805         //
806         // IMAGEPROVIDER METHODS
807         //
808
809         @Override
810         public Optional<Image> getImage(String imageId) {
811                 lock.readLock().lock();
812                 try {
813                         return fromNullable(allImages.get(imageId));
814                 } finally {
815                         lock.readLock().unlock();
816                 }
817         }
818
819         //
820         // IMAGEBUILDERFACTORY METHODS
821         //
822
823         @Override
824         public ImageBuilder newImageBuilder() {
825                 return new ImageBuilderImpl();
826         }
827
828         //
829         // IMAGESTORE METHODS
830         //
831
832         @Override
833         public void storeImage(Image image) {
834                 lock.writeLock().lock();
835                 try {
836                         allImages.put(image.getId(), image);
837                         soneImages.put(image.getSone().getId(), image);
838                 } finally {
839                         lock.writeLock().unlock();
840                 }
841         }
842
843         @Override
844         public void removeImage(Image image) {
845                 lock.writeLock().lock();
846                 try {
847                         allImages.remove(image.getId());
848                         soneImages.remove(image.getSone().getId(), image);
849                 } finally {
850                         lock.writeLock().unlock();
851                 }
852         }
853
854         @Override
855         public void bookmarkPost(Post post) {
856                 memoryBookmarkDatabase.bookmarkPost(post);
857         }
858
859         @Override
860         public void unbookmarkPost(Post post) {
861                 memoryBookmarkDatabase.unbookmarkPost(post);
862         }
863
864         @Override
865         public boolean isPostBookmarked(Post post) {
866                 return memoryBookmarkDatabase.isPostBookmarked(post);
867         }
868
869         @Override
870         public Set<Post> getBookmarkedPosts() {
871                 return memoryBookmarkDatabase.getBookmarkedPosts();
872         }
873
874         //
875         // PACKAGE-PRIVATE METHODS
876         //
877
878         /**
879          * Returns whether the given post is known.
880          *
881          * @param post
882          *              The post
883          * @return {@code true} if the post is known, {@code false} otherwise
884          */
885         boolean isPostKnown(Post post) {
886                 return postDatabase.isPostKnown(post.getId());
887         }
888
889         /**
890          * Sets whether the given post is known.
891          *
892          * @param post
893          *              The post
894          * @param known
895          *              {@code true} if the post is known, {@code false} otherwise
896          */
897         void setPostKnown(Post post, boolean known) {
898                 postDatabase.setPostKnown(post.getId(), known);
899         }
900
901         /**
902          * Returns whether the given post reply is known.
903          *
904          * @param postReply
905          *              The post reply
906          * @return {@code true} if the given post reply is known, {@code false}
907          *         otherwise
908          */
909         boolean isPostReplyKnown(PostReply postReply) {
910                 lock.readLock().lock();
911                 try {
912                         return knownPostReplies.contains(postReply.getId());
913                 } finally {
914                         lock.readLock().unlock();
915                 }
916         }
917
918         /**
919          * Sets whether the given post reply is known.
920          *
921          * @param postReply
922          *              The post reply
923          * @param known
924          *              {@code true} if the post reply is known, {@code false} otherwise
925          */
926         void setPostReplyKnown(PostReply postReply, boolean known) {
927                 lock.writeLock().lock();
928                 try {
929                         if (known) {
930                                 knownPostReplies.add(postReply.getId());
931                         } else {
932                                 knownPostReplies.remove(postReply.getId());
933                         }
934                 } finally {
935                         lock.writeLock().unlock();
936                 }
937         }
938
939         //
940         // PRIVATE METHODS
941         //
942
943         /**
944          * Gets all posts for the given Sone, creating a new collection if there is
945          * none yet.
946          *
947          * @param soneId
948          *              The ID of the Sone to get the posts for
949          * @return All posts
950          */
951         private Collection<Post> getPostsFrom(String soneId) {
952                 return postDatabase.getPostsFrom(soneId);
953         }
954
955         /** Loads the known post replies. */
956         private void loadKnownPostReplies() {
957                 Set<String> knownPostReplies = configurationLoader.loadKnownPostReplies();
958                 lock.writeLock().lock();
959                 try {
960                         this.knownPostReplies.clear();
961                         this.knownPostReplies.addAll(knownPostReplies);
962                 } finally {
963                         lock.writeLock().unlock();
964                 }
965         }
966
967         /**
968          * Saves the known post replies to the configuration.
969          *
970          * @throws DatabaseException
971          *              if a configuration error occurs
972          */
973         private void saveKnownPostReplies() throws DatabaseException {
974                 lock.readLock().lock();
975                 try {
976                         int replyCounter = 0;
977                         for (String knownReplyId : knownPostReplies) {
978                                 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(
979                                                 knownReplyId);
980                         }
981                         configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
982                 } catch (ConfigurationException ce1) {
983                         throw new DatabaseException("Could not save database.", ce1);
984                 } finally {
985                         lock.readLock().unlock();
986                 }
987         }
988
989 }