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