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.concurrent.locks.ReadWriteLock;
37 import java.util.concurrent.locks.ReentrantReadWriteLock;
39 import net.pterodactylus.sone.data.Album;
40 import net.pterodactylus.sone.data.Image;
41 import net.pterodactylus.sone.data.Post;
42 import net.pterodactylus.sone.data.PostReply;
43 import net.pterodactylus.sone.data.Sone;
44 import net.pterodactylus.sone.data.impl.DefaultSoneBuilder;
45 import net.pterodactylus.sone.database.Database;
46 import net.pterodactylus.sone.database.DatabaseException;
47 import net.pterodactylus.sone.database.PostDatabase;
48 import net.pterodactylus.sone.database.SoneBuilder;
49 import net.pterodactylus.sone.freenet.wot.Identity;
50 import net.pterodactylus.util.config.Configuration;
51 import net.pterodactylus.util.config.ConfigurationException;
53 import com.google.common.base.Function;
54 import com.google.common.base.Optional;
55 import com.google.common.collect.ArrayListMultimap;
56 import com.google.common.collect.HashMultimap;
57 import com.google.common.collect.ListMultimap;
58 import com.google.common.collect.Maps;
59 import com.google.common.collect.Multimap;
60 import com.google.common.collect.SortedSetMultimap;
61 import com.google.common.collect.TreeMultimap;
62 import com.google.common.util.concurrent.AbstractService;
63 import com.google.inject.Inject;
66 * Memory-based {@link PostDatabase} implementation.
68 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
70 public class MemoryDatabase extends AbstractService implements Database {
73 private final ReadWriteLock lock = new ReentrantReadWriteLock();
75 /** The configuration. */
76 private final Configuration configuration;
78 private final Map<String, Identity> identities = Maps.newHashMap();
79 private final Map<String, Sone> sones = new HashMap<String, Sone>();
81 /** All posts by their ID. */
82 private final Map<String, Post> allPosts = new HashMap<String, Post>();
84 /** All posts by their Sones. */
85 private final Multimap<String, Post> sonePosts = HashMultimap.create();
87 /** All posts by their recipient. */
88 private final Multimap<String, Post> recipientPosts = HashMultimap.create();
90 /** Whether posts are known. */
91 private final Set<String> knownPosts = new HashSet<String>();
93 /** All post replies by their ID. */
94 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
96 /** Replies sorted by Sone. */
97 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
100 public int compare(String leftString, String rightString) {
101 return leftString.compareTo(rightString);
103 }, PostReply.TIME_COMPARATOR);
105 /** Replies by post. */
106 private final SortedSetMultimap<String, PostReply> postReplies = TreeMultimap.create(new Comparator<String>() {
109 public int compare(String leftString, String rightString) {
110 return leftString.compareTo(rightString);
112 }, PostReply.TIME_COMPARATOR);
114 /** Whether post replies are known. */
115 private final Set<String> knownPostReplies = new HashSet<String>();
117 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
118 private final ListMultimap<String, String> albumChildren = ArrayListMultimap.create();
119 private final ListMultimap<String, String> albumImages = ArrayListMultimap.create();
121 private final Map<String, Image> allImages = new HashMap<String, Image>();
124 * Creates a new memory database.
126 * @param configuration
127 * The configuration for loading and saving elements
130 public MemoryDatabase(Configuration configuration) {
131 this.configuration = configuration;
139 public void save() throws DatabaseException {
141 saveKnownPostReplies();
149 protected void doStart() {
151 loadKnownPostReplies();
156 protected void doStop() {
160 } catch (DatabaseException de1) {
166 public Optional<Identity> getIdentity(String identityId) {
167 lock.readLock().lock();
169 return fromNullable(identities.get(identityId));
171 lock.readLock().unlock();
176 public Function<String, Optional<Sone>> getSone() {
177 return new Function<String, Optional<Sone>>() {
179 public Optional<Sone> apply(String soneId) {
180 return (soneId == null) ? Optional.<Sone>absent() : getSone(soneId);
186 public Optional<Sone> getSone(String soneId) {
187 lock.readLock().lock();
189 return fromNullable(sones.get(soneId));
191 lock.readLock().unlock();
196 public Collection<Sone> getSones() {
197 lock.readLock().lock();
199 return Collections.unmodifiableCollection(sones.values());
201 lock.readLock().unlock();
206 public Collection<Sone> getLocalSones() {
207 lock.readLock().lock();
209 return from(getSones()).filter(LOCAL_SONE_FILTER).toSet();
211 lock.readLock().unlock();
216 public Collection<Sone> getRemoteSones() {
217 lock.readLock().lock();
219 return from(getSones()).filter(not(LOCAL_SONE_FILTER)).toSet();
221 lock.readLock().unlock();
226 public SoneBuilder newSoneBuilder() {
227 return new DefaultSoneBuilder(this) {
229 public Sone build(Optional<SoneCreated> soneCreated) throws IllegalStateException {
230 Sone sone = super.build(soneCreated);
231 lock.writeLock().lock();
233 sones.put(sone.getId(), sone);
235 lock.writeLock().unlock();
243 // POSTPROVIDER METHODS
247 public Function<String, Optional<Post>> getPost() {
248 return new Function<String, Optional<Post>>() {
250 public Optional<Post> apply(String postId) {
251 return (postId == null) ? Optional.<Post>absent() : getPost(postId);
257 public Optional<Post> getPost(String postId) {
258 lock.readLock().lock();
260 return fromNullable(allPosts.get(postId));
262 lock.readLock().unlock();
267 public Collection<Post> getPosts(String soneId) {
268 lock.readLock().lock();
270 return new HashSet<Post>(sonePosts.get(soneId));
272 lock.readLock().unlock();
277 public Collection<Post> getDirectedPosts(String recipientId) {
278 lock.readLock().lock();
280 Collection<Post> posts = recipientPosts.get(recipientId);
281 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
283 lock.readLock().unlock();
292 public void storePost(Post post) {
293 checkNotNull(post, "post must not be null");
294 lock.writeLock().lock();
296 allPosts.put(post.getId(), post);
297 sonePosts.put(post.getSone().getId(), post);
298 if (post.getRecipientId().isPresent()) {
299 recipientPosts.put(post.getRecipientId().get(), post);
302 lock.writeLock().unlock();
307 public void removePost(Post post) {
308 checkNotNull(post, "post must not be null");
309 lock.writeLock().lock();
311 allPosts.remove(post.getId());
312 sonePosts.remove(post.getSone().getId(), post);
313 if (post.getRecipientId().isPresent()) {
314 recipientPosts.remove(post.getRecipientId().get(), post);
316 post.getSone().removePost(post);
318 lock.writeLock().unlock();
323 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
324 checkNotNull(sone, "sone must not be null");
325 /* verify that all posts are from the same Sone. */
326 for (Post post : posts) {
327 if (!sone.equals(post.getSone())) {
328 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
332 lock.writeLock().lock();
334 /* remove all posts by the Sone. */
335 sonePosts.removeAll(sone.getId());
336 for (Post post : posts) {
337 allPosts.remove(post.getId());
338 if (post.getRecipientId().isPresent()) {
339 recipientPosts.remove(post.getRecipientId().get(), post);
344 sonePosts.putAll(sone.getId(), posts);
345 for (Post post : posts) {
346 allPosts.put(post.getId(), post);
347 if (post.getRecipientId().isPresent()) {
348 recipientPosts.put(post.getRecipientId().get(), post);
352 lock.writeLock().unlock();
357 public void removePosts(Sone sone) {
358 checkNotNull(sone, "sone must not be null");
359 lock.writeLock().lock();
361 /* remove all posts by the Sone. */
362 sonePosts.removeAll(sone.getId());
363 for (Post post : sone.getPosts()) {
364 allPosts.remove(post.getId());
365 if (post.getRecipientId().isPresent()) {
366 recipientPosts.remove(post.getRecipientId().get(), post);
370 lock.writeLock().unlock();
375 // POSTREPLYPROVIDER METHODS
379 public Optional<PostReply> getPostReply(String id) {
380 lock.readLock().lock();
382 return fromNullable(allPostReplies.get(id));
384 lock.readLock().unlock();
389 public List<PostReply> getReplies(String postId) {
390 lock.readLock().lock();
392 if (!postReplies.containsKey(postId)) {
395 return new ArrayList<PostReply>(postReplies.get(postId));
397 lock.readLock().unlock();
402 // POSTREPLYSTORE METHODS
406 * Returns whether the given post reply is known.
410 * @return {@code true} if the given post reply is known, {@code false}
413 public boolean isPostReplyKnown(PostReply postReply) {
414 lock.readLock().lock();
416 return knownPostReplies.contains(postReply.getId());
418 lock.readLock().unlock();
423 public void setPostReplyKnown(PostReply postReply) {
424 lock.writeLock().lock();
426 knownPostReplies.add(postReply.getId());
428 lock.writeLock().unlock();
433 public void storePostReply(PostReply postReply) {
434 lock.writeLock().lock();
436 allPostReplies.put(postReply.getId(), postReply);
437 postReplies.put(postReply.getPostId(), postReply);
439 lock.writeLock().unlock();
444 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
445 checkNotNull(sone, "sone must not be null");
446 /* verify that all posts are from the same Sone. */
447 for (PostReply postReply : postReplies) {
448 if (!sone.equals(postReply.getSone())) {
449 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
453 lock.writeLock().lock();
455 /* remove all post replies of the Sone. */
456 for (PostReply postReply : getRepliesFrom(sone.getId())) {
457 removePostReply(postReply);
459 for (PostReply postReply : postReplies) {
460 allPostReplies.put(postReply.getId(), postReply);
461 sonePostReplies.put(postReply.getSone().getId(), postReply);
462 this.postReplies.put(postReply.getPostId(), postReply);
465 lock.writeLock().unlock();
470 public void removePostReply(PostReply postReply) {
471 lock.writeLock().lock();
473 allPostReplies.remove(postReply.getId());
474 postReplies.remove(postReply.getPostId(), postReply);
476 lock.writeLock().unlock();
481 public void removePostReplies(Sone sone) {
482 checkNotNull(sone, "sone must not be null");
484 lock.writeLock().lock();
486 for (PostReply postReply : sone.getReplies()) {
487 removePostReply(postReply);
490 lock.writeLock().unlock();
495 // ALBUMPROVDER METHODS
499 public Optional<Album> getAlbum(String albumId) {
500 lock.readLock().lock();
502 return fromNullable(allAlbums.get(albumId));
504 lock.readLock().unlock();
509 public List<Album> getAlbums(Album parent) {
510 lock.readLock().lock();
512 return from(albumChildren.get(parent.getId())).transformAndConcat(getAlbum()).toList();
514 lock.readLock().unlock();
519 public void moveUp(Album album) {
520 lock.writeLock().lock();
522 List<String> albums = albumChildren.get(album.getParent().getId());
523 int currentIndex = albums.indexOf(album.getId());
524 if (currentIndex == 0) {
527 albums.remove(album.getId());
528 albums.add(currentIndex - 1, album.getId());
530 lock.writeLock().unlock();
535 public void moveDown(Album album) {
536 lock.writeLock().lock();
538 List<String> albums = albumChildren.get(album.getParent().getId());
539 int currentIndex = albums.indexOf(album.getId());
540 if (currentIndex == (albums.size() - 1)) {
543 albums.remove(album.getId());
544 albums.add(currentIndex + 1, album.getId());
546 lock.writeLock().unlock();
551 // ALBUMSTORE METHODS
555 public void storeAlbum(Album album) {
556 lock.writeLock().lock();
558 allAlbums.put(album.getId(), album);
559 if (!album.isRoot()) {
560 albumChildren.put(album.getParent().getId(), album.getId());
563 lock.writeLock().unlock();
568 public void removeAlbum(Album album) {
569 lock.writeLock().lock();
571 allAlbums.remove(album.getId());
572 albumChildren.remove(album.getParent().getId(), album.getId());
574 lock.writeLock().unlock();
579 // IMAGEPROVIDER METHODS
583 public Optional<Image> getImage(String imageId) {
584 lock.readLock().lock();
586 return fromNullable(allImages.get(imageId));
588 lock.readLock().unlock();
593 public List<Image> getImages(Album parent) {
594 lock.readLock().lock();
596 return from(albumImages.get(parent.getId())).transformAndConcat(getImage()).toList();
598 lock.readLock().unlock();
603 public void moveUp(Image image) {
604 lock.writeLock().lock();
606 List<String> images = albumImages.get(image.getAlbum().getId());
607 int currentIndex = images.indexOf(image.getId());
608 if (currentIndex == 0) {
611 images.remove(image.getId());
612 images.add(currentIndex - 1, image.getId());
614 lock.writeLock().unlock();
619 public void moveDown(Image image) {
620 lock.writeLock().lock();
622 List<String> images = albumChildren.get(image.getAlbum().getId());
623 int currentIndex = images.indexOf(image.getId());
624 if (currentIndex == (images.size() - 1)) {
627 images.remove(image.getId());
628 images.add(currentIndex + 1, image.getId());
630 lock.writeLock().unlock();
635 // IMAGESTORE METHODS
639 public void storeImage(Image image) {
640 lock.writeLock().lock();
642 allImages.put(image.getId(), image);
643 albumImages.put(image.getAlbum().getId(), image.getId());
645 lock.writeLock().unlock();
650 public void removeImage(Image image) {
651 lock.writeLock().lock();
653 allImages.remove(image.getId());
654 albumImages.remove(image.getAlbum().getId(), image.getId());
656 lock.writeLock().unlock();
661 // PACKAGE-PRIVATE METHODS
665 * Returns whether the given post is known.
669 * @return {@code true} if the post is known, {@code false} otherwise
671 boolean isPostKnown(Post post) {
672 lock.readLock().lock();
674 return knownPosts.contains(post.getId());
676 lock.readLock().unlock();
681 * Sets whether the given post is known.
686 * {@code true} if the post is known, {@code false} otherwise
688 void setPostKnown(Post post, boolean known) {
689 lock.writeLock().lock();
692 knownPosts.add(post.getId());
694 knownPosts.remove(post.getId());
697 lock.writeLock().unlock();
705 /** Loads the known posts. */
706 private void loadKnownPosts() {
707 lock.writeLock().lock();
711 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
712 if (knownPostId == null) {
715 knownPosts.add(knownPostId);
718 lock.writeLock().unlock();
723 * Saves the known posts to the configuration.
725 * @throws DatabaseException
726 * if a configuration error occurs
728 private void saveKnownPosts() throws DatabaseException {
729 lock.readLock().lock();
732 for (String knownPostId : knownPosts) {
733 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
735 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
736 } catch (ConfigurationException ce1) {
737 throw new DatabaseException("Could not save database.", ce1);
739 lock.readLock().unlock();
744 * Returns all replies by the given Sone.
748 * @return The post replies of the Sone, sorted by time (newest first)
750 private Collection<PostReply> getRepliesFrom(String id) {
751 lock.readLock().lock();
753 if (sonePostReplies.containsKey(id)) {
754 return Collections.unmodifiableCollection(sonePostReplies.get(id));
756 return Collections.emptySet();
758 lock.readLock().unlock();
762 /** Loads the known post replies. */
763 private void loadKnownPostReplies() {
764 lock.writeLock().lock();
766 int replyCounter = 0;
768 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
769 if (knownReplyId == null) {
772 knownPostReplies.add(knownReplyId);
775 lock.writeLock().unlock();
780 * Saves the known post replies to the configuration.
782 * @throws DatabaseException
783 * if a configuration error occurs
785 private void saveKnownPostReplies() throws DatabaseException {
786 lock.readLock().lock();
788 int replyCounter = 0;
789 for (String knownReplyId : knownPostReplies) {
790 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
792 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
793 } catch (ConfigurationException ce1) {
794 throw new DatabaseException("Could not save database.", ce1);
796 lock.readLock().unlock();
800 private Function<String, Iterable<Album>> getAlbum() {
801 return new Function<String, Iterable<Album>>() {
803 public Iterable<Album> apply(String input) {
804 return (input == null) ? Collections.<Album>emptyList() : getAlbum(input).asSet();
809 private Function<String, Iterable<Image>> getImage() {
810 return new Function<String, Iterable<Image>>() {
812 public Iterable<Image> apply(String input) {
813 return (input == null) ? Collections.<Image>emptyList() : getImage(input).asSet();