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.Optional;
63 import com.google.common.base.Predicate;
64 import com.google.common.collect.HashMultimap;
65 import com.google.common.collect.Multimap;
66 import com.google.common.collect.SortedSetMultimap;
67 import com.google.common.collect.TreeMultimap;
68 import com.google.common.util.concurrent.AbstractService;
69 import com.google.inject.Inject;
70 import com.google.inject.Singleton;
71 import kotlin.jvm.functions.Function1;
74 * Memory-based {@link PostDatabase} implementation.
76 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
79 public class MemoryDatabase extends AbstractService implements Database {
82 private final ReadWriteLock lock = new ReentrantReadWriteLock();
84 /** The Sone provider. */
85 private final SoneProvider soneProvider;
87 /** The configuration. */
88 private final Configuration configuration;
89 private final ConfigurationLoader configurationLoader;
91 private final Map<String, Sone> allSones = new HashMap<String, Sone>();
93 /** All posts by their ID. */
94 private final Map<String, Post> allPosts = new HashMap<String, Post>();
96 /** All posts by their Sones. */
97 private final Multimap<String, Post> sonePosts = HashMultimap.create();
99 /** Whether posts are known. */
100 private final Set<String> knownPosts = new HashSet<String>();
102 /** All post replies by their ID. */
103 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
105 /** Replies sorted by Sone. */
106 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
109 public int compare(String leftString, String rightString) {
110 return leftString.compareTo(rightString);
114 /** Whether post replies are known. */
115 private final Set<String> knownPostReplies = new HashSet<String>();
117 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
118 private final Multimap<String, Album> soneAlbums = HashMultimap.create();
120 private final Map<String, Image> allImages = new HashMap<String, Image>();
121 private final Multimap<String, Image> soneImages = HashMultimap.create();
123 private final MemoryBookmarkDatabase memoryBookmarkDatabase;
124 private final MemoryFriendDatabase memoryFriendDatabase;
127 * Creates a new memory database.
129 * @param soneProvider
131 * @param configuration
132 * The configuration for loading and saving elements
135 public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
136 this.soneProvider = soneProvider;
137 this.configuration = configuration;
138 this.configurationLoader = new ConfigurationLoader(configuration);
139 memoryBookmarkDatabase =
140 new MemoryBookmarkDatabase(this, configurationLoader);
141 memoryFriendDatabase = new MemoryFriendDatabase(configurationLoader);
149 * Saves the database.
151 * @throws DatabaseException
152 * if an error occurs while saving
155 public void save() throws DatabaseException {
157 saveKnownPostReplies();
164 /** {@inheritDocs} */
166 protected void doStart() {
167 memoryBookmarkDatabase.start();
169 loadKnownPostReplies();
173 /** {@inheritDocs} */
175 protected void doStop() {
177 memoryBookmarkDatabase.stop();
180 } catch (DatabaseException de1) {
186 public SoneBuilder newSoneBuilder() {
187 return new MemorySoneBuilder(this);
191 public void storeSone(Sone sone) {
192 lock.writeLock().lock();
196 allSones.put(sone.getId(), sone);
197 sonePosts.putAll(sone.getId(), sone.getPosts());
198 for (Post post : sone.getPosts()) {
199 allPosts.put(post.getId(), post);
201 sonePostReplies.putAll(sone.getId(), sone.getReplies());
202 for (PostReply postReply : sone.getReplies()) {
203 allPostReplies.put(postReply.getId(), postReply);
205 soneAlbums.putAll(sone.getId(), toAllAlbums.apply(sone));
206 for (Album album : toAllAlbums.apply(sone)) {
207 allAlbums.put(album.getId(), album);
209 soneImages.putAll(sone.getId(), toAllImages.apply(sone));
210 for (Image image : toAllImages.apply(sone)) {
211 allImages.put(image.getId(), image);
214 lock.writeLock().unlock();
219 public void removeSone(Sone sone) {
220 lock.writeLock().lock();
222 allSones.remove(sone.getId());
223 Collection<Post> removedPosts = sonePosts.removeAll(sone.getId());
224 for (Post removedPost : removedPosts) {
225 allPosts.remove(removedPost.getId());
227 Collection<PostReply> removedPostReplies =
228 sonePostReplies.removeAll(sone.getId());
229 for (PostReply removedPostReply : removedPostReplies) {
230 allPostReplies.remove(removedPostReply.getId());
232 Collection<Album> removedAlbums =
233 soneAlbums.removeAll(sone.getId());
234 for (Album removedAlbum : removedAlbums) {
235 allAlbums.remove(removedAlbum.getId());
237 Collection<Image> removedImages =
238 soneImages.removeAll(sone.getId());
239 for (Image removedImage : removedImages) {
240 allImages.remove(removedImage.getId());
243 lock.writeLock().unlock();
249 public Function1<String, Sone> getSoneLoader() {
250 return new Function1<String, Sone>() {
252 public Sone invoke(String soneId) {
253 return getSone(soneId);
259 public Sone getSone(String soneId) {
260 lock.readLock().lock();
262 return allSones.get(soneId);
264 lock.readLock().unlock();
269 public Collection<Sone> getSones() {
270 lock.readLock().lock();
272 return new HashSet<Sone>(allSones.values());
274 lock.readLock().unlock();
279 public Collection<Sone> getLocalSones() {
280 lock.readLock().lock();
282 return from(allSones.values()).filter(LOCAL_SONE_FILTER).toSet();
284 lock.readLock().unlock();
289 public Collection<Sone> getRemoteSones() {
290 lock.readLock().lock();
292 return from(allSones.values())
293 .filter(not(LOCAL_SONE_FILTER)) .toSet();
295 lock.readLock().unlock();
300 public Collection<String> getFriends(Sone localSone) {
301 if (!localSone.isLocal()) {
302 return Collections.emptySet();
304 return memoryFriendDatabase.getFriends(localSone.getId());
308 public boolean isFriend(Sone localSone, String friendSoneId) {
309 if (!localSone.isLocal()) {
312 return memoryFriendDatabase.isFriend(localSone.getId(), friendSoneId);
316 public void addFriend(Sone localSone, String friendSoneId) {
317 if (!localSone.isLocal()) {
320 memoryFriendDatabase.addFriend(localSone.getId(), friendSoneId);
324 public void removeFriend(Sone localSone, String friendSoneId) {
325 if (!localSone.isLocal()) {
328 memoryFriendDatabase.removeFriend(localSone.getId(), friendSoneId);
332 // POSTPROVIDER METHODS
335 /** {@inheritDocs} */
337 public Optional<Post> getPost(String postId) {
338 lock.readLock().lock();
340 return fromNullable(allPosts.get(postId));
342 lock.readLock().unlock();
346 /** {@inheritDocs} */
348 public Collection<Post> getPosts(String soneId) {
349 return new HashSet<Post>(getPostsFrom(soneId));
352 /** {@inheritDocs} */
354 public Collection<Post> getDirectedPosts(final String recipientId) {
355 lock.readLock().lock();
357 return from(sonePosts.values()).filter(new Predicate<Post>() {
359 public boolean apply(Post post) {
360 return post.getRecipientId().asSet().contains(recipientId);
364 lock.readLock().unlock();
369 // POSTBUILDERFACTORY METHODS
372 /** {@inheritDocs} */
374 public PostBuilder newPostBuilder() {
375 return new MemoryPostBuilder(this, soneProvider);
382 /** {@inheritDocs} */
384 public void storePost(Post post) {
385 checkNotNull(post, "post must not be null");
386 lock.writeLock().lock();
388 allPosts.put(post.getId(), post);
389 getPostsFrom(post.getSone().getId()).add(post);
391 lock.writeLock().unlock();
395 /** {@inheritDocs} */
397 public void removePost(Post post) {
398 checkNotNull(post, "post must not be null");
399 lock.writeLock().lock();
401 allPosts.remove(post.getId());
402 getPostsFrom(post.getSone().getId()).remove(post);
403 post.getSone().removePost(post);
405 lock.writeLock().unlock();
410 // POSTREPLYPROVIDER METHODS
415 public PostReply getPostReply(String id) {
416 lock.readLock().lock();
418 return allPostReplies.get(id);
420 lock.readLock().unlock();
424 /** {@inheritDocs} */
426 public List<PostReply> getReplies(final String postId) {
427 lock.readLock().lock();
429 return from(allPostReplies.values())
430 .filter(new Predicate<PostReply>() {
432 public boolean apply(PostReply postReply) {
433 return postReply.getPostId().equals(postId);
435 }).toSortedList(TIME_COMPARATOR);
437 lock.readLock().unlock();
442 // POSTREPLYBUILDERFACTORY METHODS
445 /** {@inheritDocs} */
447 public PostReplyBuilder newPostReplyBuilder() {
448 return new MemoryPostReplyBuilder(this, soneProvider);
452 // POSTREPLYSTORE METHODS
455 /** {@inheritDocs} */
457 public void storePostReply(PostReply postReply) {
458 lock.writeLock().lock();
460 allPostReplies.put(postReply.getId(), postReply);
462 lock.writeLock().unlock();
466 /** {@inheritDocs} */
468 public void removePostReply(PostReply postReply) {
469 lock.writeLock().lock();
471 allPostReplies.remove(postReply.getId());
473 lock.writeLock().unlock();
478 // ALBUMPROVDER METHODS
483 public Album getAlbum(@Nonnull String albumId) {
484 lock.readLock().lock();
486 return allAlbums.get(albumId);
488 lock.readLock().unlock();
493 // ALBUMBUILDERFACTORY METHODS
497 public AlbumBuilder newAlbumBuilder() {
498 return new AlbumBuilderImpl();
502 // ALBUMSTORE METHODS
506 public void storeAlbum(Album album) {
507 lock.writeLock().lock();
509 allAlbums.put(album.getId(), album);
510 soneAlbums.put(album.getSone().getId(), album);
512 lock.writeLock().unlock();
517 public void removeAlbum(Album album) {
518 lock.writeLock().lock();
520 allAlbums.remove(album.getId());
521 soneAlbums.remove(album.getSone().getId(), album);
523 lock.writeLock().unlock();
528 // IMAGEPROVIDER METHODS
533 public Image getImage(@Nonnull String imageId) {
534 lock.readLock().lock();
536 return allImages.get(imageId);
538 lock.readLock().unlock();
543 // IMAGEBUILDERFACTORY METHODS
547 public ImageBuilder newImageBuilder() {
548 return new ImageBuilderImpl();
552 // IMAGESTORE METHODS
556 public void storeImage(Image image) {
557 lock.writeLock().lock();
559 allImages.put(image.getId(), image);
560 soneImages.put(image.getSone().getId(), image);
562 lock.writeLock().unlock();
567 public void removeImage(Image image) {
568 lock.writeLock().lock();
570 allImages.remove(image.getId());
571 soneImages.remove(image.getSone().getId(), image);
573 lock.writeLock().unlock();
578 public void bookmarkPost(Post post) {
579 memoryBookmarkDatabase.bookmarkPost(post);
583 public void unbookmarkPost(Post post) {
584 memoryBookmarkDatabase.unbookmarkPost(post);
588 public boolean isPostBookmarked(Post post) {
589 return memoryBookmarkDatabase.isPostBookmarked(post);
593 public Set<Post> getBookmarkedPosts() {
594 return memoryBookmarkDatabase.getBookmarkedPosts();
598 // PACKAGE-PRIVATE METHODS
602 * Returns whether the given post is known.
606 * @return {@code true} if the post is known, {@code false} otherwise
608 boolean isPostKnown(Post post) {
609 lock.readLock().lock();
611 return knownPosts.contains(post.getId());
613 lock.readLock().unlock();
618 * Sets whether the given post is known.
623 * {@code true} if the post is known, {@code false} otherwise
625 void setPostKnown(Post post, boolean known) {
626 lock.writeLock().lock();
629 knownPosts.add(post.getId());
631 knownPosts.remove(post.getId());
634 lock.writeLock().unlock();
639 * Returns whether the given post reply is known.
643 * @return {@code true} if the given post reply is known, {@code false}
646 boolean isPostReplyKnown(PostReply postReply) {
647 lock.readLock().lock();
649 return knownPostReplies.contains(postReply.getId());
651 lock.readLock().unlock();
656 * Sets whether the given post reply is known.
661 * {@code true} if the post reply is known, {@code false} otherwise
663 void setPostReplyKnown(PostReply postReply, boolean known) {
664 lock.writeLock().lock();
667 knownPostReplies.add(postReply.getId());
669 knownPostReplies.remove(postReply.getId());
672 lock.writeLock().unlock();
681 * Gets all posts for the given Sone, creating a new collection if there is
685 * The ID of the Sone to get the posts for
688 private Collection<Post> getPostsFrom(String soneId) {
689 lock.readLock().lock();
691 return sonePosts.get(soneId);
693 lock.readLock().unlock();
697 /** Loads the known posts. */
698 private void loadKnownPosts() {
699 Set<String> knownPosts = configurationLoader.loadKnownPosts();
700 lock.writeLock().lock();
702 this.knownPosts.clear();
703 this.knownPosts.addAll(knownPosts);
705 lock.writeLock().unlock();
710 * Saves the known posts to the configuration.
712 * @throws DatabaseException
713 * if a configuration error occurs
715 private void saveKnownPosts() throws DatabaseException {
716 lock.readLock().lock();
719 for (String knownPostId : knownPosts) {
720 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
722 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
723 } catch (ConfigurationException ce1) {
724 throw new DatabaseException("Could not save database.", ce1);
726 lock.readLock().unlock();
730 /** Loads the known post replies. */
731 private void loadKnownPostReplies() {
732 Set<String> knownPostReplies = configurationLoader.loadKnownPostReplies();
733 lock.writeLock().lock();
735 this.knownPostReplies.clear();
736 this.knownPostReplies.addAll(knownPostReplies);
738 lock.writeLock().unlock();
743 * Saves the known post replies to the configuration.
745 * @throws DatabaseException
746 * if a configuration error occurs
748 private void saveKnownPostReplies() throws DatabaseException {
749 lock.readLock().lock();
751 int replyCounter = 0;
752 for (String knownReplyId : knownPostReplies) {
753 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
755 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
756 } catch (ConfigurationException ce1) {
757 throw new DatabaseException("Could not save database.", ce1);
759 lock.readLock().unlock();