2 * Sone - MemoryDatabase.java - Copyright © 2013–2016 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 net.pterodactylus.sone.data.Reply.TIME_COMPARATOR;
25 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
26 import static net.pterodactylus.sone.data.Sone.toAllAlbums;
27 import static net.pterodactylus.sone.data.Sone.toAllImages;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.Comparator;
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.List;
37 import java.util.concurrent.locks.ReadWriteLock;
38 import java.util.concurrent.locks.ReentrantReadWriteLock;
40 import javax.annotation.Nonnull;
41 import javax.annotation.Nullable;
43 import net.pterodactylus.sone.data.Album;
44 import net.pterodactylus.sone.data.Image;
45 import net.pterodactylus.sone.data.Post;
46 import net.pterodactylus.sone.data.PostReply;
47 import net.pterodactylus.sone.data.Sone;
48 import net.pterodactylus.sone.data.impl.AlbumBuilderImpl;
49 import net.pterodactylus.sone.data.impl.ImageBuilderImpl;
50 import net.pterodactylus.sone.database.AlbumBuilder;
51 import net.pterodactylus.sone.database.Database;
52 import net.pterodactylus.sone.database.DatabaseException;
53 import net.pterodactylus.sone.database.ImageBuilder;
54 import net.pterodactylus.sone.database.PostBuilder;
55 import net.pterodactylus.sone.database.PostDatabase;
56 import net.pterodactylus.sone.database.PostReplyBuilder;
57 import net.pterodactylus.sone.database.SoneBuilder;
58 import net.pterodactylus.sone.database.SoneProvider;
59 import net.pterodactylus.util.config.Configuration;
60 import net.pterodactylus.util.config.ConfigurationException;
62 import com.google.common.base.Predicate;
63 import com.google.common.collect.HashMultimap;
64 import com.google.common.collect.Multimap;
65 import com.google.common.collect.SortedSetMultimap;
66 import com.google.common.collect.TreeMultimap;
67 import com.google.common.util.concurrent.AbstractService;
68 import com.google.inject.Inject;
69 import com.google.inject.Singleton;
70 import kotlin.jvm.functions.Function1;
73 * Memory-based {@link PostDatabase} implementation.
75 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
78 public class MemoryDatabase extends AbstractService implements Database {
81 private final ReadWriteLock lock = new ReentrantReadWriteLock();
83 /** The Sone provider. */
84 private final SoneProvider soneProvider;
86 /** The configuration. */
87 private final Configuration configuration;
88 private final ConfigurationLoader configurationLoader;
90 private final Map<String, Sone> allSones = new HashMap<String, Sone>();
92 /** All posts by their ID. */
93 private final Map<String, Post> allPosts = new HashMap<String, Post>();
95 /** All posts by their Sones. */
96 private final Multimap<String, Post> sonePosts = HashMultimap.create();
98 /** Whether posts are known. */
99 private final Set<String> knownPosts = new HashSet<String>();
101 /** All post replies by their ID. */
102 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
104 /** Replies sorted by Sone. */
105 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
108 public int compare(String leftString, String rightString) {
109 return leftString.compareTo(rightString);
113 /** Whether post replies are known. */
114 private final Set<String> knownPostReplies = new HashSet<String>();
116 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
117 private final Multimap<String, Album> soneAlbums = HashMultimap.create();
119 private final Map<String, Image> allImages = new HashMap<String, Image>();
120 private final Multimap<String, Image> soneImages = HashMultimap.create();
122 private final MemoryBookmarkDatabase memoryBookmarkDatabase;
123 private final MemoryFriendDatabase memoryFriendDatabase;
126 * Creates a new memory database.
128 * @param soneProvider
130 * @param configuration
131 * The configuration for loading and saving elements
134 public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
135 this.soneProvider = soneProvider;
136 this.configuration = configuration;
137 this.configurationLoader = new ConfigurationLoader(configuration);
138 memoryBookmarkDatabase =
139 new MemoryBookmarkDatabase(this, configurationLoader);
140 memoryFriendDatabase = new MemoryFriendDatabase(configurationLoader);
148 * Saves the database.
150 * @throws DatabaseException
151 * if an error occurs while saving
154 public void save() throws DatabaseException {
156 saveKnownPostReplies();
163 /** {@inheritDocs} */
165 protected void doStart() {
166 memoryBookmarkDatabase.start();
168 loadKnownPostReplies();
172 /** {@inheritDocs} */
174 protected void doStop() {
176 memoryBookmarkDatabase.stop();
179 } catch (DatabaseException de1) {
185 public SoneBuilder newSoneBuilder() {
186 return new MemorySoneBuilder(this);
190 public void storeSone(Sone sone) {
191 lock.writeLock().lock();
195 allSones.put(sone.getId(), sone);
196 sonePosts.putAll(sone.getId(), sone.getPosts());
197 for (Post post : sone.getPosts()) {
198 allPosts.put(post.getId(), post);
200 sonePostReplies.putAll(sone.getId(), sone.getReplies());
201 for (PostReply postReply : sone.getReplies()) {
202 allPostReplies.put(postReply.getId(), postReply);
204 soneAlbums.putAll(sone.getId(), toAllAlbums.apply(sone));
205 for (Album album : toAllAlbums.apply(sone)) {
206 allAlbums.put(album.getId(), album);
208 soneImages.putAll(sone.getId(), toAllImages.apply(sone));
209 for (Image image : toAllImages.apply(sone)) {
210 allImages.put(image.getId(), image);
213 lock.writeLock().unlock();
218 public void removeSone(Sone sone) {
219 lock.writeLock().lock();
221 allSones.remove(sone.getId());
222 Collection<Post> removedPosts = sonePosts.removeAll(sone.getId());
223 for (Post removedPost : removedPosts) {
224 allPosts.remove(removedPost.getId());
226 Collection<PostReply> removedPostReplies =
227 sonePostReplies.removeAll(sone.getId());
228 for (PostReply removedPostReply : removedPostReplies) {
229 allPostReplies.remove(removedPostReply.getId());
231 Collection<Album> removedAlbums =
232 soneAlbums.removeAll(sone.getId());
233 for (Album removedAlbum : removedAlbums) {
234 allAlbums.remove(removedAlbum.getId());
236 Collection<Image> removedImages =
237 soneImages.removeAll(sone.getId());
238 for (Image removedImage : removedImages) {
239 allImages.remove(removedImage.getId());
242 lock.writeLock().unlock();
248 public Function1<String, Sone> getSoneLoader() {
249 return new Function1<String, Sone>() {
251 public Sone invoke(String soneId) {
252 return getSone(soneId);
258 public Sone getSone(String soneId) {
259 lock.readLock().lock();
261 return allSones.get(soneId);
263 lock.readLock().unlock();
268 public Collection<Sone> getSones() {
269 lock.readLock().lock();
271 return new HashSet<Sone>(allSones.values());
273 lock.readLock().unlock();
278 public Collection<Sone> getLocalSones() {
279 lock.readLock().lock();
281 return from(allSones.values()).filter(LOCAL_SONE_FILTER).toSet();
283 lock.readLock().unlock();
288 public Collection<Sone> getRemoteSones() {
289 lock.readLock().lock();
291 return from(allSones.values())
292 .filter(not(LOCAL_SONE_FILTER)) .toSet();
294 lock.readLock().unlock();
299 public Collection<String> getFriends(Sone localSone) {
300 if (!localSone.isLocal()) {
301 return Collections.emptySet();
303 return memoryFriendDatabase.getFriends(localSone.getId());
307 public boolean isFriend(Sone localSone, String friendSoneId) {
308 if (!localSone.isLocal()) {
311 return memoryFriendDatabase.isFriend(localSone.getId(), friendSoneId);
315 public void addFriend(Sone localSone, String friendSoneId) {
316 if (!localSone.isLocal()) {
319 memoryFriendDatabase.addFriend(localSone.getId(), friendSoneId);
323 public void removeFriend(Sone localSone, String friendSoneId) {
324 if (!localSone.isLocal()) {
327 memoryFriendDatabase.removeFriend(localSone.getId(), friendSoneId);
331 // POSTPROVIDER METHODS
336 public Post getPost(@Nonnull String postId) {
337 lock.readLock().lock();
339 return allPosts.get(postId);
341 lock.readLock().unlock();
345 /** {@inheritDocs} */
347 public Collection<Post> getPosts(String soneId) {
348 return new HashSet<Post>(getPostsFrom(soneId));
351 /** {@inheritDocs} */
353 public Collection<Post> getDirectedPosts(final String recipientId) {
354 lock.readLock().lock();
356 return from(sonePosts.values()).filter(new Predicate<Post>() {
358 public boolean apply(Post post) {
359 return post.getRecipientId().asSet().contains(recipientId);
363 lock.readLock().unlock();
368 // POSTBUILDERFACTORY METHODS
371 /** {@inheritDocs} */
373 public PostBuilder newPostBuilder() {
374 return new MemoryPostBuilder(this, soneProvider);
381 /** {@inheritDocs} */
383 public void storePost(Post post) {
384 checkNotNull(post, "post must not be null");
385 lock.writeLock().lock();
387 allPosts.put(post.getId(), post);
388 getPostsFrom(post.getSone().getId()).add(post);
390 lock.writeLock().unlock();
394 /** {@inheritDocs} */
396 public void removePost(Post post) {
397 checkNotNull(post, "post must not be null");
398 lock.writeLock().lock();
400 allPosts.remove(post.getId());
401 getPostsFrom(post.getSone().getId()).remove(post);
402 post.getSone().removePost(post);
404 lock.writeLock().unlock();
409 // POSTREPLYPROVIDER METHODS
414 public PostReply getPostReply(String id) {
415 lock.readLock().lock();
417 return allPostReplies.get(id);
419 lock.readLock().unlock();
423 /** {@inheritDocs} */
425 public List<PostReply> getReplies(final String postId) {
426 lock.readLock().lock();
428 return from(allPostReplies.values())
429 .filter(new Predicate<PostReply>() {
431 public boolean apply(PostReply postReply) {
432 return postReply.getPostId().equals(postId);
434 }).toSortedList(TIME_COMPARATOR);
436 lock.readLock().unlock();
441 // POSTREPLYBUILDERFACTORY METHODS
444 /** {@inheritDocs} */
446 public PostReplyBuilder newPostReplyBuilder() {
447 return new MemoryPostReplyBuilder(this, soneProvider);
451 // POSTREPLYSTORE METHODS
454 /** {@inheritDocs} */
456 public void storePostReply(PostReply postReply) {
457 lock.writeLock().lock();
459 allPostReplies.put(postReply.getId(), postReply);
461 lock.writeLock().unlock();
465 /** {@inheritDocs} */
467 public void removePostReply(PostReply postReply) {
468 lock.writeLock().lock();
470 allPostReplies.remove(postReply.getId());
472 lock.writeLock().unlock();
477 // ALBUMPROVDER METHODS
482 public Album getAlbum(@Nonnull String albumId) {
483 lock.readLock().lock();
485 return allAlbums.get(albumId);
487 lock.readLock().unlock();
492 // ALBUMBUILDERFACTORY METHODS
496 public AlbumBuilder newAlbumBuilder() {
497 return new AlbumBuilderImpl();
501 // ALBUMSTORE METHODS
505 public void storeAlbum(Album album) {
506 lock.writeLock().lock();
508 allAlbums.put(album.getId(), album);
509 soneAlbums.put(album.getSone().getId(), album);
511 lock.writeLock().unlock();
516 public void removeAlbum(Album album) {
517 lock.writeLock().lock();
519 allAlbums.remove(album.getId());
520 soneAlbums.remove(album.getSone().getId(), album);
522 lock.writeLock().unlock();
527 // IMAGEPROVIDER METHODS
532 public Image getImage(@Nonnull String imageId) {
533 lock.readLock().lock();
535 return allImages.get(imageId);
537 lock.readLock().unlock();
542 // IMAGEBUILDERFACTORY METHODS
546 public ImageBuilder newImageBuilder() {
547 return new ImageBuilderImpl();
551 // IMAGESTORE METHODS
555 public void storeImage(Image image) {
556 lock.writeLock().lock();
558 allImages.put(image.getId(), image);
559 soneImages.put(image.getSone().getId(), image);
561 lock.writeLock().unlock();
566 public void removeImage(Image image) {
567 lock.writeLock().lock();
569 allImages.remove(image.getId());
570 soneImages.remove(image.getSone().getId(), image);
572 lock.writeLock().unlock();
577 public void bookmarkPost(Post post) {
578 memoryBookmarkDatabase.bookmarkPost(post);
582 public void unbookmarkPost(Post post) {
583 memoryBookmarkDatabase.unbookmarkPost(post);
587 public boolean isPostBookmarked(Post post) {
588 return memoryBookmarkDatabase.isPostBookmarked(post);
592 public Set<Post> getBookmarkedPosts() {
593 return memoryBookmarkDatabase.getBookmarkedPosts();
597 // PACKAGE-PRIVATE METHODS
601 * Returns whether the given post is known.
605 * @return {@code true} if the post is known, {@code false} otherwise
607 boolean isPostKnown(Post post) {
608 lock.readLock().lock();
610 return knownPosts.contains(post.getId());
612 lock.readLock().unlock();
617 * Sets whether the given post is known.
622 * {@code true} if the post is known, {@code false} otherwise
624 void setPostKnown(Post post, boolean known) {
625 lock.writeLock().lock();
628 knownPosts.add(post.getId());
630 knownPosts.remove(post.getId());
633 lock.writeLock().unlock();
638 * Returns whether the given post reply is known.
642 * @return {@code true} if the given post reply is known, {@code false}
645 boolean isPostReplyKnown(PostReply postReply) {
646 lock.readLock().lock();
648 return knownPostReplies.contains(postReply.getId());
650 lock.readLock().unlock();
655 * Sets whether the given post reply is known.
660 * {@code true} if the post reply is known, {@code false} otherwise
662 void setPostReplyKnown(PostReply postReply, boolean known) {
663 lock.writeLock().lock();
666 knownPostReplies.add(postReply.getId());
668 knownPostReplies.remove(postReply.getId());
671 lock.writeLock().unlock();
680 * Gets all posts for the given Sone, creating a new collection if there is
684 * The ID of the Sone to get the posts for
687 private Collection<Post> getPostsFrom(String soneId) {
688 lock.readLock().lock();
690 return sonePosts.get(soneId);
692 lock.readLock().unlock();
696 /** Loads the known posts. */
697 private void loadKnownPosts() {
698 Set<String> knownPosts = configurationLoader.loadKnownPosts();
699 lock.writeLock().lock();
701 this.knownPosts.clear();
702 this.knownPosts.addAll(knownPosts);
704 lock.writeLock().unlock();
709 * Saves the known posts to the configuration.
711 * @throws DatabaseException
712 * if a configuration error occurs
714 private void saveKnownPosts() throws DatabaseException {
715 lock.readLock().lock();
718 for (String knownPostId : knownPosts) {
719 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
721 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
722 } catch (ConfigurationException ce1) {
723 throw new DatabaseException("Could not save database.", ce1);
725 lock.readLock().unlock();
729 /** Loads the known post replies. */
730 private void loadKnownPostReplies() {
731 Set<String> knownPostReplies = configurationLoader.loadKnownPostReplies();
732 lock.writeLock().lock();
734 this.knownPostReplies.clear();
735 this.knownPostReplies.addAll(knownPostReplies);
737 lock.writeLock().unlock();
742 * Saves the known post replies to the configuration.
744 * @throws DatabaseException
745 * if a configuration error occurs
747 private void saveKnownPostReplies() throws DatabaseException {
748 lock.readLock().lock();
750 int replyCounter = 0;
751 for (String knownReplyId : knownPostReplies) {
752 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
754 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
755 } catch (ConfigurationException ce1) {
756 throw new DatabaseException("Could not save database.", ce1);
758 lock.readLock().unlock();