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