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.Preconditions.checkNotNull;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.HashMap;
26 import java.util.HashSet;
27 import java.util.List;
30 import java.util.SortedSet;
31 import java.util.TreeSet;
32 import java.util.UUID;
33 import java.util.concurrent.locks.ReadWriteLock;
34 import java.util.concurrent.locks.ReentrantReadWriteLock;
36 import net.pterodactylus.sone.data.Post;
37 import net.pterodactylus.sone.data.PostReply;
38 import net.pterodactylus.sone.data.Reply;
39 import net.pterodactylus.sone.data.Sone;
40 import net.pterodactylus.sone.data.impl.AbstractPostBuilder;
41 import net.pterodactylus.sone.data.impl.AbstractPostReplyBuilder;
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.util.concurrent.AbstractService;
53 import com.google.inject.Inject;
56 * Memory-based {@link PostDatabase} implementation.
58 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
60 public class MemoryDatabase extends AbstractService implements Database {
63 private final ReadWriteLock lock = new ReentrantReadWriteLock();
65 /** The Sone provider. */
66 private final SoneProvider soneProvider;
68 /** The configuration. */
69 private final Configuration configuration;
71 /** All posts by their ID. */
72 private final Map<String, Post> allPosts = new HashMap<String, Post>();
74 /** All posts by their Sones. */
75 private final Map<String, Collection<Post>> sonePosts = new HashMap<String, Collection<Post>>();
77 /** All posts by their recipient. */
78 private final Map<String, Collection<Post>> recipientPosts = new HashMap<String, Collection<Post>>();
80 /** Whether posts are known. */
81 private final Set<String> knownPosts = new HashSet<String>();
83 /** All post replies by their ID. */
84 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
86 /** Replies by post. */
87 private final Map<String, SortedSet<PostReply>> postReplies = new HashMap<String, SortedSet<PostReply>>();
89 /** Whether post replies are known. */
90 private final Set<String> knownPostReplies = new HashSet<String>();
93 * Creates a new memory database.
97 * @param configuration
98 * The configuration for loading and saving elements
101 public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
102 this.soneProvider = soneProvider;
103 this.configuration = configuration;
111 * Saves the database.
113 * @throws DatabaseException
114 * if an error occurs while saving
117 public void save() throws DatabaseException {
119 saveKnownPostReplies();
130 protected void doStart() {
132 loadKnownPostReplies();
140 protected void doStop() {
144 } catch (DatabaseException de1) {
150 // POSTPROVIDER METHODS
157 public Optional<Post> getPost(String postId) {
158 lock.readLock().lock();
160 return Optional.fromNullable(allPosts.get(postId));
162 lock.readLock().unlock();
170 public Collection<Post> getPosts(String soneId) {
171 return new HashSet<Post>(getPostsFrom(soneId));
178 public Collection<Post> getDirectedPosts(String recipientId) {
179 lock.readLock().lock();
181 Collection<Post> posts = recipientPosts.get(recipientId);
182 return (posts == null) ? Collections.<Post> emptySet() : new HashSet<Post>(posts);
184 lock.readLock().unlock();
189 // POSTBUILDERFACTORY METHODS
196 public PostBuilder newPostBuilder() {
197 return new MemoryPostBuilder(soneProvider);
208 public void storePost(Post post) {
209 checkNotNull(post, "post must not be null");
210 lock.writeLock().lock();
212 allPosts.put(post.getId(), post);
213 getPostsFrom(post.getSone().getId()).add(post);
214 if (post.getRecipientId().isPresent()) {
215 getPostsTo(post.getRecipientId().get()).add(post);
218 lock.writeLock().unlock();
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();
245 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
246 checkNotNull(sone, "sone must not be null");
247 /* verify that all posts are from the same Sone. */
248 for (Post post : posts) {
249 if (!sone.equals(post.getSone())) {
250 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
254 lock.writeLock().lock();
256 /* remove all posts by the Sone. */
257 getPostsFrom(sone.getId()).clear();
258 for (Post post : posts) {
259 allPosts.remove(post.getId());
260 if (post.getRecipientId().isPresent()) {
261 getPostsTo(post.getRecipientId().get()).remove(post);
266 getPostsFrom(sone.getId()).addAll(posts);
267 for (Post post : posts) {
268 allPosts.put(post.getId(), post);
269 if (post.getRecipientId().isPresent()) {
270 getPostsTo(post.getRecipientId().get()).add(post);
274 lock.writeLock().unlock();
282 public void removePosts(Sone sone) {
283 checkNotNull(sone, "sone must not be null");
284 lock.writeLock().lock();
286 /* remove all posts by the Sone. */
287 getPostsFrom(sone.getId()).clear();
288 for (Post post : sone.getPosts()) {
289 allPosts.remove(post.getId());
290 if (post.getRecipientId().isPresent()) {
291 getPostsTo(post.getRecipientId().get()).remove(post);
295 lock.writeLock().unlock();
300 // POSTREPLYPROVIDER METHODS
307 public Optional<PostReply> getPostReply(String id) {
308 lock.readLock().lock();
310 return Optional.fromNullable(allPostReplies.get(id));
312 lock.readLock().unlock();
320 public List<PostReply> getReplies(String postId) {
321 lock.readLock().lock();
323 if (!postReplies.containsKey(postId)) {
324 return Collections.emptyList();
326 return new ArrayList<PostReply>(postReplies.get(postId));
328 lock.readLock().unlock();
333 // POSTREPLYBUILDERFACTORY METHODS
340 public PostReplyBuilder newPostReplyBuilder() {
341 return new MemoryPostReplyBuilder();
345 // POSTREPLYSTORE METHODS
352 public void storePostReply(PostReply postReply) {
353 lock.writeLock().lock();
355 allPostReplies.put(postReply.getId(), postReply);
356 if (postReplies.containsKey(postReply.getPostId())) {
357 postReplies.get(postReply.getPostId()).add(postReply);
359 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
360 replies.add(postReply);
361 postReplies.put(postReply.getPostId(), replies);
364 lock.writeLock().unlock();
372 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
373 checkNotNull(sone, "sone must not be null");
374 /* verify that all posts are from the same Sone. */
375 for (PostReply postReply : postReplies) {
376 if (!sone.equals(postReply.getSone())) {
377 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
381 lock.writeLock().lock();
383 for (PostReply postReply : postReplies) {
384 allPostReplies.put(postReply.getId(), postReply);
385 if (this.postReplies.containsKey(postReply.getPostId())) {
386 this.postReplies.get(postReply.getPostId()).add(postReply);
388 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
389 replies.add(postReply);
390 this.postReplies.put(postReply.getPostId(), replies);
394 lock.writeLock().unlock();
402 public void removePostReply(PostReply postReply) {
403 lock.writeLock().lock();
405 allPostReplies.remove(postReply.getId());
406 if (postReplies.containsKey(postReply.getPostId())) {
407 postReplies.get(postReply.getPostId()).remove(postReply);
408 if (postReplies.get(postReply.getPostId()).isEmpty()) {
409 postReplies.remove(postReply.getPostId());
413 lock.writeLock().unlock();
421 public void removePostReplies(Sone sone) {
422 checkNotNull(sone, "sone must not be null");
424 lock.writeLock().lock();
426 for (PostReply postReply : sone.getReplies()) {
427 removePostReply(postReply);
430 lock.writeLock().unlock();
435 // PACKAGE-PRIVATE METHODS
439 * Returns whether the given post is known.
443 * @return {@code true} if the post is known, {@code false} otherwise
445 boolean isPostKnown(Post post) {
446 lock.readLock().lock();
448 return knownPosts.contains(post.getId());
450 lock.readLock().unlock();
455 * Sets whether the given post is known.
460 * {@code true} if the post is known, {@code false} otherwise
462 void setPostKnown(Post post, boolean known) {
463 lock.writeLock().lock();
466 knownPosts.add(post.getId());
468 knownPosts.remove(post.getId());
471 lock.writeLock().unlock();
476 * Returns whether the given post reply is known.
480 * @return {@code true} if the given post reply is known, {@code false}
483 boolean isPostReplyKnown(PostReply postReply) {
484 lock.readLock().lock();
486 return knownPostReplies.contains(postReply.getId());
488 lock.readLock().unlock();
493 * Sets whether the given post reply is known.
498 * {@code true} if the post reply is known, {@code false}
501 void setPostReplyKnown(PostReply postReply, boolean known) {
502 lock.writeLock().lock();
505 knownPostReplies.add(postReply.getId());
507 knownPostReplies.remove(postReply.getId());
510 lock.writeLock().unlock();
519 * Gets all posts for the given Sone, creating a new collection if there is
523 * The ID of the Sone to get the posts for
526 private Collection<Post> getPostsFrom(String soneId) {
527 Collection<Post> posts = null;
528 lock.readLock().lock();
530 posts = sonePosts.get(soneId);
532 lock.readLock().unlock();
538 posts = new HashSet<Post>();
539 lock.writeLock().lock();
541 sonePosts.put(soneId, posts);
543 lock.writeLock().unlock();
550 * Gets all posts that are directed the given Sone, creating a new
551 * collection if there is none yet.
554 * The ID of the Sone to get the posts for
557 private Collection<Post> getPostsTo(String recipientId) {
558 Collection<Post> posts = null;
559 lock.readLock().lock();
561 posts = recipientPosts.get(recipientId);
563 lock.readLock().unlock();
569 posts = new HashSet<Post>();
570 lock.writeLock().lock();
572 recipientPosts.put(recipientId, posts);
574 lock.writeLock().unlock();
581 * Loads the known posts.
583 private void loadKnownPosts() {
584 lock.writeLock().lock();
588 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
589 if (knownPostId == null) {
592 knownPosts.add(knownPostId);
595 lock.writeLock().unlock();
600 * Saves the known posts to the configuration.
602 * @throws DatabaseException
603 * if a configuration error occurs
605 private void saveKnownPosts() throws DatabaseException {
606 lock.readLock().lock();
609 for (String knownPostId : knownPosts) {
610 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
612 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
613 } catch (ConfigurationException ce1) {
614 throw new DatabaseException("Could not save database.", ce1);
616 lock.readLock().unlock();
621 * Loads the known post replies.
623 private void loadKnownPostReplies() {
624 lock.writeLock().lock();
626 int replyCounter = 0;
628 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
629 if (knownReplyId == null) {
632 knownPostReplies.add(knownReplyId);
635 lock.writeLock().unlock();
640 * Saves the known post replies to the configuration.
642 * @throws DatabaseException
643 * if a configuration error occurs
645 private void saveKnownPostReplies() throws DatabaseException {
646 lock.readLock().lock();
648 int replyCounter = 0;
649 for (String knownReplyId : knownPostReplies) {
650 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
652 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
653 } catch (ConfigurationException ce1) {
654 throw new DatabaseException("Could not save database.", ce1);
656 lock.readLock().unlock();
661 * {@link PostBuilder} implementation that creates a {@link MemoryPost}.
663 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
665 private class MemoryPostBuilder extends AbstractPostBuilder {
668 * Creates a new memory post builder.
670 * @param soneProvider
673 public MemoryPostBuilder(SoneProvider soneProvider) {
681 public Post build() throws IllegalStateException {
683 Post post = new MemoryPost(MemoryDatabase.this, soneProvider, randomId ? UUID.randomUUID().toString() : id, senderId, recipientId, currentTime ? System.currentTimeMillis() : time, text);
684 post.setKnown(isPostKnown(post));
691 * {@link PostReplyBuilder} implementation that creates
692 * {@link MemoryPostReply} objects.
694 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
696 private class MemoryPostReplyBuilder extends AbstractPostReplyBuilder {
702 public PostReply build() throws IllegalStateException {
705 PostReply postReply = new MemoryPostReply(MemoryDatabase.this, soneProvider, randomId ? UUID.randomUUID().toString() : id, senderId, currentTime ? System.currentTimeMillis() : time, text, postId);
706 postReply.setKnown(isPostReplyKnown(postReply));