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