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 com.google.common.base.Predicates.not;
23 import static com.google.common.collect.FluentIterable.from;
24 import static java.util.Collections.unmodifiableCollection;
25 import static net.pterodactylus.sone.data.Reply.TIME_COMPARATOR;
26 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
27 import static net.pterodactylus.sone.data.Sone.toAllAlbums;
28 import static net.pterodactylus.sone.data.Sone.toAllImages;
30 import java.util.Collection;
31 import java.util.Comparator;
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.List;
37 import java.util.concurrent.locks.ReadWriteLock;
38 import java.util.concurrent.locks.ReentrantReadWriteLock;
40 import net.pterodactylus.sone.data.Album;
41 import net.pterodactylus.sone.data.Image;
42 import net.pterodactylus.sone.data.Post;
43 import net.pterodactylus.sone.data.PostReply;
44 import net.pterodactylus.sone.data.Sone;
45 import net.pterodactylus.sone.data.impl.AlbumBuilderImpl;
46 import net.pterodactylus.sone.data.impl.ImageBuilderImpl;
47 import net.pterodactylus.sone.database.AlbumBuilder;
48 import net.pterodactylus.sone.database.Database;
49 import net.pterodactylus.sone.database.DatabaseException;
50 import net.pterodactylus.sone.database.ImageBuilder;
51 import net.pterodactylus.sone.database.PostBuilder;
52 import net.pterodactylus.sone.database.PostDatabase;
53 import net.pterodactylus.sone.database.PostReplyBuilder;
54 import net.pterodactylus.sone.database.SoneBuilder;
55 import net.pterodactylus.sone.database.SoneProvider;
56 import net.pterodactylus.util.config.Configuration;
57 import net.pterodactylus.util.config.ConfigurationException;
59 import com.google.common.base.Optional;
60 import com.google.common.base.Predicate;
61 import com.google.common.collect.HashMultimap;
62 import com.google.common.collect.Multimap;
63 import com.google.common.collect.SortedSetMultimap;
64 import com.google.common.collect.TreeMultimap;
65 import com.google.common.util.concurrent.AbstractService;
66 import com.google.inject.Inject;
67 import com.google.inject.Singleton;
70 * Memory-based {@link PostDatabase} implementation.
72 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
75 public class MemoryDatabase extends AbstractService implements Database {
78 private final ReadWriteLock lock = new ReentrantReadWriteLock();
80 /** The Sone provider. */
81 private final SoneProvider soneProvider;
83 /** The configuration. */
84 private final Configuration configuration;
86 private final Map<String, Sone> allSones = new HashMap<String, Sone>();
88 /** All posts by their ID. */
89 private final Map<String, Post> allPosts = new HashMap<String, Post>();
91 /** All posts by their Sones. */
92 private final Multimap<String, Post> sonePosts = HashMultimap.create();
94 /** Whether posts are known. */
95 private final Set<String> knownPosts = new HashSet<String>();
97 /** All post replies by their ID. */
98 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
100 /** Replies sorted by Sone. */
101 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
104 public int compare(String leftString, String rightString) {
105 return leftString.compareTo(rightString);
109 /** Whether post replies are known. */
110 private final Set<String> knownPostReplies = new HashSet<String>();
112 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
113 private final Multimap<String, Album> soneAlbums = HashMultimap.create();
115 private final Map<String, Image> allImages = new HashMap<String, Image>();
116 private final Multimap<String, Image> soneImages = HashMultimap.create();
119 * Creates a new memory database.
121 * @param soneProvider
123 * @param configuration
124 * The configuration for loading and saving elements
127 public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
128 this.soneProvider = soneProvider;
129 this.configuration = configuration;
137 * Saves the database.
139 * @throws DatabaseException
140 * if an error occurs while saving
143 public void save() throws DatabaseException {
145 saveKnownPostReplies();
152 /** {@inheritDocs} */
154 protected void doStart() {
156 loadKnownPostReplies();
160 /** {@inheritDocs} */
162 protected void doStop() {
166 } catch (DatabaseException de1) {
172 public SoneBuilder newSoneBuilder() {
173 return new MemorySoneBuilder();
177 public void storeSone(Sone sone) {
178 lock.writeLock().lock();
180 Collection<Post> removedPosts = sonePosts.removeAll(sone.getId());
181 for (Post removedPost : removedPosts) {
182 allPosts.remove(removedPost.getId());
184 Collection<PostReply> removedPostReplies =
185 sonePostReplies.removeAll(sone.getId());
186 for (PostReply removedPostReply : removedPostReplies) {
187 allPostReplies.remove(removedPostReply.getId());
189 Collection<Album> removedAlbums =
190 soneAlbums.removeAll(sone.getId());
191 for (Album removedAlbum : removedAlbums) {
192 allAlbums.remove(removedAlbum.getId());
194 Collection<Image> removedImages =
195 soneImages.removeAll(sone.getId());
196 for (Image removedImage : removedImages) {
197 allImages.remove(removedImage.getId());
200 allSones.put(sone.getId(), sone);
201 sonePosts.putAll(sone.getId(), sone.getPosts());
202 for (Post post : sone.getPosts()) {
203 allPosts.put(post.getId(), post);
205 sonePostReplies.putAll(sone.getId(), sone.getReplies());
206 for (PostReply postReply : sone.getReplies()) {
207 allPostReplies.put(postReply.getId(), postReply);
209 soneAlbums.putAll(sone.getId(), toAllAlbums.apply(sone));
210 for (Album album : toAllAlbums.apply(sone)) {
211 allAlbums.put(album.getId(), album);
213 soneImages.putAll(sone.getId(), toAllImages.apply(sone));
214 for (Image image : toAllImages.apply(sone)) {
215 allImages.put(image.getId(), image);
218 lock.writeLock().unlock();
223 public Optional<Sone> getSone(String soneId) {
224 lock.readLock().lock();
226 return fromNullable(allSones.get(soneId));
228 lock.readLock().unlock();
233 public Collection<Sone> getSones() {
234 lock.readLock().lock();
236 return new HashSet<Sone>(allSones.values());
238 lock.readLock().unlock();
243 public Collection<Sone> getLocalSones() {
244 lock.readLock().lock();
246 return from(allSones.values()).filter(LOCAL_SONE_FILTER).toSet();
248 lock.readLock().unlock();
253 public Collection<Sone> getRemoteSones() {
254 lock.readLock().lock();
256 return from(allSones.values())
257 .filter(not(LOCAL_SONE_FILTER)) .toSet();
259 lock.readLock().unlock();
264 // POSTPROVIDER METHODS
267 /** {@inheritDocs} */
269 public Optional<Post> getPost(String postId) {
270 lock.readLock().lock();
272 return fromNullable(allPosts.get(postId));
274 lock.readLock().unlock();
278 /** {@inheritDocs} */
280 public Collection<Post> getPosts(String soneId) {
281 return new HashSet<Post>(getPostsFrom(soneId));
284 /** {@inheritDocs} */
286 public Collection<Post> getDirectedPosts(final String recipientId) {
287 lock.readLock().lock();
289 return from(sonePosts.values()).filter(new Predicate<Post>() {
291 public boolean apply(Post post) {
292 return post.getRecipientId().asSet().contains(recipientId);
296 lock.readLock().unlock();
301 // POSTBUILDERFACTORY METHODS
304 /** {@inheritDocs} */
306 public PostBuilder newPostBuilder() {
307 return new MemoryPostBuilder(this, soneProvider);
314 /** {@inheritDocs} */
316 public void storePost(Post post) {
317 checkNotNull(post, "post must not be null");
318 lock.writeLock().lock();
320 allPosts.put(post.getId(), post);
321 getPostsFrom(post.getSone().getId()).add(post);
323 lock.writeLock().unlock();
327 /** {@inheritDocs} */
329 public void removePost(Post post) {
330 checkNotNull(post, "post must not be null");
331 lock.writeLock().lock();
333 allPosts.remove(post.getId());
334 getPostsFrom(post.getSone().getId()).remove(post);
335 post.getSone().removePost(post);
337 lock.writeLock().unlock();
341 /** {@inheritDocs} */
343 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
344 checkNotNull(sone, "sone must not be null");
345 /* verify that all posts are from the same Sone. */
346 for (Post post : posts) {
347 if (!sone.equals(post.getSone())) {
348 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
352 lock.writeLock().lock();
354 /* remove all posts by the Sone. */
355 Collection<Post> oldPosts = getPostsFrom(sone.getId());
356 for (Post post : oldPosts) {
357 allPosts.remove(post.getId());
361 getPostsFrom(sone.getId()).addAll(posts);
362 for (Post post : posts) {
363 allPosts.put(post.getId(), post);
366 lock.writeLock().unlock();
370 /** {@inheritDocs} */
372 public void removePosts(Sone sone) {
373 checkNotNull(sone, "sone must not be null");
374 lock.writeLock().lock();
376 /* remove all posts by the Sone. */
377 getPostsFrom(sone.getId()).clear();
378 for (Post post : sone.getPosts()) {
379 allPosts.remove(post.getId());
382 lock.writeLock().unlock();
387 // POSTREPLYPROVIDER METHODS
390 /** {@inheritDocs} */
392 public Optional<PostReply> getPostReply(String id) {
393 lock.readLock().lock();
395 return fromNullable(allPostReplies.get(id));
397 lock.readLock().unlock();
401 /** {@inheritDocs} */
403 public List<PostReply> getReplies(final String postId) {
404 lock.readLock().lock();
406 return from(allPostReplies.values())
407 .filter(new Predicate<PostReply>() {
409 public boolean apply(PostReply postReply) {
410 return postReply.getPostId().equals(postId);
412 }).toSortedList(TIME_COMPARATOR);
414 lock.readLock().unlock();
419 // POSTREPLYBUILDERFACTORY METHODS
422 /** {@inheritDocs} */
424 public PostReplyBuilder newPostReplyBuilder() {
425 return new MemoryPostReplyBuilder(this, soneProvider);
429 // POSTREPLYSTORE METHODS
432 /** {@inheritDocs} */
434 public void storePostReply(PostReply postReply) {
435 lock.writeLock().lock();
437 allPostReplies.put(postReply.getId(), postReply);
439 lock.writeLock().unlock();
443 /** {@inheritDocs} */
445 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
446 checkNotNull(sone, "sone must not be null");
447 /* verify that all posts are from the same Sone. */
448 for (PostReply postReply : postReplies) {
449 if (!sone.equals(postReply.getSone())) {
450 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
454 lock.writeLock().lock();
456 /* remove all post replies of the Sone. */
457 for (PostReply postReply : getRepliesFrom(sone.getId())) {
458 removePostReply(postReply);
460 for (PostReply postReply : postReplies) {
461 allPostReplies.put(postReply.getId(), postReply);
462 sonePostReplies.put(postReply.getSone().getId(), postReply);
465 lock.writeLock().unlock();
469 /** {@inheritDocs} */
471 public void removePostReply(PostReply postReply) {
472 lock.writeLock().lock();
474 allPostReplies.remove(postReply.getId());
476 lock.writeLock().unlock();
480 /** {@inheritDocs} */
482 public void removePostReplies(Sone sone) {
483 checkNotNull(sone, "sone must not be null");
485 lock.writeLock().lock();
487 for (PostReply postReply : sone.getReplies()) {
488 removePostReply(postReply);
491 lock.writeLock().unlock();
496 // ALBUMPROVDER METHODS
500 public Optional<Album> getAlbum(String albumId) {
501 lock.readLock().lock();
503 return fromNullable(allAlbums.get(albumId));
505 lock.readLock().unlock();
510 // ALBUMBUILDERFACTORY METHODS
514 public AlbumBuilder newAlbumBuilder() {
515 return new AlbumBuilderImpl();
519 // ALBUMSTORE METHODS
523 public void storeAlbum(Album album) {
524 lock.writeLock().lock();
526 allAlbums.put(album.getId(), album);
527 soneAlbums.put(album.getSone().getId(), album);
529 lock.writeLock().unlock();
534 public void removeAlbum(Album album) {
535 lock.writeLock().lock();
537 allAlbums.remove(album.getId());
538 soneAlbums.remove(album.getSone().getId(), album);
540 lock.writeLock().unlock();
545 // IMAGEPROVIDER METHODS
549 public Optional<Image> getImage(String imageId) {
550 lock.readLock().lock();
552 return fromNullable(allImages.get(imageId));
554 lock.readLock().unlock();
559 // IMAGEBUILDERFACTORY METHODS
563 public ImageBuilder newImageBuilder() {
564 return new ImageBuilderImpl();
568 // IMAGESTORE METHODS
572 public void storeImage(Image image) {
573 lock.writeLock().lock();
575 allImages.put(image.getId(), image);
576 soneImages.put(image.getSone().getId(), image);
578 lock.writeLock().unlock();
583 public void removeImage(Image image) {
584 lock.writeLock().lock();
586 allImages.remove(image.getId());
587 soneImages.remove(image.getSone().getId(), image);
589 lock.writeLock().unlock();
594 // PACKAGE-PRIVATE METHODS
598 * Returns whether the given post is known.
602 * @return {@code true} if the post is known, {@code false} otherwise
604 boolean isPostKnown(Post post) {
605 lock.readLock().lock();
607 return knownPosts.contains(post.getId());
609 lock.readLock().unlock();
614 * Sets whether the given post is known.
619 * {@code true} if the post is known, {@code false} otherwise
621 void setPostKnown(Post post, boolean known) {
622 lock.writeLock().lock();
625 knownPosts.add(post.getId());
627 knownPosts.remove(post.getId());
630 lock.writeLock().unlock();
635 * Returns whether the given post reply is known.
639 * @return {@code true} if the given post reply is known, {@code false}
642 boolean isPostReplyKnown(PostReply postReply) {
643 lock.readLock().lock();
645 return knownPostReplies.contains(postReply.getId());
647 lock.readLock().unlock();
652 * Sets whether the given post reply is known.
657 * {@code true} if the post reply is known, {@code false} otherwise
659 void setPostReplyKnown(PostReply postReply, boolean known) {
660 lock.writeLock().lock();
663 knownPostReplies.add(postReply.getId());
665 knownPostReplies.remove(postReply.getId());
668 lock.writeLock().unlock();
677 * Gets all posts for the given Sone, creating a new collection if there is
681 * The ID of the Sone to get the posts for
684 private Collection<Post> getPostsFrom(String soneId) {
685 lock.readLock().lock();
687 return sonePosts.get(soneId);
689 lock.readLock().unlock();
693 /** Loads the known posts. */
694 private void loadKnownPosts() {
695 lock.writeLock().lock();
699 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
700 if (knownPostId == null) {
703 knownPosts.add(knownPostId);
706 lock.writeLock().unlock();
711 * Saves the known posts to the configuration.
713 * @throws DatabaseException
714 * if a configuration error occurs
716 private void saveKnownPosts() throws DatabaseException {
717 lock.readLock().lock();
720 for (String knownPostId : knownPosts) {
721 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
723 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
724 } catch (ConfigurationException ce1) {
725 throw new DatabaseException("Could not save database.", ce1);
727 lock.readLock().unlock();
732 * Returns all replies by the given Sone.
736 * @return The post replies of the Sone, sorted by time (newest first)
738 private Collection<PostReply> getRepliesFrom(String id) {
739 lock.readLock().lock();
741 return unmodifiableCollection(sonePostReplies.get(id));
743 lock.readLock().unlock();
747 /** Loads the known post replies. */
748 private void loadKnownPostReplies() {
749 lock.writeLock().lock();
751 int replyCounter = 0;
753 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
754 if (knownReplyId == null) {
757 knownPostReplies.add(knownReplyId);
760 lock.writeLock().unlock();
765 * Saves the known post replies to the configuration.
767 * @throws DatabaseException
768 * if a configuration error occurs
770 private void saveKnownPostReplies() throws DatabaseException {
771 lock.readLock().lock();
773 int replyCounter = 0;
774 for (String knownReplyId : knownPostReplies) {
775 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
777 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
778 } catch (ConfigurationException ce1) {
779 throw new DatabaseException("Could not save database.", ce1);
781 lock.readLock().unlock();