2 * Sone - MemorySone.java - Copyright © 2010–2012 David Roden
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.
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.
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/>.
18 package net.pterodactylus.sone.database.memory;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.List;
25 import java.util.concurrent.CopyOnWriteArrayList;
26 import java.util.concurrent.CopyOnWriteArraySet;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
30 import net.pterodactylus.sone.core.Options;
31 import net.pterodactylus.sone.data.Album;
32 import net.pterodactylus.sone.data.Client;
33 import net.pterodactylus.sone.data.Image;
34 import net.pterodactylus.sone.data.Post;
35 import net.pterodactylus.sone.data.PostReply;
36 import net.pterodactylus.sone.data.Profile;
37 import net.pterodactylus.sone.data.Reply;
38 import net.pterodactylus.sone.data.Sone;
39 import net.pterodactylus.sone.database.Database;
40 import net.pterodactylus.sone.freenet.wot.Identity;
41 import net.pterodactylus.util.logging.Logging;
42 import net.pterodactylus.util.validation.Validation;
43 import freenet.keys.FreenetURI;
46 * Implementation of a {@link Sone} that keeps all added data in memory. A
47 * self-created instance of this class should be converted to a {@link Database}
48 * -based instance of {@link Sone} as soon as possible (unless it was returned
49 * by a {@link MemoryDatabase}).
51 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
53 public class MemorySone implements Sone {
56 private static final Logger logger = Logging.getLogger(Sone.class);
58 /** The ID of this Sone. */
59 private final String id;
61 /** Whether this is a local Sone. */
62 private final boolean local;
64 /** The identity of this Sone. */
65 private Identity identity;
67 /** The URI under which the Sone is stored in Freenet. */
68 private volatile FreenetURI requestUri;
70 /** The URI used to insert a new version of this Sone. */
71 /* This will be null for remote Sones! */
72 private volatile FreenetURI insertUri;
74 /** The latest edition of the Sone. */
75 private volatile long latestEdition;
77 /** The time of the last inserted update. */
78 private volatile long time;
80 /** The status of this Sone. */
81 private volatile SoneStatus status = SoneStatus.unknown;
83 /** The profile of this Sone. */
84 private volatile Profile profile = new Profile(this);
86 /** The client used by the Sone. */
87 private volatile Client client;
89 /** Whether this Sone is known. */
90 private volatile boolean known;
92 /** All friend Sones. */
93 private final Set<String> friendSones = new CopyOnWriteArraySet<String>();
96 private final Set<Post> posts = new CopyOnWriteArraySet<Post>();
99 private final Set<PostReply> replies = new CopyOnWriteArraySet<PostReply>();
101 /** The IDs of all liked posts. */
102 private final Set<String> likedPostIds = new CopyOnWriteArraySet<String>();
104 /** The IDs of all liked replies. */
105 private final Set<String> likedReplyIds = new CopyOnWriteArraySet<String>();
107 /** The albums of this Sone. */
108 private final List<Album> albums = new CopyOnWriteArrayList<Album>();
110 /** Sone-specific options. */
111 private final Options options = new Options();
114 * Creates a new Sone.
119 * {@code true} if this Sone is local, {@code false} otherwise
121 public MemorySone(String id, boolean local) {
134 public String getId() {
142 public Identity getIdentity() {
150 public Sone setIdentity(Identity identity) throws IllegalArgumentException {
151 if (!identity.getId().equals(id)) {
152 throw new IllegalArgumentException("Identity’s ID does not match Sone’s ID!");
154 this.identity = identity;
162 public boolean isLocal() {
170 public String getName() {
171 return (identity != null) ? identity.getNickname() : null;
178 public FreenetURI getRequestUri() {
179 return (requestUri != null) ? requestUri.setSuggestedEdition(latestEdition) : null;
186 public Sone setRequestUri(FreenetURI requestUri) {
187 if (this.requestUri == null) {
188 this.requestUri = requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
191 if (!this.requestUri.equalsKeypair(requestUri)) {
192 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", requestUri, this.requestUri));
202 public FreenetURI getInsertUri() {
203 return (insertUri != null) ? insertUri.setSuggestedEdition(latestEdition) : null;
210 public Sone setInsertUri(FreenetURI insertUri) {
211 if (this.insertUri == null) {
212 this.insertUri = insertUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
215 if (!this.insertUri.equalsKeypair(insertUri)) {
216 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", insertUri, this.insertUri));
226 public long getLatestEdition() {
227 return latestEdition;
234 public void setLatestEdition(long latestEdition) {
235 if (!(latestEdition > this.latestEdition)) {
236 logger.log(Level.FINE, String.format("New latest edition %d is not greater than current latest edition %d!", latestEdition, this.latestEdition));
239 this.latestEdition = latestEdition;
246 public long getTime() {
254 public Sone setTime(long time) {
263 public SoneStatus getStatus() {
271 public Sone setStatus(SoneStatus status) {
272 Validation.begin().isNotNull("Sone Status", status).check();
273 this.status = status;
281 public Profile getProfile() {
282 return new Profile(profile);
289 public void setProfile(Profile profile) {
290 this.profile = new Profile(profile);
297 public Client getClient() {
305 public Sone setClient(Client client) {
306 this.client = client;
314 public boolean isKnown() {
322 public Sone setKnown(boolean known) {
331 public List<String> getFriends() {
332 List<String> friends = new ArrayList<String>(friendSones);
340 public boolean hasFriend(String friendSoneId) {
341 return friendSones.contains(friendSoneId);
348 public Sone addFriend(String friendSone) {
349 if (!friendSone.equals(id)) {
350 friendSones.add(friendSone);
359 public Sone removeFriend(String friendSoneId) {
360 friendSones.remove(friendSoneId);
368 public List<Post> getPosts() {
369 List<Post> sortedPosts;
370 synchronized (this) {
371 sortedPosts = new ArrayList<Post>(posts);
373 Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
381 public Sone setPosts(Collection<Post> posts) {
382 synchronized (this) {
384 this.posts.addAll(posts);
393 public void addPost(Post post) {
394 if (post.getSone().equals(this) && posts.add(post)) {
395 logger.log(Level.FINEST, String.format("Adding %s to “%s”.", post, getName()));
403 public void removePost(Post post) {
404 if (post.getSone().equals(this)) {
413 public Set<PostReply> getReplies() {
414 return Collections.unmodifiableSet(replies);
421 public Sone setReplies(Collection<PostReply> replies) {
422 this.replies.clear();
423 this.replies.addAll(replies);
431 public void addReply(PostReply reply) {
432 if (reply.getSone().equals(this)) {
441 public void removeReply(PostReply reply) {
442 if (reply.getSone().equals(this)) {
443 replies.remove(reply);
451 public Set<String> getLikedPostIds() {
452 return Collections.unmodifiableSet(likedPostIds);
459 public Sone setLikePostIds(Set<String> likedPostIds) {
460 this.likedPostIds.clear();
461 this.likedPostIds.addAll(likedPostIds);
469 public boolean isLikedPostId(String postId) {
470 return likedPostIds.contains(postId);
477 public Sone addLikedPostId(String postId) {
478 likedPostIds.add(postId);
486 public Sone removeLikedPostId(String postId) {
487 likedPostIds.remove(postId);
495 public Set<String> getLikedReplyIds() {
496 return Collections.unmodifiableSet(likedReplyIds);
503 public Sone setLikeReplyIds(Set<String> likedReplyIds) {
504 this.likedReplyIds.clear();
505 this.likedReplyIds.addAll(likedReplyIds);
513 public boolean isLikedReplyId(String replyId) {
514 return likedReplyIds.contains(replyId);
521 public Sone addLikedReplyId(String replyId) {
522 likedReplyIds.add(replyId);
530 public Sone removeLikedReplyId(String replyId) {
531 likedReplyIds.remove(replyId);
539 public List<Album> getAlbums() {
540 return Collections.unmodifiableList(albums);
547 public List<Album> getAllAlbums() {
548 List<Album> flatAlbums = new ArrayList<Album>();
549 flatAlbums.addAll(albums);
550 int lastAlbumIndex = 0;
551 while (lastAlbumIndex < flatAlbums.size()) {
552 int previousAlbumCount = flatAlbums.size();
553 for (Album album : new ArrayList<Album>(flatAlbums.subList(lastAlbumIndex, flatAlbums.size()))) {
554 flatAlbums.addAll(album.getAlbums());
556 lastAlbumIndex = previousAlbumCount;
565 public List<Image> getAllImages() {
566 List<Image> allImages = new ArrayList<Image>();
567 for (Album album : getAllAlbums()) {
568 allImages.addAll(album.getImages());
577 public void addAlbum(Album album) {
578 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
579 if (!albums.contains(album)) {
588 public void setAlbums(Collection<? extends Album> albums) {
589 Validation.begin().isNotNull("Albums", albums).check();
591 for (Album album : albums) {
600 public void removeAlbum(Album album) {
601 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
602 albums.remove(album);
609 public Album moveAlbumUp(Album album) {
610 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).isNull("Album Parent", album.getParent()).check();
611 int oldIndex = albums.indexOf(album);
615 albums.remove(oldIndex);
616 albums.add(oldIndex - 1, album);
617 return albums.get(oldIndex);
624 public Album moveAlbumDown(Album album) {
625 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).isNull("Album Parent", album.getParent()).check();
626 int oldIndex = albums.indexOf(album);
627 if ((oldIndex < 0) || (oldIndex >= (albums.size() - 1))) {
630 albums.remove(oldIndex);
631 albums.add(oldIndex + 1, album);
632 return albums.get(oldIndex);
639 public Options getOptions() {
644 // FINGERPRINTABLE METHODS
651 public synchronized String getFingerprint() {
652 StringBuilder fingerprint = new StringBuilder();
653 fingerprint.append(profile.getFingerprint());
655 fingerprint.append("Posts(");
656 for (Post post : getPosts()) {
657 fingerprint.append("Post(").append(post.getId()).append(')');
659 fingerprint.append(")");
661 List<PostReply> replies = new ArrayList<PostReply>(getReplies());
662 Collections.sort(replies, Reply.TIME_COMPARATOR);
663 fingerprint.append("Replies(");
664 for (PostReply reply : replies) {
665 fingerprint.append("Reply(").append(reply.getId()).append(')');
667 fingerprint.append(')');
669 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
670 Collections.sort(likedPostIds);
671 fingerprint.append("LikedPosts(");
672 for (String likedPostId : likedPostIds) {
673 fingerprint.append("Post(").append(likedPostId).append(')');
675 fingerprint.append(')');
677 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
678 Collections.sort(likedReplyIds);
679 fingerprint.append("LikedReplies(");
680 for (String likedReplyId : likedReplyIds) {
681 fingerprint.append("Reply(").append(likedReplyId).append(')');
683 fingerprint.append(')');
685 fingerprint.append("Albums(");
686 for (Album album : albums) {
687 fingerprint.append(album.getFingerprint());
689 fingerprint.append(')');
691 return fingerprint.toString();
695 // INTERFACE Comparable<Sone>
702 public int compareTo(Sone sone) {
703 return NICE_NAME_COMPARATOR.compare(this, sone);
714 public int hashCode() {
715 return id.hashCode();
722 public boolean equals(Object object) {
723 if (!(object instanceof Sone)) {
726 return ((Sone) object).getId().equals(id);
733 public String toString() {
734 return getClass().getName() + "[identity=" + identity + ",requestUri=" + requestUri + ",insertUri(" + String.valueOf(insertUri).length() + "),friends(" + friendSones.size() + "),posts(" + posts.size() + "),replies(" + replies.size() + ")]";