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