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.util.config.Configuration;
59 import net.pterodactylus.util.config.ConfigurationException;
61 import com.google.common.base.Predicate;
62 import com.google.common.collect.HashMultimap;
63 import com.google.common.collect.Multimap;
64 import com.google.common.collect.SortedSetMultimap;
65 import com.google.common.collect.TreeMultimap;
66 import com.google.common.util.concurrent.AbstractService;
67 import com.google.inject.Inject;
68 import com.google.inject.Singleton;
69 import kotlin.jvm.functions.Function1;
72 * Memory-based {@link PostDatabase} implementation.
74 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
77 public class MemoryDatabase extends AbstractService implements Database {
80 private final ReadWriteLock lock = new ReentrantReadWriteLock();
82 /** The configuration. */
83 private final Configuration configuration;
84 private final ConfigurationLoader configurationLoader;
86 private final Map<String, Sone> allSones = new HashMap<String, Sone>();
88 /** All posts by their ID. */
89 private final Map<String, Post> allPosts = new HashMap<String, Post>();
91 /** All posts by their Sones. */
92 private final Multimap<String, Post> sonePosts = HashMultimap.create();
94 /** Whether posts are known. */
95 private final Set<String> knownPosts = new HashSet<String>();
97 /** All post replies by their ID. */
98 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
100 /** Replies sorted by Sone. */
101 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
104 public int compare(String leftString, String rightString) {
105 return leftString.compareTo(rightString);
109 /** Whether post replies are known. */
110 private final Set<String> knownPostReplies = new HashSet<String>();
112 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
113 private final Multimap<String, Album> soneAlbums = HashMultimap.create();
115 private final Map<String, Image> allImages = new HashMap<String, Image>();
116 private final Multimap<String, Image> soneImages = HashMultimap.create();
118 private final MemoryBookmarkDatabase memoryBookmarkDatabase;
119 private final MemoryFriendDatabase memoryFriendDatabase;
122 * Creates a new memory database.
124 * @param configuration
125 * The configuration for loading and saving elements
128 public MemoryDatabase(Configuration configuration) {
129 this.configuration = configuration;
130 this.configurationLoader = new ConfigurationLoader(configuration);
131 memoryBookmarkDatabase =
132 new MemoryBookmarkDatabase(this, configurationLoader);
133 memoryFriendDatabase = new MemoryFriendDatabase(configurationLoader);
141 * Saves the database.
143 * @throws DatabaseException
144 * if an error occurs while saving
147 public void save() throws DatabaseException {
149 saveKnownPostReplies();
156 /** {@inheritDocs} */
158 protected void doStart() {
159 memoryBookmarkDatabase.start();
161 loadKnownPostReplies();
165 /** {@inheritDocs} */
167 protected void doStop() {
169 memoryBookmarkDatabase.stop();
172 } catch (DatabaseException de1) {
178 public SoneBuilder newSoneBuilder() {
179 return new MemorySoneBuilder(this);
183 public void storeSone(Sone sone) {
184 lock.writeLock().lock();
188 allSones.put(sone.getId(), sone);
189 sonePosts.putAll(sone.getId(), sone.getPosts());
190 for (Post post : sone.getPosts()) {
191 allPosts.put(post.getId(), post);
193 sonePostReplies.putAll(sone.getId(), sone.getReplies());
194 for (PostReply postReply : sone.getReplies()) {
195 allPostReplies.put(postReply.getId(), postReply);
197 soneAlbums.putAll(sone.getId(), toAllAlbums.apply(sone));
198 for (Album album : toAllAlbums.apply(sone)) {
199 allAlbums.put(album.getId(), album);
201 soneImages.putAll(sone.getId(), toAllImages.apply(sone));
202 for (Image image : toAllImages.apply(sone)) {
203 allImages.put(image.getId(), image);
206 lock.writeLock().unlock();
211 public void removeSone(Sone sone) {
212 lock.writeLock().lock();
214 allSones.remove(sone.getId());
215 Collection<Post> removedPosts = sonePosts.removeAll(sone.getId());
216 for (Post removedPost : removedPosts) {
217 allPosts.remove(removedPost.getId());
219 Collection<PostReply> removedPostReplies =
220 sonePostReplies.removeAll(sone.getId());
221 for (PostReply removedPostReply : removedPostReplies) {
222 allPostReplies.remove(removedPostReply.getId());
224 Collection<Album> removedAlbums =
225 soneAlbums.removeAll(sone.getId());
226 for (Album removedAlbum : removedAlbums) {
227 allAlbums.remove(removedAlbum.getId());
229 Collection<Image> removedImages =
230 soneImages.removeAll(sone.getId());
231 for (Image removedImage : removedImages) {
232 allImages.remove(removedImage.getId());
235 lock.writeLock().unlock();
241 public Function1<String, Sone> getSoneLoader() {
242 return new Function1<String, Sone>() {
244 public Sone invoke(String soneId) {
245 return getSone(soneId);
251 public Sone getSone(String soneId) {
252 lock.readLock().lock();
254 return allSones.get(soneId);
256 lock.readLock().unlock();
261 public Collection<Sone> getSones() {
262 lock.readLock().lock();
264 return new HashSet<Sone>(allSones.values());
266 lock.readLock().unlock();
271 public Collection<Sone> getLocalSones() {
272 lock.readLock().lock();
274 return from(allSones.values()).filter(LOCAL_SONE_FILTER).toSet();
276 lock.readLock().unlock();
281 public Collection<Sone> getRemoteSones() {
282 lock.readLock().lock();
284 return from(allSones.values())
285 .filter(not(LOCAL_SONE_FILTER)) .toSet();
287 lock.readLock().unlock();
292 public Collection<String> getFriends(Sone localSone) {
293 if (!localSone.isLocal()) {
294 return Collections.emptySet();
296 return memoryFriendDatabase.getFriends(localSone.getId());
300 public boolean isFriend(Sone localSone, String friendSoneId) {
301 if (!localSone.isLocal()) {
304 return memoryFriendDatabase.isFriend(localSone.getId(), friendSoneId);
308 public void addFriend(Sone localSone, String friendSoneId) {
309 if (!localSone.isLocal()) {
312 memoryFriendDatabase.addFriend(localSone.getId(), friendSoneId);
316 public void removeFriend(Sone localSone, String friendSoneId) {
317 if (!localSone.isLocal()) {
320 memoryFriendDatabase.removeFriend(localSone.getId(), friendSoneId);
324 // POSTPROVIDER METHODS
329 public Post getPost(@Nonnull String postId) {
330 lock.readLock().lock();
332 return allPosts.get(postId);
334 lock.readLock().unlock();
338 /** {@inheritDocs} */
340 public Collection<Post> getPosts(String soneId) {
341 return new HashSet<Post>(getPostsFrom(soneId));
344 /** {@inheritDocs} */
346 public Collection<Post> getDirectedPosts(final String recipientId) {
347 lock.readLock().lock();
349 return from(sonePosts.values()).filter(new Predicate<Post>() {
351 public boolean apply(Post post) {
352 return post.getRecipientId().asSet().contains(recipientId);
356 lock.readLock().unlock();
361 // POSTBUILDERFACTORY METHODS
364 /** {@inheritDocs} */
366 public PostBuilder newPostBuilder() {
367 return new MemoryPostBuilder(this, this);
374 /** {@inheritDocs} */
376 public void storePost(Post post) {
377 checkNotNull(post, "post must not be null");
378 lock.writeLock().lock();
380 allPosts.put(post.getId(), post);
381 getPostsFrom(post.getSone().getId()).add(post);
383 lock.writeLock().unlock();
387 /** {@inheritDocs} */
389 public void removePost(Post post) {
390 checkNotNull(post, "post must not be null");
391 lock.writeLock().lock();
393 allPosts.remove(post.getId());
394 getPostsFrom(post.getSone().getId()).remove(post);
395 post.getSone().removePost(post);
397 lock.writeLock().unlock();
402 // POSTREPLYPROVIDER METHODS
407 public PostReply getPostReply(String id) {
408 lock.readLock().lock();
410 return allPostReplies.get(id);
412 lock.readLock().unlock();
416 /** {@inheritDocs} */
418 public List<PostReply> getReplies(final String postId) {
419 lock.readLock().lock();
421 return from(allPostReplies.values())
422 .filter(new Predicate<PostReply>() {
424 public boolean apply(PostReply postReply) {
425 return postReply.getPostId().equals(postId);
427 }).toSortedList(TIME_COMPARATOR);
429 lock.readLock().unlock();
434 // POSTREPLYBUILDERFACTORY METHODS
437 /** {@inheritDocs} */
439 public PostReplyBuilder newPostReplyBuilder() {
440 return new MemoryPostReplyBuilder(this, this);
444 // POSTREPLYSTORE METHODS
447 /** {@inheritDocs} */
449 public void storePostReply(PostReply postReply) {
450 lock.writeLock().lock();
452 allPostReplies.put(postReply.getId(), postReply);
454 lock.writeLock().unlock();
458 /** {@inheritDocs} */
460 public void removePostReply(PostReply postReply) {
461 lock.writeLock().lock();
463 allPostReplies.remove(postReply.getId());
465 lock.writeLock().unlock();
470 // ALBUMPROVDER METHODS
475 public Album getAlbum(@Nonnull String albumId) {
476 lock.readLock().lock();
478 return allAlbums.get(albumId);
480 lock.readLock().unlock();
485 // ALBUMBUILDERFACTORY METHODS
489 public AlbumBuilder newAlbumBuilder() {
490 return new AlbumBuilderImpl();
494 // ALBUMSTORE METHODS
498 public void storeAlbum(Album album) {
499 lock.writeLock().lock();
501 allAlbums.put(album.getId(), album);
502 soneAlbums.put(album.getSone().getId(), album);
504 lock.writeLock().unlock();
509 public void removeAlbum(Album album) {
510 lock.writeLock().lock();
512 allAlbums.remove(album.getId());
513 soneAlbums.remove(album.getSone().getId(), album);
515 lock.writeLock().unlock();
520 // IMAGEPROVIDER METHODS
525 public Image getImage(@Nonnull String imageId) {
526 lock.readLock().lock();
528 return allImages.get(imageId);
530 lock.readLock().unlock();
535 // IMAGEBUILDERFACTORY METHODS
539 public ImageBuilder newImageBuilder() {
540 return new ImageBuilderImpl();
544 // IMAGESTORE METHODS
548 public void storeImage(Image image) {
549 lock.writeLock().lock();
551 allImages.put(image.getId(), image);
552 soneImages.put(image.getSone().getId(), image);
554 lock.writeLock().unlock();
559 public void removeImage(Image image) {
560 lock.writeLock().lock();
562 allImages.remove(image.getId());
563 soneImages.remove(image.getSone().getId(), image);
565 lock.writeLock().unlock();
570 public void bookmarkPost(Post post) {
571 memoryBookmarkDatabase.bookmarkPost(post);
575 public void unbookmarkPost(Post post) {
576 memoryBookmarkDatabase.unbookmarkPost(post);
580 public boolean isPostBookmarked(Post post) {
581 return memoryBookmarkDatabase.isPostBookmarked(post);
585 public Set<Post> getBookmarkedPosts() {
586 return memoryBookmarkDatabase.getBookmarkedPosts();
590 // PACKAGE-PRIVATE METHODS
594 * Returns whether the given post is known.
598 * @return {@code true} if the post is known, {@code false} otherwise
600 boolean isPostKnown(Post post) {
601 lock.readLock().lock();
603 return knownPosts.contains(post.getId());
605 lock.readLock().unlock();
610 * Sets whether the given post is known.
615 * {@code true} if the post is known, {@code false} otherwise
617 void setPostKnown(Post post, boolean known) {
618 lock.writeLock().lock();
621 knownPosts.add(post.getId());
623 knownPosts.remove(post.getId());
626 lock.writeLock().unlock();
631 * Returns whether the given post reply is known.
635 * @return {@code true} if the given post reply is known, {@code false}
638 boolean isPostReplyKnown(PostReply postReply) {
639 lock.readLock().lock();
641 return knownPostReplies.contains(postReply.getId());
643 lock.readLock().unlock();
648 * Sets whether the given post reply is known.
653 * {@code true} if the post reply is known, {@code false} otherwise
655 void setPostReplyKnown(PostReply postReply, boolean known) {
656 lock.writeLock().lock();
659 knownPostReplies.add(postReply.getId());
661 knownPostReplies.remove(postReply.getId());
664 lock.writeLock().unlock();
673 * Gets all posts for the given Sone, creating a new collection if there is
677 * The ID of the Sone to get the posts for
680 private Collection<Post> getPostsFrom(String soneId) {
681 lock.readLock().lock();
683 return sonePosts.get(soneId);
685 lock.readLock().unlock();
689 /** Loads the known posts. */
690 private void loadKnownPosts() {
691 Set<String> knownPosts = configurationLoader.loadKnownPosts();
692 lock.writeLock().lock();
694 this.knownPosts.clear();
695 this.knownPosts.addAll(knownPosts);
697 lock.writeLock().unlock();
702 * Saves the known posts to the configuration.
704 * @throws DatabaseException
705 * if a configuration error occurs
707 private void saveKnownPosts() throws DatabaseException {
708 lock.readLock().lock();
711 for (String knownPostId : knownPosts) {
712 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
714 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
715 } catch (ConfigurationException ce1) {
716 throw new DatabaseException("Could not save database.", ce1);
718 lock.readLock().unlock();
722 /** Loads the known post replies. */
723 private void loadKnownPostReplies() {
724 Set<String> knownPostReplies = configurationLoader.loadKnownPostReplies();
725 lock.writeLock().lock();
727 this.knownPostReplies.clear();
728 this.knownPostReplies.addAll(knownPostReplies);
730 lock.writeLock().unlock();
735 * Saves the known post replies to the configuration.
737 * @throws DatabaseException
738 * if a configuration error occurs
740 private void saveKnownPostReplies() throws DatabaseException {
741 lock.readLock().lock();
743 int replyCounter = 0;
744 for (String knownReplyId : knownPostReplies) {
745 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
747 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
748 } catch (ConfigurationException ce1) {
749 throw new DatabaseException("Could not save database.", ce1);
751 lock.readLock().unlock();