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 java.util.logging.Logger.getLogger;
26 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.Collections;
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;
39 import java.util.logging.Level;
40 import java.util.logging.Logger;
42 import net.pterodactylus.sone.data.Album;
43 import net.pterodactylus.sone.data.Image;
44 import net.pterodactylus.sone.data.Post;
45 import net.pterodactylus.sone.data.PostReply;
46 import net.pterodactylus.sone.data.Sone;
47 import net.pterodactylus.sone.data.impl.DefaultSoneBuilder;
48 import net.pterodactylus.sone.database.Database;
49 import net.pterodactylus.sone.database.DatabaseException;
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.SetMultimap;
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 Database} implementation.
70 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
72 public class MemoryDatabase extends AbstractService implements Database {
74 private static final Logger logger = getLogger(MemoryDatabase.class.getName());
77 private final ReadWriteLock lock = new ReentrantReadWriteLock();
79 /** The configuration. */
80 private final Configuration configuration;
82 private final Map<String, Identity> identities = Maps.newHashMap();
83 private final Map<String, Sone> sones = new HashMap<String, Sone>();
84 private final MemoryPostDatabase memoryPostDatabase;
86 /** All post replies by their ID. */
87 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
88 private final SetMultimap<String, String> likedPostRepliesBySone = HashMultimap.create();
89 private final SetMultimap<String, String> postReplyLikingSones = HashMultimap.create();
91 /** Replies sorted by Sone. */
92 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
95 public int compare(String leftString, String rightString) {
96 return leftString.compareTo(rightString);
98 }, PostReply.TIME_COMPARATOR);
100 /** Replies by post. */
101 private final SortedSetMultimap<String, PostReply> postReplies = TreeMultimap.create(new Comparator<String>() {
104 public int compare(String leftString, String rightString) {
105 return leftString.compareTo(rightString);
107 }, PostReply.TIME_COMPARATOR);
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 ListMultimap<String, String> albumChildren = ArrayListMultimap.create();
114 private final ListMultimap<String, String> albumImages = ArrayListMultimap.create();
116 private final Map<String, Image> allImages = new HashMap<String, Image>();
119 * Creates a new memory database.
121 * @param configuration
122 * The configuration for loading and saving elements
125 public MemoryDatabase(Configuration configuration) {
126 this.configuration = configuration;
127 memoryPostDatabase = new MemoryPostDatabase(this, lock, configuration);
135 protected void doStart() {
136 memoryPostDatabase.start();
137 loadKnownPostReplies();
142 protected void doStop() {
144 memoryPostDatabase.stop();
145 } catch (DatabaseException de1) {
146 logger.log(Level.WARNING, "Could not stop post database!", de1);
152 public Optional<Identity> getIdentity(String identityId) {
153 lock.readLock().lock();
155 return fromNullable(identities.get(identityId));
157 lock.readLock().unlock();
162 public void storeIdentity(Identity identitiy) {
163 lock.writeLock().lock();
165 identities.put(identitiy.getId(), identitiy);
167 lock.writeLock().unlock();
172 public Function<String, Optional<Sone>> getSone() {
173 return new Function<String, Optional<Sone>>() {
175 public Optional<Sone> apply(String soneId) {
176 return (soneId == null) ? Optional.<Sone>absent() : getSone(soneId);
182 public Optional<Sone> getSone(String soneId) {
183 lock.readLock().lock();
185 return fromNullable(sones.get(soneId));
187 lock.readLock().unlock();
192 public Collection<Sone> getSones() {
193 lock.readLock().lock();
195 return Collections.unmodifiableCollection(sones.values());
197 lock.readLock().unlock();
202 public Collection<Sone> getLocalSones() {
203 lock.readLock().lock();
205 return from(getSones()).filter(LOCAL_SONE_FILTER).toSet();
207 lock.readLock().unlock();
212 public Collection<Sone> getRemoteSones() {
213 lock.readLock().lock();
215 return from(getSones()).filter(not(LOCAL_SONE_FILTER)).toSet();
217 lock.readLock().unlock();
222 public void storeSone(Sone sone) {
223 lock.writeLock().lock();
225 sones.put(sone.getId(), sone);
227 lock.writeLock().unlock();
232 public SoneBuilder newSoneBuilder() {
233 return new DefaultSoneBuilder(this) {
235 public Sone build(Optional<SoneCreated> soneCreated) throws IllegalStateException {
236 Sone sone = super.build(soneCreated);
237 lock.writeLock().lock();
239 sones.put(sone.getId(), sone);
241 lock.writeLock().unlock();
249 // POSTPROVIDER METHODS
253 public Function<String, Optional<Post>> getPost() {
254 return memoryPostDatabase.getPost();
258 public Optional<Post> getPost(String postId) {
259 return memoryPostDatabase.getPost(postId);
263 public Collection<Post> getPosts(String soneId) {
264 return memoryPostDatabase.getPosts(soneId);
268 public Collection<Post> getDirectedPosts(String recipientId) {
269 return memoryPostDatabase.getDirectedPosts(recipientId);
273 * Returns whether the given post is known.
277 * @return {@code true} if the post is known, {@code false} otherwise
280 public boolean isPostKnown(Post post) {
281 return memoryPostDatabase.isPostKnown(post);
285 * Sets whether the given post is known.
291 public void setPostKnown(Post post) {
292 memoryPostDatabase.setPostKnown(post);
296 public void likePost(Post post, Sone localSone) {
297 memoryPostDatabase.likePost(post, localSone);
301 public void unlikePost(Post post, Sone localSone) {
302 memoryPostDatabase.unlikePost(post, localSone);
305 public boolean isLiked(Post post, Sone sone) {
306 return memoryPostDatabase.isLiked(post, sone);
310 public Set<Sone> getLikes(Post post) {
311 return memoryPostDatabase.getLikes(post);
319 public void storePost(Post post) {
320 memoryPostDatabase.storePost(post);
324 public void removePost(Post post) {
325 memoryPostDatabase.removePost(post);
329 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
330 /* verify that all posts are from the same Sone. */
332 memoryPostDatabase.storePosts(sone, posts);
336 public void removePosts(Sone sone) {
337 memoryPostDatabase.removePosts(sone);
341 // POSTREPLYPROVIDER METHODS
345 public Optional<PostReply> getPostReply(String id) {
346 lock.readLock().lock();
348 return fromNullable(allPostReplies.get(id));
350 lock.readLock().unlock();
355 public List<PostReply> getReplies(String postId) {
356 lock.readLock().lock();
358 if (!postReplies.containsKey(postId)) {
361 return new ArrayList<PostReply>(postReplies.get(postId));
363 lock.readLock().unlock();
368 public void likePostReply(PostReply postReply, Sone localSone) {
369 lock.writeLock().lock();
371 likedPostRepliesBySone.put(localSone.getId(), postReply.getId());
372 postReplyLikingSones.put(postReply.getId(), localSone.getId());
374 lock.writeLock().unlock();
379 public void unlikePostReply(PostReply postReply, Sone localSone) {
380 lock.writeLock().lock();
382 likedPostRepliesBySone.remove(localSone.getId(), postReply.getId());
383 postReplyLikingSones.remove(postReply.getId(), localSone.getId());
385 lock.writeLock().unlock();
390 public boolean isLiked(PostReply postReply, Sone sone) {
391 lock.readLock().lock();
393 return postReplyLikingSones.containsEntry(postReply.getId(), sone.getId());
395 lock.readLock().unlock();
400 public Set<Sone> getLikes(PostReply postReply) {
401 lock.readLock().lock();
403 return from(postReplyLikingSones.get(postReply.getId())).transform(getSone()).transformAndConcat(this.<Sone>unwrap()).toSet();
405 lock.readLock().unlock();
410 // POSTREPLYSTORE METHODS
414 * Returns whether the given post reply is known.
418 * @return {@code true} if the given post reply is known, {@code false}
421 public boolean isPostReplyKnown(PostReply postReply) {
422 lock.readLock().lock();
424 return knownPostReplies.contains(postReply.getId());
426 lock.readLock().unlock();
431 public void setPostReplyKnown(PostReply postReply) {
432 lock.writeLock().lock();
434 knownPostReplies.add(postReply.getId());
436 lock.writeLock().unlock();
441 public void storePostReply(PostReply postReply) {
442 lock.writeLock().lock();
444 allPostReplies.put(postReply.getId(), postReply);
445 postReplies.put(postReply.getPostId(), postReply);
447 lock.writeLock().unlock();
452 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
453 checkNotNull(sone, "sone must not be null");
454 /* verify that all posts are from the same Sone. */
455 for (PostReply postReply : postReplies) {
456 if (!sone.equals(postReply.getSone())) {
457 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
461 lock.writeLock().lock();
463 /* remove all post replies of the Sone. */
464 for (PostReply postReply : getRepliesFrom(sone.getId())) {
465 removePostReply(postReply);
467 for (PostReply postReply : postReplies) {
468 allPostReplies.put(postReply.getId(), postReply);
469 sonePostReplies.put(postReply.getSone().getId(), postReply);
470 this.postReplies.put(postReply.getPostId(), postReply);
473 lock.writeLock().unlock();
478 public void removePostReply(PostReply postReply) {
479 lock.writeLock().lock();
481 allPostReplies.remove(postReply.getId());
482 postReplies.remove(postReply.getPostId(), postReply);
484 lock.writeLock().unlock();
489 public void removePostReplies(Sone sone) {
490 checkNotNull(sone, "sone must not be null");
492 lock.writeLock().lock();
494 for (PostReply postReply : sone.getReplies()) {
495 removePostReply(postReply);
498 lock.writeLock().unlock();
503 // ALBUMPROVDER METHODS
507 public Optional<Album> getAlbum(String albumId) {
508 lock.readLock().lock();
510 return fromNullable(allAlbums.get(albumId));
512 lock.readLock().unlock();
517 public List<Album> getAlbums(Album parent) {
518 lock.readLock().lock();
520 return from(albumChildren.get(parent.getId())).transformAndConcat(getAlbum()).toList();
522 lock.readLock().unlock();
527 public void moveUp(Album album) {
528 lock.writeLock().lock();
530 List<String> albums = albumChildren.get(album.getParent().getId());
531 int currentIndex = albums.indexOf(album.getId());
532 if (currentIndex == 0) {
535 albums.remove(album.getId());
536 albums.add(currentIndex - 1, album.getId());
538 lock.writeLock().unlock();
543 public void moveDown(Album album) {
544 lock.writeLock().lock();
546 List<String> albums = albumChildren.get(album.getParent().getId());
547 int currentIndex = albums.indexOf(album.getId());
548 if (currentIndex == (albums.size() - 1)) {
551 albums.remove(album.getId());
552 albums.add(currentIndex + 1, album.getId());
554 lock.writeLock().unlock();
559 // ALBUMSTORE METHODS
563 public void storeAlbum(Album album) {
564 lock.writeLock().lock();
566 allAlbums.put(album.getId(), album);
567 if (!album.isRoot()) {
568 albumChildren.put(album.getParent().getId(), album.getId());
571 lock.writeLock().unlock();
576 public void removeAlbum(Album album) {
577 lock.writeLock().lock();
579 allAlbums.remove(album.getId());
580 albumChildren.remove(album.getParent().getId(), album.getId());
582 lock.writeLock().unlock();
587 // IMAGEPROVIDER METHODS
591 public Optional<Image> getImage(String imageId) {
592 lock.readLock().lock();
594 return fromNullable(allImages.get(imageId));
596 lock.readLock().unlock();
601 public List<Image> getImages(Album parent) {
602 lock.readLock().lock();
604 return from(albumImages.get(parent.getId())).transformAndConcat(getImage()).toList();
606 lock.readLock().unlock();
611 public void moveUp(Image image) {
612 lock.writeLock().lock();
614 List<String> images = albumImages.get(image.getAlbum().getId());
615 int currentIndex = images.indexOf(image.getId());
616 if (currentIndex == 0) {
619 images.remove(image.getId());
620 images.add(currentIndex - 1, image.getId());
622 lock.writeLock().unlock();
627 public void moveDown(Image image) {
628 lock.writeLock().lock();
630 List<String> images = albumChildren.get(image.getAlbum().getId());
631 int currentIndex = images.indexOf(image.getId());
632 if (currentIndex == (images.size() - 1)) {
635 images.remove(image.getId());
636 images.add(currentIndex + 1, image.getId());
638 lock.writeLock().unlock();
643 // IMAGESTORE METHODS
647 public void storeImage(Image image) {
648 lock.writeLock().lock();
650 allImages.put(image.getId(), image);
651 albumImages.put(image.getAlbum().getId(), image.getId());
653 lock.writeLock().unlock();
658 public void removeImage(Image image) {
659 lock.writeLock().lock();
661 allImages.remove(image.getId());
662 albumImages.remove(image.getAlbum().getId(), image.getId());
664 lock.writeLock().unlock();
673 * Returns all replies by the given Sone.
677 * @return The post replies of the Sone, sorted by time (newest first)
679 private Collection<PostReply> getRepliesFrom(String id) {
680 lock.readLock().lock();
682 if (sonePostReplies.containsKey(id)) {
683 return Collections.unmodifiableCollection(sonePostReplies.get(id));
685 return Collections.emptySet();
687 lock.readLock().unlock();
691 /** Loads the known post replies. */
692 private void loadKnownPostReplies() {
693 lock.writeLock().lock();
695 int replyCounter = 0;
697 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
698 if (knownReplyId == null) {
701 knownPostReplies.add(knownReplyId);
704 lock.writeLock().unlock();
709 * Saves the known post replies to the configuration.
711 * @throws DatabaseException
712 * if a configuration error occurs
714 private void saveKnownPostReplies() throws DatabaseException {
715 lock.readLock().lock();
717 int replyCounter = 0;
718 for (String knownReplyId : knownPostReplies) {
719 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
721 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
722 } catch (ConfigurationException ce1) {
723 throw new DatabaseException("Could not save database.", ce1);
725 lock.readLock().unlock();
729 private Function<String, Iterable<Album>> getAlbum() {
730 return new Function<String, Iterable<Album>>() {
732 public Iterable<Album> apply(String input) {
733 return (input == null) ? Collections.<Album>emptyList() : getAlbum(input).asSet();
738 private Function<String, Iterable<Image>> getImage() {
739 return new Function<String, Iterable<Image>>() {
741 public Iterable<Image> apply(String input) {
742 return (input == null) ? Collections.<Image>emptyList() : getImage(input).asSet();
747 static <T> Function<Optional<T>, Iterable<T>> unwrap() {
748 return new Function<Optional<T>, Iterable<T>>() {
750 public Iterable<T> apply(Optional<T> input) {
751 return (input == null) ? Collections.<T>emptyList() : input.asSet();