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;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.Comparator;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.List;
32 import java.util.SortedSet;
33 import java.util.TreeSet;
34 import java.util.concurrent.locks.ReadWriteLock;
35 import java.util.concurrent.locks.ReentrantReadWriteLock;
37 import net.pterodactylus.sone.data.Album;
38 import net.pterodactylus.sone.data.Image;
39 import net.pterodactylus.sone.data.Post;
40 import net.pterodactylus.sone.data.PostReply;
41 import net.pterodactylus.sone.data.Reply;
42 import net.pterodactylus.sone.data.Sone;
43 import net.pterodactylus.sone.database.Database;
44 import net.pterodactylus.sone.database.DatabaseException;
45 import net.pterodactylus.sone.database.PostBuilder;
46 import net.pterodactylus.sone.database.PostDatabase;
47 import net.pterodactylus.sone.database.PostReplyBuilder;
48 import net.pterodactylus.sone.database.SoneProvider;
49 import net.pterodactylus.util.config.Configuration;
50 import net.pterodactylus.util.config.ConfigurationException;
52 import com.google.common.base.Optional;
53 import com.google.common.collect.SortedSetMultimap;
54 import com.google.common.collect.TreeMultimap;
55 import com.google.common.util.concurrent.AbstractService;
56 import com.google.inject.Inject;
59 * Memory-based {@link PostDatabase} implementation.
61 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
63 public class MemoryDatabase extends AbstractService implements Database {
66 private final ReadWriteLock lock = new ReentrantReadWriteLock();
68 /** The Sone provider. */
69 private final SoneProvider soneProvider;
71 /** The configuration. */
72 private final Configuration configuration;
74 /** All posts by their ID. */
75 private final Map<String, Post> allPosts = new HashMap<String, Post>();
77 /** All posts by their Sones. */
78 private final Map<String, Collection<Post>> sonePosts = new HashMap<String, Collection<Post>>();
80 /** All posts by their recipient. */
81 private final Map<String, Collection<Post>> recipientPosts = new HashMap<String, Collection<Post>>();
83 /** Whether posts are known. */
84 private final Set<String> knownPosts = new HashSet<String>();
86 /** All post replies by their ID. */
87 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
89 /** Replies sorted by Sone. */
90 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
93 public int compare(String leftString, String rightString) {
94 return leftString.compareTo(rightString);
96 }, PostReply.TIME_COMPARATOR);
98 /** Replies by post. */
99 private final Map<String, SortedSet<PostReply>> postReplies = new HashMap<String, SortedSet<PostReply>>();
101 /** Whether post replies are known. */
102 private final Set<String> knownPostReplies = new HashSet<String>();
104 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
106 private final Map<String, Image> allImages = new HashMap<String, Image>();
109 * Creates a new memory database.
111 * @param soneProvider
113 * @param configuration
114 * The configuration for loading and saving elements
117 public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
118 this.soneProvider = soneProvider;
119 this.configuration = configuration;
127 * Saves the database.
129 * @throws DatabaseException
130 * if an error occurs while saving
133 public void save() throws DatabaseException {
135 saveKnownPostReplies();
142 /** {@inheritDocs} */
144 protected void doStart() {
146 loadKnownPostReplies();
150 /** {@inheritDocs} */
152 protected void doStop() {
156 } catch (DatabaseException de1) {
162 // POSTPROVIDER METHODS
165 /** {@inheritDocs} */
167 public Optional<Post> getPost(String postId) {
168 lock.readLock().lock();
170 return fromNullable(allPosts.get(postId));
172 lock.readLock().unlock();
176 /** {@inheritDocs} */
178 public Collection<Post> getPosts(String soneId) {
179 return new HashSet<Post>(getPostsFrom(soneId));
182 /** {@inheritDocs} */
184 public Collection<Post> getDirectedPosts(String recipientId) {
185 lock.readLock().lock();
187 Collection<Post> posts = recipientPosts.get(recipientId);
188 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
190 lock.readLock().unlock();
195 // POSTBUILDERFACTORY METHODS
198 /** {@inheritDocs} */
200 public PostBuilder newPostBuilder() {
201 return new MemoryPostBuilder(this, soneProvider);
208 /** {@inheritDocs} */
210 public void storePost(Post post) {
211 checkNotNull(post, "post must not be null");
212 lock.writeLock().lock();
214 allPosts.put(post.getId(), post);
215 getPostsFrom(post.getSone().getId()).add(post);
216 if (post.getRecipientId().isPresent()) {
217 getPostsTo(post.getRecipientId().get()).add(post);
220 lock.writeLock().unlock();
224 /** {@inheritDocs} */
226 public void removePost(Post post) {
227 checkNotNull(post, "post must not be null");
228 lock.writeLock().lock();
230 allPosts.remove(post.getId());
231 getPostsFrom(post.getSone().getId()).remove(post);
232 if (post.getRecipientId().isPresent()) {
233 getPostsTo(post.getRecipientId().get()).remove(post);
235 post.getSone().removePost(post);
237 lock.writeLock().unlock();
241 /** {@inheritDocs} */
243 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
244 checkNotNull(sone, "sone must not be null");
245 /* verify that all posts are from the same Sone. */
246 for (Post post : posts) {
247 if (!sone.equals(post.getSone())) {
248 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
252 lock.writeLock().lock();
254 /* remove all posts by the Sone. */
255 getPostsFrom(sone.getId()).clear();
256 for (Post post : posts) {
257 allPosts.remove(post.getId());
258 if (post.getRecipientId().isPresent()) {
259 getPostsTo(post.getRecipientId().get()).remove(post);
264 getPostsFrom(sone.getId()).addAll(posts);
265 for (Post post : posts) {
266 allPosts.put(post.getId(), post);
267 if (post.getRecipientId().isPresent()) {
268 getPostsTo(post.getRecipientId().get()).add(post);
272 lock.writeLock().unlock();
276 /** {@inheritDocs} */
278 public void removePosts(Sone sone) {
279 checkNotNull(sone, "sone must not be null");
280 lock.writeLock().lock();
282 /* remove all posts by the Sone. */
283 getPostsFrom(sone.getId()).clear();
284 for (Post post : sone.getPosts()) {
285 allPosts.remove(post.getId());
286 if (post.getRecipientId().isPresent()) {
287 getPostsTo(post.getRecipientId().get()).remove(post);
291 lock.writeLock().unlock();
296 // POSTREPLYPROVIDER METHODS
299 /** {@inheritDocs} */
301 public Optional<PostReply> getPostReply(String id) {
302 lock.readLock().lock();
304 return fromNullable(allPostReplies.get(id));
306 lock.readLock().unlock();
310 /** {@inheritDocs} */
312 public List<PostReply> getReplies(String postId) {
313 lock.readLock().lock();
315 if (!postReplies.containsKey(postId)) {
316 return Collections.emptyList();
318 return new ArrayList<PostReply>(postReplies.get(postId));
320 lock.readLock().unlock();
325 // POSTREPLYBUILDERFACTORY METHODS
328 /** {@inheritDocs} */
330 public PostReplyBuilder newPostReplyBuilder() {
331 return new MemoryPostReplyBuilder(this, soneProvider);
335 // POSTREPLYSTORE METHODS
338 /** {@inheritDocs} */
340 public void storePostReply(PostReply postReply) {
341 lock.writeLock().lock();
343 allPostReplies.put(postReply.getId(), postReply);
344 if (postReplies.containsKey(postReply.getPostId())) {
345 postReplies.get(postReply.getPostId()).add(postReply);
347 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
348 replies.add(postReply);
349 postReplies.put(postReply.getPostId(), replies);
352 lock.writeLock().unlock();
356 /** {@inheritDocs} */
358 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
359 checkNotNull(sone, "sone must not be null");
360 /* verify that all posts are from the same Sone. */
361 for (PostReply postReply : postReplies) {
362 if (!sone.equals(postReply.getSone())) {
363 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
367 lock.writeLock().lock();
369 /* remove all post replies of the Sone. */
370 for (PostReply postReply : getRepliesFrom(sone.getId())) {
371 removePostReply(postReply);
373 for (PostReply postReply : postReplies) {
374 allPostReplies.put(postReply.getId(), postReply);
375 sonePostReplies.put(postReply.getSone().getId(), postReply);
376 if (this.postReplies.containsKey(postReply.getPostId())) {
377 this.postReplies.get(postReply.getPostId()).add(postReply);
379 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
380 replies.add(postReply);
381 this.postReplies.put(postReply.getPostId(), replies);
385 lock.writeLock().unlock();
389 /** {@inheritDocs} */
391 public void removePostReply(PostReply postReply) {
392 lock.writeLock().lock();
394 allPostReplies.remove(postReply.getId());
395 if (postReplies.containsKey(postReply.getPostId())) {
396 postReplies.get(postReply.getPostId()).remove(postReply);
397 if (postReplies.get(postReply.getPostId()).isEmpty()) {
398 postReplies.remove(postReply.getPostId());
402 lock.writeLock().unlock();
406 /** {@inheritDocs} */
408 public void removePostReplies(Sone sone) {
409 checkNotNull(sone, "sone must not be null");
411 lock.writeLock().lock();
413 for (PostReply postReply : sone.getReplies()) {
414 removePostReply(postReply);
417 lock.writeLock().unlock();
422 // ALBUMPROVDER METHODS
426 public Optional<Album> getAlbum(String albumId) {
427 lock.readLock().lock();
429 return fromNullable(allAlbums.get(albumId));
431 lock.readLock().unlock();
436 // ALBUMSTORE METHODS
440 public void storeAlbum(Album album) {
441 lock.writeLock().lock();
443 allAlbums.put(album.getId(), album);
445 lock.writeLock().unlock();
450 public void removeAlbum(Album album) {
451 lock.writeLock().lock();
453 allAlbums.remove(album.getId());
455 lock.writeLock().unlock();
460 // IMAGEPROVIDER METHODS
464 public Optional<Image> getImage(String imageId) {
465 lock.readLock().lock();
467 return fromNullable(allImages.get(imageId));
469 lock.readLock().unlock();
474 // IMAGESTORE METHODS
478 public void storeImage(Image image) {
479 lock.writeLock().lock();
481 allImages.put(image.getId(), image);
483 lock.writeLock().unlock();
488 public void removeImage(Image image) {
489 lock.writeLock().lock();
491 allImages.remove(image.getId());
493 lock.writeLock().unlock();
498 // PACKAGE-PRIVATE METHODS
502 * Returns whether the given post is known.
506 * @return {@code true} if the post is known, {@code false} otherwise
508 boolean isPostKnown(Post post) {
509 lock.readLock().lock();
511 return knownPosts.contains(post.getId());
513 lock.readLock().unlock();
518 * Sets whether the given post is known.
523 * {@code true} if the post is known, {@code false} otherwise
525 void setPostKnown(Post post, boolean known) {
526 lock.writeLock().lock();
529 knownPosts.add(post.getId());
531 knownPosts.remove(post.getId());
534 lock.writeLock().unlock();
539 * Returns whether the given post reply is known.
543 * @return {@code true} if the given post reply is known, {@code false}
546 boolean isPostReplyKnown(PostReply postReply) {
547 lock.readLock().lock();
549 return knownPostReplies.contains(postReply.getId());
551 lock.readLock().unlock();
556 * Sets whether the given post reply is known.
561 * {@code true} if the post reply is known, {@code false} otherwise
563 void setPostReplyKnown(PostReply postReply, boolean known) {
564 lock.writeLock().lock();
567 knownPostReplies.add(postReply.getId());
569 knownPostReplies.remove(postReply.getId());
572 lock.writeLock().unlock();
581 * Gets all posts for the given Sone, creating a new collection if there is
585 * The ID of the Sone to get the posts for
588 private Collection<Post> getPostsFrom(String soneId) {
589 Collection<Post> posts = null;
590 lock.readLock().lock();
592 posts = sonePosts.get(soneId);
594 lock.readLock().unlock();
600 posts = new HashSet<Post>();
601 lock.writeLock().lock();
603 sonePosts.put(soneId, posts);
605 lock.writeLock().unlock();
612 * Gets all posts that are directed the given Sone, creating a new collection
613 * if there is none yet.
616 * The ID of the Sone to get the posts for
619 private Collection<Post> getPostsTo(String recipientId) {
620 Collection<Post> posts = null;
621 lock.readLock().lock();
623 posts = recipientPosts.get(recipientId);
625 lock.readLock().unlock();
631 posts = new HashSet<Post>();
632 lock.writeLock().lock();
634 recipientPosts.put(recipientId, posts);
636 lock.writeLock().unlock();
642 /** Loads the known posts. */
643 private void loadKnownPosts() {
644 lock.writeLock().lock();
648 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
649 if (knownPostId == null) {
652 knownPosts.add(knownPostId);
655 lock.writeLock().unlock();
660 * Saves the known posts to the configuration.
662 * @throws DatabaseException
663 * if a configuration error occurs
665 private void saveKnownPosts() throws DatabaseException {
666 lock.readLock().lock();
669 for (String knownPostId : knownPosts) {
670 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
672 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
673 } catch (ConfigurationException ce1) {
674 throw new DatabaseException("Could not save database.", ce1);
676 lock.readLock().unlock();
681 * Returns all replies by the given Sone.
685 * @return The post replies of the Sone, sorted by time (newest first)
687 private Collection<PostReply> getRepliesFrom(String id) {
688 lock.readLock().lock();
690 if (sonePostReplies.containsKey(id)) {
691 return Collections.unmodifiableCollection(sonePostReplies.get(id));
693 return Collections.emptySet();
695 lock.readLock().unlock();
699 /** Loads the known post replies. */
700 private void loadKnownPostReplies() {
701 lock.writeLock().lock();
703 int replyCounter = 0;
705 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
706 if (knownReplyId == null) {
709 knownPostReplies.add(knownReplyId);
712 lock.writeLock().unlock();
717 * Saves the known post replies to the configuration.
719 * @throws DatabaseException
720 * if a configuration error occurs
722 private void saveKnownPostReplies() throws DatabaseException {
723 lock.readLock().lock();
725 int replyCounter = 0;
726 for (String knownReplyId : knownPostReplies) {
727 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
729 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
730 } catch (ConfigurationException ce1) {
731 throw new DatabaseException("Could not save database.", ce1);
733 lock.readLock().unlock();