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 net.pterodactylus.sone.data.Album;
41 import net.pterodactylus.sone.data.Image;
42 import net.pterodactylus.sone.data.Post;
43 import net.pterodactylus.sone.data.PostReply;
44 import net.pterodactylus.sone.data.Sone;
45 import net.pterodactylus.sone.data.impl.AlbumBuilderImpl;
46 import net.pterodactylus.sone.data.impl.ImageBuilderImpl;
47 import net.pterodactylus.sone.database.AlbumBuilder;
48 import net.pterodactylus.sone.database.Database;
49 import net.pterodactylus.sone.database.DatabaseException;
50 import net.pterodactylus.sone.database.ImageBuilder;
51 import net.pterodactylus.sone.database.PostBuilder;
52 import net.pterodactylus.sone.database.PostDatabase;
53 import net.pterodactylus.sone.database.PostReplyBuilder;
54 import net.pterodactylus.sone.database.SoneBuilder;
55 import net.pterodactylus.sone.database.SoneProvider;
56 import net.pterodactylus.util.config.Configuration;
57 import net.pterodactylus.util.config.ConfigurationException;
59 import com.google.common.base.Function;
60 import com.google.common.base.Optional;
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;
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 Sone provider. */
82 private final SoneProvider soneProvider;
84 /** The configuration. */
85 private final Configuration configuration;
86 private final ConfigurationLoader configurationLoader;
88 private final Map<String, Sone> allSones = new HashMap<String, Sone>();
90 /** All posts by their ID. */
91 private final Map<String, Post> allPosts = new HashMap<String, Post>();
93 /** All posts by their Sones. */
94 private final Multimap<String, Post> sonePosts = HashMultimap.create();
96 /** Whether posts are known. */
97 private final Set<String> knownPosts = new HashSet<String>();
99 /** All post replies by their ID. */
100 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
102 /** Replies sorted by Sone. */
103 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
106 public int compare(String leftString, String rightString) {
107 return leftString.compareTo(rightString);
111 /** Whether post replies are known. */
112 private final Set<String> knownPostReplies = new HashSet<String>();
114 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
115 private final Multimap<String, Album> soneAlbums = HashMultimap.create();
117 private final Map<String, Image> allImages = new HashMap<String, Image>();
118 private final Multimap<String, Image> soneImages = HashMultimap.create();
120 private final MemoryBookmarkDatabase memoryBookmarkDatabase;
121 private final MemoryFriendDatabase memoryFriendDatabase;
124 * Creates a new memory database.
126 * @param soneProvider
128 * @param configuration
129 * The configuration for loading and saving elements
132 public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
133 this.soneProvider = soneProvider;
134 this.configuration = configuration;
135 this.configurationLoader = new ConfigurationLoader(configuration);
136 memoryBookmarkDatabase =
137 new MemoryBookmarkDatabase(this, configurationLoader);
138 memoryFriendDatabase = new MemoryFriendDatabase(configurationLoader);
146 * Saves the database.
148 * @throws DatabaseException
149 * if an error occurs while saving
152 public void save() throws DatabaseException {
154 saveKnownPostReplies();
161 /** {@inheritDocs} */
163 protected void doStart() {
164 memoryBookmarkDatabase.start();
166 loadKnownPostReplies();
170 /** {@inheritDocs} */
172 protected void doStop() {
174 memoryBookmarkDatabase.stop();
177 } catch (DatabaseException de1) {
183 public SoneBuilder newSoneBuilder() {
184 return new MemorySoneBuilder(this);
188 public void storeSone(Sone sone) {
189 lock.writeLock().lock();
193 allSones.put(sone.getId(), sone);
194 sonePosts.putAll(sone.getId(), sone.getPosts());
195 for (Post post : sone.getPosts()) {
196 allPosts.put(post.getId(), post);
198 sonePostReplies.putAll(sone.getId(), sone.getReplies());
199 for (PostReply postReply : sone.getReplies()) {
200 allPostReplies.put(postReply.getId(), postReply);
202 soneAlbums.putAll(sone.getId(), toAllAlbums.apply(sone));
203 for (Album album : toAllAlbums.apply(sone)) {
204 allAlbums.put(album.getId(), album);
206 soneImages.putAll(sone.getId(), toAllImages.apply(sone));
207 for (Image image : toAllImages.apply(sone)) {
208 allImages.put(image.getId(), image);
211 lock.writeLock().unlock();
216 public void removeSone(Sone sone) {
217 lock.writeLock().lock();
219 allSones.remove(sone.getId());
220 Collection<Post> removedPosts = sonePosts.removeAll(sone.getId());
221 for (Post removedPost : removedPosts) {
222 allPosts.remove(removedPost.getId());
224 Collection<PostReply> removedPostReplies =
225 sonePostReplies.removeAll(sone.getId());
226 for (PostReply removedPostReply : removedPostReplies) {
227 allPostReplies.remove(removedPostReply.getId());
229 Collection<Album> removedAlbums =
230 soneAlbums.removeAll(sone.getId());
231 for (Album removedAlbum : removedAlbums) {
232 allAlbums.remove(removedAlbum.getId());
234 Collection<Image> removedImages =
235 soneImages.removeAll(sone.getId());
236 for (Image removedImage : removedImages) {
237 allImages.remove(removedImage.getId());
240 lock.writeLock().unlock();
245 public Function<String, Optional<Sone>> soneLoader() {
246 return new Function<String, Optional<Sone>>() {
248 public Optional<Sone> apply(String soneId) {
249 return getSone(soneId);
255 public Optional<Sone> getSone(String soneId) {
256 lock.readLock().lock();
258 return fromNullable(allSones.get(soneId));
260 lock.readLock().unlock();
265 public Collection<Sone> getSones() {
266 lock.readLock().lock();
268 return new HashSet<Sone>(allSones.values());
270 lock.readLock().unlock();
275 public Collection<Sone> getLocalSones() {
276 lock.readLock().lock();
278 return from(allSones.values()).filter(LOCAL_SONE_FILTER).toSet();
280 lock.readLock().unlock();
285 public Collection<Sone> getRemoteSones() {
286 lock.readLock().lock();
288 return from(allSones.values())
289 .filter(not(LOCAL_SONE_FILTER)) .toSet();
291 lock.readLock().unlock();
296 public Collection<String> getFriends(Sone localSone) {
297 if (!localSone.isLocal()) {
298 return Collections.emptySet();
300 return memoryFriendDatabase.getFriends(localSone.getId());
304 public boolean isFriend(Sone localSone, String friendSoneId) {
305 if (!localSone.isLocal()) {
308 return memoryFriendDatabase.isFriend(localSone.getId(), friendSoneId);
312 public void addFriend(Sone localSone, String friendSoneId) {
313 if (!localSone.isLocal()) {
316 memoryFriendDatabase.addFriend(localSone.getId(), friendSoneId);
320 public void removeFriend(Sone localSone, String friendSoneId) {
321 if (!localSone.isLocal()) {
324 memoryFriendDatabase.removeFriend(localSone.getId(), friendSoneId);
328 // POSTPROVIDER METHODS
331 /** {@inheritDocs} */
333 public Optional<Post> getPost(String postId) {
334 lock.readLock().lock();
336 return fromNullable(allPosts.get(postId));
338 lock.readLock().unlock();
342 /** {@inheritDocs} */
344 public Collection<Post> getPosts(String soneId) {
345 return new HashSet<Post>(getPostsFrom(soneId));
348 /** {@inheritDocs} */
350 public Collection<Post> getDirectedPosts(final String recipientId) {
351 lock.readLock().lock();
353 return from(sonePosts.values()).filter(new Predicate<Post>() {
355 public boolean apply(Post post) {
356 return post.getRecipientId().asSet().contains(recipientId);
360 lock.readLock().unlock();
365 // POSTBUILDERFACTORY METHODS
368 /** {@inheritDocs} */
370 public PostBuilder newPostBuilder() {
371 return new MemoryPostBuilder(this, soneProvider);
378 /** {@inheritDocs} */
380 public void storePost(Post post) {
381 checkNotNull(post, "post must not be null");
382 lock.writeLock().lock();
384 allPosts.put(post.getId(), post);
385 getPostsFrom(post.getSone().getId()).add(post);
387 lock.writeLock().unlock();
391 /** {@inheritDocs} */
393 public void removePost(Post post) {
394 checkNotNull(post, "post must not be null");
395 lock.writeLock().lock();
397 allPosts.remove(post.getId());
398 getPostsFrom(post.getSone().getId()).remove(post);
399 post.getSone().removePost(post);
401 lock.writeLock().unlock();
406 // POSTREPLYPROVIDER METHODS
409 /** {@inheritDocs} */
411 public Optional<PostReply> getPostReply(String id) {
412 lock.readLock().lock();
414 return fromNullable(allPostReplies.get(id));
416 lock.readLock().unlock();
420 /** {@inheritDocs} */
422 public List<PostReply> getReplies(final String postId) {
423 lock.readLock().lock();
425 return from(allPostReplies.values())
426 .filter(new Predicate<PostReply>() {
428 public boolean apply(PostReply postReply) {
429 return postReply.getPostId().equals(postId);
431 }).toSortedList(TIME_COMPARATOR);
433 lock.readLock().unlock();
438 // POSTREPLYBUILDERFACTORY METHODS
441 /** {@inheritDocs} */
443 public PostReplyBuilder newPostReplyBuilder() {
444 return new MemoryPostReplyBuilder(this, soneProvider);
448 // POSTREPLYSTORE METHODS
451 /** {@inheritDocs} */
453 public void storePostReply(PostReply postReply) {
454 lock.writeLock().lock();
456 allPostReplies.put(postReply.getId(), postReply);
458 lock.writeLock().unlock();
462 /** {@inheritDocs} */
464 public void removePostReply(PostReply postReply) {
465 lock.writeLock().lock();
467 allPostReplies.remove(postReply.getId());
469 lock.writeLock().unlock();
474 // ALBUMPROVDER METHODS
478 public Optional<Album> getAlbum(String albumId) {
479 lock.readLock().lock();
481 return fromNullable(allAlbums.get(albumId));
483 lock.readLock().unlock();
488 // ALBUMBUILDERFACTORY METHODS
492 public AlbumBuilder newAlbumBuilder() {
493 return new AlbumBuilderImpl();
497 // ALBUMSTORE METHODS
501 public void storeAlbum(Album album) {
502 lock.writeLock().lock();
504 allAlbums.put(album.getId(), album);
505 soneAlbums.put(album.getSone().getId(), album);
507 lock.writeLock().unlock();
512 public void removeAlbum(Album album) {
513 lock.writeLock().lock();
515 allAlbums.remove(album.getId());
516 soneAlbums.remove(album.getSone().getId(), album);
518 lock.writeLock().unlock();
523 // IMAGEPROVIDER METHODS
527 public Optional<Image> getImage(String imageId) {
528 lock.readLock().lock();
530 return fromNullable(allImages.get(imageId));
532 lock.readLock().unlock();
537 // IMAGEBUILDERFACTORY METHODS
541 public ImageBuilder newImageBuilder() {
542 return new ImageBuilderImpl();
546 // IMAGESTORE METHODS
550 public void storeImage(Image image) {
551 lock.writeLock().lock();
553 allImages.put(image.getId(), image);
554 soneImages.put(image.getSone().getId(), image);
556 lock.writeLock().unlock();
561 public void removeImage(Image image) {
562 lock.writeLock().lock();
564 allImages.remove(image.getId());
565 soneImages.remove(image.getSone().getId(), image);
567 lock.writeLock().unlock();
572 public void bookmarkPost(Post post) {
573 memoryBookmarkDatabase.bookmarkPost(post);
577 public void unbookmarkPost(Post post) {
578 memoryBookmarkDatabase.unbookmarkPost(post);
582 public boolean isPostBookmarked(Post post) {
583 return memoryBookmarkDatabase.isPostBookmarked(post);
587 public Set<Post> getBookmarkedPosts() {
588 return memoryBookmarkDatabase.getBookmarkedPosts();
592 // PACKAGE-PRIVATE METHODS
596 * Returns whether the given post is known.
600 * @return {@code true} if the post is known, {@code false} otherwise
602 boolean isPostKnown(Post post) {
603 lock.readLock().lock();
605 return knownPosts.contains(post.getId());
607 lock.readLock().unlock();
612 * Sets whether the given post is known.
617 * {@code true} if the post is known, {@code false} otherwise
619 void setPostKnown(Post post, boolean known) {
620 lock.writeLock().lock();
623 knownPosts.add(post.getId());
625 knownPosts.remove(post.getId());
628 lock.writeLock().unlock();
633 * Returns whether the given post reply is known.
637 * @return {@code true} if the given post reply is known, {@code false}
640 boolean isPostReplyKnown(PostReply postReply) {
641 lock.readLock().lock();
643 return knownPostReplies.contains(postReply.getId());
645 lock.readLock().unlock();
650 * Sets whether the given post reply is known.
655 * {@code true} if the post reply is known, {@code false} otherwise
657 void setPostReplyKnown(PostReply postReply, boolean known) {
658 lock.writeLock().lock();
661 knownPostReplies.add(postReply.getId());
663 knownPostReplies.remove(postReply.getId());
666 lock.writeLock().unlock();
675 * Gets all posts for the given Sone, creating a new collection if there is
679 * The ID of the Sone to get the posts for
682 private Collection<Post> getPostsFrom(String soneId) {
683 lock.readLock().lock();
685 return sonePosts.get(soneId);
687 lock.readLock().unlock();
691 /** Loads the known posts. */
692 private void loadKnownPosts() {
693 Set<String> knownPosts = configurationLoader.loadKnownPosts();
694 lock.writeLock().lock();
696 this.knownPosts.clear();
697 this.knownPosts.addAll(knownPosts);
699 lock.writeLock().unlock();
704 * Saves the known posts to the configuration.
706 * @throws DatabaseException
707 * if a configuration error occurs
709 private void saveKnownPosts() throws DatabaseException {
710 lock.readLock().lock();
713 for (String knownPostId : knownPosts) {
714 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
716 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
717 } catch (ConfigurationException ce1) {
718 throw new DatabaseException("Could not save database.", ce1);
720 lock.readLock().unlock();
724 /** Loads the known post replies. */
725 private void loadKnownPostReplies() {
726 Set<String> knownPostReplies = configurationLoader.loadKnownPostReplies();
727 lock.writeLock().lock();
729 this.knownPostReplies.clear();
730 this.knownPostReplies.addAll(knownPostReplies);
732 lock.writeLock().unlock();
737 * Saves the known post replies to the configuration.
739 * @throws DatabaseException
740 * if a configuration error occurs
742 private void saveKnownPostReplies() throws DatabaseException {
743 lock.readLock().lock();
745 int replyCounter = 0;
746 for (String knownReplyId : knownPostReplies) {
747 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
749 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
750 } catch (ConfigurationException ce1) {
751 throw new DatabaseException("Could not save database.", ce1);
753 lock.readLock().unlock();