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 Optional<Post> getPost(String postId) {
248 lock.readLock().lock();
250 return fromNullable(allPosts.get(postId));
252 lock.readLock().unlock();
257 public Collection<Post> getPosts(String soneId) {
258 lock.readLock().lock();
260 return new HashSet<Post>(sonePosts.get(soneId));
262 lock.readLock().unlock();
267 public Collection<Post> getDirectedPosts(String recipientId) {
268 lock.readLock().lock();
270 Collection<Post> posts = recipientPosts.get(recipientId);
271 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
273 lock.readLock().unlock();
282 public void storePost(Post post) {
283 checkNotNull(post, "post must not be null");
284 lock.writeLock().lock();
286 allPosts.put(post.getId(), post);
287 sonePosts.put(post.getSone().getId(), post);
288 if (post.getRecipientId().isPresent()) {
289 recipientPosts.put(post.getRecipientId().get(), post);
292 lock.writeLock().unlock();
297 public void removePost(Post post) {
298 checkNotNull(post, "post must not be null");
299 lock.writeLock().lock();
301 allPosts.remove(post.getId());
302 sonePosts.remove(post.getSone().getId(), post);
303 if (post.getRecipientId().isPresent()) {
304 recipientPosts.remove(post.getRecipientId().get(), post);
306 post.getSone().removePost(post);
308 lock.writeLock().unlock();
313 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
314 checkNotNull(sone, "sone must not be null");
315 /* verify that all posts are from the same Sone. */
316 for (Post post : posts) {
317 if (!sone.equals(post.getSone())) {
318 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
322 lock.writeLock().lock();
324 /* remove all posts by the Sone. */
325 sonePosts.removeAll(sone.getId());
326 for (Post post : posts) {
327 allPosts.remove(post.getId());
328 if (post.getRecipientId().isPresent()) {
329 recipientPosts.remove(post.getRecipientId().get(), post);
334 sonePosts.putAll(sone.getId(), posts);
335 for (Post post : posts) {
336 allPosts.put(post.getId(), post);
337 if (post.getRecipientId().isPresent()) {
338 recipientPosts.put(post.getRecipientId().get(), post);
342 lock.writeLock().unlock();
347 public void removePosts(Sone sone) {
348 checkNotNull(sone, "sone must not be null");
349 lock.writeLock().lock();
351 /* remove all posts by the Sone. */
352 sonePosts.removeAll(sone.getId());
353 for (Post post : sone.getPosts()) {
354 allPosts.remove(post.getId());
355 if (post.getRecipientId().isPresent()) {
356 recipientPosts.remove(post.getRecipientId().get(), post);
360 lock.writeLock().unlock();
365 // POSTREPLYPROVIDER METHODS
369 public Optional<PostReply> getPostReply(String id) {
370 lock.readLock().lock();
372 return fromNullable(allPostReplies.get(id));
374 lock.readLock().unlock();
379 public List<PostReply> getReplies(String postId) {
380 lock.readLock().lock();
382 if (!postReplies.containsKey(postId)) {
385 return new ArrayList<PostReply>(postReplies.get(postId));
387 lock.readLock().unlock();
392 // POSTREPLYSTORE METHODS
396 * Returns whether the given post reply is known.
400 * @return {@code true} if the given post reply is known, {@code false}
403 public boolean isPostReplyKnown(PostReply postReply) {
404 lock.readLock().lock();
406 return knownPostReplies.contains(postReply.getId());
408 lock.readLock().unlock();
413 public void setPostReplyKnown(PostReply postReply) {
414 lock.writeLock().lock();
416 knownPostReplies.add(postReply.getId());
418 lock.writeLock().unlock();
423 public void storePostReply(PostReply postReply) {
424 lock.writeLock().lock();
426 allPostReplies.put(postReply.getId(), postReply);
427 postReplies.put(postReply.getPostId(), postReply);
429 lock.writeLock().unlock();
434 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
435 checkNotNull(sone, "sone must not be null");
436 /* verify that all posts are from the same Sone. */
437 for (PostReply postReply : postReplies) {
438 if (!sone.equals(postReply.getSone())) {
439 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
443 lock.writeLock().lock();
445 /* remove all post replies of the Sone. */
446 for (PostReply postReply : getRepliesFrom(sone.getId())) {
447 removePostReply(postReply);
449 for (PostReply postReply : postReplies) {
450 allPostReplies.put(postReply.getId(), postReply);
451 sonePostReplies.put(postReply.getSone().getId(), postReply);
452 this.postReplies.put(postReply.getPostId(), postReply);
455 lock.writeLock().unlock();
460 public void removePostReply(PostReply postReply) {
461 lock.writeLock().lock();
463 allPostReplies.remove(postReply.getId());
464 postReplies.remove(postReply.getPostId(), postReply);
466 lock.writeLock().unlock();
471 public void removePostReplies(Sone sone) {
472 checkNotNull(sone, "sone must not be null");
474 lock.writeLock().lock();
476 for (PostReply postReply : sone.getReplies()) {
477 removePostReply(postReply);
480 lock.writeLock().unlock();
485 // ALBUMPROVDER METHODS
489 public Optional<Album> getAlbum(String albumId) {
490 lock.readLock().lock();
492 return fromNullable(allAlbums.get(albumId));
494 lock.readLock().unlock();
499 public List<Album> getAlbums(Album parent) {
500 lock.readLock().lock();
502 return from(albumChildren.get(parent.getId())).transformAndConcat(getAlbum()).toList();
504 lock.readLock().unlock();
509 public void moveUp(Album album) {
510 lock.writeLock().lock();
512 List<String> albums = albumChildren.get(album.getParent().getId());
513 int currentIndex = albums.indexOf(album.getId());
514 if (currentIndex == 0) {
517 albums.remove(album.getId());
518 albums.add(currentIndex - 1, album.getId());
520 lock.writeLock().unlock();
525 public void moveDown(Album album) {
526 lock.writeLock().lock();
528 List<String> albums = albumChildren.get(album.getParent().getId());
529 int currentIndex = albums.indexOf(album.getId());
530 if (currentIndex == (albums.size() - 1)) {
533 albums.remove(album.getId());
534 albums.add(currentIndex + 1, album.getId());
536 lock.writeLock().unlock();
541 // ALBUMSTORE METHODS
545 public void storeAlbum(Album album) {
546 lock.writeLock().lock();
548 allAlbums.put(album.getId(), album);
549 if (!album.isRoot()) {
550 albumChildren.put(album.getParent().getId(), album.getId());
553 lock.writeLock().unlock();
558 public void removeAlbum(Album album) {
559 lock.writeLock().lock();
561 allAlbums.remove(album.getId());
562 albumChildren.remove(album.getParent().getId(), album.getId());
564 lock.writeLock().unlock();
569 // IMAGEPROVIDER METHODS
573 public Optional<Image> getImage(String imageId) {
574 lock.readLock().lock();
576 return fromNullable(allImages.get(imageId));
578 lock.readLock().unlock();
583 public List<Image> getImages(Album parent) {
584 lock.readLock().lock();
586 return from(albumImages.get(parent.getId())).transformAndConcat(getImage()).toList();
588 lock.readLock().unlock();
593 public void moveUp(Image image) {
594 lock.writeLock().lock();
596 List<String> images = albumImages.get(image.getAlbum().getId());
597 int currentIndex = images.indexOf(image.getId());
598 if (currentIndex == 0) {
601 images.remove(image.getId());
602 images.add(currentIndex - 1, image.getId());
604 lock.writeLock().unlock();
609 public void moveDown(Image image) {
610 lock.writeLock().lock();
612 List<String> images = albumChildren.get(image.getAlbum().getId());
613 int currentIndex = images.indexOf(image.getId());
614 if (currentIndex == (images.size() - 1)) {
617 images.remove(image.getId());
618 images.add(currentIndex + 1, image.getId());
620 lock.writeLock().unlock();
625 // IMAGESTORE METHODS
629 public void storeImage(Image image) {
630 lock.writeLock().lock();
632 allImages.put(image.getId(), image);
633 albumImages.put(image.getAlbum().getId(), image.getId());
635 lock.writeLock().unlock();
640 public void removeImage(Image image) {
641 lock.writeLock().lock();
643 allImages.remove(image.getId());
644 albumImages.remove(image.getAlbum().getId(), image.getId());
646 lock.writeLock().unlock();
651 // PACKAGE-PRIVATE METHODS
655 * Returns whether the given post is known.
659 * @return {@code true} if the post is known, {@code false} otherwise
661 boolean isPostKnown(Post post) {
662 lock.readLock().lock();
664 return knownPosts.contains(post.getId());
666 lock.readLock().unlock();
671 * Sets whether the given post is known.
676 * {@code true} if the post is known, {@code false} otherwise
678 void setPostKnown(Post post, boolean known) {
679 lock.writeLock().lock();
682 knownPosts.add(post.getId());
684 knownPosts.remove(post.getId());
687 lock.writeLock().unlock();
695 /** Loads the known posts. */
696 private void loadKnownPosts() {
697 lock.writeLock().lock();
701 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
702 if (knownPostId == null) {
705 knownPosts.add(knownPostId);
708 lock.writeLock().unlock();
713 * Saves the known posts to the configuration.
715 * @throws DatabaseException
716 * if a configuration error occurs
718 private void saveKnownPosts() throws DatabaseException {
719 lock.readLock().lock();
722 for (String knownPostId : knownPosts) {
723 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
725 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
726 } catch (ConfigurationException ce1) {
727 throw new DatabaseException("Could not save database.", ce1);
729 lock.readLock().unlock();
734 * Returns all replies by the given Sone.
738 * @return The post replies of the Sone, sorted by time (newest first)
740 private Collection<PostReply> getRepliesFrom(String id) {
741 lock.readLock().lock();
743 if (sonePostReplies.containsKey(id)) {
744 return Collections.unmodifiableCollection(sonePostReplies.get(id));
746 return Collections.emptySet();
748 lock.readLock().unlock();
752 /** Loads the known post replies. */
753 private void loadKnownPostReplies() {
754 lock.writeLock().lock();
756 int replyCounter = 0;
758 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
759 if (knownReplyId == null) {
762 knownPostReplies.add(knownReplyId);
765 lock.writeLock().unlock();
770 * Saves the known post replies to the configuration.
772 * @throws DatabaseException
773 * if a configuration error occurs
775 private void saveKnownPostReplies() throws DatabaseException {
776 lock.readLock().lock();
778 int replyCounter = 0;
779 for (String knownReplyId : knownPostReplies) {
780 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
782 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
783 } catch (ConfigurationException ce1) {
784 throw new DatabaseException("Could not save database.", ce1);
786 lock.readLock().unlock();
790 private Function<String, Iterable<Album>> getAlbum() {
791 return new Function<String, Iterable<Album>>() {
793 public Iterable<Album> apply(String input) {
794 return (input == null) ? Collections.<Album>emptyList() : getAlbum(input).asSet();
799 private Function<String, Iterable<Image>> getImage() {
800 return new Function<String, Iterable<Image>>() {
802 public Iterable<Image> apply(String input) {
803 return (input == null) ? Collections.<Image>emptyList() : getImage(input).asSet();