Return to storing the ID instead of getting it from the identity.
[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 ID of this Sone. */
63         private final String id;
64
65         /** The identity of this Sone. */
66         private Identity identity;
67
68         /** The URI under which the Sone is stored in Freenet. */
69         private volatile FreenetURI requestUri;
70
71         /** The URI used to insert a new version of this Sone. */
72         /* This will be null for remote Sones! */
73         private volatile FreenetURI insertUri;
74
75         /** The latest edition of the Sone. */
76         private volatile long latestEdition;
77
78         /** The time of the last inserted update. */
79         private volatile long time;
80
81         /** The profile of this Sone. */
82         private volatile Profile profile;
83
84         /** All friend Sones. */
85         private final Set<Sone> friendSones = Collections.synchronizedSet(new HashSet<Sone>());
86
87         /** All posts. */
88         private final Set<Post> posts = Collections.synchronizedSet(new HashSet<Post>());
89
90         /** All replies. */
91         private final Set<Reply> replies = Collections.synchronizedSet(new HashSet<Reply>());
92
93         /** The IDs of all liked posts. */
94         private final Set<String> likedPostIds = Collections.synchronizedSet(new HashSet<String>());
95
96         /** The IDs of all liked replies. */
97         private final Set<String> likedReplyIds = Collections.synchronizedSet(new HashSet<String>());
98
99         /** Modification count. */
100         private volatile long modificationCounter = 0;
101
102         /**
103          * Creates a new Sone.
104          *
105          * @param id
106          *            The ID of the Sone
107          */
108         public Sone(String id) {
109                 this.id = id;
110         }
111
112         //
113         // ACCESSORS
114         //
115
116         /**
117          * Returns the identity of this Sone.
118          *
119          * @return The identity of this Sone
120          */
121         public String getId() {
122                 return id;
123         }
124
125         /**
126          * Returns the identity of this Sone.
127          *
128          * @return The identity of this Sone
129          */
130         public Identity getIdentity() {
131                 return identity;
132         }
133
134         /**
135          * Sets the identity of this Sone. The {@link Identity#getId() ID} of the
136          * identity has to match this Sone’s {@link #getId()}.
137          *
138          * @param identity
139          *            The identity of this Sone
140          * @return This Sone (for method chaining)
141          * @throws IllegalArgumentException
142          *             if the ID of the identity does not match this Sone’s ID
143          */
144         public Sone setIdentity(Identity identity) throws IllegalArgumentException {
145                 if (!identity.getId().equals(id)) {
146                         throw new IllegalArgumentException("Identity’s ID does not match Sone’s ID!");
147                 }
148                 this.identity = identity;
149                 return this;
150         }
151
152         /**
153          * Returns the name of this Sone.
154          *
155          * @return The name of this Sone
156          */
157         public String getName() {
158                 return (identity != null) ? identity.getNickname() : null;
159         }
160
161         /**
162          * Returns the request URI of this Sone.
163          *
164          * @return The request URI of this Sone
165          */
166         public FreenetURI getRequestUri() {
167                 return requestUri.setSuggestedEdition(latestEdition);
168         }
169
170         /**
171          * Sets the request URI of this Sone.
172          *
173          * @param requestUri
174          *            The request URI of this Sone
175          * @return This Sone (for method chaining)
176          */
177         public Sone setRequestUri(FreenetURI requestUri) {
178                 if (this.requestUri == null) {
179                         this.requestUri = requestUri.setDocName("Sone").setMetaString(new String[0]);
180                         return this;
181                 }
182                 if (!this.requestUri.equalsKeypair(requestUri)) {
183                         logger.log(Level.WARNING, "Request URI %s tried to overwrite %s!", new Object[] { requestUri, this.requestUri });
184                         return this;
185                 }
186                 setLatestEdition(requestUri.getEdition());
187                 return this;
188         }
189
190         /**
191          * Returns the insert URI of this Sone.
192          *
193          * @return The insert URI of this Sone
194          */
195         public FreenetURI getInsertUri() {
196                 return insertUri.setSuggestedEdition(latestEdition);
197         }
198
199         /**
200          * Sets the insert URI of this Sone.
201          *
202          * @param insertUri
203          *            The insert URI of this Sone
204          * @return This Sone (for method chaining)
205          */
206         public Sone setInsertUri(FreenetURI insertUri) {
207                 if (this.insertUri == null) {
208                         this.insertUri = insertUri.setDocName("Sone").setMetaString(new String[0]);
209                         return this;
210                 }
211                 if (!this.insertUri.equalsKeypair(insertUri)) {
212                         logger.log(Level.WARNING, "Request URI %s tried to overwrite %s!", new Object[] { insertUri, this.insertUri });
213                         return this;
214                 }
215                 setLatestEdition(insertUri.getEdition());
216                 return this;
217         }
218
219         /**
220          * Returns the latest edition of this Sone.
221          *
222          * @return The latest edition of this Sone
223          */
224         public long getLatestEdition() {
225                 return latestEdition;
226         }
227
228         /**
229          * Sets the latest edition of this Sone. If the given latest edition is not
230          * greater than the current latest edition, the latest edition of this Sone
231          * is not changed.
232          *
233          * @param latestEdition
234          *            The latest edition of this Sone
235          */
236         public void setLatestEdition(long latestEdition) {
237                 if (!(latestEdition > this.latestEdition)) {
238                         logger.log(Level.INFO, "New latest edition %d is not greater than current latest edition %d!", new Object[] { latestEdition, this.latestEdition });
239                         return;
240                 }
241                 this.latestEdition = latestEdition;
242         }
243
244         /**
245          * Return the time of the last inserted update of this Sone.
246          *
247          * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
248          */
249         public long getTime() {
250                 return time;
251         }
252
253         /**
254          * Sets the time of the last inserted update of this Sone.
255          *
256          * @param time
257          *            The time of the update (in milliseconds since Jan 1, 1970 UTC)
258          * @return This Sone (for method chaining)
259          */
260         public Sone setTime(long time) {
261                 this.time = time;
262                 return this;
263         }
264
265         /**
266          * Returns a copy of the profile. If you want to update values in the
267          * profile of this Sone, update the values in the returned {@link Profile}
268          * and use {@link #setProfile(Profile)} to change the profile in this Sone.
269          *
270          * @return A copy of the profile
271          */
272         public Profile getProfile() {
273                 return new Profile(profile);
274         }
275
276         /**
277          * Sets the profile of this Sone. A copy of the given profile is stored so
278          * that subsequent modifications of the given profile are not reflected in
279          * this Sone!
280          *
281          * @param profile
282          *            The profile to set
283          */
284         public synchronized void setProfile(Profile profile) {
285                 this.profile = new Profile(profile);
286                 modificationCounter++;
287         }
288
289         /**
290          * Returns all friend Sones of this Sone.
291          *
292          * @return The friend Sones of this Sone
293          */
294         public List<Sone> getFriends() {
295                 List<Sone> friends = new ArrayList<Sone>(friendSones);
296                 Collections.sort(friends, new Comparator<Sone>() {
297
298                         @Override
299                         public int compare(Sone leftSone, Sone rightSone) {
300                                 int diff = SoneAccessor.getNiceName(leftSone).compareToIgnoreCase(SoneAccessor.getNiceName(rightSone));
301                                 if (diff != 0) {
302                                         return diff;
303                                 }
304                                 return (int) Math.max(Integer.MIN_VALUE, Math.min(Integer.MAX_VALUE, rightSone.getTime() - leftSone.getTime()));
305                         }
306                 });
307                 return friends;
308         }
309
310         /**
311          * Sets all friends of this Sone at once.
312          *
313          * @param friends
314          *            The new (and only) friends of this Sone
315          * @return This Sone (for method chaining)
316          */
317         public Sone setFriends(Collection<Sone> friends) {
318                 friendSones.clear();
319                 friendSones.addAll(friends);
320                 return this;
321         }
322
323         /**
324          * Returns whether this Sone has the given Sone as a friend Sone.
325          *
326          * @param friendSone
327          *            The friend Sone to check for
328          * @return {@code true} if this Sone has the given Sone as a friend,
329          *         {@code false} otherwise
330          */
331         public boolean hasFriend(Sone friendSone) {
332                 return friendSones.contains(friendSone);
333         }
334
335         /**
336          * Adds the given Sone as a friend Sone.
337          *
338          * @param friendSone
339          *            The friend Sone to add
340          * @return This Sone (for method chaining)
341          */
342         public Sone addFriend(Sone friendSone) {
343                 if (!friendSone.equals(this)) {
344                         friendSones.add(friendSone);
345                 }
346                 return this;
347         }
348
349         /**
350          * Removes the given Sone as a friend Sone.
351          *
352          * @param friendSone
353          *            The friend Sone to remove
354          * @return This Sone (for method chaining)
355          */
356         public Sone removeFriend(Sone friendSone) {
357                 friendSones.remove(friendSone);
358                 return this;
359         }
360
361         /**
362          * Returns the list of posts of this Sone, sorted by time, newest first.
363          *
364          * @return All posts of this Sone
365          */
366         public List<Post> getPosts() {
367                 List<Post> sortedPosts = new ArrayList<Post>(posts);
368                 Collections.sort(sortedPosts, new Comparator<Post>() {
369
370                         @Override
371                         public int compare(Post leftPost, Post rightPost) {
372                                 return (int) Math.max(Integer.MIN_VALUE, Math.min(Integer.MAX_VALUE, rightPost.getTime() - leftPost.getTime()));
373                         }
374
375                 });
376                 return sortedPosts;
377         }
378
379         /**
380          * Sets all posts of this Sone at once.
381          *
382          * @param posts
383          *            The new (and only) posts of this Sone
384          * @return This Sone (for method chaining)
385          */
386         public synchronized Sone setPosts(Collection<Post> posts) {
387                 this.posts.clear();
388                 this.posts.addAll(posts);
389                 modificationCounter++;
390                 return this;
391         }
392
393         /**
394          * Adds the given post to this Sone. The post will not be added if its
395          * {@link Post#getSone() Sone} is not this Sone.
396          *
397          * @param post
398          *            The post to add
399          */
400         public synchronized void addPost(Post post) {
401                 if (post.getSone().equals(this) && posts.add(post)) {
402                         logger.log(Level.FINEST, "Adding %s to “%s”.", new Object[] { post, getName() });
403                         modificationCounter++;
404                 }
405         }
406
407         /**
408          * Removes the given post from this Sone.
409          *
410          * @param post
411          *            The post to remove
412          */
413         public synchronized void removePost(Post post) {
414                 if (post.getSone().equals(this) && posts.remove(post)) {
415                         modificationCounter++;
416                 }
417         }
418
419         /**
420          * Returns all replies this Sone made.
421          *
422          * @return All replies this Sone made
423          */
424         public Set<Reply> getReplies() {
425                 logger.log(Level.FINEST, "Friends of %s: %s", new Object[] { this, friendSones });
426                 return Collections.unmodifiableSet(replies);
427         }
428
429         /**
430          * Sets all replies of this Sone at once.
431          *
432          * @param replies
433          *            The new (and only) replies of this Sone
434          * @return This Sone (for method chaining)
435          */
436         public synchronized Sone setReplies(Collection<Reply> replies) {
437                 this.replies.clear();
438                 this.replies.addAll(replies);
439                 modificationCounter++;
440                 return this;
441         }
442
443         /**
444          * Adds a reply to this Sone. If the given reply was not made by this Sone,
445          * nothing is added to this Sone.
446          *
447          * @param reply
448          *            The reply to add
449          */
450         public synchronized void addReply(Reply reply) {
451                 if (reply.getSone().equals(this) && replies.add(reply)) {
452                         modificationCounter++;
453                 }
454         }
455
456         /**
457          * Removes a reply from this Sone.
458          *
459          * @param reply
460          *            The reply to remove
461          */
462         public synchronized void removeReply(Reply reply) {
463                 if (reply.getSone().equals(this) && replies.remove(reply)) {
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         // OBJECT METHODS
615         //
616
617         /**
618          * {@inheritDoc}
619          */
620         @Override
621         public int hashCode() {
622                 return id.hashCode();
623         }
624
625         /**
626          * {@inheritDoc}
627          */
628         @Override
629         public boolean equals(Object object) {
630                 if (!(object instanceof Sone)) {
631                         return false;
632                 }
633                 return ((Sone) object).id.equals(id);
634         }
635
636         /**
637          * {@inheritDoc}
638          */
639         @Override
640         public String toString() {
641                 return getClass().getName() + "[identity=" + identity + ",requestUri=" + requestUri + ",insertUri=" + insertUri + ",friends(" + friendSones.size() + "),posts(" + posts.size() + "),replies(" + replies.size() + ")]";
642         }
643
644 }