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 Optional<Sone> getSone(String soneId) {
177 lock.readLock().lock();
179 return fromNullable(sones.get(soneId));
181 lock.readLock().unlock();
186 public Collection<Sone> getSones() {
187 lock.readLock().lock();
189 return Collections.unmodifiableCollection(sones.values());
191 lock.readLock().unlock();
196 public Collection<Sone> getLocalSones() {
197 lock.readLock().lock();
199 return from(getSones()).filter(LOCAL_SONE_FILTER).toSet();
201 lock.readLock().unlock();
206 public Collection<Sone> getRemoteSones() {
207 lock.readLock().lock();
209 return from(getSones()).filter(not(LOCAL_SONE_FILTER)).toSet();
211 lock.readLock().unlock();
216 public SoneBuilder newSoneBuilder() {
217 return new DefaultSoneBuilder(this) {
219 public Sone build(Optional<SoneCreated> soneCreated) throws IllegalStateException {
220 Sone sone = super.build(soneCreated);
221 sones.put(sone.getId(), sone);
228 // POSTPROVIDER METHODS
232 public Optional<Post> getPost(String postId) {
233 lock.readLock().lock();
235 return fromNullable(allPosts.get(postId));
237 lock.readLock().unlock();
242 public Collection<Post> getPosts(String soneId) {
243 lock.readLock().lock();
245 return new HashSet<Post>(sonePosts.get(soneId));
247 lock.readLock().unlock();
252 public Collection<Post> getDirectedPosts(String recipientId) {
253 lock.readLock().lock();
255 Collection<Post> posts = recipientPosts.get(recipientId);
256 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
258 lock.readLock().unlock();
267 public void storePost(Post post) {
268 checkNotNull(post, "post must not be null");
269 lock.writeLock().lock();
271 allPosts.put(post.getId(), post);
272 sonePosts.put(post.getSone().getId(), post);
273 if (post.getRecipientId().isPresent()) {
274 recipientPosts.put(post.getRecipientId().get(), post);
277 lock.writeLock().unlock();
282 public void removePost(Post post) {
283 checkNotNull(post, "post must not be null");
284 lock.writeLock().lock();
286 allPosts.remove(post.getId());
287 sonePosts.remove(post.getSone().getId(), post);
288 if (post.getRecipientId().isPresent()) {
289 recipientPosts.remove(post.getRecipientId().get(), post);
291 post.getSone().removePost(post);
293 lock.writeLock().unlock();
298 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
299 checkNotNull(sone, "sone must not be null");
300 /* verify that all posts are from the same Sone. */
301 for (Post post : posts) {
302 if (!sone.equals(post.getSone())) {
303 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
307 lock.writeLock().lock();
309 /* remove all posts by the Sone. */
310 sonePosts.removeAll(sone.getId());
311 for (Post post : posts) {
312 allPosts.remove(post.getId());
313 if (post.getRecipientId().isPresent()) {
314 recipientPosts.remove(post.getRecipientId().get(), post);
319 sonePosts.putAll(sone.getId(), posts);
320 for (Post post : posts) {
321 allPosts.put(post.getId(), post);
322 if (post.getRecipientId().isPresent()) {
323 recipientPosts.put(post.getRecipientId().get(), post);
327 lock.writeLock().unlock();
332 public void removePosts(Sone sone) {
333 checkNotNull(sone, "sone must not be null");
334 lock.writeLock().lock();
336 /* remove all posts by the Sone. */
337 sonePosts.removeAll(sone.getId());
338 for (Post post : sone.getPosts()) {
339 allPosts.remove(post.getId());
340 if (post.getRecipientId().isPresent()) {
341 recipientPosts.remove(post.getRecipientId().get(), post);
345 lock.writeLock().unlock();
350 // POSTREPLYPROVIDER METHODS
354 public Optional<PostReply> getPostReply(String id) {
355 lock.readLock().lock();
357 return fromNullable(allPostReplies.get(id));
359 lock.readLock().unlock();
364 public List<PostReply> getReplies(String postId) {
365 lock.readLock().lock();
367 if (!postReplies.containsKey(postId)) {
370 return new ArrayList<PostReply>(postReplies.get(postId));
372 lock.readLock().unlock();
377 // POSTREPLYSTORE METHODS
381 * Returns whether the given post reply is known.
385 * @return {@code true} if the given post reply is known, {@code false}
388 public boolean isPostReplyKnown(PostReply postReply) {
389 lock.readLock().lock();
391 return knownPostReplies.contains(postReply.getId());
393 lock.readLock().unlock();
398 public void setPostReplyKnown(PostReply postReply) {
399 lock.writeLock().lock();
401 knownPostReplies.add(postReply.getId());
403 lock.writeLock().unlock();
408 public void storePostReply(PostReply postReply) {
409 lock.writeLock().lock();
411 allPostReplies.put(postReply.getId(), postReply);
412 postReplies.put(postReply.getPostId(), postReply);
414 lock.writeLock().unlock();
419 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
420 checkNotNull(sone, "sone must not be null");
421 /* verify that all posts are from the same Sone. */
422 for (PostReply postReply : postReplies) {
423 if (!sone.equals(postReply.getSone())) {
424 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
428 lock.writeLock().lock();
430 /* remove all post replies of the Sone. */
431 for (PostReply postReply : getRepliesFrom(sone.getId())) {
432 removePostReply(postReply);
434 for (PostReply postReply : postReplies) {
435 allPostReplies.put(postReply.getId(), postReply);
436 sonePostReplies.put(postReply.getSone().getId(), postReply);
437 this.postReplies.put(postReply.getPostId(), postReply);
440 lock.writeLock().unlock();
445 public void removePostReply(PostReply postReply) {
446 lock.writeLock().lock();
448 allPostReplies.remove(postReply.getId());
449 postReplies.remove(postReply.getPostId(), postReply);
451 lock.writeLock().unlock();
456 public void removePostReplies(Sone sone) {
457 checkNotNull(sone, "sone must not be null");
459 lock.writeLock().lock();
461 for (PostReply postReply : sone.getReplies()) {
462 removePostReply(postReply);
465 lock.writeLock().unlock();
470 // ALBUMPROVDER METHODS
474 public Optional<Album> getAlbum(String albumId) {
475 lock.readLock().lock();
477 return fromNullable(allAlbums.get(albumId));
479 lock.readLock().unlock();
484 public List<Album> getAlbums(Album parent) {
485 lock.readLock().lock();
487 return from(albumChildren.get(parent.getId())).transformAndConcat(getAlbum()).toList();
489 lock.readLock().unlock();
494 public void moveUp(Album album) {
495 lock.writeLock().lock();
497 List<String> albums = albumChildren.get(album.getParent().getId());
498 int currentIndex = albums.indexOf(album.getId());
499 if (currentIndex == 0) {
502 albums.remove(album.getId());
503 albums.add(currentIndex - 1, album.getId());
505 lock.writeLock().unlock();
510 public void moveDown(Album album) {
511 lock.writeLock().lock();
513 List<String> albums = albumChildren.get(album.getParent().getId());
514 int currentIndex = albums.indexOf(album.getId());
515 if (currentIndex == (albums.size() - 1)) {
518 albums.remove(album.getId());
519 albums.add(currentIndex + 1, album.getId());
521 lock.writeLock().unlock();
526 // ALBUMSTORE METHODS
530 public void storeAlbum(Album album) {
531 lock.writeLock().lock();
533 allAlbums.put(album.getId(), album);
534 albumChildren.put(album.getParent().getId(), album.getId());
536 lock.writeLock().unlock();
541 public void removeAlbum(Album album) {
542 lock.writeLock().lock();
544 allAlbums.remove(album.getId());
545 albumChildren.remove(album.getParent().getId(), album.getId());
547 lock.writeLock().unlock();
552 // IMAGEPROVIDER METHODS
556 public Optional<Image> getImage(String imageId) {
557 lock.readLock().lock();
559 return fromNullable(allImages.get(imageId));
561 lock.readLock().unlock();
566 public List<Image> getImages(Album parent) {
567 lock.readLock().lock();
569 return from(albumImages.get(parent.getId())).transformAndConcat(getImage()).toList();
571 lock.readLock().unlock();
576 public void moveUp(Image image) {
577 lock.writeLock().lock();
579 List<String> images = albumImages.get(image.getAlbum().getId());
580 int currentIndex = images.indexOf(image.getId());
581 if (currentIndex == 0) {
584 images.remove(image.getId());
585 images.add(currentIndex - 1, image.getId());
587 lock.writeLock().unlock();
592 public void moveDown(Image image) {
593 lock.writeLock().lock();
595 List<String> images = albumChildren.get(image.getAlbum().getId());
596 int currentIndex = images.indexOf(image.getId());
597 if (currentIndex == (images.size() - 1)) {
600 images.remove(image.getId());
601 images.add(currentIndex + 1, image.getId());
603 lock.writeLock().unlock();
608 // IMAGESTORE METHODS
612 public void storeImage(Image image) {
613 lock.writeLock().lock();
615 allImages.put(image.getId(), image);
616 albumImages.put(image.getAlbum().getId(), image.getId());
618 lock.writeLock().unlock();
623 public void removeImage(Image image) {
624 lock.writeLock().lock();
626 allImages.remove(image.getId());
627 albumImages.remove(image.getAlbum().getId(), image.getId());
629 lock.writeLock().unlock();
634 // PACKAGE-PRIVATE METHODS
638 * Returns whether the given post is known.
642 * @return {@code true} if the post is known, {@code false} otherwise
644 boolean isPostKnown(Post post) {
645 lock.readLock().lock();
647 return knownPosts.contains(post.getId());
649 lock.readLock().unlock();
654 * Sets whether the given post is known.
659 * {@code true} if the post is known, {@code false} otherwise
661 void setPostKnown(Post post, boolean known) {
662 lock.writeLock().lock();
665 knownPosts.add(post.getId());
667 knownPosts.remove(post.getId());
670 lock.writeLock().unlock();
678 /** Loads the known posts. */
679 private void loadKnownPosts() {
680 lock.writeLock().lock();
684 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
685 if (knownPostId == null) {
688 knownPosts.add(knownPostId);
691 lock.writeLock().unlock();
696 * Saves the known posts to the configuration.
698 * @throws DatabaseException
699 * if a configuration error occurs
701 private void saveKnownPosts() throws DatabaseException {
702 lock.readLock().lock();
705 for (String knownPostId : knownPosts) {
706 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
708 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
709 } catch (ConfigurationException ce1) {
710 throw new DatabaseException("Could not save database.", ce1);
712 lock.readLock().unlock();
717 * Returns all replies by the given Sone.
721 * @return The post replies of the Sone, sorted by time (newest first)
723 private Collection<PostReply> getRepliesFrom(String id) {
724 lock.readLock().lock();
726 if (sonePostReplies.containsKey(id)) {
727 return Collections.unmodifiableCollection(sonePostReplies.get(id));
729 return Collections.emptySet();
731 lock.readLock().unlock();
735 /** Loads the known post replies. */
736 private void loadKnownPostReplies() {
737 lock.writeLock().lock();
739 int replyCounter = 0;
741 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
742 if (knownReplyId == null) {
745 knownPostReplies.add(knownReplyId);
748 lock.writeLock().unlock();
753 * Saves the known post replies to the configuration.
755 * @throws DatabaseException
756 * if a configuration error occurs
758 private void saveKnownPostReplies() throws DatabaseException {
759 lock.readLock().lock();
761 int replyCounter = 0;
762 for (String knownReplyId : knownPostReplies) {
763 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
765 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
766 } catch (ConfigurationException ce1) {
767 throw new DatabaseException("Could not save database.", ce1);
769 lock.readLock().unlock();
773 private Function<String, Iterable<Album>> getAlbum() {
774 return new Function<String, Iterable<Album>>() {
776 public Iterable<Album> apply(String input) {
777 return (input == null) ? Collections.<Album>emptyList() : getAlbum(input).asSet();
782 private Function<String, Iterable<Image>> getImage() {
783 return new Function<String, Iterable<Image>>() {
785 public Iterable<Image> apply(String input) {
786 return (input == null) ? Collections.<Image>emptyList() : getImage(input).asSet();