Extract memory-backed post database into its own class.
[Sone.git] / src / main / java / net / pterodactylus / sone / database / memory / MemoryPostDatabase.java
1 /*
2  * Sone - MemoryPostDatabase.java - Copyright © 2014 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.collect.FluentIterable.from;
23 import static com.google.common.collect.HashMultimap.create;
24
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.Map;
30 import java.util.Set;
31 import java.util.concurrent.locks.ReadWriteLock;
32
33 import net.pterodactylus.sone.data.Post;
34 import net.pterodactylus.sone.data.Sone;
35 import net.pterodactylus.sone.database.DatabaseException;
36 import net.pterodactylus.sone.database.PostDatabase;
37 import net.pterodactylus.util.config.Configuration;
38 import net.pterodactylus.util.config.ConfigurationException;
39
40 import com.google.common.base.Function;
41 import com.google.common.base.Optional;
42 import com.google.common.collect.Multimap;
43 import com.google.common.collect.SetMultimap;
44
45 /**
46  * Memory-based {@link PostDatabase} implementation.
47  *
48  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
49  */
50 public class MemoryPostDatabase implements PostDatabase {
51
52         private final MemoryDatabase memoryDatabase;
53         private final ReadWriteLock readWriteLock;
54         private final Configuration configuration;
55         private final Map<String, Post> allPosts = new HashMap<String, Post>();
56         private final Multimap<String, Post> sonePosts = create();
57         private final SetMultimap<String, String> likedPostsBySone = create();
58         private final SetMultimap<String, String> postLikingSones = create();
59         private final Multimap<String, Post> recipientPosts = create();
60         private final Set<String> knownPosts = new HashSet<String>();
61
62         public MemoryPostDatabase(MemoryDatabase memoryDatabase, ReadWriteLock readWriteLock, Configuration configuration) {
63                 this.memoryDatabase = memoryDatabase;
64                 this.readWriteLock = readWriteLock;
65                 this.configuration = configuration;
66         }
67
68         @Override
69         public Function<String, Optional<Post>> getPost() {
70                 return new Function<String, Optional<Post>>() {
71                         @Override
72                         public Optional<Post> apply(String postId) {
73                                 return (postId == null) ? Optional.<Post>absent() : getPost(postId);
74                         }
75                 };
76         }
77
78         @Override
79         public Optional<Post> getPost(String postId) {
80                 readWriteLock.readLock().lock();
81                 try {
82                         return fromNullable(allPosts.get(postId));
83                 } finally {
84                         readWriteLock.readLock().unlock();
85                 }
86         }
87
88         @Override
89         public Collection<Post> getPosts(String soneId) {
90                 readWriteLock.readLock().lock();
91                 try {
92                         return new HashSet<Post>(sonePosts.get(soneId));
93                 } finally {
94                         readWriteLock.readLock().unlock();
95                 }
96         }
97
98         @Override
99         public Collection<Post> getDirectedPosts(String recipientId) {
100                 readWriteLock.readLock().lock();
101                 try {
102                         Collection<Post> posts = recipientPosts.get(recipientId);
103                         return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
104                 } finally {
105                         readWriteLock.readLock().unlock();
106                 }
107         }
108
109         /**
110          * Returns whether the given post is known.
111          *
112          * @param post
113          *              The post
114          * @return {@code true} if the post is known, {@code false} otherwise
115          */
116         @Override
117         public boolean isPostKnown(Post post) {
118                 readWriteLock.readLock().lock();
119                 try {
120                         return knownPosts.contains(post.getId());
121                 } finally {
122                         readWriteLock.readLock().unlock();
123                 }
124         }
125
126         /**
127          * Sets whether the given post is known.
128          *
129          * @param post
130          *              The post
131          */
132         @Override
133         public void setPostKnown(Post post) {
134                 readWriteLock.writeLock().lock();
135                 try {
136                         knownPosts.add(post.getId());
137                 } finally {
138                         readWriteLock.writeLock().unlock();
139                 }
140         }
141
142         @Override
143         public void likePost(Post post, Sone localSone) {
144                 readWriteLock.writeLock().lock();
145                 try {
146                         likedPostsBySone.put(localSone.getId(), post.getId());
147                         postLikingSones.put(post.getId(), localSone.getId());
148                 } finally {
149                         readWriteLock.writeLock().unlock();
150                 }
151         }
152
153         @Override
154         public void unlikePost(Post post, Sone localSone) {
155                 readWriteLock.writeLock().lock();
156                 try {
157                         likedPostsBySone.remove(localSone.getId(), post.getId());
158                         postLikingSones.remove(post.getId(), localSone.getId());
159                 } finally {
160                         readWriteLock.writeLock().unlock();
161                 }
162         }
163
164         public boolean isLiked(Post post, Sone sone) {
165                 readWriteLock.readLock().lock();
166                 try {
167                         return likedPostsBySone.containsEntry(sone.getId(), post.getId());
168                 } finally {
169                         readWriteLock.readLock().unlock();
170                 }
171         }
172
173         @Override
174         public Set<Sone> getLikes(Post post) {
175                 readWriteLock.readLock().lock();
176                 try {
177                         return from(postLikingSones.get(post.getId())).transform(memoryDatabase.getSone()).transformAndConcat(MemoryDatabase.<Sone>unwrap()).toSet();
178                 } finally {
179                         readWriteLock.readLock().unlock();
180                 }
181         }
182
183         @Override
184         public void storePost(Post post) {
185                 checkNotNull(post, "post must not be null");
186                 readWriteLock.writeLock().lock();
187                 try {
188                         allPosts.put(post.getId(), post);
189                         sonePosts.put(post.getSone().getId(), post);
190                         if (post.getRecipientId().isPresent()) {
191                                 recipientPosts.put(post.getRecipientId().get(), post);
192                         }
193                 } finally {
194                         readWriteLock.writeLock().unlock();
195                 }
196         }
197
198         @Override
199         public void removePost(Post post) {
200                 checkNotNull(post, "post must not be null");
201                 readWriteLock.writeLock().lock();
202                 try {
203                         allPosts.remove(post.getId());
204                         sonePosts.remove(post.getSone().getId(), post);
205                         if (post.getRecipientId().isPresent()) {
206                                 recipientPosts.remove(post.getRecipientId().get(), post);
207                         }
208                         post.getSone().removePost(post);
209                 } finally {
210                         readWriteLock.writeLock().unlock();
211                 }
212         }
213
214         @Override
215         public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
216                 checkNotNull(sone, "sone must not be null");
217                 /* verify that all posts are from the same Sone. */
218                 for (Post post : posts) {
219                         if (!sone.equals(post.getSone())) {
220                                 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
221                         }
222                 }
223
224                 readWriteLock.writeLock().lock();
225                 try {
226                         /* remove all posts by the Sone. */
227                         sonePosts.removeAll(sone.getId());
228                         for (Post post : posts) {
229                                 allPosts.remove(post.getId());
230                                 if (post.getRecipientId().isPresent()) {
231                                         recipientPosts.remove(post.getRecipientId().get(), post);
232                                 }
233                         }
234
235                         /* add new posts. */
236                         sonePosts.putAll(sone.getId(), posts);
237                         for (Post post : posts) {
238                                 allPosts.put(post.getId(), post);
239                                 if (post.getRecipientId().isPresent()) {
240                                         recipientPosts.put(post.getRecipientId().get(), post);
241                                 }
242                         }
243                 } finally {
244                         readWriteLock.writeLock().unlock();
245                 }
246         }
247
248         @Override
249         public void removePosts(Sone sone) {
250                 checkNotNull(sone, "sone must not be null");
251                 readWriteLock.writeLock().lock();
252                 try {
253                         /* remove all posts by the Sone. */
254                         sonePosts.removeAll(sone.getId());
255                         for (Post post : sone.getPosts()) {
256                                 allPosts.remove(post.getId());
257                                 if (post.getRecipientId().isPresent()) {
258                                         recipientPosts.remove(post.getRecipientId().get(), post);
259                                 }
260                         }
261                 } finally {
262                         readWriteLock.writeLock().unlock();
263                 }
264         }
265
266         public void start() {
267                 readWriteLock.writeLock().lock();
268                 try {
269                         int postCounter = 0;
270                         while (true) {
271                                 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
272                                 if (knownPostId == null) {
273                                         break;
274                                 }
275                                 knownPosts.add(knownPostId);
276                         }
277                 } finally {
278                         readWriteLock.writeLock().unlock();
279                 }
280         }
281
282         public void stop() throws DatabaseException {
283                 save();
284         }
285
286         public void save() throws DatabaseException {
287                 readWriteLock.readLock().lock();
288                 try {
289                         int postCounter = 0;
290                         for (String knownPostId : knownPosts) {
291                                 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
292                         }
293                         configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
294                 } catch (ConfigurationException ce1) {
295                         throw new DatabaseException("Could not save database.", ce1);
296                 } finally {
297                         readWriteLock.readLock().unlock();
298                 }
299         }
300
301 }