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