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