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.Post;
39 import net.pterodactylus.sone.data.PostReply;
40 import net.pterodactylus.sone.data.Reply;
41 import net.pterodactylus.sone.data.Sone;
42 import net.pterodactylus.sone.database.Database;
43 import net.pterodactylus.sone.database.DatabaseException;
44 import net.pterodactylus.sone.database.PostBuilder;
45 import net.pterodactylus.sone.database.PostDatabase;
46 import net.pterodactylus.sone.database.PostReplyBuilder;
47 import net.pterodactylus.sone.database.SoneProvider;
48 import net.pterodactylus.util.config.Configuration;
49 import net.pterodactylus.util.config.ConfigurationException;
51 import com.google.common.base.Optional;
52 import com.google.common.collect.SortedSetMultimap;
53 import com.google.common.collect.TreeMultimap;
54 import com.google.common.util.concurrent.AbstractService;
55 import com.google.inject.Inject;
58 * Memory-based {@link PostDatabase} implementation.
60 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
62 public class MemoryDatabase extends AbstractService implements Database {
65 private final ReadWriteLock lock = new ReentrantReadWriteLock();
67 /** The Sone provider. */
68 private final SoneProvider soneProvider;
70 /** The configuration. */
71 private final Configuration configuration;
73 /** All posts by their ID. */
74 private final Map<String, Post> allPosts = new HashMap<String, Post>();
76 /** All posts by their Sones. */
77 private final Map<String, Collection<Post>> sonePosts = new HashMap<String, Collection<Post>>();
79 /** All posts by their recipient. */
80 private final Map<String, Collection<Post>> recipientPosts = new HashMap<String, Collection<Post>>();
82 /** Whether posts are known. */
83 private final Set<String> knownPosts = new HashSet<String>();
85 /** All post replies by their ID. */
86 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
88 /** Replies sorted by Sone. */
89 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
92 public int compare(String leftString, String rightString) {
93 return leftString.compareTo(rightString);
95 }, PostReply.TIME_COMPARATOR);
97 /** Replies by post. */
98 private final Map<String, SortedSet<PostReply>> postReplies = new HashMap<String, SortedSet<PostReply>>();
100 /** Whether post replies are known. */
101 private final Set<String> knownPostReplies = new HashSet<String>();
103 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
106 * Creates a new memory database.
108 * @param soneProvider
110 * @param configuration
111 * The configuration for loading and saving elements
114 public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
115 this.soneProvider = soneProvider;
116 this.configuration = configuration;
124 * Saves the database.
126 * @throws DatabaseException
127 * if an error occurs while saving
130 public void save() throws DatabaseException {
132 saveKnownPostReplies();
139 /** {@inheritDocs} */
141 protected void doStart() {
143 loadKnownPostReplies();
147 /** {@inheritDocs} */
149 protected void doStop() {
153 } catch (DatabaseException de1) {
159 // POSTPROVIDER METHODS
162 /** {@inheritDocs} */
164 public Optional<Post> getPost(String postId) {
165 lock.readLock().lock();
167 return fromNullable(allPosts.get(postId));
169 lock.readLock().unlock();
173 /** {@inheritDocs} */
175 public Collection<Post> getPosts(String soneId) {
176 return new HashSet<Post>(getPostsFrom(soneId));
179 /** {@inheritDocs} */
181 public Collection<Post> getDirectedPosts(String recipientId) {
182 lock.readLock().lock();
184 Collection<Post> posts = recipientPosts.get(recipientId);
185 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
187 lock.readLock().unlock();
192 // POSTBUILDERFACTORY METHODS
195 /** {@inheritDocs} */
197 public PostBuilder newPostBuilder() {
198 return new MemoryPostBuilder(this, soneProvider);
205 /** {@inheritDocs} */
207 public void storePost(Post post) {
208 checkNotNull(post, "post must not be null");
209 lock.writeLock().lock();
211 allPosts.put(post.getId(), post);
212 getPostsFrom(post.getSone().getId()).add(post);
213 if (post.getRecipientId().isPresent()) {
214 getPostsTo(post.getRecipientId().get()).add(post);
217 lock.writeLock().unlock();
221 /** {@inheritDocs} */
223 public void removePost(Post post) {
224 checkNotNull(post, "post must not be null");
225 lock.writeLock().lock();
227 allPosts.remove(post.getId());
228 getPostsFrom(post.getSone().getId()).remove(post);
229 if (post.getRecipientId().isPresent()) {
230 getPostsTo(post.getRecipientId().get()).remove(post);
232 post.getSone().removePost(post);
234 lock.writeLock().unlock();
238 /** {@inheritDocs} */
240 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
241 checkNotNull(sone, "sone must not be null");
242 /* verify that all posts are from the same Sone. */
243 for (Post post : posts) {
244 if (!sone.equals(post.getSone())) {
245 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
249 lock.writeLock().lock();
251 /* remove all posts by the Sone. */
252 getPostsFrom(sone.getId()).clear();
253 for (Post post : posts) {
254 allPosts.remove(post.getId());
255 if (post.getRecipientId().isPresent()) {
256 getPostsTo(post.getRecipientId().get()).remove(post);
261 getPostsFrom(sone.getId()).addAll(posts);
262 for (Post post : posts) {
263 allPosts.put(post.getId(), post);
264 if (post.getRecipientId().isPresent()) {
265 getPostsTo(post.getRecipientId().get()).add(post);
269 lock.writeLock().unlock();
273 /** {@inheritDocs} */
275 public void removePosts(Sone sone) {
276 checkNotNull(sone, "sone must not be null");
277 lock.writeLock().lock();
279 /* remove all posts by the Sone. */
280 getPostsFrom(sone.getId()).clear();
281 for (Post post : sone.getPosts()) {
282 allPosts.remove(post.getId());
283 if (post.getRecipientId().isPresent()) {
284 getPostsTo(post.getRecipientId().get()).remove(post);
288 lock.writeLock().unlock();
293 // POSTREPLYPROVIDER METHODS
296 /** {@inheritDocs} */
298 public Optional<PostReply> getPostReply(String id) {
299 lock.readLock().lock();
301 return fromNullable(allPostReplies.get(id));
303 lock.readLock().unlock();
307 /** {@inheritDocs} */
309 public List<PostReply> getReplies(String postId) {
310 lock.readLock().lock();
312 if (!postReplies.containsKey(postId)) {
313 return Collections.emptyList();
315 return new ArrayList<PostReply>(postReplies.get(postId));
317 lock.readLock().unlock();
322 // POSTREPLYBUILDERFACTORY METHODS
325 /** {@inheritDocs} */
327 public PostReplyBuilder newPostReplyBuilder() {
328 return new MemoryPostReplyBuilder(this, soneProvider);
332 // POSTREPLYSTORE METHODS
335 /** {@inheritDocs} */
337 public void storePostReply(PostReply postReply) {
338 lock.writeLock().lock();
340 allPostReplies.put(postReply.getId(), postReply);
341 if (postReplies.containsKey(postReply.getPostId())) {
342 postReplies.get(postReply.getPostId()).add(postReply);
344 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
345 replies.add(postReply);
346 postReplies.put(postReply.getPostId(), replies);
349 lock.writeLock().unlock();
353 /** {@inheritDocs} */
355 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
356 checkNotNull(sone, "sone must not be null");
357 /* verify that all posts are from the same Sone. */
358 for (PostReply postReply : postReplies) {
359 if (!sone.equals(postReply.getSone())) {
360 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
364 lock.writeLock().lock();
366 /* remove all post replies of the Sone. */
367 for (PostReply postReply : getRepliesFrom(sone.getId())) {
368 removePostReply(postReply);
370 for (PostReply postReply : postReplies) {
371 allPostReplies.put(postReply.getId(), postReply);
372 sonePostReplies.put(postReply.getSone().getId(), postReply);
373 if (this.postReplies.containsKey(postReply.getPostId())) {
374 this.postReplies.get(postReply.getPostId()).add(postReply);
376 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
377 replies.add(postReply);
378 this.postReplies.put(postReply.getPostId(), replies);
382 lock.writeLock().unlock();
386 /** {@inheritDocs} */
388 public void removePostReply(PostReply postReply) {
389 lock.writeLock().lock();
391 allPostReplies.remove(postReply.getId());
392 if (postReplies.containsKey(postReply.getPostId())) {
393 postReplies.get(postReply.getPostId()).remove(postReply);
394 if (postReplies.get(postReply.getPostId()).isEmpty()) {
395 postReplies.remove(postReply.getPostId());
399 lock.writeLock().unlock();
403 /** {@inheritDocs} */
405 public void removePostReplies(Sone sone) {
406 checkNotNull(sone, "sone must not be null");
408 lock.writeLock().lock();
410 for (PostReply postReply : sone.getReplies()) {
411 removePostReply(postReply);
414 lock.writeLock().unlock();
419 // ALBUMPROVDER METHODS
423 public Optional<Album> getAlbum(String albumId) {
424 lock.readLock().lock();
426 return fromNullable(allAlbums.get(albumId));
428 lock.readLock().unlock();
433 // ALBUMSTORE METHODS
437 public void storeAlbum(Album album) {
438 lock.writeLock().lock();
440 allAlbums.put(album.getId(), album);
442 lock.writeLock().unlock();
447 public void removeAlbum(Album album) {
448 lock.writeLock().lock();
450 allAlbums.remove(album.getId());
452 lock.writeLock().unlock();
457 // PACKAGE-PRIVATE METHODS
461 * Returns whether the given post is known.
465 * @return {@code true} if the post is known, {@code false} otherwise
467 boolean isPostKnown(Post post) {
468 lock.readLock().lock();
470 return knownPosts.contains(post.getId());
472 lock.readLock().unlock();
477 * Sets whether the given post is known.
482 * {@code true} if the post is known, {@code false} otherwise
484 void setPostKnown(Post post, boolean known) {
485 lock.writeLock().lock();
488 knownPosts.add(post.getId());
490 knownPosts.remove(post.getId());
493 lock.writeLock().unlock();
498 * Returns whether the given post reply is known.
502 * @return {@code true} if the given post reply is known, {@code false}
505 boolean isPostReplyKnown(PostReply postReply) {
506 lock.readLock().lock();
508 return knownPostReplies.contains(postReply.getId());
510 lock.readLock().unlock();
515 * Sets whether the given post reply is known.
520 * {@code true} if the post reply is known, {@code false} otherwise
522 void setPostReplyKnown(PostReply postReply, boolean known) {
523 lock.writeLock().lock();
526 knownPostReplies.add(postReply.getId());
528 knownPostReplies.remove(postReply.getId());
531 lock.writeLock().unlock();
540 * Gets all posts for the given Sone, creating a new collection if there is
544 * The ID of the Sone to get the posts for
547 private Collection<Post> getPostsFrom(String soneId) {
548 Collection<Post> posts = null;
549 lock.readLock().lock();
551 posts = sonePosts.get(soneId);
553 lock.readLock().unlock();
559 posts = new HashSet<Post>();
560 lock.writeLock().lock();
562 sonePosts.put(soneId, posts);
564 lock.writeLock().unlock();
571 * Gets all posts that are directed the given Sone, creating a new collection
572 * if there is none yet.
575 * The ID of the Sone to get the posts for
578 private Collection<Post> getPostsTo(String recipientId) {
579 Collection<Post> posts = null;
580 lock.readLock().lock();
582 posts = recipientPosts.get(recipientId);
584 lock.readLock().unlock();
590 posts = new HashSet<Post>();
591 lock.writeLock().lock();
593 recipientPosts.put(recipientId, posts);
595 lock.writeLock().unlock();
601 /** Loads the known posts. */
602 private void loadKnownPosts() {
603 lock.writeLock().lock();
607 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
608 if (knownPostId == null) {
611 knownPosts.add(knownPostId);
614 lock.writeLock().unlock();
619 * Saves the known posts to the configuration.
621 * @throws DatabaseException
622 * if a configuration error occurs
624 private void saveKnownPosts() throws DatabaseException {
625 lock.readLock().lock();
628 for (String knownPostId : knownPosts) {
629 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
631 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
632 } catch (ConfigurationException ce1) {
633 throw new DatabaseException("Could not save database.", ce1);
635 lock.readLock().unlock();
640 * Returns all replies by the given Sone.
644 * @return The post replies of the Sone, sorted by time (newest first)
646 private Collection<PostReply> getRepliesFrom(String id) {
647 lock.readLock().lock();
649 if (sonePostReplies.containsKey(id)) {
650 return Collections.unmodifiableCollection(sonePostReplies.get(id));
652 return Collections.emptySet();
654 lock.readLock().unlock();
658 /** Loads the known post replies. */
659 private void loadKnownPostReplies() {
660 lock.writeLock().lock();
662 int replyCounter = 0;
664 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
665 if (knownReplyId == null) {
668 knownPostReplies.add(knownReplyId);
671 lock.writeLock().unlock();
676 * Saves the known post replies to the configuration.
678 * @throws DatabaseException
679 * if a configuration error occurs
681 private void saveKnownPostReplies() throws DatabaseException {
682 lock.readLock().lock();
684 int replyCounter = 0;
685 for (String knownReplyId : knownPostReplies) {
686 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
688 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
689 } catch (ConfigurationException ce1) {
690 throw new DatabaseException("Could not save database.", ce1);
692 lock.readLock().unlock();