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