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