Merge branch 'master' into next
[Sone.git] / src / main / java / net / pterodactylus / sone / data / Sone.java
1 /*
2  * FreenetSone - Sone.java - Copyright © 2010 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.data;
19
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.Comparator;
24 import java.util.HashSet;
25 import java.util.List;
26 import java.util.Set;
27 import java.util.UUID;
28 import java.util.logging.Level;
29 import java.util.logging.Logger;
30
31 import net.pterodactylus.sone.template.SoneAccessor;
32 import net.pterodactylus.util.logging.Logging;
33 import freenet.keys.FreenetURI;
34
35 /**
36  * A Sone defines everything about a user: her profile, her status updates, her
37  * replies, her likes and dislikes, etc.
38  * <p>
39  * Operations that modify the Sone need to synchronize on the Sone in question.
40  *
41  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
42  */
43 public class Sone {
44
45         /** The logger. */
46         private static final Logger logger = Logging.getLogger(Sone.class);
47
48         /** A GUID for this Sone. */
49         private final UUID id;
50
51         /** The name of this Sone. */
52         private volatile String name;
53
54         /** The URI under which the Sone is stored in Freenet. */
55         private volatile FreenetURI requestUri;
56
57         /** The URI used to insert a new version of this Sone. */
58         /* This will be null for remote Sones! */
59         private volatile FreenetURI insertUri;
60
61         /** The time of the last inserted update. */
62         private volatile long time;
63
64         /** The profile of this Sone. */
65         private volatile Profile profile;
66
67         /** All friend Sones. */
68         private final Set<Sone> friendSones = Collections.synchronizedSet(new HashSet<Sone>());
69
70         /** All posts. */
71         private final Set<Post> posts = Collections.synchronizedSet(new HashSet<Post>());
72
73         /** All replies. */
74         private final Set<Reply> replies = Collections.synchronizedSet(new HashSet<Reply>());
75
76         /** The IDs of all blocked Sones. */
77         private final Set<String> blockedSoneIds = Collections.synchronizedSet(new HashSet<String>());
78
79         /** The IDs of all liked posts. */
80         private final Set<String> likedPostIds = Collections.synchronizedSet(new HashSet<String>());
81
82         /** The IDs of all liked replies. */
83         private final Set<String> likedReplyIds = Collections.synchronizedSet(new HashSet<String>());
84
85         /** Modification count. */
86         private volatile long modificationCounter = 0;
87
88         /**
89          * Creates a new Sone.
90          *
91          * @param id
92          *            The ID of this Sone
93          */
94         public Sone(String id) {
95                 this.id = UUID.fromString(id);
96         }
97
98         //
99         // ACCESSORS
100         //
101
102         /**
103          * Returns the ID of this Sone.
104          *
105          * @return The ID of this Sone
106          */
107         public String getId() {
108                 return id.toString();
109         }
110
111         /**
112          * Returns the name of this Sone.
113          *
114          * @return The name of this Sone
115          */
116         public String getName() {
117                 return name;
118         }
119
120         /**
121          * Sets the name of this Sone.
122          *
123          * @param name
124          *            The name of this Sone
125          * @return This sone (for method chaining)
126          */
127         public Sone setName(String name) {
128                 this.name = name;
129                 return this;
130         }
131
132         /**
133          * Returns the request URI of this Sone.
134          *
135          * @return The request URI of this Sone
136          */
137         public FreenetURI getRequestUri() {
138                 return requestUri;
139         }
140
141         /**
142          * Sets the request URI of this Sone.
143          *
144          * @param requestUri
145          *            The request URI of this Sone
146          * @return This Sone (for method chaining)
147          */
148         public Sone setRequestUri(FreenetURI requestUri) {
149                 if (this.requestUri == null) {
150                         this.requestUri = requestUri;
151                         updateEditions();
152                         return this;
153                 }
154                 if (!this.requestUri.equalsKeypair(requestUri)) {
155                         logger.log(Level.WARNING, "Request URI %s tried to overwrite %s!", new Object[] { requestUri, this.requestUri });
156                         return this;
157                 }
158                 long latestEdition = requestUri.getEdition();
159                 if ((latestEdition > this.requestUri.getEdition()) || (latestEdition > this.requestUri.getSuggestedEdition())) {
160                         this.requestUri.setSuggestedEdition(latestEdition);
161                 }
162                 return this;
163         }
164
165         /**
166          * Returns the insert URI of this Sone.
167          *
168          * @return The insert URI of this Sone
169          */
170         public FreenetURI getInsertUri() {
171                 return insertUri;
172         }
173
174         /**
175          * Sets the insert URI of this Sone.
176          *
177          * @param insertUri
178          *            The insert URI of this Sone
179          * @return This Sone (for method chaining)
180          */
181         public Sone setInsertUri(FreenetURI insertUri) {
182                 if (this.insertUri == null) {
183                         this.insertUri = insertUri;
184                         updateEditions();
185                         return this;
186                 }
187                 if (!this.insertUri.equalsKeypair(insertUri)) {
188                         logger.log(Level.WARNING, "Request URI %s tried to overwrite %s!", new Object[] { insertUri, this.insertUri });
189                         return this;
190                 }
191                 long latestEdition = insertUri.getEdition();
192                 if ((latestEdition > this.insertUri.getEdition()) || (latestEdition > this.insertUri.getSuggestedEdition())) {
193                         this.insertUri.setSuggestedEdition(latestEdition);
194                 }
195                 return this;
196         }
197
198         /**
199          * Return the time of the last inserted update of this Sone.
200          *
201          * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
202          */
203         public long getTime() {
204                 return time;
205         }
206
207         /**
208          * Sets the time of the last inserted update of this Sone.
209          *
210          * @param time
211          *            The time of the update (in milliseconds since Jan 1, 1970 UTC)
212          * @return This Sone (for method chaining)
213          */
214         public Sone setTime(long time) {
215                 this.time = time;
216                 return this;
217         }
218
219         /**
220          * Returns a copy of the profile. If you want to update values in the
221          * profile of this Sone, update the values in the returned {@link Profile}
222          * and use {@link #setProfile(Profile)} to change the profile in this Sone.
223          *
224          * @return A copy of the profile
225          */
226         public Profile getProfile() {
227                 return new Profile(profile);
228         }
229
230         /**
231          * Sets the profile of this Sone. A copy of the given profile is stored so
232          * that subsequent modifications of the given profile are not reflected in
233          * this Sone!
234          *
235          * @param profile
236          *            The profile to set
237          */
238         public synchronized void setProfile(Profile profile) {
239                 this.profile = new Profile(profile);
240                 modificationCounter++;
241         }
242
243         /**
244          * Returns all friend Sones of this Sone.
245          *
246          * @return The friend Sones of this Sone
247          */
248         public List<Sone> getFriends() {
249                 List<Sone> friends = new ArrayList<Sone>(friendSones);
250                 Collections.sort(friends, new Comparator<Sone>() {
251
252                         @Override
253                         public int compare(Sone leftSone, Sone rightSone) {
254                                 int diff = SoneAccessor.getNiceName(leftSone).compareToIgnoreCase(SoneAccessor.getNiceName(rightSone));
255                                 if (diff != 0) {
256                                         return diff;
257                                 }
258                                 return (int) Math.max(Integer.MIN_VALUE, Math.min(Integer.MAX_VALUE, rightSone.getTime() - leftSone.getTime()));
259                         }
260                 });
261                 return friends;
262         }
263
264         /**
265          * Sets all friends of this Sone at once.
266          *
267          * @param friends
268          *            The new (and only) friends of this Sone
269          * @return This Sone (for method chaining)
270          */
271         public Sone setFriends(Collection<Sone> friends) {
272                 friendSones.clear();
273                 friendSones.addAll(friends);
274                 return this;
275         }
276
277         /**
278          * Returns whether this Sone has the given Sone as a friend Sone.
279          *
280          * @param friendSone
281          *            The friend Sone to check for
282          * @return {@code true} if this Sone has the given Sone as a friend,
283          *         {@code false} otherwise
284          */
285         public boolean hasFriend(Sone friendSone) {
286                 return friendSones.contains(friendSone);
287         }
288
289         /**
290          * Adds the given Sone as a friend Sone.
291          *
292          * @param friendSone
293          *            The friend Sone to add
294          * @return This Sone (for method chaining)
295          */
296         public Sone addFriend(Sone friendSone) {
297                 if (!friendSone.equals(this)) {
298                         friendSones.add(friendSone);
299                 }
300                 return this;
301         }
302
303         /**
304          * Removes the given Sone as a friend Sone.
305          *
306          * @param friendSone
307          *            The friend Sone to remove
308          * @return This Sone (for method chaining)
309          */
310         public Sone removeFriend(Sone friendSone) {
311                 friendSones.remove(friendSone);
312                 return this;
313         }
314
315         /**
316          * Returns the list of posts of this Sone, sorted by time, newest first.
317          *
318          * @return All posts of this Sone
319          */
320         public List<Post> getPosts() {
321                 List<Post> sortedPosts = new ArrayList<Post>(posts);
322                 Collections.sort(sortedPosts, new Comparator<Post>() {
323
324                         @Override
325                         public int compare(Post leftPost, Post rightPost) {
326                                 return (int) Math.max(Integer.MIN_VALUE, Math.min(Integer.MAX_VALUE, rightPost.getTime() - leftPost.getTime()));
327                         }
328
329                 });
330                 return sortedPosts;
331         }
332
333         /**
334          * Sets all posts of this Sone at once.
335          *
336          * @param posts
337          *            The new (and only) posts of this Sone
338          * @return This Sone (for method chaining)
339          */
340         public synchronized Sone setPosts(Collection<Post> posts) {
341                 this.posts.clear();
342                 this.posts.addAll(posts);
343                 modificationCounter++;
344                 return this;
345         }
346
347         /**
348          * Adds the given post to this Sone. The post will not be added if its
349          * {@link Post#getSone() Sone} is not this Sone.
350          *
351          * @param post
352          *            The post to add
353          */
354         public synchronized void addPost(Post post) {
355                 if (post.getSone().equals(this) && posts.add(post)) {
356                         logger.log(Level.FINEST, "Adding %s to “%s”.", new Object[] { post, getName() });
357                         modificationCounter++;
358                 }
359         }
360
361         /**
362          * Removes the given post from this Sone.
363          *
364          * @param post
365          *            The post to remove
366          */
367         public synchronized void removePost(Post post) {
368                 if (post.getSone().equals(this) && posts.remove(post)) {
369                         modificationCounter++;
370                 }
371         }
372
373         /**
374          * Returns all replies this Sone made.
375          *
376          * @return All replies this Sone made
377          */
378         public Set<Reply> getReplies() {
379                 logger.log(Level.FINEST, "Friends of %s: %s", new Object[] { this, friendSones });
380                 return Collections.unmodifiableSet(replies);
381         }
382
383         /**
384          * Sets all replies of this Sone at once.
385          *
386          * @param replies
387          *            The new (and only) replies of this Sone
388          * @return This Sone (for method chaining)
389          */
390         public synchronized Sone setReplies(Collection<Reply> replies) {
391                 this.replies.clear();
392                 this.replies.addAll(replies);
393                 modificationCounter++;
394                 return this;
395         }
396
397         /**
398          * Adds a reply to this Sone. If the given reply was not made by this Sone,
399          * nothing is added to this Sone.
400          *
401          * @param reply
402          *            The reply to add
403          */
404         public synchronized void addReply(Reply reply) {
405                 if (reply.getSone().equals(this) && replies.add(reply)) {
406                         modificationCounter++;
407                 }
408         }
409
410         /**
411          * Removes a reply from this Sone.
412          *
413          * @param reply
414          *            The reply to remove
415          */
416         public synchronized void removeReply(Reply reply) {
417                 if (reply.getSone().equals(this) && replies.remove(reply)) {
418                         modificationCounter++;
419                 }
420         }
421
422         /**
423          * Returns the IDs of all blocked Sones. These Sones will not propagated
424          * using the “known Sones” mechanism.
425          *
426          * @return The IDs of all blocked Sones
427          */
428         public Set<String> getBlockedSoneIds() {
429                 return Collections.unmodifiableSet(blockedSoneIds);
430         }
431
432         /**
433          * Returns whether the given Sone ID is blocked.
434          *
435          * @param soneId
436          *            The Sone ID to check
437          * @return {@code true} if the given Sone ID is blocked, {@code false}
438          *         otherwise
439          */
440         public boolean isSoneBlocked(String soneId) {
441                 return blockedSoneIds.contains(soneId);
442         }
443
444         /**
445          * Adds the given ID to the list of blocked IDs.
446          *
447          * @param soneId
448          *            The Sone ID to block
449          */
450         public synchronized void addBlockedSoneId(String soneId) {
451                 if (blockedSoneIds.add(soneId)) {
452                         modificationCounter++;
453                 }
454         }
455
456         /**
457          * Removes the given ID from the list of blocked IDs.
458          *
459          * @param soneId
460          *            The Sone ID to unblock
461          */
462         public synchronized void removeBlockedSoneId(String soneId) {
463                 if (blockedSoneIds.remove(soneId)) {
464                         modificationCounter++;
465                 }
466         }
467
468         /**
469          * Returns the IDs of all liked posts.
470          *
471          * @return All liked posts’ IDs
472          */
473         public Set<String> getLikedPostIds() {
474                 return Collections.unmodifiableSet(likedPostIds);
475         }
476
477         /**
478          * Sets the IDs of all liked posts.
479          *
480          * @param likedPostIds
481          *            All liked posts’ IDs
482          * @return This Sone (for method chaining)
483          */
484         public synchronized Sone setLikePostIds(Set<String> likedPostIds) {
485                 this.likedPostIds.clear();
486                 this.likedPostIds.addAll(likedPostIds);
487                 modificationCounter++;
488                 return this;
489         }
490
491         /**
492          * Checks whether the given post ID is liked by this Sone.
493          *
494          * @param postId
495          *            The ID of the post
496          * @return {@code true} if this Sone likes the given post, {@code false}
497          *         otherwise
498          */
499         public boolean isLikedPostId(String postId) {
500                 return likedPostIds.contains(postId);
501         }
502
503         /**
504          * Adds the given post ID to the list of posts this Sone likes.
505          *
506          * @param postId
507          *            The ID of the post
508          * @return This Sone (for method chaining)
509          */
510         public synchronized Sone addLikedPostId(String postId) {
511                 if (likedPostIds.add(postId)) {
512                         modificationCounter++;
513                 }
514                 return this;
515         }
516
517         /**
518          * Removes the given post ID from the list of posts this Sone likes.
519          *
520          * @param postId
521          *            The ID of the post
522          * @return This Sone (for method chaining)
523          */
524         public synchronized Sone removeLikedPostId(String postId) {
525                 if (likedPostIds.remove(postId)) {
526                         modificationCounter++;
527                 }
528                 return this;
529         }
530
531         /**
532          * Returns the IDs of all liked replies.
533          *
534          * @return All liked replies’ IDs
535          */
536         public Set<String> getLikedReplyIds() {
537                 return Collections.unmodifiableSet(likedReplyIds);
538         }
539
540         /**
541          * Sets the IDs of all liked replies.
542          *
543          * @param likedReplyIds
544          *            All liked replies’ IDs
545          * @return This Sone (for method chaining)
546          */
547         public synchronized Sone setLikeReplyIds(Set<String> likedReplyIds) {
548                 this.likedReplyIds.clear();
549                 this.likedReplyIds.addAll(likedReplyIds);
550                 modificationCounter++;
551                 return this;
552         }
553
554         /**
555          * Checks whether the given reply ID is liked by this Sone.
556          *
557          * @param replyId
558          *            The ID of the reply
559          * @return {@code true} if this Sone likes the given reply, {@code false}
560          *         otherwise
561          */
562         public boolean isLikedReplyId(String replyId) {
563                 return likedReplyIds.contains(replyId);
564         }
565
566         /**
567          * Adds the given reply ID to the list of replies this Sone likes.
568          *
569          * @param replyId
570          *            The ID of the reply
571          * @return This Sone (for method chaining)
572          */
573         public synchronized Sone addLikedReplyId(String replyId) {
574                 if (likedReplyIds.add(replyId)) {
575                         modificationCounter++;
576                 }
577                 return this;
578         }
579
580         /**
581          * Removes the given post ID from the list of replies this Sone likes.
582          *
583          * @param replyId
584          *            The ID of the reply
585          * @return This Sone (for method chaining)
586          */
587         public synchronized Sone removeLikedReplyId(String replyId) {
588                 if (likedReplyIds.remove(replyId)) {
589                         modificationCounter++;
590                 }
591                 return this;
592         }
593
594         /**
595          * Returns the modification counter.
596          *
597          * @return The modification counter
598          */
599         public synchronized long getModificationCounter() {
600                 return modificationCounter;
601         }
602
603         /**
604          * Sets the modification counter.
605          *
606          * @param modificationCounter
607          *            The new modification counter
608          */
609         public synchronized void setModificationCounter(long modificationCounter) {
610                 this.modificationCounter = modificationCounter;
611         }
612
613         /**
614          * Updates the suggested edition in both the request URI and the insert URI.
615          *
616          * @param latestEdition
617          *            The latest edition to update the URIs to
618          */
619         public void updateUris(long latestEdition) {
620                 if ((requestUri != null) && (requestUri.getEdition() < latestEdition)) {
621                         requestUri = requestUri.setSuggestedEdition(latestEdition);
622                 }
623                 if ((insertUri != null) && (insertUri.getEdition() < latestEdition)) {
624                         insertUri = insertUri.setSuggestedEdition(latestEdition);
625                 }
626         }
627
628         //
629         // PRIVATE METHODS
630         //
631
632         /**
633          * Updates the editions of the request URI and the insert URI (if latter is
634          * not {@code null}) with the greater edition of either one.
635          */
636         private void updateEditions() {
637                 long requestEdition = 0;
638                 if (requestUri != null) {
639                         requestEdition = requestUri.getEdition();
640                 }
641                 long insertEdition = 0;
642                 if (insertUri != null) {
643                         insertEdition = insertUri.getEdition();
644                 }
645                 updateUris(Math.max(requestEdition, insertEdition));
646         }
647
648         //
649         // OBJECT METHODS
650         //
651
652         /**
653          * {@inheritDoc}
654          */
655         @Override
656         public int hashCode() {
657                 return id.hashCode();
658         }
659
660         /**
661          * {@inheritDoc}
662          */
663         @Override
664         public boolean equals(Object object) {
665                 if (!(object instanceof Sone)) {
666                         return false;
667                 }
668                 return ((Sone) object).id.equals(id);
669         }
670
671         /**
672          * {@inheritDoc}
673          */
674         @Override
675         public String toString() {
676                 return getClass().getName() + "[id=" + id + ",name=" + name + ",requestUri=" + requestUri + ",insertUri=" + insertUri + ",friends(" + friendSones.size() + "),posts(" + posts.size() + "),replies(" + replies.size() + ")]";
677         }
678
679 }