Actually return a Sone builder.
[Sone.git] / src / main / java / net / pterodactylus / sone / database / memory / MemoryDatabase.java
1 /*
2  * Sone - MemoryDatabase.java - Copyright © 2013 David Roden
3  *
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.pterodactylus.sone.database.memory;
19
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;
26
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;
34 import java.util.Map;
35 import java.util.Set;
36 import java.util.SortedSet;
37 import java.util.TreeSet;
38 import java.util.concurrent.locks.ReadWriteLock;
39 import java.util.concurrent.locks.ReentrantReadWriteLock;
40
41 import net.pterodactylus.sone.data.Album;
42 import net.pterodactylus.sone.data.Image;
43 import net.pterodactylus.sone.data.Post;
44 import net.pterodactylus.sone.data.PostReply;
45 import net.pterodactylus.sone.data.Reply;
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.PostDatabase;
51 import net.pterodactylus.sone.database.SoneBuilder;
52 import net.pterodactylus.sone.freenet.wot.Identity;
53 import net.pterodactylus.util.config.Configuration;
54 import net.pterodactylus.util.config.ConfigurationException;
55
56 import com.google.common.base.Function;
57 import com.google.common.base.Optional;
58 import com.google.common.collect.ArrayListMultimap;
59 import com.google.common.collect.HashMultimap;
60 import com.google.common.collect.ListMultimap;
61 import com.google.common.collect.Maps;
62 import com.google.common.collect.Multimap;
63 import com.google.common.collect.SortedSetMultimap;
64 import com.google.common.collect.TreeMultimap;
65 import com.google.common.util.concurrent.AbstractService;
66 import com.google.inject.Inject;
67
68 /**
69  * Memory-based {@link PostDatabase} implementation.
70  *
71  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
72  */
73 public class MemoryDatabase extends AbstractService implements Database {
74
75         /** The lock. */
76         private final ReadWriteLock lock = new ReentrantReadWriteLock();
77
78         /** The configuration. */
79         private final Configuration configuration;
80
81         private final Map<String, Identity> identities = Maps.newHashMap();
82         private final Map<String, Sone> sones = new HashMap<String, Sone>();
83
84         /** All posts by their ID. */
85         private final Map<String, Post> allPosts = new HashMap<String, Post>();
86
87         /** All posts by their Sones. */
88         private final Multimap<String, Post> sonePosts = HashMultimap.create();
89
90         /** All posts by their recipient. */
91         private final Multimap<String, Post> recipientPosts = HashMultimap.create();
92
93         /** Whether posts are known. */
94         private final Set<String> knownPosts = new HashSet<String>();
95
96         /** All post replies by their ID. */
97         private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
98
99         /** Replies sorted by Sone. */
100         private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
101
102                 @Override
103                 public int compare(String leftString, String rightString) {
104                         return leftString.compareTo(rightString);
105                 }
106         }, PostReply.TIME_COMPARATOR);
107
108         /** Replies by post. */
109         private final SortedSetMultimap<String, PostReply> postReplies = TreeMultimap.create(new Comparator<String>() {
110
111                 @Override
112                 public int compare(String leftString, String rightString) {
113                         return leftString.compareTo(rightString);
114                 }
115         }, PostReply.TIME_COMPARATOR);
116
117         /** Whether post replies are known. */
118         private final Set<String> knownPostReplies = new HashSet<String>();
119
120         private final Map<String, Album> allAlbums = new HashMap<String, Album>();
121         private final ListMultimap<String, String> albumChildren = ArrayListMultimap.create();
122         private final ListMultimap<String, String> albumImages = ArrayListMultimap.create();
123
124         private final Map<String, Image> allImages = new HashMap<String, Image>();
125
126         /**
127          * Creates a new memory database.
128          *
129          * @param configuration
130          *              The configuration for loading and saving elements
131          */
132         @Inject
133         public MemoryDatabase(Configuration configuration) {
134                 this.configuration = configuration;
135         }
136
137         //
138         // DATABASE METHODS
139         //
140
141         @Override
142         public void save() throws DatabaseException {
143                 saveKnownPosts();
144                 saveKnownPostReplies();
145         }
146
147         //
148         // SERVICE METHODS
149         //
150
151         @Override
152         protected void doStart() {
153                 loadKnownPosts();
154                 loadKnownPostReplies();
155                 notifyStarted();
156         }
157
158         @Override
159         protected void doStop() {
160                 try {
161                         save();
162                         notifyStopped();
163                 } catch (DatabaseException de1) {
164                         notifyFailed(de1);
165                 }
166         }
167
168         @Override
169         public Optional<Identity> getIdentity(String identityId) {
170                 lock.readLock().lock();
171                 try {
172                         return fromNullable(identities.get(identityId));
173                 } finally {
174                         lock.readLock().unlock();
175                 }
176         }
177
178         @Override
179         public Optional<Sone> getSone(String soneId) {
180                 lock.readLock().lock();
181                 try {
182                         return fromNullable(sones.get(soneId));
183                 } finally {
184                         lock.readLock().unlock();
185                 }
186         }
187
188         @Override
189         public Collection<Sone> getSones() {
190                 lock.readLock().lock();
191                 try {
192                         return Collections.unmodifiableCollection(sones.values());
193                 } finally {
194                         lock.readLock().unlock();
195                 }
196         }
197
198         @Override
199         public Collection<Sone> getLocalSones() {
200                 lock.readLock().lock();
201                 try {
202                         return from(getSones()).filter(LOCAL_SONE_FILTER).toSet();
203                 } finally {
204                         lock.readLock().unlock();
205                 }
206         }
207
208         @Override
209         public Collection<Sone> getRemoteSones() {
210                 lock.readLock().lock();
211                 try {
212                         return from(getSones()).filter(not(LOCAL_SONE_FILTER)).toSet();
213                 } finally {
214                         lock.readLock().unlock();
215                 }
216         }
217
218         @Override
219         public SoneBuilder newSoneBuilder() {
220                 return new DefaultSoneBuilder(this) {
221                         @Override
222                         public Sone build(Optional<SoneCreated> soneCreated) throws IllegalStateException {
223                                 Sone sone = super.build(soneCreated);
224                                 sones.put(sone.getId(), sone);
225                                 return sone;
226                         }
227                 };
228         }
229
230         //
231         // POSTPROVIDER METHODS
232         //
233
234         @Override
235         public Optional<Post> getPost(String postId) {
236                 lock.readLock().lock();
237                 try {
238                         return fromNullable(allPosts.get(postId));
239                 } finally {
240                         lock.readLock().unlock();
241                 }
242         }
243
244         @Override
245         public Collection<Post> getPosts(String soneId) {
246                 lock.readLock().lock();
247                 try {
248                         return new HashSet<Post>(sonePosts.get(soneId));
249                 } finally {
250                         lock.readLock().unlock();
251                 }
252         }
253
254         @Override
255         public Collection<Post> getDirectedPosts(String recipientId) {
256                 lock.readLock().lock();
257                 try {
258                         Collection<Post> posts = recipientPosts.get(recipientId);
259                         return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
260                 } finally {
261                         lock.readLock().unlock();
262                 }
263         }
264
265         //
266         // POSTSTORE METHODS
267         //
268
269         @Override
270         public void storePost(Post post) {
271                 checkNotNull(post, "post must not be null");
272                 lock.writeLock().lock();
273                 try {
274                         allPosts.put(post.getId(), post);
275                         sonePosts.put(post.getSone().getId(), post);
276                         if (post.getRecipientId().isPresent()) {
277                                 recipientPosts.put(post.getRecipientId().get(), post);
278                         }
279                 } finally {
280                         lock.writeLock().unlock();
281                 }
282         }
283
284         @Override
285         public void removePost(Post post) {
286                 checkNotNull(post, "post must not be null");
287                 lock.writeLock().lock();
288                 try {
289                         allPosts.remove(post.getId());
290                         sonePosts.remove(post.getSone().getId(), post);
291                         if (post.getRecipientId().isPresent()) {
292                                 recipientPosts.remove(post.getRecipientId().get(), post);
293                         }
294                         post.getSone().removePost(post);
295                 } finally {
296                         lock.writeLock().unlock();
297                 }
298         }
299
300         @Override
301         public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
302                 checkNotNull(sone, "sone must not be null");
303                 /* verify that all posts are from the same Sone. */
304                 for (Post post : posts) {
305                         if (!sone.equals(post.getSone())) {
306                                 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
307                         }
308                 }
309
310                 lock.writeLock().lock();
311                 try {
312                         /* remove all posts by the Sone. */
313                         sonePosts.removeAll(sone.getId());
314                         for (Post post : posts) {
315                                 allPosts.remove(post.getId());
316                                 if (post.getRecipientId().isPresent()) {
317                                         recipientPosts.remove(post.getRecipientId().get(), post);
318                                 }
319                         }
320
321                         /* add new posts. */
322                         sonePosts.putAll(sone.getId(), posts);
323                         for (Post post : posts) {
324                                 allPosts.put(post.getId(), post);
325                                 if (post.getRecipientId().isPresent()) {
326                                         recipientPosts.put(post.getRecipientId().get(), post);
327                                 }
328                         }
329                 } finally {
330                         lock.writeLock().unlock();
331                 }
332         }
333
334         @Override
335         public void removePosts(Sone sone) {
336                 checkNotNull(sone, "sone must not be null");
337                 lock.writeLock().lock();
338                 try {
339                         /* remove all posts by the Sone. */
340                         sonePosts.removeAll(sone.getId());
341                         for (Post post : sone.getPosts()) {
342                                 allPosts.remove(post.getId());
343                                 if (post.getRecipientId().isPresent()) {
344                                         recipientPosts.remove(post.getRecipientId().get(), post);
345                                 }
346                         }
347                 } finally {
348                         lock.writeLock().unlock();
349                 }
350         }
351
352         //
353         // POSTREPLYPROVIDER METHODS
354         //
355
356         @Override
357         public Optional<PostReply> getPostReply(String id) {
358                 lock.readLock().lock();
359                 try {
360                         return fromNullable(allPostReplies.get(id));
361                 } finally {
362                         lock.readLock().unlock();
363                 }
364         }
365
366         @Override
367         public List<PostReply> getReplies(String postId) {
368                 lock.readLock().lock();
369                 try {
370                         if (!postReplies.containsKey(postId)) {
371                                 return emptyList();
372                         }
373                         return new ArrayList<PostReply>(postReplies.get(postId));
374                 } finally {
375                         lock.readLock().unlock();
376                 }
377         }
378
379         //
380         // POSTREPLYSTORE METHODS
381         //
382
383         /**
384          * Returns whether the given post reply is known.
385          *
386          * @param postReply
387          *              The post reply
388          * @return {@code true} if the given post reply is known, {@code false}
389          *         otherwise
390          */
391         public boolean isPostReplyKnown(PostReply postReply) {
392                 lock.readLock().lock();
393                 try {
394                         return knownPostReplies.contains(postReply.getId());
395                 } finally {
396                         lock.readLock().unlock();
397                 }
398         }
399
400         @Override
401         public void setPostReplyKnown(PostReply postReply) {
402                 lock.writeLock().lock();
403                 try {
404                         knownPostReplies.add(postReply.getId());
405                 } finally {
406                         lock.writeLock().unlock();
407                 }
408         }
409
410         @Override
411         public void storePostReply(PostReply postReply) {
412                 lock.writeLock().lock();
413                 try {
414                         allPostReplies.put(postReply.getId(), postReply);
415                         postReplies.put(postReply.getPostId(), postReply);
416                 } finally {
417                         lock.writeLock().unlock();
418                 }
419         }
420
421         @Override
422         public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
423                 checkNotNull(sone, "sone must not be null");
424                 /* verify that all posts are from the same Sone. */
425                 for (PostReply postReply : postReplies) {
426                         if (!sone.equals(postReply.getSone())) {
427                                 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
428                         }
429                 }
430
431                 lock.writeLock().lock();
432                 try {
433                         /* remove all post replies of the Sone. */
434                         for (PostReply postReply : getRepliesFrom(sone.getId())) {
435                                 removePostReply(postReply);
436                         }
437                         for (PostReply postReply : postReplies) {
438                                 allPostReplies.put(postReply.getId(), postReply);
439                                 sonePostReplies.put(postReply.getSone().getId(), postReply);
440                                 this.postReplies.put(postReply.getPostId(), postReply);
441                         }
442                 } finally {
443                         lock.writeLock().unlock();
444                 }
445         }
446
447         @Override
448         public void removePostReply(PostReply postReply) {
449                 lock.writeLock().lock();
450                 try {
451                         allPostReplies.remove(postReply.getId());
452                         postReplies.remove(postReply.getPostId(), postReply);
453                 } finally {
454                         lock.writeLock().unlock();
455                 }
456         }
457
458         @Override
459         public void removePostReplies(Sone sone) {
460                 checkNotNull(sone, "sone must not be null");
461
462                 lock.writeLock().lock();
463                 try {
464                         for (PostReply postReply : sone.getReplies()) {
465                                 removePostReply(postReply);
466                         }
467                 } finally {
468                         lock.writeLock().unlock();
469                 }
470         }
471
472         //
473         // ALBUMPROVDER METHODS
474         //
475
476         @Override
477         public Optional<Album> getAlbum(String albumId) {
478                 lock.readLock().lock();
479                 try {
480                         return fromNullable(allAlbums.get(albumId));
481                 } finally {
482                         lock.readLock().unlock();
483                 }
484         }
485
486         @Override
487         public List<Album> getAlbums(Album parent) {
488                 lock.readLock().lock();
489                 try {
490                         return from(albumChildren.get(parent.getId())).transformAndConcat(getAlbum()).toList();
491                 } finally {
492                         lock.readLock().unlock();
493                 }
494         }
495
496         @Override
497         public void moveUp(Album album) {
498                 lock.writeLock().lock();
499                 try {
500                         List<String> albums = albumChildren.get(album.getParent().getId());
501                         int currentIndex = albums.indexOf(album.getId());
502                         if (currentIndex == 0) {
503                                 return;
504                         }
505                         albums.remove(album.getId());
506                         albums.add(currentIndex - 1, album.getId());
507                 } finally {
508                         lock.writeLock().unlock();
509                 }
510         }
511
512         @Override
513         public void moveDown(Album album) {
514                 lock.writeLock().lock();
515                 try {
516                         List<String> albums = albumChildren.get(album.getParent().getId());
517                         int currentIndex = albums.indexOf(album.getId());
518                         if (currentIndex == (albums.size() - 1)) {
519                                 return;
520                         }
521                         albums.remove(album.getId());
522                         albums.add(currentIndex + 1, album.getId());
523                 } finally {
524                         lock.writeLock().unlock();
525                 }
526         }
527
528         //
529         // ALBUMSTORE METHODS
530         //
531
532         @Override
533         public void storeAlbum(Album album) {
534                 lock.writeLock().lock();
535                 try {
536                         allAlbums.put(album.getId(), album);
537                         albumChildren.put(album.getParent().getId(), album.getId());
538                 } finally {
539                         lock.writeLock().unlock();
540                 }
541         }
542
543         @Override
544         public void removeAlbum(Album album) {
545                 lock.writeLock().lock();
546                 try {
547                         allAlbums.remove(album.getId());
548                         albumChildren.remove(album.getParent().getId(), album.getId());
549                 } finally {
550                         lock.writeLock().unlock();
551                 }
552         }
553
554         //
555         // IMAGEPROVIDER METHODS
556         //
557
558         @Override
559         public Optional<Image> getImage(String imageId) {
560                 lock.readLock().lock();
561                 try {
562                         return fromNullable(allImages.get(imageId));
563                 } finally {
564                         lock.readLock().unlock();
565                 }
566         }
567
568         @Override
569         public List<Image> getImages(Album parent) {
570                 lock.readLock().lock();
571                 try {
572                         return from(albumImages.get(parent.getId())).transformAndConcat(getImage()).toList();
573                 } finally {
574                         lock.readLock().unlock();
575                 }
576         }
577
578         @Override
579         public void moveUp(Image image) {
580                 lock.writeLock().lock();
581                 try {
582                         List<String> images = albumImages.get(image.getAlbum().getId());
583                         int currentIndex = images.indexOf(image.getId());
584                         if (currentIndex == 0) {
585                                 return;
586                         }
587                         images.remove(image.getId());
588                         images.add(currentIndex - 1, image.getId());
589                 } finally {
590                         lock.writeLock().unlock();
591                 }
592         }
593
594         @Override
595         public void moveDown(Image image) {
596                 lock.writeLock().lock();
597                 try {
598                         List<String> images = albumChildren.get(image.getAlbum().getId());
599                         int currentIndex = images.indexOf(image.getId());
600                         if (currentIndex == (images.size() - 1)) {
601                                 return;
602                         }
603                         images.remove(image.getId());
604                         images.add(currentIndex + 1, image.getId());
605                 } finally {
606                         lock.writeLock().unlock();
607                 }
608         }
609
610         //
611         // IMAGESTORE METHODS
612         //
613
614         @Override
615         public void storeImage(Image image) {
616                 lock.writeLock().lock();
617                 try {
618                         allImages.put(image.getId(), image);
619                         albumImages.put(image.getAlbum().getId(), image.getId());
620                 } finally {
621                         lock.writeLock().unlock();
622                 }
623         }
624
625         @Override
626         public void removeImage(Image image) {
627                 lock.writeLock().lock();
628                 try {
629                         allImages.remove(image.getId());
630                         albumImages.remove(image.getAlbum().getId(), image.getId());
631                 } finally {
632                         lock.writeLock().unlock();
633                 }
634         }
635
636         //
637         // PACKAGE-PRIVATE METHODS
638         //
639
640         /**
641          * Returns whether the given post is known.
642          *
643          * @param post
644          *              The post
645          * @return {@code true} if the post is known, {@code false} otherwise
646          */
647         boolean isPostKnown(Post post) {
648                 lock.readLock().lock();
649                 try {
650                         return knownPosts.contains(post.getId());
651                 } finally {
652                         lock.readLock().unlock();
653                 }
654         }
655
656         /**
657          * Sets whether the given post is known.
658          *
659          * @param post
660          *              The post
661          * @param known
662          *              {@code true} if the post is known, {@code false} otherwise
663          */
664         void setPostKnown(Post post, boolean known) {
665                 lock.writeLock().lock();
666                 try {
667                         if (known) {
668                                 knownPosts.add(post.getId());
669                         } else {
670                                 knownPosts.remove(post.getId());
671                         }
672                 } finally {
673                         lock.writeLock().unlock();
674                 }
675         }
676
677         //
678         // PRIVATE METHODS
679         //
680
681         /** Loads the known posts. */
682         private void loadKnownPosts() {
683                 lock.writeLock().lock();
684                 try {
685                         int postCounter = 0;
686                         while (true) {
687                                 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
688                                 if (knownPostId == null) {
689                                         break;
690                                 }
691                                 knownPosts.add(knownPostId);
692                         }
693                 } finally {
694                         lock.writeLock().unlock();
695                 }
696         }
697
698         /**
699          * Saves the known posts to the configuration.
700          *
701          * @throws DatabaseException
702          *              if a configuration error occurs
703          */
704         private void saveKnownPosts() throws DatabaseException {
705                 lock.readLock().lock();
706                 try {
707                         int postCounter = 0;
708                         for (String knownPostId : knownPosts) {
709                                 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
710                         }
711                         configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
712                 } catch (ConfigurationException ce1) {
713                         throw new DatabaseException("Could not save database.", ce1);
714                 } finally {
715                         lock.readLock().unlock();
716                 }
717         }
718
719         /**
720          * Returns all replies by the given Sone.
721          *
722          * @param id
723          *              The ID of the Sone
724          * @return The post replies of the Sone, sorted by time (newest first)
725          */
726         private Collection<PostReply> getRepliesFrom(String id) {
727                 lock.readLock().lock();
728                 try {
729                         if (sonePostReplies.containsKey(id)) {
730                                 return Collections.unmodifiableCollection(sonePostReplies.get(id));
731                         }
732                         return Collections.emptySet();
733                 } finally {
734                         lock.readLock().unlock();
735                 }
736         }
737
738         /** Loads the known post replies. */
739         private void loadKnownPostReplies() {
740                 lock.writeLock().lock();
741                 try {
742                         int replyCounter = 0;
743                         while (true) {
744                                 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
745                                 if (knownReplyId == null) {
746                                         break;
747                                 }
748                                 knownPostReplies.add(knownReplyId);
749                         }
750                 } finally {
751                         lock.writeLock().unlock();
752                 }
753         }
754
755         /**
756          * Saves the known post replies to the configuration.
757          *
758          * @throws DatabaseException
759          *              if a configuration error occurs
760          */
761         private void saveKnownPostReplies() throws DatabaseException {
762                 lock.readLock().lock();
763                 try {
764                         int replyCounter = 0;
765                         for (String knownReplyId : knownPostReplies) {
766                                 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
767                         }
768                         configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
769                 } catch (ConfigurationException ce1) {
770                         throw new DatabaseException("Could not save database.", ce1);
771                 } finally {
772                         lock.readLock().unlock();
773                 }
774         }
775
776         private Function<String, Iterable<Album>> getAlbum() {
777                 return new Function<String, Iterable<Album>>() {
778                         @Override
779                         public Iterable<Album> apply(String input) {
780                                 return (input == null) ? Collections.<Album>emptyList() : getAlbum(input).asSet();
781                         }
782                 };
783         }
784
785         private Function<String, Iterable<Image>> getImage() {
786                 return new Function<String, Iterable<Image>>() {
787                         @Override
788                         public Iterable<Image> apply(String input) {
789                                 return (input == null) ? Collections.<Image>emptyList() : getImage(input).asSet();
790                         }
791                 };
792         }
793
794 }