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.data.impl.AlbumBuilderImpl;
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.PostBuilder;
47 import net.pterodactylus.sone.database.PostDatabase;
48 import net.pterodactylus.sone.database.PostReplyBuilder;
49 import net.pterodactylus.sone.database.SoneProvider;
50 import net.pterodactylus.util.config.Configuration;
51 import net.pterodactylus.util.config.ConfigurationException;
53 import com.google.common.base.Optional;
54 import com.google.common.collect.SortedSetMultimap;
55 import com.google.common.collect.TreeMultimap;
56 import com.google.common.util.concurrent.AbstractService;
57 import com.google.inject.Inject;
60 * Memory-based {@link PostDatabase} implementation.
62 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
64 public class MemoryDatabase extends AbstractService implements Database {
67 private final ReadWriteLock lock = new ReentrantReadWriteLock();
69 /** The Sone provider. */
70 private final SoneProvider soneProvider;
72 /** The configuration. */
73 private final Configuration configuration;
75 /** All posts by their ID. */
76 private final Map<String, Post> allPosts = new HashMap<String, Post>();
78 /** All posts by their Sones. */
79 private final Map<String, Collection<Post>> sonePosts = new HashMap<String, Collection<Post>>();
81 /** All posts by their recipient. */
82 private final Map<String, Collection<Post>> recipientPosts = new HashMap<String, Collection<Post>>();
84 /** Whether posts are known. */
85 private final Set<String> knownPosts = new HashSet<String>();
87 /** All post replies by their ID. */
88 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
90 /** Replies sorted by Sone. */
91 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
94 public int compare(String leftString, String rightString) {
95 return leftString.compareTo(rightString);
97 }, PostReply.TIME_COMPARATOR);
99 /** Replies by post. */
100 private final Map<String, SortedSet<PostReply>> postReplies = new HashMap<String, SortedSet<PostReply>>();
102 /** Whether post replies are known. */
103 private final Set<String> knownPostReplies = new HashSet<String>();
105 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
108 * Creates a new memory database.
110 * @param soneProvider
112 * @param configuration
113 * The configuration for loading and saving elements
116 public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
117 this.soneProvider = soneProvider;
118 this.configuration = configuration;
126 * Saves the database.
128 * @throws DatabaseException
129 * if an error occurs while saving
132 public void save() throws DatabaseException {
134 saveKnownPostReplies();
141 /** {@inheritDocs} */
143 protected void doStart() {
145 loadKnownPostReplies();
149 /** {@inheritDocs} */
151 protected void doStop() {
155 } catch (DatabaseException de1) {
161 // POSTPROVIDER METHODS
164 /** {@inheritDocs} */
166 public Optional<Post> getPost(String postId) {
167 lock.readLock().lock();
169 return fromNullable(allPosts.get(postId));
171 lock.readLock().unlock();
175 /** {@inheritDocs} */
177 public Collection<Post> getPosts(String soneId) {
178 return new HashSet<Post>(getPostsFrom(soneId));
181 /** {@inheritDocs} */
183 public Collection<Post> getDirectedPosts(String recipientId) {
184 lock.readLock().lock();
186 Collection<Post> posts = recipientPosts.get(recipientId);
187 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
189 lock.readLock().unlock();
194 // POSTBUILDERFACTORY METHODS
197 /** {@inheritDocs} */
199 public PostBuilder newPostBuilder() {
200 return new MemoryPostBuilder(this, soneProvider);
207 /** {@inheritDocs} */
209 public void storePost(Post post) {
210 checkNotNull(post, "post must not be null");
211 lock.writeLock().lock();
213 allPosts.put(post.getId(), post);
214 getPostsFrom(post.getSone().getId()).add(post);
215 if (post.getRecipientId().isPresent()) {
216 getPostsTo(post.getRecipientId().get()).add(post);
219 lock.writeLock().unlock();
223 /** {@inheritDocs} */
225 public void removePost(Post post) {
226 checkNotNull(post, "post must not be null");
227 lock.writeLock().lock();
229 allPosts.remove(post.getId());
230 getPostsFrom(post.getSone().getId()).remove(post);
231 if (post.getRecipientId().isPresent()) {
232 getPostsTo(post.getRecipientId().get()).remove(post);
234 post.getSone().removePost(post);
236 lock.writeLock().unlock();
240 /** {@inheritDocs} */
242 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
243 checkNotNull(sone, "sone must not be null");
244 /* verify that all posts are from the same Sone. */
245 for (Post post : posts) {
246 if (!sone.equals(post.getSone())) {
247 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
251 lock.writeLock().lock();
253 /* remove all posts by the Sone. */
254 getPostsFrom(sone.getId()).clear();
255 for (Post post : posts) {
256 allPosts.remove(post.getId());
257 if (post.getRecipientId().isPresent()) {
258 getPostsTo(post.getRecipientId().get()).remove(post);
263 getPostsFrom(sone.getId()).addAll(posts);
264 for (Post post : posts) {
265 allPosts.put(post.getId(), post);
266 if (post.getRecipientId().isPresent()) {
267 getPostsTo(post.getRecipientId().get()).add(post);
271 lock.writeLock().unlock();
275 /** {@inheritDocs} */
277 public void removePosts(Sone sone) {
278 checkNotNull(sone, "sone must not be null");
279 lock.writeLock().lock();
281 /* remove all posts by the Sone. */
282 getPostsFrom(sone.getId()).clear();
283 for (Post post : sone.getPosts()) {
284 allPosts.remove(post.getId());
285 if (post.getRecipientId().isPresent()) {
286 getPostsTo(post.getRecipientId().get()).remove(post);
290 lock.writeLock().unlock();
295 // POSTREPLYPROVIDER METHODS
298 /** {@inheritDocs} */
300 public Optional<PostReply> getPostReply(String id) {
301 lock.readLock().lock();
303 return fromNullable(allPostReplies.get(id));
305 lock.readLock().unlock();
309 /** {@inheritDocs} */
311 public List<PostReply> getReplies(String postId) {
312 lock.readLock().lock();
314 if (!postReplies.containsKey(postId)) {
315 return Collections.emptyList();
317 return new ArrayList<PostReply>(postReplies.get(postId));
319 lock.readLock().unlock();
324 // POSTREPLYBUILDERFACTORY METHODS
327 /** {@inheritDocs} */
329 public PostReplyBuilder newPostReplyBuilder() {
330 return new MemoryPostReplyBuilder(this, soneProvider);
334 // POSTREPLYSTORE METHODS
337 /** {@inheritDocs} */
339 public void storePostReply(PostReply postReply) {
340 lock.writeLock().lock();
342 allPostReplies.put(postReply.getId(), postReply);
343 if (postReplies.containsKey(postReply.getPostId())) {
344 postReplies.get(postReply.getPostId()).add(postReply);
346 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
347 replies.add(postReply);
348 postReplies.put(postReply.getPostId(), replies);
351 lock.writeLock().unlock();
355 /** {@inheritDocs} */
357 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
358 checkNotNull(sone, "sone must not be null");
359 /* verify that all posts are from the same Sone. */
360 for (PostReply postReply : postReplies) {
361 if (!sone.equals(postReply.getSone())) {
362 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
366 lock.writeLock().lock();
368 /* remove all post replies of the Sone. */
369 for (PostReply postReply : getRepliesFrom(sone.getId())) {
370 removePostReply(postReply);
372 for (PostReply postReply : postReplies) {
373 allPostReplies.put(postReply.getId(), postReply);
374 sonePostReplies.put(postReply.getSone().getId(), postReply);
375 if (this.postReplies.containsKey(postReply.getPostId())) {
376 this.postReplies.get(postReply.getPostId()).add(postReply);
378 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
379 replies.add(postReply);
380 this.postReplies.put(postReply.getPostId(), replies);
384 lock.writeLock().unlock();
388 /** {@inheritDocs} */
390 public void removePostReply(PostReply postReply) {
391 lock.writeLock().lock();
393 allPostReplies.remove(postReply.getId());
394 if (postReplies.containsKey(postReply.getPostId())) {
395 postReplies.get(postReply.getPostId()).remove(postReply);
396 if (postReplies.get(postReply.getPostId()).isEmpty()) {
397 postReplies.remove(postReply.getPostId());
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);
453 lock.writeLock().unlock();
458 public void removeAlbum(Album album) {
459 lock.writeLock().lock();
461 allAlbums.remove(album.getId());
463 lock.writeLock().unlock();
468 // PACKAGE-PRIVATE METHODS
472 * Returns whether the given post is known.
476 * @return {@code true} if the post is known, {@code false} otherwise
478 boolean isPostKnown(Post post) {
479 lock.readLock().lock();
481 return knownPosts.contains(post.getId());
483 lock.readLock().unlock();
488 * Sets whether the given post is known.
493 * {@code true} if the post is known, {@code false} otherwise
495 void setPostKnown(Post post, boolean known) {
496 lock.writeLock().lock();
499 knownPosts.add(post.getId());
501 knownPosts.remove(post.getId());
504 lock.writeLock().unlock();
509 * Returns whether the given post reply is known.
513 * @return {@code true} if the given post reply is known, {@code false}
516 boolean isPostReplyKnown(PostReply postReply) {
517 lock.readLock().lock();
519 return knownPostReplies.contains(postReply.getId());
521 lock.readLock().unlock();
526 * Sets whether the given post reply is known.
531 * {@code true} if the post reply is known, {@code false} otherwise
533 void setPostReplyKnown(PostReply postReply, boolean known) {
534 lock.writeLock().lock();
537 knownPostReplies.add(postReply.getId());
539 knownPostReplies.remove(postReply.getId());
542 lock.writeLock().unlock();
551 * Gets all posts for the given Sone, creating a new collection if there is
555 * The ID of the Sone to get the posts for
558 private Collection<Post> getPostsFrom(String soneId) {
559 Collection<Post> posts = null;
560 lock.readLock().lock();
562 posts = sonePosts.get(soneId);
564 lock.readLock().unlock();
570 posts = new HashSet<Post>();
571 lock.writeLock().lock();
573 sonePosts.put(soneId, posts);
575 lock.writeLock().unlock();
582 * Gets all posts that are directed the given Sone, creating a new collection
583 * if there is none yet.
586 * The ID of the Sone to get the posts for
589 private Collection<Post> getPostsTo(String recipientId) {
590 Collection<Post> posts = null;
591 lock.readLock().lock();
593 posts = recipientPosts.get(recipientId);
595 lock.readLock().unlock();
601 posts = new HashSet<Post>();
602 lock.writeLock().lock();
604 recipientPosts.put(recipientId, posts);
606 lock.writeLock().unlock();
612 /** Loads the known posts. */
613 private void loadKnownPosts() {
614 lock.writeLock().lock();
618 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
619 if (knownPostId == null) {
622 knownPosts.add(knownPostId);
625 lock.writeLock().unlock();
630 * Saves the known posts to the configuration.
632 * @throws DatabaseException
633 * if a configuration error occurs
635 private void saveKnownPosts() throws DatabaseException {
636 lock.readLock().lock();
639 for (String knownPostId : knownPosts) {
640 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
642 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
643 } catch (ConfigurationException ce1) {
644 throw new DatabaseException("Could not save database.", ce1);
646 lock.readLock().unlock();
651 * Returns all replies by the given Sone.
655 * @return The post replies of the Sone, sorted by time (newest first)
657 private Collection<PostReply> getRepliesFrom(String id) {
658 lock.readLock().lock();
660 if (sonePostReplies.containsKey(id)) {
661 return Collections.unmodifiableCollection(sonePostReplies.get(id));
663 return Collections.emptySet();
665 lock.readLock().unlock();
669 /** Loads the known post replies. */
670 private void loadKnownPostReplies() {
671 lock.writeLock().lock();
673 int replyCounter = 0;
675 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
676 if (knownReplyId == null) {
679 knownPostReplies.add(knownReplyId);
682 lock.writeLock().unlock();
687 * Saves the known post replies to the configuration.
689 * @throws DatabaseException
690 * if a configuration error occurs
692 private void saveKnownPostReplies() throws DatabaseException {
693 lock.readLock().lock();
695 int replyCounter = 0;
696 for (String knownReplyId : knownPostReplies) {
697 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
699 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
700 } catch (ConfigurationException ce1) {
701 throw new DatabaseException("Could not save database.", ce1);
703 lock.readLock().unlock();