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>();
118 private final Map<String, Image> allImages = new HashMap<String, Image>();
121 * Creates a new memory database.
123 * @param soneProvider
125 * @param configuration
126 * The configuration for loading and saving elements
129 public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
130 this.soneProvider = soneProvider;
131 this.configuration = configuration;
139 * Saves the database.
141 * @throws DatabaseException
142 * if an error occurs while saving
145 public void save() throws DatabaseException {
147 saveKnownPostReplies();
154 /** {@inheritDocs} */
156 protected void doStart() {
158 loadKnownPostReplies();
162 /** {@inheritDocs} */
164 protected void doStop() {
168 } catch (DatabaseException de1) {
174 // POSTPROVIDER METHODS
177 /** {@inheritDocs} */
179 public Optional<Post> getPost(String postId) {
180 lock.readLock().lock();
182 return fromNullable(allPosts.get(postId));
184 lock.readLock().unlock();
188 /** {@inheritDocs} */
190 public Collection<Post> getPosts(String soneId) {
191 return new HashSet<Post>(getPostsFrom(soneId));
194 /** {@inheritDocs} */
196 public Collection<Post> getDirectedPosts(String recipientId) {
197 lock.readLock().lock();
199 Collection<Post> posts = recipientPosts.get(recipientId);
200 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
202 lock.readLock().unlock();
207 // POSTBUILDERFACTORY METHODS
210 /** {@inheritDocs} */
212 public PostBuilder newPostBuilder() {
213 return new MemoryPostBuilder(this, soneProvider);
220 /** {@inheritDocs} */
222 public void storePost(Post post) {
223 checkNotNull(post, "post must not be null");
224 lock.writeLock().lock();
226 allPosts.put(post.getId(), post);
227 getPostsFrom(post.getSone().getId()).add(post);
228 if (post.getRecipientId().isPresent()) {
229 getPostsTo(post.getRecipientId().get()).add(post);
232 lock.writeLock().unlock();
236 /** {@inheritDocs} */
238 public void removePost(Post post) {
239 checkNotNull(post, "post must not be null");
240 lock.writeLock().lock();
242 allPosts.remove(post.getId());
243 getPostsFrom(post.getSone().getId()).remove(post);
244 if (post.getRecipientId().isPresent()) {
245 getPostsTo(post.getRecipientId().get()).remove(post);
247 post.getSone().removePost(post);
249 lock.writeLock().unlock();
253 /** {@inheritDocs} */
255 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
256 checkNotNull(sone, "sone must not be null");
257 /* verify that all posts are from the same Sone. */
258 for (Post post : posts) {
259 if (!sone.equals(post.getSone())) {
260 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
264 lock.writeLock().lock();
266 /* remove all posts by the Sone. */
267 Collection<Post> oldPosts = getPostsFrom(sone.getId());
268 for (Post post : oldPosts) {
269 allPosts.remove(post.getId());
270 if (post.getRecipientId().isPresent()) {
271 getPostsTo(post.getRecipientId().get()).remove(post);
276 getPostsFrom(sone.getId()).addAll(posts);
277 for (Post post : posts) {
278 allPosts.put(post.getId(), post);
279 if (post.getRecipientId().isPresent()) {
280 getPostsTo(post.getRecipientId().get()).add(post);
284 lock.writeLock().unlock();
288 /** {@inheritDocs} */
290 public void removePosts(Sone sone) {
291 checkNotNull(sone, "sone must not be null");
292 lock.writeLock().lock();
294 /* remove all posts by the Sone. */
295 getPostsFrom(sone.getId()).clear();
296 for (Post post : sone.getPosts()) {
297 allPosts.remove(post.getId());
298 if (post.getRecipientId().isPresent()) {
299 getPostsTo(post.getRecipientId().get()).remove(post);
303 lock.writeLock().unlock();
308 // POSTREPLYPROVIDER METHODS
311 /** {@inheritDocs} */
313 public Optional<PostReply> getPostReply(String id) {
314 lock.readLock().lock();
316 return fromNullable(allPostReplies.get(id));
318 lock.readLock().unlock();
322 /** {@inheritDocs} */
324 public List<PostReply> getReplies(String postId) {
325 lock.readLock().lock();
327 if (!postReplies.containsKey(postId)) {
328 return Collections.emptyList();
330 return new ArrayList<PostReply>(postReplies.get(postId));
332 lock.readLock().unlock();
337 // POSTREPLYBUILDERFACTORY METHODS
340 /** {@inheritDocs} */
342 public PostReplyBuilder newPostReplyBuilder() {
343 return new MemoryPostReplyBuilder(this, soneProvider);
347 // POSTREPLYSTORE METHODS
350 /** {@inheritDocs} */
352 public void storePostReply(PostReply postReply) {
353 lock.writeLock().lock();
355 allPostReplies.put(postReply.getId(), postReply);
356 postReplies.put(postReply.getPostId(), postReply);
358 lock.writeLock().unlock();
362 /** {@inheritDocs} */
364 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
365 checkNotNull(sone, "sone must not be null");
366 /* verify that all posts are from the same Sone. */
367 for (PostReply postReply : postReplies) {
368 if (!sone.equals(postReply.getSone())) {
369 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
373 lock.writeLock().lock();
375 /* remove all post replies of the Sone. */
376 for (PostReply postReply : getRepliesFrom(sone.getId())) {
377 removePostReply(postReply);
379 for (PostReply postReply : postReplies) {
380 allPostReplies.put(postReply.getId(), postReply);
381 sonePostReplies.put(postReply.getSone().getId(), postReply);
382 this.postReplies.put(postReply.getPostId(), postReply);
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);
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 // ALBUMBUILDERFACTORY METHODS
437 public AlbumBuilder newAlbumBuilder() {
438 return new AlbumBuilderImpl();
442 // ALBUMSTORE METHODS
446 public void storeAlbum(Album album) {
447 lock.writeLock().lock();
449 allAlbums.put(album.getId(), album);
451 lock.writeLock().unlock();
456 public void removeAlbum(Album album) {
457 lock.writeLock().lock();
459 allAlbums.remove(album.getId());
461 lock.writeLock().unlock();
466 // IMAGEPROVIDER METHODS
470 public Optional<Image> getImage(String imageId) {
471 lock.readLock().lock();
473 return fromNullable(allImages.get(imageId));
475 lock.readLock().unlock();
480 // IMAGEBUILDERFACTORY METHODS
484 public ImageBuilder newImageBuilder() {
485 return new ImageBuilderImpl();
489 // IMAGESTORE METHODS
493 public void storeImage(Image image) {
494 lock.writeLock().lock();
496 allImages.put(image.getId(), image);
498 lock.writeLock().unlock();
503 public void removeImage(Image image) {
504 lock.writeLock().lock();
506 allImages.remove(image.getId());
508 lock.writeLock().unlock();
513 // PACKAGE-PRIVATE METHODS
517 * Returns whether the given post is known.
521 * @return {@code true} if the post is known, {@code false} otherwise
523 boolean isPostKnown(Post post) {
524 lock.readLock().lock();
526 return knownPosts.contains(post.getId());
528 lock.readLock().unlock();
533 * Sets whether the given post is known.
538 * {@code true} if the post is known, {@code false} otherwise
540 void setPostKnown(Post post, boolean known) {
541 lock.writeLock().lock();
544 knownPosts.add(post.getId());
546 knownPosts.remove(post.getId());
549 lock.writeLock().unlock();
554 * Returns whether the given post reply is known.
558 * @return {@code true} if the given post reply is known, {@code false}
561 boolean isPostReplyKnown(PostReply postReply) {
562 lock.readLock().lock();
564 return knownPostReplies.contains(postReply.getId());
566 lock.readLock().unlock();
571 * Sets whether the given post reply is known.
576 * {@code true} if the post reply is known, {@code false} otherwise
578 void setPostReplyKnown(PostReply postReply, boolean known) {
579 lock.writeLock().lock();
582 knownPostReplies.add(postReply.getId());
584 knownPostReplies.remove(postReply.getId());
587 lock.writeLock().unlock();
596 * Gets all posts for the given Sone, creating a new collection if there is
600 * The ID of the Sone to get the posts for
603 private Collection<Post> getPostsFrom(String soneId) {
604 lock.readLock().lock();
606 return sonePosts.get(soneId);
608 lock.readLock().unlock();
613 * Gets all posts that are directed the given Sone, creating a new collection
614 * if there is none yet.
617 * The ID of the Sone to get the posts for
620 private Collection<Post> getPostsTo(String recipientId) {
621 lock.readLock().lock();
623 return recipientPosts.get(recipientId);
625 lock.readLock().unlock();
629 /** Loads the known posts. */
630 private void loadKnownPosts() {
631 lock.writeLock().lock();
635 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
636 if (knownPostId == null) {
639 knownPosts.add(knownPostId);
642 lock.writeLock().unlock();
647 * Saves the known posts to the configuration.
649 * @throws DatabaseException
650 * if a configuration error occurs
652 private void saveKnownPosts() throws DatabaseException {
653 lock.readLock().lock();
656 for (String knownPostId : knownPosts) {
657 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
659 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
660 } catch (ConfigurationException ce1) {
661 throw new DatabaseException("Could not save database.", ce1);
663 lock.readLock().unlock();
668 * Returns all replies by the given Sone.
672 * @return The post replies of the Sone, sorted by time (newest first)
674 private Collection<PostReply> getRepliesFrom(String id) {
675 lock.readLock().lock();
677 return Collections.unmodifiableCollection(sonePostReplies.get(id));
679 lock.readLock().unlock();
683 /** Loads the known post replies. */
684 private void loadKnownPostReplies() {
685 lock.writeLock().lock();
687 int replyCounter = 0;
689 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
690 if (knownReplyId == null) {
693 knownPostReplies.add(knownReplyId);
696 lock.writeLock().unlock();
701 * Saves the known post replies to the configuration.
703 * @throws DatabaseException
704 * if a configuration error occurs
706 private void saveKnownPostReplies() throws DatabaseException {
707 lock.readLock().lock();
709 int replyCounter = 0;
710 for (String knownReplyId : knownPostReplies) {
711 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
713 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
714 } catch (ConfigurationException ce1) {
715 throw new DatabaseException("Could not save database.", ce1);
717 lock.readLock().unlock();