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