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