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.emptyList;
25 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.Comparator;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.List;
36 import java.util.SortedSet;
37 import java.util.TreeSet;
38 import java.util.concurrent.locks.ReadWriteLock;
39 import java.util.concurrent.locks.ReentrantReadWriteLock;
41 import net.pterodactylus.sone.data.Album;
42 import net.pterodactylus.sone.data.Image;
43 import net.pterodactylus.sone.data.Post;
44 import net.pterodactylus.sone.data.PostReply;
45 import net.pterodactylus.sone.data.Reply;
46 import net.pterodactylus.sone.data.Sone;
47 import net.pterodactylus.sone.database.Database;
48 import net.pterodactylus.sone.database.DatabaseException;
49 import net.pterodactylus.sone.database.PostDatabase;
50 import net.pterodactylus.sone.database.SoneBuilder;
51 import net.pterodactylus.sone.freenet.wot.Identity;
52 import net.pterodactylus.util.config.Configuration;
53 import net.pterodactylus.util.config.ConfigurationException;
55 import com.google.common.base.Function;
56 import com.google.common.base.Optional;
57 import com.google.common.collect.ArrayListMultimap;
58 import com.google.common.collect.HashMultimap;
59 import com.google.common.collect.ListMultimap;
60 import com.google.common.collect.Maps;
61 import com.google.common.collect.Multimap;
62 import com.google.common.collect.SortedSetMultimap;
63 import com.google.common.collect.TreeMultimap;
64 import com.google.common.util.concurrent.AbstractService;
65 import com.google.inject.Inject;
68 * Memory-based {@link PostDatabase} implementation.
70 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
72 public class MemoryDatabase extends AbstractService implements Database {
75 private final ReadWriteLock lock = new ReentrantReadWriteLock();
77 /** The configuration. */
78 private final Configuration configuration;
80 private final Map<String, Identity> identities = Maps.newHashMap();
81 private final Map<String, Sone> sones = new HashMap<String, Sone>();
83 /** All posts by their ID. */
84 private final Map<String, Post> allPosts = new HashMap<String, Post>();
86 /** All posts by their Sones. */
87 private final Multimap<String, Post> sonePosts = HashMultimap.create();
89 /** All posts by their recipient. */
90 private final Multimap<String, Post> recipientPosts = HashMultimap.create();
92 /** Whether posts are known. */
93 private final Set<String> knownPosts = new HashSet<String>();
95 /** All post replies by their ID. */
96 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
98 /** Replies sorted by Sone. */
99 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
102 public int compare(String leftString, String rightString) {
103 return leftString.compareTo(rightString);
105 }, PostReply.TIME_COMPARATOR);
107 /** Replies by post. */
108 private final Map<String, SortedSet<PostReply>> postReplies = new HashMap<String, SortedSet<PostReply>>();
110 /** Whether post replies are known. */
111 private final Set<String> knownPostReplies = new HashSet<String>();
113 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
114 private final ListMultimap<String, String> albumChildren = ArrayListMultimap.create();
115 private final ListMultimap<String, String> albumImages = ArrayListMultimap.create();
117 private final Map<String, Image> allImages = new HashMap<String, Image>();
120 * Creates a new memory database.
122 * @param configuration
123 * The configuration for loading and saving elements
126 public MemoryDatabase(Configuration configuration) {
127 this.configuration = configuration;
135 public void save() throws DatabaseException {
137 saveKnownPostReplies();
145 protected void doStart() {
147 loadKnownPostReplies();
152 protected void doStop() {
156 } catch (DatabaseException de1) {
162 public Optional<Identity> getIdentity(String identityId) {
163 lock.readLock().lock();
165 return fromNullable(identities.get(identityId));
167 lock.readLock().unlock();
172 public Optional<Sone> getSone(String soneId) {
173 lock.readLock().lock();
175 return fromNullable(sones.get(soneId));
177 lock.readLock().unlock();
182 public Collection<Sone> getSones() {
183 lock.readLock().lock();
185 return Collections.unmodifiableCollection(sones.values());
187 lock.readLock().unlock();
192 public Collection<Sone> getLocalSones() {
193 lock.readLock().lock();
195 return from(getSones()).filter(LOCAL_SONE_FILTER).toSet();
197 lock.readLock().unlock();
202 public Collection<Sone> getRemoteSones() {
203 lock.readLock().lock();
205 return from(getSones()).filter(not(LOCAL_SONE_FILTER)).toSet();
207 lock.readLock().unlock();
212 public SoneBuilder newSoneBuilder() {
217 // POSTPROVIDER METHODS
221 public Optional<Post> getPost(String postId) {
222 lock.readLock().lock();
224 return fromNullable(allPosts.get(postId));
226 lock.readLock().unlock();
231 public Collection<Post> getPosts(String soneId) {
232 lock.readLock().lock();
234 return new HashSet<Post>(sonePosts.get(soneId));
236 lock.readLock().unlock();
241 public Collection<Post> getDirectedPosts(String recipientId) {
242 lock.readLock().lock();
244 Collection<Post> posts = recipientPosts.get(recipientId);
245 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
247 lock.readLock().unlock();
256 public void storePost(Post post) {
257 checkNotNull(post, "post must not be null");
258 lock.writeLock().lock();
260 allPosts.put(post.getId(), post);
261 sonePosts.put(post.getSone().getId(), post);
262 if (post.getRecipientId().isPresent()) {
263 recipientPosts.put(post.getRecipientId().get(), post);
266 lock.writeLock().unlock();
271 public void removePost(Post post) {
272 checkNotNull(post, "post must not be null");
273 lock.writeLock().lock();
275 allPosts.remove(post.getId());
276 sonePosts.remove(post.getSone().getId(), post);
277 if (post.getRecipientId().isPresent()) {
278 recipientPosts.remove(post.getRecipientId().get(), post);
280 post.getSone().removePost(post);
282 lock.writeLock().unlock();
287 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
288 checkNotNull(sone, "sone must not be null");
289 /* verify that all posts are from the same Sone. */
290 for (Post post : posts) {
291 if (!sone.equals(post.getSone())) {
292 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
296 lock.writeLock().lock();
298 /* remove all posts by the Sone. */
299 sonePosts.removeAll(sone.getId());
300 for (Post post : posts) {
301 allPosts.remove(post.getId());
302 if (post.getRecipientId().isPresent()) {
303 recipientPosts.remove(post.getRecipientId().get(), post);
308 sonePosts.putAll(sone.getId(), posts);
309 for (Post post : posts) {
310 allPosts.put(post.getId(), post);
311 if (post.getRecipientId().isPresent()) {
312 recipientPosts.put(post.getRecipientId().get(), post);
316 lock.writeLock().unlock();
321 public void removePosts(Sone sone) {
322 checkNotNull(sone, "sone must not be null");
323 lock.writeLock().lock();
325 /* remove all posts by the Sone. */
326 sonePosts.removeAll(sone.getId());
327 for (Post post : sone.getPosts()) {
328 allPosts.remove(post.getId());
329 if (post.getRecipientId().isPresent()) {
330 recipientPosts.remove(post.getRecipientId().get(), post);
334 lock.writeLock().unlock();
339 // POSTREPLYPROVIDER METHODS
343 public Optional<PostReply> getPostReply(String id) {
344 lock.readLock().lock();
346 return fromNullable(allPostReplies.get(id));
348 lock.readLock().unlock();
353 public List<PostReply> getReplies(String postId) {
354 lock.readLock().lock();
356 if (!postReplies.containsKey(postId)) {
359 return new ArrayList<PostReply>(postReplies.get(postId));
361 lock.readLock().unlock();
366 // POSTREPLYSTORE METHODS
370 * Returns whether the given post reply is known.
374 * @return {@code true} if the given post reply is known, {@code false}
377 public boolean isPostReplyKnown(PostReply postReply) {
378 lock.readLock().lock();
380 return knownPostReplies.contains(postReply.getId());
382 lock.readLock().unlock();
387 public void setPostReplyKnown(PostReply postReply) {
388 lock.writeLock().lock();
390 knownPostReplies.add(postReply.getId());
392 lock.writeLock().unlock();
397 public void storePostReply(PostReply postReply) {
398 lock.writeLock().lock();
400 allPostReplies.put(postReply.getId(), postReply);
401 if (postReplies.containsKey(postReply.getPostId())) {
402 postReplies.get(postReply.getPostId()).add(postReply);
404 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
405 replies.add(postReply);
406 postReplies.put(postReply.getPostId(), replies);
409 lock.writeLock().unlock();
414 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
415 checkNotNull(sone, "sone must not be null");
416 /* verify that all posts are from the same Sone. */
417 for (PostReply postReply : postReplies) {
418 if (!sone.equals(postReply.getSone())) {
419 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
423 lock.writeLock().lock();
425 /* remove all post replies of the Sone. */
426 for (PostReply postReply : getRepliesFrom(sone.getId())) {
427 removePostReply(postReply);
429 for (PostReply postReply : postReplies) {
430 allPostReplies.put(postReply.getId(), postReply);
431 sonePostReplies.put(postReply.getSone().getId(), postReply);
432 if (this.postReplies.containsKey(postReply.getPostId())) {
433 this.postReplies.get(postReply.getPostId()).add(postReply);
435 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
436 replies.add(postReply);
437 this.postReplies.put(postReply.getPostId(), replies);
441 lock.writeLock().unlock();
446 public void removePostReply(PostReply postReply) {
447 lock.writeLock().lock();
449 allPostReplies.remove(postReply.getId());
450 if (postReplies.containsKey(postReply.getPostId())) {
451 postReplies.get(postReply.getPostId()).remove(postReply);
452 if (postReplies.get(postReply.getPostId()).isEmpty()) {
453 postReplies.remove(postReply.getPostId());
457 lock.writeLock().unlock();
462 public void removePostReplies(Sone sone) {
463 checkNotNull(sone, "sone must not be null");
465 lock.writeLock().lock();
467 for (PostReply postReply : sone.getReplies()) {
468 removePostReply(postReply);
471 lock.writeLock().unlock();
476 // ALBUMPROVDER METHODS
480 public Optional<Album> getAlbum(String albumId) {
481 lock.readLock().lock();
483 return fromNullable(allAlbums.get(albumId));
485 lock.readLock().unlock();
490 public List<Album> getAlbums(Album parent) {
491 lock.readLock().lock();
493 return from(albumChildren.get(parent.getId())).transformAndConcat(getAlbum()).toList();
495 lock.readLock().unlock();
500 public void moveUp(Album album) {
501 lock.writeLock().lock();
503 List<String> albums = albumChildren.get(album.getParent().getId());
504 int currentIndex = albums.indexOf(album.getId());
505 if (currentIndex == 0) {
508 albums.remove(album.getId());
509 albums.add(currentIndex - 1, album.getId());
511 lock.writeLock().unlock();
516 public void moveDown(Album album) {
517 lock.writeLock().lock();
519 List<String> albums = albumChildren.get(album.getParent().getId());
520 int currentIndex = albums.indexOf(album.getId());
521 if (currentIndex == (albums.size() - 1)) {
524 albums.remove(album.getId());
525 albums.add(currentIndex + 1, album.getId());
527 lock.writeLock().unlock();
532 // ALBUMSTORE METHODS
536 public void storeAlbum(Album album) {
537 lock.writeLock().lock();
539 allAlbums.put(album.getId(), album);
540 albumChildren.put(album.getParent().getId(), album.getId());
542 lock.writeLock().unlock();
547 public void removeAlbum(Album album) {
548 lock.writeLock().lock();
550 allAlbums.remove(album.getId());
551 albumChildren.remove(album.getParent().getId(), album.getId());
553 lock.writeLock().unlock();
558 // IMAGEPROVIDER METHODS
562 public Optional<Image> getImage(String imageId) {
563 lock.readLock().lock();
565 return fromNullable(allImages.get(imageId));
567 lock.readLock().unlock();
572 public List<Image> getImages(Album parent) {
573 lock.readLock().lock();
575 return from(albumImages.get(parent.getId())).transformAndConcat(getImage()).toList();
577 lock.readLock().unlock();
582 public void moveUp(Image image) {
583 lock.writeLock().lock();
585 List<String> images = albumImages.get(image.getAlbum().getId());
586 int currentIndex = images.indexOf(image.getId());
587 if (currentIndex == 0) {
590 images.remove(image.getId());
591 images.add(currentIndex - 1, image.getId());
593 lock.writeLock().unlock();
598 public void moveDown(Image image) {
599 lock.writeLock().lock();
601 List<String> images = albumChildren.get(image.getAlbum().getId());
602 int currentIndex = images.indexOf(image.getId());
603 if (currentIndex == (images.size() - 1)) {
606 images.remove(image.getId());
607 images.add(currentIndex + 1, image.getId());
609 lock.writeLock().unlock();
614 // IMAGESTORE METHODS
618 public void storeImage(Image image) {
619 lock.writeLock().lock();
621 allImages.put(image.getId(), image);
622 albumImages.put(image.getAlbum().getId(), image.getId());
624 lock.writeLock().unlock();
629 public void removeImage(Image image) {
630 lock.writeLock().lock();
632 allImages.remove(image.getId());
633 albumImages.remove(image.getAlbum().getId(), image.getId());
635 lock.writeLock().unlock();
640 // PACKAGE-PRIVATE METHODS
644 * Returns whether the given post is known.
648 * @return {@code true} if the post is known, {@code false} otherwise
650 boolean isPostKnown(Post post) {
651 lock.readLock().lock();
653 return knownPosts.contains(post.getId());
655 lock.readLock().unlock();
660 * Sets whether the given post is known.
665 * {@code true} if the post is known, {@code false} otherwise
667 void setPostKnown(Post post, boolean known) {
668 lock.writeLock().lock();
671 knownPosts.add(post.getId());
673 knownPosts.remove(post.getId());
676 lock.writeLock().unlock();
684 /** Loads the known posts. */
685 private void loadKnownPosts() {
686 lock.writeLock().lock();
690 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
691 if (knownPostId == null) {
694 knownPosts.add(knownPostId);
697 lock.writeLock().unlock();
702 * Saves the known posts to the configuration.
704 * @throws DatabaseException
705 * if a configuration error occurs
707 private void saveKnownPosts() throws DatabaseException {
708 lock.readLock().lock();
711 for (String knownPostId : knownPosts) {
712 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
714 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
715 } catch (ConfigurationException ce1) {
716 throw new DatabaseException("Could not save database.", ce1);
718 lock.readLock().unlock();
723 * Returns all replies by the given Sone.
727 * @return The post replies of the Sone, sorted by time (newest first)
729 private Collection<PostReply> getRepliesFrom(String id) {
730 lock.readLock().lock();
732 if (sonePostReplies.containsKey(id)) {
733 return Collections.unmodifiableCollection(sonePostReplies.get(id));
735 return Collections.emptySet();
737 lock.readLock().unlock();
741 /** Loads the known post replies. */
742 private void loadKnownPostReplies() {
743 lock.writeLock().lock();
745 int replyCounter = 0;
747 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
748 if (knownReplyId == null) {
751 knownPostReplies.add(knownReplyId);
754 lock.writeLock().unlock();
759 * Saves the known post replies to the configuration.
761 * @throws DatabaseException
762 * if a configuration error occurs
764 private void saveKnownPostReplies() throws DatabaseException {
765 lock.readLock().lock();
767 int replyCounter = 0;
768 for (String knownReplyId : knownPostReplies) {
769 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
771 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
772 } catch (ConfigurationException ce1) {
773 throw new DatabaseException("Could not save database.", ce1);
775 lock.readLock().unlock();
779 private Function<String, Iterable<Album>> getAlbum() {
780 return new Function<String, Iterable<Album>>() {
782 public Iterable<Album> apply(String input) {
783 return (input == null) ? Collections.<Album>emptyList() : getAlbum(input).asSet();
788 private Function<String, Iterable<Image>> getImage() {
789 return new Function<String, Iterable<Image>>() {
791 public Iterable<Image> apply(String input) {
792 return (input == null) ? Collections.<Image>emptyList() : getImage(input).asSet();