2 * Sone - MemoryDatabase.java - Copyright © 2013 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 net.pterodactylus.sone.data.Reply.TIME_COMPARATOR;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.Comparator;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.List;
33 import java.util.concurrent.locks.ReadWriteLock;
34 import java.util.concurrent.locks.ReentrantReadWriteLock;
36 import net.pterodactylus.sone.data.Album;
37 import net.pterodactylus.sone.data.Image;
38 import net.pterodactylus.sone.data.Post;
39 import net.pterodactylus.sone.data.PostReply;
40 import net.pterodactylus.sone.data.Sone;
41 import net.pterodactylus.sone.data.impl.AlbumBuilderImpl;
42 import net.pterodactylus.sone.data.impl.ImageBuilderImpl;
43 import net.pterodactylus.sone.database.AlbumBuilder;
44 import net.pterodactylus.sone.database.Database;
45 import net.pterodactylus.sone.database.DatabaseException;
46 import net.pterodactylus.sone.database.ImageBuilder;
47 import net.pterodactylus.sone.database.PostBuilder;
48 import net.pterodactylus.sone.database.PostDatabase;
49 import net.pterodactylus.sone.database.PostReplyBuilder;
50 import net.pterodactylus.sone.database.SoneProvider;
51 import net.pterodactylus.util.config.Configuration;
52 import net.pterodactylus.util.config.ConfigurationException;
54 import com.google.common.base.Optional;
55 import com.google.common.collect.HashMultimap;
56 import com.google.common.collect.Multimap;
57 import com.google.common.collect.SortedSetMultimap;
58 import com.google.common.collect.TreeMultimap;
59 import com.google.common.util.concurrent.AbstractService;
60 import com.google.inject.Inject;
61 import com.google.inject.Singleton;
64 * Memory-based {@link PostDatabase} implementation.
66 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
69 public class MemoryDatabase extends AbstractService implements Database {
72 private final ReadWriteLock lock = new ReentrantReadWriteLock();
74 /** The Sone provider. */
75 private final SoneProvider soneProvider;
77 /** The configuration. */
78 private final Configuration configuration;
80 /** All posts by their ID. */
81 private final Map<String, Post> allPosts = new HashMap<String, Post>();
83 /** All posts by their Sones. */
84 private final Multimap<String, Post> sonePosts = HashMultimap.create();
86 /** All posts by their recipient. */
87 private final Multimap<String, Post> recipientPosts = HashMultimap.create();
89 /** Whether posts are known. */
90 private final Set<String> knownPosts = new HashSet<String>();
92 /** All post replies by their ID. */
93 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
95 /** Replies sorted by Sone. */
96 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
99 public int compare(String leftString, String rightString) {
100 return leftString.compareTo(rightString);
104 /** Replies by post. */
105 private final SortedSetMultimap<String, PostReply> postReplies = 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();
123 * Creates a new memory database.
125 * @param soneProvider
127 * @param configuration
128 * The configuration for loading and saving elements
131 public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
132 this.soneProvider = soneProvider;
133 this.configuration = configuration;
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() {
160 loadKnownPostReplies();
164 /** {@inheritDocs} */
166 protected void doStop() {
170 } catch (DatabaseException de1) {
176 // POSTPROVIDER METHODS
179 /** {@inheritDocs} */
181 public Optional<Post> getPost(String postId) {
182 lock.readLock().lock();
184 return fromNullable(allPosts.get(postId));
186 lock.readLock().unlock();
190 /** {@inheritDocs} */
192 public Collection<Post> getPosts(String soneId) {
193 return new HashSet<Post>(getPostsFrom(soneId));
196 /** {@inheritDocs} */
198 public Collection<Post> getDirectedPosts(String recipientId) {
199 lock.readLock().lock();
201 Collection<Post> posts = recipientPosts.get(recipientId);
202 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
204 lock.readLock().unlock();
209 // POSTBUILDERFACTORY METHODS
212 /** {@inheritDocs} */
214 public PostBuilder newPostBuilder() {
215 return new MemoryPostBuilder(this, soneProvider);
222 /** {@inheritDocs} */
224 public void storePost(Post post) {
225 checkNotNull(post, "post must not be null");
226 lock.writeLock().lock();
228 allPosts.put(post.getId(), post);
229 getPostsFrom(post.getSone().getId()).add(post);
230 if (post.getRecipientId().isPresent()) {
231 getPostsTo(post.getRecipientId().get()).add(post);
234 lock.writeLock().unlock();
238 /** {@inheritDocs} */
240 public void removePost(Post post) {
241 checkNotNull(post, "post must not be null");
242 lock.writeLock().lock();
244 allPosts.remove(post.getId());
245 getPostsFrom(post.getSone().getId()).remove(post);
246 if (post.getRecipientId().isPresent()) {
247 getPostsTo(post.getRecipientId().get()).remove(post);
249 post.getSone().removePost(post);
251 lock.writeLock().unlock();
255 /** {@inheritDocs} */
257 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
258 checkNotNull(sone, "sone must not be null");
259 /* verify that all posts are from the same Sone. */
260 for (Post post : posts) {
261 if (!sone.equals(post.getSone())) {
262 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
266 lock.writeLock().lock();
268 /* remove all posts by the Sone. */
269 Collection<Post> oldPosts = getPostsFrom(sone.getId());
270 for (Post post : oldPosts) {
271 allPosts.remove(post.getId());
272 if (post.getRecipientId().isPresent()) {
273 getPostsTo(post.getRecipientId().get()).remove(post);
278 getPostsFrom(sone.getId()).addAll(posts);
279 for (Post post : posts) {
280 allPosts.put(post.getId(), post);
281 if (post.getRecipientId().isPresent()) {
282 getPostsTo(post.getRecipientId().get()).add(post);
286 lock.writeLock().unlock();
290 /** {@inheritDocs} */
292 public void removePosts(Sone sone) {
293 checkNotNull(sone, "sone must not be null");
294 lock.writeLock().lock();
296 /* remove all posts by the Sone. */
297 getPostsFrom(sone.getId()).clear();
298 for (Post post : sone.getPosts()) {
299 allPosts.remove(post.getId());
300 if (post.getRecipientId().isPresent()) {
301 getPostsTo(post.getRecipientId().get()).remove(post);
305 lock.writeLock().unlock();
310 // POSTREPLYPROVIDER METHODS
313 /** {@inheritDocs} */
315 public Optional<PostReply> getPostReply(String id) {
316 lock.readLock().lock();
318 return fromNullable(allPostReplies.get(id));
320 lock.readLock().unlock();
324 /** {@inheritDocs} */
326 public List<PostReply> getReplies(String postId) {
327 lock.readLock().lock();
329 if (!postReplies.containsKey(postId)) {
330 return Collections.emptyList();
332 return new ArrayList<PostReply>(postReplies.get(postId));
334 lock.readLock().unlock();
339 // POSTREPLYBUILDERFACTORY METHODS
342 /** {@inheritDocs} */
344 public PostReplyBuilder newPostReplyBuilder() {
345 return new MemoryPostReplyBuilder(this, soneProvider);
349 // POSTREPLYSTORE METHODS
352 /** {@inheritDocs} */
354 public void storePostReply(PostReply postReply) {
355 lock.writeLock().lock();
357 allPostReplies.put(postReply.getId(), postReply);
358 postReplies.put(postReply.getPostId(), postReply);
360 lock.writeLock().unlock();
364 /** {@inheritDocs} */
366 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
367 checkNotNull(sone, "sone must not be null");
368 /* verify that all posts are from the same Sone. */
369 for (PostReply postReply : postReplies) {
370 if (!sone.equals(postReply.getSone())) {
371 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
375 lock.writeLock().lock();
377 /* remove all post replies of the Sone. */
378 for (PostReply postReply : getRepliesFrom(sone.getId())) {
379 removePostReply(postReply);
381 for (PostReply postReply : postReplies) {
382 allPostReplies.put(postReply.getId(), postReply);
383 sonePostReplies.put(postReply.getSone().getId(), postReply);
384 this.postReplies.put(postReply.getPostId(), postReply);
387 lock.writeLock().unlock();
391 /** {@inheritDocs} */
393 public void removePostReply(PostReply postReply) {
394 lock.writeLock().lock();
396 allPostReplies.remove(postReply.getId());
397 if (postReplies.containsKey(postReply.getPostId())) {
398 postReplies.get(postReply.getPostId()).remove(postReply);
401 lock.writeLock().unlock();
405 /** {@inheritDocs} */
407 public void removePostReplies(Sone sone) {
408 checkNotNull(sone, "sone must not be null");
410 lock.writeLock().lock();
412 for (PostReply postReply : sone.getReplies()) {
413 removePostReply(postReply);
416 lock.writeLock().unlock();
421 // ALBUMPROVDER METHODS
425 public Optional<Album> getAlbum(String albumId) {
426 lock.readLock().lock();
428 return fromNullable(allAlbums.get(albumId));
430 lock.readLock().unlock();
435 // ALBUMBUILDERFACTORY METHODS
439 public AlbumBuilder newAlbumBuilder() {
440 return new AlbumBuilderImpl();
444 // ALBUMSTORE METHODS
448 public void storeAlbum(Album album) {
449 lock.writeLock().lock();
451 allAlbums.put(album.getId(), album);
452 soneAlbums.put(album.getSone().getId(), album);
454 lock.writeLock().unlock();
459 public void removeAlbum(Album album) {
460 lock.writeLock().lock();
462 allAlbums.remove(album.getId());
463 soneAlbums.remove(album.getSone().getId(), album);
465 lock.writeLock().unlock();
470 // IMAGEPROVIDER METHODS
474 public Optional<Image> getImage(String imageId) {
475 lock.readLock().lock();
477 return fromNullable(allImages.get(imageId));
479 lock.readLock().unlock();
484 // IMAGEBUILDERFACTORY METHODS
488 public ImageBuilder newImageBuilder() {
489 return new ImageBuilderImpl();
493 // IMAGESTORE METHODS
497 public void storeImage(Image image) {
498 lock.writeLock().lock();
500 allImages.put(image.getId(), image);
501 soneImages.put(image.getSone().getId(), image);
503 lock.writeLock().unlock();
508 public void removeImage(Image image) {
509 lock.writeLock().lock();
511 allImages.remove(image.getId());
512 soneImages.remove(image.getSone().getId(), image);
514 lock.writeLock().unlock();
519 // PACKAGE-PRIVATE METHODS
523 * Returns whether the given post is known.
527 * @return {@code true} if the post is known, {@code false} otherwise
529 boolean isPostKnown(Post post) {
530 lock.readLock().lock();
532 return knownPosts.contains(post.getId());
534 lock.readLock().unlock();
539 * Sets whether the given post is known.
544 * {@code true} if the post is known, {@code false} otherwise
546 void setPostKnown(Post post, boolean known) {
547 lock.writeLock().lock();
550 knownPosts.add(post.getId());
552 knownPosts.remove(post.getId());
555 lock.writeLock().unlock();
560 * Returns whether the given post reply is known.
564 * @return {@code true} if the given post reply is known, {@code false}
567 boolean isPostReplyKnown(PostReply postReply) {
568 lock.readLock().lock();
570 return knownPostReplies.contains(postReply.getId());
572 lock.readLock().unlock();
577 * Sets whether the given post reply is known.
582 * {@code true} if the post reply is known, {@code false} otherwise
584 void setPostReplyKnown(PostReply postReply, boolean known) {
585 lock.writeLock().lock();
588 knownPostReplies.add(postReply.getId());
590 knownPostReplies.remove(postReply.getId());
593 lock.writeLock().unlock();
602 * Gets all posts for the given Sone, creating a new collection if there is
606 * The ID of the Sone to get the posts for
609 private Collection<Post> getPostsFrom(String soneId) {
610 lock.readLock().lock();
612 return sonePosts.get(soneId);
614 lock.readLock().unlock();
619 * Gets all posts that are directed the given Sone, creating a new collection
620 * if there is none yet.
623 * The ID of the Sone to get the posts for
626 private Collection<Post> getPostsTo(String recipientId) {
627 lock.readLock().lock();
629 return recipientPosts.get(recipientId);
631 lock.readLock().unlock();
635 /** Loads the known posts. */
636 private void loadKnownPosts() {
637 lock.writeLock().lock();
641 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
642 if (knownPostId == null) {
645 knownPosts.add(knownPostId);
648 lock.writeLock().unlock();
653 * Saves the known posts to the configuration.
655 * @throws DatabaseException
656 * if a configuration error occurs
658 private void saveKnownPosts() throws DatabaseException {
659 lock.readLock().lock();
662 for (String knownPostId : knownPosts) {
663 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
665 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
666 } catch (ConfigurationException ce1) {
667 throw new DatabaseException("Could not save database.", ce1);
669 lock.readLock().unlock();
674 * Returns all replies by the given Sone.
678 * @return The post replies of the Sone, sorted by time (newest first)
680 private Collection<PostReply> getRepliesFrom(String id) {
681 lock.readLock().lock();
683 return Collections.unmodifiableCollection(sonePostReplies.get(id));
685 lock.readLock().unlock();
689 /** Loads the known post replies. */
690 private void loadKnownPostReplies() {
691 lock.writeLock().lock();
693 int replyCounter = 0;
695 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
696 if (knownReplyId == null) {
699 knownPostReplies.add(knownReplyId);
702 lock.writeLock().unlock();
707 * Saves the known post replies to the configuration.
709 * @throws DatabaseException
710 * if a configuration error occurs
712 private void saveKnownPostReplies() throws DatabaseException {
713 lock.readLock().lock();
715 int replyCounter = 0;
716 for (String knownReplyId : knownPostReplies) {
717 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
719 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
720 } catch (ConfigurationException ce1) {
721 throw new DatabaseException("Could not save database.", ce1);
723 lock.readLock().unlock();