2 * Sone - MemoryDatabase.java - Copyright © 2013 David Roden
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.
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.
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/>.
18 package net.pterodactylus.sone.database.memory;
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;
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;
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;
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;
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;
91 * Memory-based {@link PostDatabase} implementation.
93 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
96 public class MemoryDatabase extends AbstractService implements Database {
98 private static final Logger logger = Logger.getLogger("Sone.Database.Memory");
99 private static final String LATEST_EDITION_PROPERTY = "Sone.LatestEdition";
101 private final ReadWriteLock lock = new ReentrantReadWriteLock();
103 /** The Sone provider. */
104 private final SoneProvider soneProvider;
106 /** The configuration. */
107 private final Configuration configuration;
108 private final ConfigurationLoader configurationLoader;
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>();
114 /** All post replies by their ID. */
115 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
117 /** Replies sorted by Sone. */
118 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
121 public int compare(String leftString, String rightString) {
122 return leftString.compareTo(rightString);
126 /** Whether post replies are known. */
127 private final Set<String> knownPostReplies = new HashSet<String>();
129 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
130 private final Multimap<String, Album> soneAlbums = HashMultimap.create();
132 private final Map<String, Image> allImages = new HashMap<String, Image>();
133 private final Multimap<String, Image> soneImages = HashMultimap.create();
135 private final MemorySoneDatabase soneDatabase;
136 private final MemoryPostDatabase postDatabase;
137 private final MemoryBookmarkDatabase memoryBookmarkDatabase;
138 private final MemoryFriendDatabase memoryFriendDatabase;
141 * Creates a new memory database.
143 * @param soneProvider
145 * @param configuration
146 * The configuration for loading and saving elements
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);
165 public Optional<LocalSone> getLocalSone(String localSoneId) {
166 lock.readLock().lock();
168 if (!localSones.contains(localSoneId)) {
169 return Optional.absent();
171 return Optional.of((LocalSone) allSones.get(localSoneId));
173 lock.readLock().unlock();
178 public LocalSone registerLocalSone(OwnIdentity ownIdentity) {
179 final LocalSone localSone = loadLocalSone(ownIdentity);
180 localSones.add(ownIdentity.getId());
184 private LocalSone loadLocalSone(OwnIdentity ownIdentity) {
185 LocalSone localSone = (LocalSone) newSoneBuilder().local().from(ownIdentity).build();
186 localSone.setLatestEdition(
187 Optional.fromNullable(
188 Longs.tryParse(ownIdentity.getProperty(LATEST_EDITION_PROPERTY)))
190 localSone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
191 localSone.setKnown(true);
197 public void loadSone(LocalSone sone) {
198 long soneTime = configurationLoader.getLocalSoneTime(sone.getId());
199 if (soneTime == -1) {
204 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
205 Profile profile = configurationSoneParser.parseProfile();
208 Collection<Post> posts;
210 posts = configurationSoneParser.parsePosts(this);
211 } catch (InvalidPostFound ipf) {
212 logger.log(Level.WARNING, "Invalid post found, aborting load!");
217 Collection<PostReply> postReplies;
219 postReplies = configurationSoneParser.parsePostReplies(this);
220 } catch (InvalidPostReplyFound iprf) {
221 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
225 /* load post likes. */
226 Set<String> likedPostIds = configurationSoneParser.parseLikedPostIds();
228 /* load reply likes. */
229 Set<String> likedReplyIds = configurationSoneParser.parseLikedPostReplyIds();
232 List<Album> topLevelAlbums;
234 topLevelAlbums = configurationSoneParser.parseTopLevelAlbums(this);
235 } catch (InvalidAlbumFound iaf) {
236 logger.log(Level.WARNING, "Invalid album found, aborting load!");
238 } catch (InvalidParentAlbumFound ipaf) {
239 logger.log(Level.WARNING,
240 format("Invalid parent album ID: %s", ipaf.getAlbumParentId()));
246 configurationSoneParser.parseImages(this);
247 } catch (InvalidImageFound iif) {
248 logger.log(WARNING, "Invalid image found, aborting load!");
250 } catch (InvalidParentAlbumFound ipaf) {
251 logger.log(Level.WARNING,
252 format("Invalid album image (%s) encountered, aborting load!",
253 ipaf.getAlbumParentId()));
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));
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())));
275 /* if we’re still here, Sone was loaded successfully. */
276 lock.writeLock().lock();
278 sone.setTime(soneTime);
279 sone.setProfile(profile);
280 sone.setLikePostIds(likedPostIds);
281 sone.setLikeReplyIds(likedReplyIds);
283 String lastInsertFingerprint = configurationLoader.getLastInsertFingerprint(sone.getId());
284 lastInsertFingerprints.put(sone.getId(), lastInsertFingerprint);
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());
292 lock.writeLock().unlock();
294 for (Post post : posts) {
297 for (PostReply reply : postReplies) {
298 reply.setKnown(true);
301 logger.info(String.format("Sone loaded successfully: %s", sone));
305 public String getLastInsertFingerprint(Sone sone) {
306 lock.readLock().lock();
308 if (!lastInsertFingerprints.containsKey(sone.getId())) {
311 return lastInsertFingerprints.get(sone.getId());
313 lock.readLock().unlock();
318 public void setLastInsertFingerprint(Sone sone, String lastInsertFingerprint) {
319 lock.writeLock().lock();
321 lastInsertFingerprints.put(sone.getId(), lastInsertFingerprint);
323 lock.writeLock().unlock();
328 * Saves the database.
330 * @throws DatabaseException
331 * if an error occurs while saving
334 public void save() throws DatabaseException {
335 lock.writeLock().lock();
337 saveKnownPostReplies();
338 for (Sone localSone : from(localSones).transform(soneLoader()).transform(Optionals.<Sone>get())) {
342 lock.writeLock().unlock();
346 private synchronized void saveSone(Sone sone) {
347 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
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()));
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());
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());
371 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
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());
382 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
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());
393 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
395 /* save post likes. */
396 int postLikeCounter = 0;
397 for (String postId : sone.getLikedPostIds()) {
398 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
400 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
402 /* save reply likes. */
403 int replyLikeCounter = 0;
404 for (String replyId : sone.getLikedReplyIds()) {
405 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
407 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
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();
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());
421 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
424 int imageCounter = 0;
425 for (Album album : albums) {
426 for (Image image : album.getImages()) {
427 if (!image.isInserted()) {
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());
441 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
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());
451 configuration.save();
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);
463 /** {@inheritDocs} */
465 protected void doStart() {
466 soneDatabase.start();
467 memoryFriendDatabase.start();
468 postDatabase.start();
469 memoryBookmarkDatabase.start();
470 loadKnownPostReplies();
474 /** {@inheritDocs} */
476 protected void doStop() {
479 memoryFriendDatabase.stop();
481 memoryBookmarkDatabase.stop();
484 } catch (DatabaseException de1) {
490 public SoneBuilder newSoneBuilder() {
491 return new MemorySoneBuilder(this);
495 public void storeSone(Sone sone) {
496 lock.writeLock().lock();
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));
506 lock.writeLock().unlock();
511 public boolean isSoneKnown(Sone sone) {
512 return soneDatabase.isKnownSone(sone.getId());
516 public void setSoneKnown(Sone sone) {
517 soneDatabase.setSoneKnown(sone.getId());
520 private void storePosts(String soneId, Collection<Post> posts) {
521 postDatabase.storePosts(soneId, posts);
524 private void storePostReplies(String soneId, Collection<PostReply> postReplies) {
525 sonePostReplies.putAll(soneId, postReplies);
526 for (PostReply postReply : postReplies) {
527 allPostReplies.put(postReply.getId(), postReply);
531 private void storeAlbums(String soneId, Collection<Album> albums) {
532 soneAlbums.putAll(soneId, albums);
533 for (Album album : albums) {
534 allAlbums.put(album.getId(), album);
538 private void storeImages(String soneId, Collection<Image> images) {
539 soneImages.putAll(soneId, images);
540 for (Image image : images) {
541 allImages.put(image.getId(), image);
546 public void removeSone(Sone sone) {
547 lock.writeLock().lock();
549 allSones.remove(sone.getId());
550 postDatabase.removePostsFor(sone.getId());
551 Collection<PostReply> removedPostReplies =
552 sonePostReplies.removeAll(sone.getId());
553 for (PostReply removedPostReply : removedPostReplies) {
554 allPostReplies.remove(removedPostReply.getId());
556 Collection<Album> removedAlbums =
557 soneAlbums.removeAll(sone.getId());
558 for (Album removedAlbum : removedAlbums) {
559 allAlbums.remove(removedAlbum.getId());
561 Collection<Image> removedImages =
562 soneImages.removeAll(sone.getId());
563 for (Image removedImage : removedImages) {
564 allImages.remove(removedImage.getId());
567 lock.writeLock().unlock();
572 public Function<String, Optional<Sone>> soneLoader() {
573 return new Function<String, Optional<Sone>>() {
575 public Optional<Sone> apply(String soneId) {
576 return getSone(soneId);
582 public Optional<Sone> getSone(String soneId) {
583 lock.readLock().lock();
585 return fromNullable(allSones.get(soneId));
587 lock.readLock().unlock();
592 public Collection<Sone> getSones() {
593 lock.readLock().lock();
595 return new HashSet<Sone>(allSones.values());
597 lock.readLock().unlock();
602 public Collection<LocalSone> getLocalSones() {
603 lock.readLock().lock();
605 return from(allSones.values()).filter(LOCAL_SONE_FILTER).transform(new Function<Sone, LocalSone>() {
607 public LocalSone apply(Sone sone) {
608 // FIXME – Sones will not always implement LocalSone
609 return (LocalSone) sone;
613 lock.readLock().unlock();
618 public Collection<Sone> getRemoteSones() {
619 lock.readLock().lock();
621 return from(allSones.values())
622 .filter(not(LOCAL_SONE_FILTER)) .toSet();
624 lock.readLock().unlock();
629 public Collection<String> getFriends(LocalSone localSone) {
630 if (!localSone.isLocal()) {
631 return Collections.emptySet();
633 return memoryFriendDatabase.getFriends(localSone.getId());
637 public Optional<Long> getSoneFollowingTime(String remoteSoneId) {
638 return memoryFriendDatabase.getSoneFollowingTime(remoteSoneId);
642 public boolean isFriend(LocalSone localSone, String friendSoneId) {
643 if (!localSone.isLocal()) {
646 return memoryFriendDatabase.isFriend(localSone.getId(), friendSoneId);
650 public void addFriend(LocalSone localSone, String friendSoneId) {
651 memoryFriendDatabase.addFriend(localSone.getId(), friendSoneId);
655 public void removeFriend(LocalSone localSone, String friendSoneId) {
656 memoryFriendDatabase.removeFriend(localSone.getId(), friendSoneId);
660 // POSTPROVIDER METHODS
663 /** {@inheritDocs} */
665 public Optional<Post> getPost(String postId) {
666 return postDatabase.getPost(postId);
669 /** {@inheritDocs} */
671 public Collection<Post> getPosts(String soneId) {
672 return new HashSet<Post>(getPostsFrom(soneId));
675 /** {@inheritDocs} */
677 public Collection<Post> getDirectedPosts(final String recipientId) {
678 return postDatabase.getDirectedPosts(recipientId);
682 // POSTBUILDERFACTORY METHODS
685 /** {@inheritDocs} */
687 public PostBuilder newPostBuilder() {
688 return new MemoryPostBuilder(this, soneProvider);
695 /** {@inheritDocs} */
697 public void storePost(Post post) {
698 checkNotNull(post, "post must not be null");
699 postDatabase.storePost(post);
702 /** {@inheritDocs} */
704 public void removePost(Post post) {
705 checkNotNull(post, "post must not be null");
706 postDatabase.removePost(post.getId());
710 // POSTREPLYPROVIDER METHODS
713 /** {@inheritDocs} */
715 public Optional<PostReply> getPostReply(String id) {
716 lock.readLock().lock();
718 return fromNullable(allPostReplies.get(id));
720 lock.readLock().unlock();
724 /** {@inheritDocs} */
726 public List<PostReply> getReplies(final String postId) {
727 lock.readLock().lock();
729 return from(allPostReplies.values())
730 .filter(new Predicate<PostReply>() {
732 public boolean apply(PostReply postReply) {
733 return postReply.getPostId().equals(postId);
735 }).toSortedList(TIME_COMPARATOR);
737 lock.readLock().unlock();
742 // POSTREPLYBUILDERFACTORY METHODS
745 /** {@inheritDocs} */
747 public PostReplyBuilder newPostReplyBuilder() {
748 return new MemoryPostReplyBuilder(this, soneProvider);
752 // POSTREPLYSTORE METHODS
755 /** {@inheritDocs} */
757 public void storePostReply(PostReply postReply) {
758 lock.writeLock().lock();
760 allPostReplies.put(postReply.getId(), postReply);
762 lock.writeLock().unlock();
766 /** {@inheritDocs} */
768 public void removePostReply(PostReply postReply) {
769 lock.writeLock().lock();
771 allPostReplies.remove(postReply.getId());
773 lock.writeLock().unlock();
778 // ALBUMPROVDER METHODS
782 public Optional<Album> getAlbum(String albumId) {
783 lock.readLock().lock();
785 return fromNullable(allAlbums.get(albumId));
787 lock.readLock().unlock();
792 // ALBUMBUILDERFACTORY METHODS
796 public AlbumBuilder newAlbumBuilder() {
797 return new AlbumBuilderImpl();
801 // ALBUMSTORE METHODS
805 public void storeAlbum(Album album) {
806 lock.writeLock().lock();
808 allAlbums.put(album.getId(), album);
809 soneAlbums.put(album.getSone().getId(), album);
811 lock.writeLock().unlock();
816 public void removeAlbum(Album album) {
817 lock.writeLock().lock();
819 allAlbums.remove(album.getId());
820 soneAlbums.remove(album.getSone().getId(), album);
822 lock.writeLock().unlock();
827 // IMAGEPROVIDER METHODS
831 public Optional<Image> getImage(String imageId) {
832 lock.readLock().lock();
834 return fromNullable(allImages.get(imageId));
836 lock.readLock().unlock();
841 // IMAGEBUILDERFACTORY METHODS
845 public ImageBuilder newImageBuilder() {
846 return new ImageBuilderImpl();
850 // IMAGESTORE METHODS
854 public void storeImage(Image image) {
855 lock.writeLock().lock();
857 allImages.put(image.getId(), image);
858 soneImages.put(image.getSone().getId(), image);
860 lock.writeLock().unlock();
865 public void removeImage(Image image) {
866 lock.writeLock().lock();
868 allImages.remove(image.getId());
869 soneImages.remove(image.getSone().getId(), image);
871 lock.writeLock().unlock();
876 public void bookmarkPost(Post post) {
877 memoryBookmarkDatabase.bookmarkPost(post);
881 public void unbookmarkPost(Post post) {
882 memoryBookmarkDatabase.unbookmarkPost(post);
886 public boolean isPostBookmarked(Post post) {
887 return memoryBookmarkDatabase.isPostBookmarked(post);
891 public Set<Post> getBookmarkedPosts() {
892 return memoryBookmarkDatabase.getBookmarkedPosts();
896 // PACKAGE-PRIVATE METHODS
900 * Returns whether the given post is known.
904 * @return {@code true} if the post is known, {@code false} otherwise
906 boolean isPostKnown(Post post) {
907 return postDatabase.isPostKnown(post.getId());
911 * Sets whether the given post is known.
916 * {@code true} if the post is known, {@code false} otherwise
918 void setPostKnown(Post post, boolean known) {
919 postDatabase.setPostKnown(post.getId(), known);
923 * Returns whether the given post reply is known.
927 * @return {@code true} if the given post reply is known, {@code false}
930 boolean isPostReplyKnown(PostReply postReply) {
931 lock.readLock().lock();
933 return knownPostReplies.contains(postReply.getId());
935 lock.readLock().unlock();
940 * Sets whether the given post reply is known.
945 * {@code true} if the post reply is known, {@code false} otherwise
947 void setPostReplyKnown(PostReply postReply, boolean known) {
948 lock.writeLock().lock();
951 knownPostReplies.add(postReply.getId());
953 knownPostReplies.remove(postReply.getId());
956 lock.writeLock().unlock();
965 * Gets all posts for the given Sone, creating a new collection if there is
969 * The ID of the Sone to get the posts for
972 private Collection<Post> getPostsFrom(String soneId) {
973 return postDatabase.getPostsFrom(soneId);
976 /** Loads the known post replies. */
977 private void loadKnownPostReplies() {
978 Set<String> knownPostReplies = configurationLoader.loadKnownPostReplies();
979 lock.writeLock().lock();
981 this.knownPostReplies.clear();
982 this.knownPostReplies.addAll(knownPostReplies);
984 lock.writeLock().unlock();
989 * Saves the known post replies to the configuration.
991 * @throws DatabaseException
992 * if a configuration error occurs
994 private void saveKnownPostReplies() throws DatabaseException {
995 lock.readLock().lock();
997 int replyCounter = 0;
998 for (String knownReplyId : knownPostReplies) {
999 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(
1002 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1003 } catch (ConfigurationException ce1) {
1004 throw new DatabaseException("Could not save database.", ce1);
1006 lock.readLock().unlock();