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.SetMultimap;
61 import com.google.common.collect.SortedSetMultimap;
62 import com.google.common.collect.TreeMultimap;
63 import com.google.common.util.concurrent.AbstractService;
64 import com.google.inject.Inject;
67 * Memory-based {@link Database} implementation.
69 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
71 public class MemoryDatabase extends AbstractService implements Database {
73 private static final Logger logger = getLogger(MemoryDatabase.class.getName());
76 private final ReadWriteLock lock = new ReentrantReadWriteLock();
78 /** The configuration. */
79 private final Configuration configuration;
81 private final Map<String, Sone> sones = new HashMap<String, Sone>();
82 private final MemoryIdentityDatabase memoryIdentityDatabase;
83 private final MemoryPostDatabase memoryPostDatabase;
85 /** All post replies by their ID. */
86 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
87 private final SetMultimap<String, String> likedPostRepliesBySone = HashMultimap.create();
88 private final SetMultimap<String, String> postReplyLikingSones = HashMultimap.create();
90 /** Replies sorted by Sone. */
91 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
94 public int compare(String leftString, String rightString) {
95 return leftString.compareTo(rightString);
97 }, PostReply.TIME_COMPARATOR);
99 /** Replies by post. */
100 private final SortedSetMultimap<String, PostReply> postReplies = TreeMultimap.create(new Comparator<String>() {
103 public int compare(String leftString, String rightString) {
104 return leftString.compareTo(rightString);
106 }, PostReply.TIME_COMPARATOR);
108 /** Whether post replies are known. */
109 private final Set<String> knownPostReplies = new HashSet<String>();
111 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
112 private final ListMultimap<String, String> albumChildren = ArrayListMultimap.create();
113 private final ListMultimap<String, String> albumImages = ArrayListMultimap.create();
115 private final Map<String, Image> allImages = new HashMap<String, Image>();
118 * Creates a new memory database.
120 * @param configuration
121 * The configuration for loading and saving elements
124 public MemoryDatabase(Configuration configuration) {
125 this.configuration = configuration;
126 memoryPostDatabase = new MemoryPostDatabase(this, lock, configuration);
127 memoryIdentityDatabase = new MemoryIdentityDatabase(lock);
135 protected void doStart() {
136 memoryPostDatabase.start();
137 loadKnownPostReplies();
142 protected void doStop() {
144 memoryPostDatabase.stop();
145 configuration.save();
146 } catch (DatabaseException de1) {
147 logger.log(Level.WARNING, "Could not stop post database!", de1);
148 } catch (ConfigurationException ce1) {
149 logger.log(Level.WARNING, "Could not save configuration!", ce1);
155 public Optional<Identity> getIdentity(String identityId) {
156 return memoryIdentityDatabase.getIdentity(identityId);
160 public void storeIdentity(Identity identitiy) {
161 memoryIdentityDatabase.storeIdentity(identitiy);
165 public Function<String, Optional<Sone>> getSone() {
166 return new Function<String, Optional<Sone>>() {
168 public Optional<Sone> apply(String soneId) {
169 return (soneId == null) ? Optional.<Sone>absent() : getSone(soneId);
175 public Optional<Sone> getSone(String soneId) {
176 lock.readLock().lock();
178 return fromNullable(sones.get(soneId));
180 lock.readLock().unlock();
185 public Collection<Sone> getSones() {
186 lock.readLock().lock();
188 return Collections.unmodifiableCollection(sones.values());
190 lock.readLock().unlock();
195 public Collection<Sone> getLocalSones() {
196 lock.readLock().lock();
198 return from(getSones()).filter(LOCAL_SONE_FILTER).toSet();
200 lock.readLock().unlock();
205 public Collection<Sone> getRemoteSones() {
206 lock.readLock().lock();
208 return from(getSones()).filter(not(LOCAL_SONE_FILTER)).toSet();
210 lock.readLock().unlock();
215 public void storeSone(Sone sone) {
216 lock.writeLock().lock();
218 sones.put(sone.getId(), sone);
220 lock.writeLock().unlock();
225 public SoneBuilder newSoneBuilder() {
226 return new DefaultSoneBuilder(this) {
228 public Sone build(Optional<SoneCreated> soneCreated) throws IllegalStateException {
229 Sone sone = super.build(soneCreated);
230 lock.writeLock().lock();
232 sones.put(sone.getId(), sone);
234 lock.writeLock().unlock();
242 // POSTPROVIDER METHODS
246 public Function<String, Optional<Post>> getPost() {
247 return memoryPostDatabase.getPost();
251 public Optional<Post> getPost(String postId) {
252 return memoryPostDatabase.getPost(postId);
256 public Collection<Post> getPosts(String soneId) {
257 return memoryPostDatabase.getPosts(soneId);
261 public Collection<Post> getDirectedPosts(String recipientId) {
262 return memoryPostDatabase.getDirectedPosts(recipientId);
266 * Returns whether the given post is known.
270 * @return {@code true} if the post is known, {@code false} otherwise
273 public boolean isPostKnown(Post post) {
274 return memoryPostDatabase.isPostKnown(post);
278 * Sets whether the given post is known.
284 public void setPostKnown(Post post) {
285 memoryPostDatabase.setPostKnown(post);
289 public void likePost(Post post, Sone localSone) {
290 memoryPostDatabase.likePost(post, localSone);
294 public void unlikePost(Post post, Sone localSone) {
295 memoryPostDatabase.unlikePost(post, localSone);
298 public boolean isLiked(Post post, Sone sone) {
299 return memoryPostDatabase.isLiked(post, sone);
303 public Set<Sone> getLikes(Post post) {
304 return memoryPostDatabase.getLikes(post);
312 public void storePost(Post post) {
313 memoryPostDatabase.storePost(post);
317 public void removePost(Post post) {
318 memoryPostDatabase.removePost(post);
322 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
323 /* verify that all posts are from the same Sone. */
325 memoryPostDatabase.storePosts(sone, posts);
329 public void removePosts(Sone sone) {
330 memoryPostDatabase.removePosts(sone);
334 // POSTREPLYPROVIDER METHODS
338 public Optional<PostReply> getPostReply(String id) {
339 lock.readLock().lock();
341 return fromNullable(allPostReplies.get(id));
343 lock.readLock().unlock();
348 public List<PostReply> getReplies(String postId) {
349 lock.readLock().lock();
351 if (!postReplies.containsKey(postId)) {
354 return new ArrayList<PostReply>(postReplies.get(postId));
356 lock.readLock().unlock();
361 public void likePostReply(PostReply postReply, Sone localSone) {
362 lock.writeLock().lock();
364 likedPostRepliesBySone.put(localSone.getId(), postReply.getId());
365 postReplyLikingSones.put(postReply.getId(), localSone.getId());
367 lock.writeLock().unlock();
372 public void unlikePostReply(PostReply postReply, Sone localSone) {
373 lock.writeLock().lock();
375 likedPostRepliesBySone.remove(localSone.getId(), postReply.getId());
376 postReplyLikingSones.remove(postReply.getId(), localSone.getId());
378 lock.writeLock().unlock();
383 public boolean isLiked(PostReply postReply, Sone sone) {
384 lock.readLock().lock();
386 return postReplyLikingSones.containsEntry(postReply.getId(), sone.getId());
388 lock.readLock().unlock();
393 public Set<Sone> getLikes(PostReply postReply) {
394 lock.readLock().lock();
396 return from(postReplyLikingSones.get(postReply.getId())).transform(getSone()).transformAndConcat(this.<Sone>unwrap()).toSet();
398 lock.readLock().unlock();
403 // POSTREPLYSTORE METHODS
407 * Returns whether the given post reply is known.
411 * @return {@code true} if the given post reply is known, {@code false}
414 public boolean isPostReplyKnown(PostReply postReply) {
415 lock.readLock().lock();
417 return knownPostReplies.contains(postReply.getId());
419 lock.readLock().unlock();
424 public void setPostReplyKnown(PostReply postReply) {
425 lock.writeLock().lock();
427 knownPostReplies.add(postReply.getId());
429 lock.writeLock().unlock();
434 public void storePostReply(PostReply postReply) {
435 lock.writeLock().lock();
437 allPostReplies.put(postReply.getId(), postReply);
438 postReplies.put(postReply.getPostId(), postReply);
440 lock.writeLock().unlock();
445 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
446 checkNotNull(sone, "sone must not be null");
447 /* verify that all posts are from the same Sone. */
448 for (PostReply postReply : postReplies) {
449 if (!sone.equals(postReply.getSone())) {
450 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
454 lock.writeLock().lock();
456 /* remove all post replies of the Sone. */
457 for (PostReply postReply : getRepliesFrom(sone.getId())) {
458 removePostReply(postReply);
460 for (PostReply postReply : postReplies) {
461 allPostReplies.put(postReply.getId(), postReply);
462 sonePostReplies.put(postReply.getSone().getId(), postReply);
463 this.postReplies.put(postReply.getPostId(), postReply);
466 lock.writeLock().unlock();
471 public void removePostReply(PostReply postReply) {
472 lock.writeLock().lock();
474 allPostReplies.remove(postReply.getId());
475 postReplies.remove(postReply.getPostId(), postReply);
477 lock.writeLock().unlock();
482 public void removePostReplies(Sone sone) {
483 checkNotNull(sone, "sone must not be null");
485 lock.writeLock().lock();
487 for (PostReply postReply : sone.getReplies()) {
488 removePostReply(postReply);
491 lock.writeLock().unlock();
496 // ALBUMPROVDER METHODS
500 public Optional<Album> getAlbum(String albumId) {
501 lock.readLock().lock();
503 return fromNullable(allAlbums.get(albumId));
505 lock.readLock().unlock();
510 public List<Album> getAlbums(Album parent) {
511 lock.readLock().lock();
513 return from(albumChildren.get(parent.getId())).transformAndConcat(getAlbum()).toList();
515 lock.readLock().unlock();
520 public void moveUp(Album album) {
521 lock.writeLock().lock();
523 List<String> albums = albumChildren.get(album.getParent().getId());
524 int currentIndex = albums.indexOf(album.getId());
525 if (currentIndex == 0) {
528 albums.remove(album.getId());
529 albums.add(currentIndex - 1, album.getId());
531 lock.writeLock().unlock();
536 public void moveDown(Album album) {
537 lock.writeLock().lock();
539 List<String> albums = albumChildren.get(album.getParent().getId());
540 int currentIndex = albums.indexOf(album.getId());
541 if (currentIndex == (albums.size() - 1)) {
544 albums.remove(album.getId());
545 albums.add(currentIndex + 1, album.getId());
547 lock.writeLock().unlock();
552 // ALBUMSTORE METHODS
556 public void storeAlbum(Album album) {
557 lock.writeLock().lock();
559 allAlbums.put(album.getId(), album);
560 if (!album.isRoot()) {
561 albumChildren.put(album.getParent().getId(), album.getId());
564 lock.writeLock().unlock();
569 public void removeAlbum(Album album) {
570 lock.writeLock().lock();
572 allAlbums.remove(album.getId());
573 albumChildren.remove(album.getParent().getId(), album.getId());
575 lock.writeLock().unlock();
580 // IMAGEPROVIDER METHODS
584 public Optional<Image> getImage(String imageId) {
585 lock.readLock().lock();
587 return fromNullable(allImages.get(imageId));
589 lock.readLock().unlock();
594 public List<Image> getImages(Album parent) {
595 lock.readLock().lock();
597 return from(albumImages.get(parent.getId())).transformAndConcat(getImage()).toList();
599 lock.readLock().unlock();
604 public void moveUp(Image image) {
605 lock.writeLock().lock();
607 List<String> images = albumImages.get(image.getAlbum().getId());
608 int currentIndex = images.indexOf(image.getId());
609 if (currentIndex == 0) {
612 images.remove(image.getId());
613 images.add(currentIndex - 1, image.getId());
615 lock.writeLock().unlock();
620 public void moveDown(Image image) {
621 lock.writeLock().lock();
623 List<String> images = albumChildren.get(image.getAlbum().getId());
624 int currentIndex = images.indexOf(image.getId());
625 if (currentIndex == (images.size() - 1)) {
628 images.remove(image.getId());
629 images.add(currentIndex + 1, image.getId());
631 lock.writeLock().unlock();
636 // IMAGESTORE METHODS
640 public void storeImage(Image image) {
641 lock.writeLock().lock();
643 allImages.put(image.getId(), image);
644 albumImages.put(image.getAlbum().getId(), image.getId());
646 lock.writeLock().unlock();
651 public void removeImage(Image image) {
652 lock.writeLock().lock();
654 allImages.remove(image.getId());
655 albumImages.remove(image.getAlbum().getId(), image.getId());
657 lock.writeLock().unlock();
666 * Returns all replies by the given Sone.
670 * @return The post replies of the Sone, sorted by time (newest first)
672 private Collection<PostReply> getRepliesFrom(String id) {
673 lock.readLock().lock();
675 if (sonePostReplies.containsKey(id)) {
676 return Collections.unmodifiableCollection(sonePostReplies.get(id));
678 return Collections.emptySet();
680 lock.readLock().unlock();
684 /** Loads the known post replies. */
685 private void loadKnownPostReplies() {
686 lock.writeLock().lock();
688 int replyCounter = 0;
690 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
691 if (knownReplyId == null) {
694 knownPostReplies.add(knownReplyId);
697 lock.writeLock().unlock();
702 * Saves the known post replies to the configuration.
704 * @throws DatabaseException
705 * if a configuration error occurs
707 private void saveKnownPostReplies() throws DatabaseException {
708 lock.readLock().lock();
710 int replyCounter = 0;
711 for (String knownReplyId : knownPostReplies) {
712 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
714 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
715 } catch (ConfigurationException ce1) {
716 throw new DatabaseException("Could not save database.", ce1);
718 lock.readLock().unlock();
722 private Function<String, Iterable<Album>> getAlbum() {
723 return new Function<String, Iterable<Album>>() {
725 public Iterable<Album> apply(String input) {
726 return (input == null) ? Collections.<Album>emptyList() : getAlbum(input).asSet();
731 private Function<String, Iterable<Image>> getImage() {
732 return new Function<String, Iterable<Image>>() {
734 public Iterable<Image> apply(String input) {
735 return (input == null) ? Collections.<Image>emptyList() : getImage(input).asSet();
740 static <T> Function<Optional<T>, Iterable<T>> unwrap() {
741 return new Function<Optional<T>, Iterable<T>>() {
743 public Iterable<T> apply(Optional<T> input) {
744 return (input == null) ? Collections.<T>emptyList() : input.asSet();