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.Preconditions.checkNotNull;
21 import static com.google.common.base.Predicates.not;
22 import static com.google.common.collect.FluentIterable.from;
23 import static net.pterodactylus.sone.data.Reply.TIME_COMPARATOR;
24 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
25 import static net.pterodactylus.sone.data.Sone.toAllAlbums;
26 import static net.pterodactylus.sone.data.Sone.toAllImages;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.Comparator;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.List;
36 import java.util.concurrent.locks.ReadWriteLock;
37 import java.util.concurrent.locks.ReentrantReadWriteLock;
39 import javax.annotation.Nonnull;
40 import javax.annotation.Nullable;
42 import net.pterodactylus.sone.data.Album;
43 import net.pterodactylus.sone.data.Image;
44 import net.pterodactylus.sone.data.Post;
45 import net.pterodactylus.sone.data.PostReply;
46 import net.pterodactylus.sone.data.Sone;
47 import net.pterodactylus.sone.data.impl.AlbumBuilderImpl;
48 import net.pterodactylus.sone.data.impl.ImageBuilderImpl;
49 import net.pterodactylus.sone.database.AlbumBuilder;
50 import net.pterodactylus.sone.database.Database;
51 import net.pterodactylus.sone.database.DatabaseException;
52 import net.pterodactylus.sone.database.ImageBuilder;
53 import net.pterodactylus.sone.database.PostBuilder;
54 import net.pterodactylus.sone.database.PostDatabase;
55 import net.pterodactylus.sone.database.PostReplyBuilder;
56 import net.pterodactylus.sone.database.SoneBuilder;
57 import net.pterodactylus.util.config.Configuration;
58 import net.pterodactylus.util.config.ConfigurationException;
60 import com.google.common.base.Predicate;
61 import com.google.common.collect.HashMultimap;
62 import com.google.common.collect.Multimap;
63 import com.google.common.collect.SortedSetMultimap;
64 import com.google.common.collect.TreeMultimap;
65 import com.google.common.util.concurrent.AbstractService;
66 import com.google.inject.Inject;
67 import com.google.inject.Singleton;
68 import kotlin.jvm.functions.Function1;
71 * Memory-based {@link PostDatabase} implementation.
73 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
76 public class MemoryDatabase extends AbstractService implements Database {
79 private final ReadWriteLock lock = new ReentrantReadWriteLock();
81 /** The configuration. */
82 private final Configuration configuration;
83 private final ConfigurationLoader configurationLoader;
85 private final Map<String, Sone> allSones = new HashMap<String, Sone>();
87 /** All posts by their ID. */
88 private final Map<String, Post> allPosts = new HashMap<String, Post>();
90 /** All posts by their Sones. */
91 private final Multimap<String, Post> sonePosts = HashMultimap.create();
93 /** Whether posts are known. */
94 private final Set<String> knownPosts = new HashSet<String>();
96 /** All post replies by their ID. */
97 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
99 /** Replies sorted by Sone. */
100 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
103 public int compare(String leftString, String rightString) {
104 return leftString.compareTo(rightString);
108 /** Whether post replies are known. */
109 private final Set<String> knownPostReplies = new HashSet<String>();
111 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
112 private final Multimap<String, Album> soneAlbums = HashMultimap.create();
114 private final Map<String, Image> allImages = new HashMap<String, Image>();
115 private final Multimap<String, Image> soneImages = HashMultimap.create();
117 private final MemoryBookmarkDatabase memoryBookmarkDatabase;
118 private final MemoryFriendDatabase memoryFriendDatabase;
121 * Creates a new memory database.
123 * @param configuration
124 * The configuration for loading and saving elements
127 public MemoryDatabase(Configuration configuration) {
128 this.configuration = configuration;
129 this.configurationLoader = new ConfigurationLoader(configuration);
130 memoryBookmarkDatabase =
131 new MemoryBookmarkDatabase(this, configurationLoader);
132 memoryFriendDatabase = new MemoryFriendDatabase(configurationLoader);
140 * Saves the database.
142 * @throws DatabaseException
143 * if an error occurs while saving
146 public void save() throws DatabaseException {
148 saveKnownPostReplies();
155 /** {@inheritDocs} */
157 protected void doStart() {
158 memoryBookmarkDatabase.start();
160 loadKnownPostReplies();
164 /** {@inheritDocs} */
166 protected void doStop() {
168 memoryBookmarkDatabase.stop();
171 } catch (DatabaseException de1) {
177 public SoneBuilder newSoneBuilder() {
178 return new MemorySoneBuilder(this);
182 public void storeSone(Sone sone) {
183 lock.writeLock().lock();
187 allSones.put(sone.getId(), sone);
188 sonePosts.putAll(sone.getId(), sone.getPosts());
189 for (Post post : sone.getPosts()) {
190 allPosts.put(post.getId(), post);
192 sonePostReplies.putAll(sone.getId(), sone.getReplies());
193 for (PostReply postReply : sone.getReplies()) {
194 allPostReplies.put(postReply.getId(), postReply);
196 soneAlbums.putAll(sone.getId(), toAllAlbums.apply(sone));
197 for (Album album : toAllAlbums.apply(sone)) {
198 allAlbums.put(album.getId(), album);
200 soneImages.putAll(sone.getId(), toAllImages.apply(sone));
201 for (Image image : toAllImages.apply(sone)) {
202 allImages.put(image.getId(), image);
205 lock.writeLock().unlock();
210 public void removeSone(Sone sone) {
211 lock.writeLock().lock();
213 allSones.remove(sone.getId());
214 Collection<Post> removedPosts = sonePosts.removeAll(sone.getId());
215 for (Post removedPost : removedPosts) {
216 allPosts.remove(removedPost.getId());
218 Collection<PostReply> removedPostReplies =
219 sonePostReplies.removeAll(sone.getId());
220 for (PostReply removedPostReply : removedPostReplies) {
221 allPostReplies.remove(removedPostReply.getId());
223 Collection<Album> removedAlbums =
224 soneAlbums.removeAll(sone.getId());
225 for (Album removedAlbum : removedAlbums) {
226 allAlbums.remove(removedAlbum.getId());
228 Collection<Image> removedImages =
229 soneImages.removeAll(sone.getId());
230 for (Image removedImage : removedImages) {
231 allImages.remove(removedImage.getId());
234 lock.writeLock().unlock();
240 public Function1<String, Sone> getSoneLoader() {
241 return new Function1<String, Sone>() {
243 public Sone invoke(String soneId) {
244 return getSone(soneId);
250 public Sone getSone(String soneId) {
251 lock.readLock().lock();
253 return allSones.get(soneId);
255 lock.readLock().unlock();
260 public Collection<Sone> getSones() {
261 lock.readLock().lock();
263 return new HashSet<Sone>(allSones.values());
265 lock.readLock().unlock();
270 public Collection<Sone> getLocalSones() {
271 lock.readLock().lock();
273 return from(allSones.values()).filter(LOCAL_SONE_FILTER).toSet();
275 lock.readLock().unlock();
280 public Collection<Sone> getRemoteSones() {
281 lock.readLock().lock();
283 return from(allSones.values())
284 .filter(not(LOCAL_SONE_FILTER)) .toSet();
286 lock.readLock().unlock();
291 public Collection<String> getFriends(Sone localSone) {
292 if (!localSone.isLocal()) {
293 return Collections.emptySet();
295 return memoryFriendDatabase.getFriends(localSone.getId());
299 public boolean isFriend(Sone localSone, String friendSoneId) {
300 if (!localSone.isLocal()) {
303 return memoryFriendDatabase.isFriend(localSone.getId(), friendSoneId);
307 public void addFriend(Sone localSone, String friendSoneId) {
308 if (!localSone.isLocal()) {
311 memoryFriendDatabase.addFriend(localSone.getId(), friendSoneId);
315 public void removeFriend(Sone localSone, String friendSoneId) {
316 if (!localSone.isLocal()) {
319 memoryFriendDatabase.removeFriend(localSone.getId(), friendSoneId);
324 public Long getFollowingTime(@Nonnull String friendSoneId) {
325 return memoryFriendDatabase.getFollowingTime(friendSoneId);
329 // POSTPROVIDER METHODS
334 public Post getPost(@Nonnull String postId) {
335 lock.readLock().lock();
337 return allPosts.get(postId);
339 lock.readLock().unlock();
343 /** {@inheritDocs} */
345 public Collection<Post> getPosts(String soneId) {
346 return new HashSet<Post>(getPostsFrom(soneId));
349 /** {@inheritDocs} */
351 public Collection<Post> getDirectedPosts(final String recipientId) {
352 lock.readLock().lock();
354 return from(sonePosts.values()).filter(new Predicate<Post>() {
356 public boolean apply(Post post) {
357 return post.getRecipientId().asSet().contains(recipientId);
361 lock.readLock().unlock();
366 // POSTBUILDERFACTORY METHODS
369 /** {@inheritDocs} */
371 public PostBuilder newPostBuilder() {
372 return new MemoryPostBuilder(this, this);
379 /** {@inheritDocs} */
381 public void storePost(Post post) {
382 checkNotNull(post, "post must not be null");
383 lock.writeLock().lock();
385 allPosts.put(post.getId(), post);
386 getPostsFrom(post.getSone().getId()).add(post);
388 lock.writeLock().unlock();
392 /** {@inheritDocs} */
394 public void removePost(Post post) {
395 checkNotNull(post, "post must not be null");
396 lock.writeLock().lock();
398 allPosts.remove(post.getId());
399 getPostsFrom(post.getSone().getId()).remove(post);
400 post.getSone().removePost(post);
402 lock.writeLock().unlock();
407 // POSTREPLYPROVIDER METHODS
412 public PostReply getPostReply(String id) {
413 lock.readLock().lock();
415 return allPostReplies.get(id);
417 lock.readLock().unlock();
421 /** {@inheritDocs} */
423 public List<PostReply> getReplies(final String postId) {
424 lock.readLock().lock();
426 return from(allPostReplies.values())
427 .filter(new Predicate<PostReply>() {
429 public boolean apply(PostReply postReply) {
430 return postReply.getPostId().equals(postId);
432 }).toSortedList(TIME_COMPARATOR);
434 lock.readLock().unlock();
439 // POSTREPLYBUILDERFACTORY METHODS
442 /** {@inheritDocs} */
444 public PostReplyBuilder newPostReplyBuilder() {
445 return new MemoryPostReplyBuilder(this, this);
449 // POSTREPLYSTORE METHODS
452 /** {@inheritDocs} */
454 public void storePostReply(PostReply postReply) {
455 lock.writeLock().lock();
457 allPostReplies.put(postReply.getId(), postReply);
459 lock.writeLock().unlock();
463 /** {@inheritDocs} */
465 public void removePostReply(PostReply postReply) {
466 lock.writeLock().lock();
468 allPostReplies.remove(postReply.getId());
470 lock.writeLock().unlock();
475 // ALBUMPROVDER METHODS
480 public Album getAlbum(@Nonnull String albumId) {
481 lock.readLock().lock();
483 return allAlbums.get(albumId);
485 lock.readLock().unlock();
490 // ALBUMBUILDERFACTORY METHODS
494 public AlbumBuilder newAlbumBuilder() {
495 return new AlbumBuilderImpl();
499 // ALBUMSTORE METHODS
503 public void storeAlbum(Album album) {
504 lock.writeLock().lock();
506 allAlbums.put(album.getId(), album);
507 soneAlbums.put(album.getSone().getId(), album);
509 lock.writeLock().unlock();
514 public void removeAlbum(Album album) {
515 lock.writeLock().lock();
517 allAlbums.remove(album.getId());
518 soneAlbums.remove(album.getSone().getId(), album);
520 lock.writeLock().unlock();
525 // IMAGEPROVIDER METHODS
530 public Image getImage(@Nonnull String imageId) {
531 lock.readLock().lock();
533 return allImages.get(imageId);
535 lock.readLock().unlock();
540 // IMAGEBUILDERFACTORY METHODS
544 public ImageBuilder newImageBuilder() {
545 return new ImageBuilderImpl();
549 // IMAGESTORE METHODS
553 public void storeImage(Image image) {
554 lock.writeLock().lock();
556 allImages.put(image.getId(), image);
557 soneImages.put(image.getSone().getId(), image);
559 lock.writeLock().unlock();
564 public void removeImage(Image image) {
565 lock.writeLock().lock();
567 allImages.remove(image.getId());
568 soneImages.remove(image.getSone().getId(), image);
570 lock.writeLock().unlock();
575 public void bookmarkPost(Post post) {
576 memoryBookmarkDatabase.bookmarkPost(post);
580 public void unbookmarkPost(Post post) {
581 memoryBookmarkDatabase.unbookmarkPost(post);
585 public boolean isPostBookmarked(Post post) {
586 return memoryBookmarkDatabase.isPostBookmarked(post);
590 public Set<Post> getBookmarkedPosts() {
591 return memoryBookmarkDatabase.getBookmarkedPosts();
595 // PACKAGE-PRIVATE METHODS
599 * Returns whether the given post is known.
603 * @return {@code true} if the post is known, {@code false} otherwise
605 boolean isPostKnown(Post post) {
606 lock.readLock().lock();
608 return knownPosts.contains(post.getId());
610 lock.readLock().unlock();
615 * Sets whether the given post is known.
620 * {@code true} if the post is known, {@code false} otherwise
622 void setPostKnown(Post post, boolean known) {
623 lock.writeLock().lock();
626 knownPosts.add(post.getId());
628 knownPosts.remove(post.getId());
631 lock.writeLock().unlock();
636 * Returns whether the given post reply is known.
640 * @return {@code true} if the given post reply is known, {@code false}
643 boolean isPostReplyKnown(PostReply postReply) {
644 lock.readLock().lock();
646 return knownPostReplies.contains(postReply.getId());
648 lock.readLock().unlock();
653 * Sets whether the given post reply is known.
658 * {@code true} if the post reply is known, {@code false} otherwise
660 void setPostReplyKnown(PostReply postReply, boolean known) {
661 lock.writeLock().lock();
664 knownPostReplies.add(postReply.getId());
666 knownPostReplies.remove(postReply.getId());
669 lock.writeLock().unlock();
678 * Gets all posts for the given Sone, creating a new collection if there is
682 * The ID of the Sone to get the posts for
685 private Collection<Post> getPostsFrom(String soneId) {
686 lock.readLock().lock();
688 return sonePosts.get(soneId);
690 lock.readLock().unlock();
694 /** Loads the known posts. */
695 private void loadKnownPosts() {
696 Set<String> knownPosts = configurationLoader.loadKnownPosts();
697 lock.writeLock().lock();
699 this.knownPosts.clear();
700 this.knownPosts.addAll(knownPosts);
702 lock.writeLock().unlock();
707 * Saves the known posts to the configuration.
709 * @throws DatabaseException
710 * if a configuration error occurs
712 private void saveKnownPosts() throws DatabaseException {
713 lock.readLock().lock();
716 for (String knownPostId : knownPosts) {
717 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
719 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
720 } catch (ConfigurationException ce1) {
721 throw new DatabaseException("Could not save database.", ce1);
723 lock.readLock().unlock();
727 /** Loads the known post replies. */
728 private void loadKnownPostReplies() {
729 Set<String> knownPostReplies = configurationLoader.loadKnownPostReplies();
730 lock.writeLock().lock();
732 this.knownPostReplies.clear();
733 this.knownPostReplies.addAll(knownPostReplies);
735 lock.writeLock().unlock();
740 * Saves the known post replies to the configuration.
742 * @throws DatabaseException
743 * if a configuration error occurs
745 private void saveKnownPostReplies() throws DatabaseException {
746 lock.readLock().lock();
748 int replyCounter = 0;
749 for (String knownReplyId : knownPostReplies) {
750 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
752 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
753 } catch (ConfigurationException ce1) {
754 throw new DatabaseException("Could not save database.", ce1);
756 lock.readLock().unlock();