2 * Sone - Core.java - Copyright © 2010 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.core;
20 import java.net.MalformedURLException;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.List;
28 import java.util.Map.Entry;
29 import java.util.concurrent.ExecutorService;
30 import java.util.concurrent.Executors;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
34 import net.pterodactylus.sone.core.Options.DefaultOption;
35 import net.pterodactylus.sone.core.Options.Option;
36 import net.pterodactylus.sone.core.Options.OptionWatcher;
37 import net.pterodactylus.sone.data.Client;
38 import net.pterodactylus.sone.data.Post;
39 import net.pterodactylus.sone.data.Profile;
40 import net.pterodactylus.sone.data.Profile.Field;
41 import net.pterodactylus.sone.data.Reply;
42 import net.pterodactylus.sone.data.Sone;
43 import net.pterodactylus.sone.fcp.FcpInterface;
44 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
45 import net.pterodactylus.sone.freenet.wot.Identity;
46 import net.pterodactylus.sone.freenet.wot.IdentityListener;
47 import net.pterodactylus.sone.freenet.wot.IdentityManager;
48 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
49 import net.pterodactylus.sone.freenet.wot.Trust;
50 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
51 import net.pterodactylus.sone.main.SonePlugin;
52 import net.pterodactylus.util.config.Configuration;
53 import net.pterodactylus.util.config.ConfigurationException;
54 import net.pterodactylus.util.logging.Logging;
55 import net.pterodactylus.util.number.Numbers;
56 import net.pterodactylus.util.thread.Ticker;
57 import net.pterodactylus.util.validation.EqualityValidator;
58 import net.pterodactylus.util.validation.IntegerRangeValidator;
59 import net.pterodactylus.util.validation.OrValidator;
60 import net.pterodactylus.util.validation.Validation;
61 import net.pterodactylus.util.version.Version;
62 import freenet.keys.FreenetURI;
67 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
69 public class Core implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener {
72 * Enumeration for the possible states of a {@link Sone}.
74 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
76 public enum SoneStatus {
78 /** The Sone is unknown, i.e. not yet downloaded. */
81 /** The Sone is idle, i.e. not being downloaded or inserted. */
84 /** The Sone is currently being inserted. */
87 /** The Sone is currently being downloaded. */
92 private static final Logger logger = Logging.getLogger(Core.class);
95 private final Options options = new Options();
97 /** The preferences. */
98 private final Preferences preferences = new Preferences(options);
100 /** The core listener manager. */
101 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
103 /** The configuration. */
104 private Configuration configuration;
106 /** Whether we’re currently saving the configuration. */
107 private boolean storingConfiguration = false;
109 /** The identity manager. */
110 private final IdentityManager identityManager;
112 /** Interface to freenet. */
113 private final FreenetInterface freenetInterface;
115 /** The Sone downloader. */
116 private final SoneDownloader soneDownloader;
118 /** Sone downloader thread-pool. */
119 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
121 /** The update checker. */
122 private final UpdateChecker updateChecker;
124 /** The FCP interface. */
125 private volatile FcpInterface fcpInterface;
127 /** Whether the core has been stopped. */
128 @SuppressWarnings("unused")
129 private volatile boolean stopped;
131 /** The Sones’ statuses. */
132 /* synchronize access on itself. */
133 private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
135 /** Locked local Sones. */
136 /* synchronize on itself. */
137 private final Set<Sone> lockedSones = new HashSet<Sone>();
139 /** Sone inserters. */
140 /* synchronize access on this on localSones. */
141 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
143 /** Sone rescuers. */
144 /* synchronize access on this on localSones. */
145 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
147 /** All local Sones. */
148 /* synchronize access on this on itself. */
149 private Map<String, Sone> localSones = new HashMap<String, Sone>();
151 /** All remote Sones. */
152 /* synchronize access on this on itself. */
153 private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
155 /** All new Sones. */
156 private Set<String> newSones = new HashSet<String>();
158 /** All known Sones. */
159 /* synchronize access on {@link #newSones}. */
160 private Set<String> knownSones = new HashSet<String>();
163 private Map<String, Post> posts = new HashMap<String, Post>();
165 /** All new posts. */
166 private Set<String> newPosts = new HashSet<String>();
168 /** All known posts. */
169 /* synchronize access on {@link #newPosts}. */
170 private Set<String> knownPosts = new HashSet<String>();
173 private Map<String, Reply> replies = new HashMap<String, Reply>();
175 /** All new replies. */
176 private Set<String> newReplies = new HashSet<String>();
178 /** All known replies. */
179 private Set<String> knownReplies = new HashSet<String>();
181 /** All bookmarked posts. */
182 /* synchronize access on itself. */
183 private Set<String> bookmarkedPosts = new HashSet<String>();
185 /** Trusted identities, sorted by own identities. */
186 private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
188 /** Ticker for threads that mark own elements as known. */
189 private Ticker localElementTicker = new Ticker();
192 * Creates a new core.
194 * @param configuration
195 * The configuration of the core
196 * @param freenetInterface
197 * The freenet interface
198 * @param identityManager
199 * The identity manager
201 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
202 this.configuration = configuration;
203 this.freenetInterface = freenetInterface;
204 this.identityManager = identityManager;
205 this.soneDownloader = new SoneDownloader(this, freenetInterface);
206 this.updateChecker = new UpdateChecker(freenetInterface);
210 // LISTENER MANAGEMENT
214 * Adds a new core listener.
216 * @param coreListener
217 * The listener to add
219 public void addCoreListener(CoreListener coreListener) {
220 coreListenerManager.addListener(coreListener);
224 * Removes a core listener.
226 * @param coreListener
227 * The listener to remove
229 public void removeCoreListener(CoreListener coreListener) {
230 coreListenerManager.removeListener(coreListener);
238 * Sets the configuration to use. This will automatically save the current
239 * configuration to the given configuration.
241 * @param configuration
242 * The new configuration to use
244 public void setConfiguration(Configuration configuration) {
245 this.configuration = configuration;
250 * Returns the options used by the core.
252 * @return The options of the core
254 public Preferences getPreferences() {
259 * Returns the identity manager used by the core.
261 * @return The identity manager
263 public IdentityManager getIdentityManager() {
264 return identityManager;
268 * Returns the update checker.
270 * @return The update checker
272 public UpdateChecker getUpdateChecker() {
273 return updateChecker;
277 * Sets the FCP interface to use.
279 * @param fcpInterface
280 * The FCP interface to use
282 public void setFcpInterface(FcpInterface fcpInterface) {
283 this.fcpInterface = fcpInterface;
287 * Returns the status of the given Sone.
290 * The Sone to get the status for
291 * @return The status of the Sone
293 public SoneStatus getSoneStatus(Sone sone) {
294 synchronized (soneStatuses) {
295 return soneStatuses.get(sone);
300 * Sets the status of the given Sone.
303 * The Sone to set the status of
307 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
308 synchronized (soneStatuses) {
309 soneStatuses.put(sone, soneStatus);
314 * Returns the Sone rescuer for the given local Sone.
317 * The local Sone to get the rescuer for
318 * @return The Sone rescuer for the given Sone
320 public SoneRescuer getSoneRescuer(Sone sone) {
321 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", isLocalSone(sone)).check();
322 synchronized (localSones) {
323 SoneRescuer soneRescuer = soneRescuers.get(sone);
324 if (soneRescuer == null) {
325 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
326 soneRescuers.put(sone, soneRescuer);
334 * Returns whether the given Sone is currently locked.
338 * @return {@code true} if the Sone is locked, {@code false} if it is not
340 public boolean isLocked(Sone sone) {
341 synchronized (lockedSones) {
342 return lockedSones.contains(sone);
347 * Returns all Sones, remote and local.
351 public Set<Sone> getSones() {
352 Set<Sone> allSones = new HashSet<Sone>();
353 allSones.addAll(getLocalSones());
354 allSones.addAll(getRemoteSones());
359 * Returns the Sone with the given ID, regardless whether it’s local or
363 * The ID of the Sone to get
364 * @return The Sone with the given ID, or {@code null} if there is no such
367 public Sone getSone(String id) {
368 return getSone(id, true);
372 * Returns the Sone with the given ID, regardless whether it’s local or
376 * The ID of the Sone to get
378 * {@code true} to create a new Sone if none exists,
379 * {@code false} to return {@code null} if a Sone with the given
381 * @return The Sone with the given ID, or {@code null} if there is no such
385 public Sone getSone(String id, boolean create) {
386 if (isLocalSone(id)) {
387 return getLocalSone(id);
389 return getRemoteSone(id, create);
393 * Checks whether the core knows a Sone with the given ID.
397 * @return {@code true} if there is a Sone with the given ID, {@code false}
400 public boolean hasSone(String id) {
401 return isLocalSone(id) || isRemoteSone(id);
405 * Returns whether the given Sone is a local Sone.
408 * The Sone to check for its locality
409 * @return {@code true} if the given Sone is local, {@code false} otherwise
411 public boolean isLocalSone(Sone sone) {
412 synchronized (localSones) {
413 return localSones.containsKey(sone.getId());
418 * Returns whether the given ID is the ID of a local Sone.
421 * The Sone ID to check for its locality
422 * @return {@code true} if the given ID is a local Sone, {@code false}
425 public boolean isLocalSone(String id) {
426 synchronized (localSones) {
427 return localSones.containsKey(id);
432 * Returns all local Sones.
434 * @return All local Sones
436 public Set<Sone> getLocalSones() {
437 synchronized (localSones) {
438 return new HashSet<Sone>(localSones.values());
443 * Returns the local Sone with the given ID.
446 * The ID of the Sone to get
447 * @return The Sone with the given ID
449 public Sone getLocalSone(String id) {
450 return getLocalSone(id, true);
454 * Returns the local Sone with the given ID, optionally creating a new Sone.
459 * {@code true} to create a new Sone if none exists,
460 * {@code false} to return null if none exists
461 * @return The Sone with the given ID, or {@code null}
463 public Sone getLocalSone(String id, boolean create) {
464 synchronized (localSones) {
465 Sone sone = localSones.get(id);
466 if ((sone == null) && create) {
468 localSones.put(id, sone);
469 setSoneStatus(sone, SoneStatus.unknown);
476 * Returns all remote Sones.
478 * @return All remote Sones
480 public Set<Sone> getRemoteSones() {
481 synchronized (remoteSones) {
482 return new HashSet<Sone>(remoteSones.values());
487 * Returns the remote Sone with the given ID.
490 * The ID of the remote Sone to get
491 * @return The Sone with the given ID
493 public Sone getRemoteSone(String id) {
494 return getRemoteSone(id, true);
498 * Returns the remote Sone with the given ID.
501 * The ID of the remote Sone to get
503 * {@code true} to always create a Sone, {@code false} to return
504 * {@code null} if no Sone with the given ID exists
505 * @return The Sone with the given ID
507 public Sone getRemoteSone(String id, boolean create) {
508 synchronized (remoteSones) {
509 Sone sone = remoteSones.get(id);
510 if ((sone == null) && create) {
512 remoteSones.put(id, sone);
513 setSoneStatus(sone, SoneStatus.unknown);
520 * Returns whether the given Sone is a remote Sone.
524 * @return {@code true} if the given Sone is a remote Sone, {@code false}
527 public boolean isRemoteSone(Sone sone) {
528 synchronized (remoteSones) {
529 return remoteSones.containsKey(sone.getId());
534 * Returns whether the Sone with the given ID is a remote Sone.
537 * The ID of the Sone to check
538 * @return {@code true} if the Sone with the given ID is a remote Sone,
539 * {@code false} otherwise
541 public boolean isRemoteSone(String id) {
542 synchronized (remoteSones) {
543 return remoteSones.containsKey(id);
548 * Returns whether the Sone with the given ID is a new Sone.
551 * The ID of the sone to check for
552 * @return {@code true} if the given Sone is new, false otherwise
554 public boolean isNewSone(String soneId) {
555 synchronized (newSones) {
556 return !knownSones.contains(soneId) && newSones.contains(soneId);
561 * Returns whether the given Sone has been modified.
564 * The Sone to check for modifications
565 * @return {@code true} if a modification has been detected in the Sone,
566 * {@code false} otherwise
568 public boolean isModifiedSone(Sone sone) {
569 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
573 * Returns whether the target Sone is trusted by the origin Sone.
579 * @return {@code true} if the target Sone is trusted by the origin Sone
581 public boolean isSoneTrusted(Sone origin, Sone target) {
582 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
583 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
587 * Returns the post with the given ID.
590 * The ID of the post to get
591 * @return The post with the given ID, or a new post with the given ID
593 public Post getPost(String postId) {
594 return getPost(postId, true);
598 * Returns the post with the given ID, optionally creating a new post.
601 * The ID of the post to get
603 * {@code true} it create a new post if no post with the given ID
604 * exists, {@code false} to return {@code null}
605 * @return The post, or {@code null} if there is no such post
608 public Post getPost(String postId, boolean create) {
609 synchronized (posts) {
610 Post post = posts.get(postId);
611 if ((post == null) && create) {
612 post = new Post(postId);
613 posts.put(postId, post);
620 * Returns whether the given post ID is new.
624 * @return {@code true} if the post is considered to be new, {@code false}
627 public boolean isNewPost(String postId) {
628 synchronized (newPosts) {
629 return !knownPosts.contains(postId) && newPosts.contains(postId);
634 * Returns all posts that have the given Sone as recipient.
636 * @see Post#getRecipient()
638 * The recipient of the posts
639 * @return All posts that have the given Sone as recipient
641 public Set<Post> getDirectedPosts(Sone recipient) {
642 Validation.begin().isNotNull("Recipient", recipient).check();
643 Set<Post> directedPosts = new HashSet<Post>();
644 synchronized (posts) {
645 for (Post post : posts.values()) {
646 if (recipient.equals(post.getRecipient())) {
647 directedPosts.add(post);
651 return directedPosts;
655 * Returns the reply with the given ID. If there is no reply with the given
656 * ID yet, a new one is created.
659 * The ID of the reply to get
662 public Reply getReply(String replyId) {
663 return getReply(replyId, true);
667 * Returns the reply with the given ID. If there is no reply with the given
668 * ID yet, a new one is created, unless {@code create} is false in which
669 * case {@code null} is returned.
672 * The ID of the reply to get
674 * {@code true} to always return a {@link Reply}, {@code false}
675 * to return {@code null} if no reply can be found
676 * @return The reply, or {@code null} if there is no such reply
678 public Reply getReply(String replyId, boolean create) {
679 synchronized (replies) {
680 Reply reply = replies.get(replyId);
681 if (create && (reply == null)) {
682 reply = new Reply(replyId);
683 replies.put(replyId, reply);
690 * Returns all replies for the given post, order ascending by time.
693 * The post to get all replies for
694 * @return All replies for the given post
696 public List<Reply> getReplies(Post post) {
697 Set<Sone> sones = getSones();
698 List<Reply> replies = new ArrayList<Reply>();
699 for (Sone sone : sones) {
700 for (Reply reply : sone.getReplies()) {
701 if (reply.getPost().equals(post)) {
706 Collections.sort(replies, Reply.TIME_COMPARATOR);
711 * Returns whether the reply with the given ID is new.
714 * The ID of the reply to check
715 * @return {@code true} if the reply is considered to be new, {@code false}
718 public boolean isNewReply(String replyId) {
719 synchronized (newReplies) {
720 return !knownReplies.contains(replyId) && newReplies.contains(replyId);
725 * Returns all Sones that have liked the given post.
728 * The post to get the liking Sones for
729 * @return The Sones that like the given post
731 public Set<Sone> getLikes(Post post) {
732 Set<Sone> sones = new HashSet<Sone>();
733 for (Sone sone : getSones()) {
734 if (sone.getLikedPostIds().contains(post.getId())) {
742 * Returns all Sones that have liked the given reply.
745 * The reply to get the liking Sones for
746 * @return The Sones that like the given reply
748 public Set<Sone> getLikes(Reply reply) {
749 Set<Sone> sones = new HashSet<Sone>();
750 for (Sone sone : getSones()) {
751 if (sone.getLikedReplyIds().contains(reply.getId())) {
759 * Returns whether the given post is bookmarked.
763 * @return {@code true} if the given post is bookmarked, {@code false}
766 public boolean isBookmarked(Post post) {
767 return isPostBookmarked(post.getId());
771 * Returns whether the post with the given ID is bookmarked.
774 * The ID of the post to check
775 * @return {@code true} if the post with the given ID is bookmarked,
776 * {@code false} otherwise
778 public boolean isPostBookmarked(String id) {
779 synchronized (bookmarkedPosts) {
780 return bookmarkedPosts.contains(id);
785 * Returns all currently known bookmarked posts.
787 * @return All bookmarked posts
789 public Set<Post> getBookmarkedPosts() {
790 Set<Post> posts = new HashSet<Post>();
791 synchronized (bookmarkedPosts) {
792 for (String bookmarkedPostId : bookmarkedPosts) {
793 Post post = getPost(bookmarkedPostId, false);
807 * Locks the given Sone. A locked Sone will not be inserted by
808 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
814 public void lockSone(Sone sone) {
815 synchronized (lockedSones) {
816 if (lockedSones.add(sone)) {
817 coreListenerManager.fireSoneLocked(sone);
823 * Unlocks the given Sone.
825 * @see #lockSone(Sone)
829 public void unlockSone(Sone sone) {
830 synchronized (lockedSones) {
831 if (lockedSones.remove(sone)) {
832 coreListenerManager.fireSoneUnlocked(sone);
838 * Adds a local Sone from the given ID which has to be the ID of an own
842 * The ID of an own identity to add a Sone for
843 * @return The added (or already existing) Sone
845 public Sone addLocalSone(String id) {
846 synchronized (localSones) {
847 if (localSones.containsKey(id)) {
848 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
849 return localSones.get(id);
851 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
852 if (ownIdentity == null) {
853 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
856 return addLocalSone(ownIdentity);
861 * Adds a local Sone from the given own identity.
864 * The own identity to create a Sone from
865 * @return The added (or already existing) Sone
867 public Sone addLocalSone(OwnIdentity ownIdentity) {
868 if (ownIdentity == null) {
869 logger.log(Level.WARNING, "Given OwnIdentity is null!");
872 synchronized (localSones) {
875 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
876 } catch (MalformedURLException mue1) {
877 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
880 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
881 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
882 /* TODO - load posts ’n stuff */
883 localSones.put(ownIdentity.getId(), sone);
884 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
885 soneInserter.addSoneInsertListener(this);
886 soneInserters.put(sone, soneInserter);
887 setSoneStatus(sone, SoneStatus.idle);
889 soneInserter.start();
895 * Creates a new Sone for the given own identity.
898 * The own identity to create a Sone for
899 * @return The created Sone
901 public Sone createSone(OwnIdentity ownIdentity) {
903 ownIdentity.addContext("Sone");
904 } catch (WebOfTrustException wote1) {
905 logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
908 Sone sone = addLocalSone(ownIdentity);
909 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
910 sone.addFriend("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
916 * Adds the Sone of the given identity.
919 * The identity whose Sone to add
920 * @return The added or already existing Sone
922 public Sone addRemoteSone(Identity identity) {
923 if (identity == null) {
924 logger.log(Level.WARNING, "Given Identity is null!");
927 synchronized (remoteSones) {
928 final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
929 boolean newSone = sone.getRequestUri() == null;
930 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
931 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
933 synchronized (newSones) {
934 newSone = !knownSones.contains(sone.getId());
936 newSones.add(sone.getId());
940 coreListenerManager.fireNewSoneFound(sone);
941 for (Sone localSone : getLocalSones()) {
942 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
943 localSone.addFriend(sone.getId());
949 remoteSones.put(identity.getId(), sone);
950 soneDownloader.addSone(sone);
951 setSoneStatus(sone, SoneStatus.unknown);
952 soneDownloaders.execute(new Runnable() {
955 @SuppressWarnings("synthetic-access")
957 soneDownloader.fetchSone(sone, sone.getRequestUri());
966 * Retrieves the trust relationship from the origin to the target. If the
967 * trust relationship can not be retrieved, {@code null} is returned.
969 * @see Identity#getTrust(OwnIdentity)
971 * The origin of the trust tree
973 * The target of the trust
974 * @return The trust relationship
976 public Trust getTrust(Sone origin, Sone target) {
977 if (!isLocalSone(origin)) {
978 logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
981 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
985 * Sets the trust value of the given origin Sone for the target Sone.
992 * The trust value (from {@code -100} to {@code 100})
994 public void setTrust(Sone origin, Sone target, int trustValue) {
995 Validation.begin().isNotNull("Trust Origin", origin).check().isInstanceOf("Trust Origin", origin.getIdentity(), OwnIdentity.class).isNotNull("Trust Target", target).isLessOrEqual("Trust Value", trustValue, 100).isGreaterOrEqual("Trust Value", trustValue, -100).check();
997 ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
998 } catch (WebOfTrustException wote1) {
999 logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
1004 * Removes any trust assignment for the given target Sone.
1011 public void removeTrust(Sone origin, Sone target) {
1012 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1014 ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1015 } catch (WebOfTrustException wote1) {
1016 logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
1021 * Assigns the configured positive trust value for the given target.
1028 public void trustSone(Sone origin, Sone target) {
1029 setTrust(origin, target, preferences.getPositiveTrust());
1033 * Assigns the configured negative trust value for the given target.
1040 public void distrustSone(Sone origin, Sone target) {
1041 setTrust(origin, target, preferences.getNegativeTrust());
1045 * Removes the trust assignment for the given target.
1052 public void untrustSone(Sone origin, Sone target) {
1053 removeTrust(origin, target);
1057 * Updates the stored Sone with the given Sone.
1062 public void updateSone(Sone sone) {
1063 updateSone(sone, false);
1067 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1068 * {@code true}, an older Sone than the current Sone can be given to restore
1072 * The Sone to update
1073 * @param soneRescueMode
1074 * {@code true} if the stored Sone should be updated regardless
1075 * of the age of the given Sone
1077 public void updateSone(Sone sone, boolean soneRescueMode) {
1078 if (hasSone(sone.getId())) {
1079 Sone storedSone = getSone(sone.getId());
1080 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1081 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1084 synchronized (posts) {
1085 if (!soneRescueMode) {
1086 for (Post post : storedSone.getPosts()) {
1087 posts.remove(post.getId());
1088 if (!sone.getPosts().contains(post)) {
1089 coreListenerManager.firePostRemoved(post);
1093 List<Post> storedPosts = storedSone.getPosts();
1094 synchronized (newPosts) {
1095 for (Post post : sone.getPosts()) {
1096 post.setSone(storedSone);
1097 if (!storedPosts.contains(post) && !knownPosts.contains(post.getId())) {
1098 newPosts.add(post.getId());
1099 coreListenerManager.fireNewPostFound(post);
1101 posts.put(post.getId(), post);
1105 synchronized (replies) {
1106 if (!soneRescueMode) {
1107 for (Reply reply : storedSone.getReplies()) {
1108 replies.remove(reply.getId());
1109 if (!sone.getReplies().contains(reply)) {
1110 coreListenerManager.fireReplyRemoved(reply);
1114 Set<Reply> storedReplies = storedSone.getReplies();
1115 synchronized (newReplies) {
1116 for (Reply reply : sone.getReplies()) {
1117 reply.setSone(storedSone);
1118 if (!storedReplies.contains(reply) && !knownReplies.contains(reply.getId())) {
1119 newReplies.add(reply.getId());
1120 coreListenerManager.fireNewReplyFound(reply);
1122 replies.put(reply.getId(), reply);
1126 synchronized (storedSone) {
1127 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1128 storedSone.setTime(sone.getTime());
1130 storedSone.setClient(sone.getClient());
1131 storedSone.setProfile(sone.getProfile());
1132 if (soneRescueMode) {
1133 for (Post post : sone.getPosts()) {
1134 storedSone.addPost(post);
1136 for (Reply reply : sone.getReplies()) {
1137 storedSone.addReply(reply);
1139 for (String likedPostId : sone.getLikedPostIds()) {
1140 storedSone.addLikedPostId(likedPostId);
1142 for (String likedReplyId : sone.getLikedReplyIds()) {
1143 storedSone.addLikedReplyId(likedReplyId);
1146 storedSone.setPosts(sone.getPosts());
1147 storedSone.setReplies(sone.getReplies());
1148 storedSone.setLikePostIds(sone.getLikedPostIds());
1149 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1151 storedSone.setLatestEdition(sone.getLatestEdition());
1157 * Deletes the given Sone. This will remove the Sone from the
1158 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1159 * and remove the context from its identity.
1162 * The Sone to delete
1164 public void deleteSone(Sone sone) {
1165 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1166 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1169 synchronized (localSones) {
1170 if (!localSones.containsKey(sone.getId())) {
1171 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1174 localSones.remove(sone.getId());
1175 SoneInserter soneInserter = soneInserters.remove(sone);
1176 soneInserter.removeSoneInsertListener(this);
1177 soneInserter.stop();
1180 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1181 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1182 } catch (WebOfTrustException wote1) {
1183 logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1186 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1187 } catch (ConfigurationException ce1) {
1188 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1193 * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1194 * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1197 * The Sone to mark as known
1199 public void markSoneKnown(Sone sone) {
1200 synchronized (newSones) {
1201 if (newSones.remove(sone.getId())) {
1202 knownSones.add(sone.getId());
1203 coreListenerManager.fireMarkSoneKnown(sone);
1204 saveConfiguration();
1210 * Loads and updates the given Sone from the configuration. If any error is
1211 * encountered, loading is aborted and the given Sone is not changed.
1214 * The Sone to load and update
1216 public void loadSone(Sone sone) {
1217 if (!isLocalSone(sone)) {
1218 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1222 /* initialize options. */
1223 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1226 String sonePrefix = "Sone/" + sone.getId();
1227 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1228 if (soneTime == null) {
1229 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1232 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1235 Profile profile = new Profile();
1236 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1237 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1238 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1239 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1240 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1241 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1243 /* load profile fields. */
1245 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1246 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1247 if (fieldName == null) {
1250 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1251 profile.addField(fieldName).setValue(fieldValue);
1255 Set<Post> posts = new HashSet<Post>();
1257 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1258 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1259 if (postId == null) {
1262 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1263 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1264 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1265 if ((postTime == 0) || (postText == null)) {
1266 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1269 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1270 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1271 post.setRecipient(getSone(postRecipientId));
1277 Set<Reply> replies = new HashSet<Reply>();
1279 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1280 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1281 if (replyId == null) {
1284 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1285 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1286 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1287 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1288 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1291 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1294 /* load post likes. */
1295 Set<String> likedPostIds = new HashSet<String>();
1297 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1298 if (likedPostId == null) {
1301 likedPostIds.add(likedPostId);
1304 /* load reply likes. */
1305 Set<String> likedReplyIds = new HashSet<String>();
1307 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1308 if (likedReplyId == null) {
1311 likedReplyIds.add(likedReplyId);
1315 Set<String> friends = new HashSet<String>();
1317 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1318 if (friendId == null) {
1321 friends.add(friendId);
1325 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1327 /* if we’re still here, Sone was loaded successfully. */
1328 synchronized (sone) {
1329 sone.setTime(soneTime);
1330 sone.setProfile(profile);
1331 sone.setPosts(posts);
1332 sone.setReplies(replies);
1333 sone.setLikePostIds(likedPostIds);
1334 sone.setLikeReplyIds(likedReplyIds);
1335 sone.setFriends(friends);
1336 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1338 synchronized (newSones) {
1339 for (String friend : friends) {
1340 knownSones.add(friend);
1343 synchronized (newPosts) {
1344 for (Post post : posts) {
1345 knownPosts.add(post.getId());
1348 synchronized (newReplies) {
1349 for (Reply reply : replies) {
1350 knownReplies.add(reply.getId());
1356 * Saves the given Sone. This will persist all local settings for the given
1357 * Sone, such as the friends list and similar, private options.
1362 public synchronized void saveSone(Sone sone) {
1363 if (!isLocalSone(sone)) {
1364 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1367 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1368 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1372 logger.log(Level.INFO, "Saving Sone: %s", sone);
1374 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1376 /* save Sone into configuration. */
1377 String sonePrefix = "Sone/" + sone.getId();
1378 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1379 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1382 Profile profile = sone.getProfile();
1383 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1384 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1385 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1386 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1387 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1388 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1390 /* save profile fields. */
1391 int fieldCounter = 0;
1392 for (Field profileField : profile.getFields()) {
1393 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1394 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1395 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1397 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1400 int postCounter = 0;
1401 for (Post post : sone.getPosts()) {
1402 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1403 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1404 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1405 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1406 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1408 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1411 int replyCounter = 0;
1412 for (Reply reply : sone.getReplies()) {
1413 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1414 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1415 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1416 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1417 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1419 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1421 /* save post likes. */
1422 int postLikeCounter = 0;
1423 for (String postId : sone.getLikedPostIds()) {
1424 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1426 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1428 /* save reply likes. */
1429 int replyLikeCounter = 0;
1430 for (String replyId : sone.getLikedReplyIds()) {
1431 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1433 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1436 int friendCounter = 0;
1437 for (String friendId : sone.getFriends()) {
1438 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1440 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1443 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1445 configuration.save();
1446 logger.log(Level.INFO, "Sone %s saved.", sone);
1447 } catch (ConfigurationException ce1) {
1448 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1449 } catch (WebOfTrustException wote1) {
1450 logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1455 * Creates a new post.
1458 * The Sone that creates the post
1460 * The text of the post
1461 * @return The created post
1463 public Post createPost(Sone sone, String text) {
1464 return createPost(sone, System.currentTimeMillis(), text);
1468 * Creates a new post.
1471 * The Sone that creates the post
1473 * The time of the post
1475 * The text of the post
1476 * @return The created post
1478 public Post createPost(Sone sone, long time, String text) {
1479 return createPost(sone, null, time, text);
1483 * Creates a new post.
1486 * The Sone that creates the post
1488 * The recipient Sone, or {@code null} if this post does not have
1491 * The text of the post
1492 * @return The created post
1494 public Post createPost(Sone sone, Sone recipient, String text) {
1495 return createPost(sone, recipient, System.currentTimeMillis(), text);
1499 * Creates a new post.
1502 * The Sone that creates the post
1504 * The recipient Sone, or {@code null} if this post does not have
1507 * The time of the post
1509 * The text of the post
1510 * @return The created post
1512 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1513 if (!isLocalSone(sone)) {
1514 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1517 final Post post = new Post(sone, time, text);
1518 if (recipient != null) {
1519 post.setRecipient(recipient);
1521 synchronized (posts) {
1522 posts.put(post.getId(), post);
1524 synchronized (newPosts) {
1525 newPosts.add(post.getId());
1526 coreListenerManager.fireNewPostFound(post);
1530 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1537 markPostKnown(post);
1539 }, "Mark " + post + " read.");
1544 * Deletes the given post.
1547 * The post to delete
1549 public void deletePost(Post post) {
1550 if (!isLocalSone(post.getSone())) {
1551 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1554 post.getSone().removePost(post);
1555 synchronized (posts) {
1556 posts.remove(post.getId());
1558 coreListenerManager.firePostRemoved(post);
1559 synchronized (newPosts) {
1560 markPostKnown(post);
1561 knownPosts.remove(post.getId());
1563 saveSone(post.getSone());
1567 * Marks the given post as known, if it is currently a new post (according
1568 * to {@link #isNewPost(String)}).
1571 * The post to mark as known
1573 public void markPostKnown(Post post) {
1574 synchronized (newPosts) {
1575 if (newPosts.remove(post.getId())) {
1576 knownPosts.add(post.getId());
1577 coreListenerManager.fireMarkPostKnown(post);
1578 saveConfiguration();
1584 * Bookmarks the given post.
1587 * The post to bookmark
1589 public void bookmark(Post post) {
1590 bookmarkPost(post.getId());
1594 * Bookmarks the post with the given ID.
1597 * The ID of the post to bookmark
1599 public void bookmarkPost(String id) {
1600 synchronized (bookmarkedPosts) {
1601 bookmarkedPosts.add(id);
1606 * Removes the given post from the bookmarks.
1609 * The post to unbookmark
1611 public void unbookmark(Post post) {
1612 unbookmarkPost(post.getId());
1616 * Removes the post with the given ID from the bookmarks.
1619 * The ID of the post to unbookmark
1621 public void unbookmarkPost(String id) {
1622 synchronized (bookmarkedPosts) {
1623 bookmarkedPosts.remove(id);
1628 * Creates a new reply.
1631 * The Sone that creates the reply
1633 * The post that this reply refers to
1635 * The text of the reply
1636 * @return The created reply
1638 public Reply createReply(Sone sone, Post post, String text) {
1639 return createReply(sone, post, System.currentTimeMillis(), text);
1643 * Creates a new reply.
1646 * The Sone that creates the reply
1648 * The post that this reply refers to
1650 * The time of the reply
1652 * The text of the reply
1653 * @return The created reply
1655 public Reply createReply(Sone sone, Post post, long time, String text) {
1656 if (!isLocalSone(sone)) {
1657 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1660 final Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1661 synchronized (replies) {
1662 replies.put(reply.getId(), reply);
1664 synchronized (newReplies) {
1665 newReplies.add(reply.getId());
1666 coreListenerManager.fireNewReplyFound(reply);
1668 sone.addReply(reply);
1670 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1677 markReplyKnown(reply);
1679 }, "Mark " + reply + " read.");
1684 * Deletes the given reply.
1687 * The reply to delete
1689 public void deleteReply(Reply reply) {
1690 Sone sone = reply.getSone();
1691 if (!isLocalSone(sone)) {
1692 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1695 synchronized (replies) {
1696 replies.remove(reply.getId());
1698 synchronized (newReplies) {
1699 markReplyKnown(reply);
1700 knownReplies.remove(reply.getId());
1702 sone.removeReply(reply);
1707 * Marks the given reply as known, if it is currently a new reply (according
1708 * to {@link #isNewReply(String)}).
1711 * The reply to mark as known
1713 public void markReplyKnown(Reply reply) {
1714 synchronized (newReplies) {
1715 if (newReplies.remove(reply.getId())) {
1716 knownReplies.add(reply.getId());
1717 coreListenerManager.fireMarkReplyKnown(reply);
1718 saveConfiguration();
1726 public void start() {
1727 loadConfiguration();
1728 updateChecker.addUpdateListener(this);
1729 updateChecker.start();
1735 public void stop() {
1736 synchronized (localSones) {
1737 for (SoneInserter soneInserter : soneInserters.values()) {
1738 soneInserter.removeSoneInsertListener(this);
1739 soneInserter.stop();
1741 for (Sone localSone : localSones.values()) {
1742 saveSone(localSone);
1745 updateChecker.stop();
1746 updateChecker.removeUpdateListener(this);
1747 soneDownloader.stop();
1748 saveConfiguration();
1753 * Saves the current options.
1755 public void saveConfiguration() {
1756 synchronized (configuration) {
1757 if (storingConfiguration) {
1758 logger.log(Level.FINE, "Already storing configuration…");
1761 storingConfiguration = true;
1764 /* store the options first. */
1766 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1767 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1768 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1769 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1770 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1771 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1772 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1773 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1774 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1775 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1776 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1777 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1778 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1780 /* save known Sones. */
1781 int soneCounter = 0;
1782 synchronized (newSones) {
1783 for (String knownSoneId : knownSones) {
1784 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1786 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1789 /* save known posts. */
1790 int postCounter = 0;
1791 synchronized (newPosts) {
1792 for (String knownPostId : knownPosts) {
1793 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1795 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1798 /* save known replies. */
1799 int replyCounter = 0;
1800 synchronized (newReplies) {
1801 for (String knownReplyId : knownReplies) {
1802 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1804 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1807 /* save bookmarked posts. */
1808 int bookmarkedPostCounter = 0;
1809 synchronized (bookmarkedPosts) {
1810 for (String bookmarkedPostId : bookmarkedPosts) {
1811 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1814 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1817 configuration.save();
1819 } catch (ConfigurationException ce1) {
1820 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1822 synchronized (configuration) {
1823 storingConfiguration = false;
1833 * Loads the configuration.
1835 @SuppressWarnings("unchecked")
1836 private void loadConfiguration() {
1837 /* create options. */
1838 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1841 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1842 SoneInserter.setInsertionDelay(newValue);
1846 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
1847 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
1848 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1849 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
1850 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
1851 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1852 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1855 @SuppressWarnings("synthetic-access")
1856 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1857 fcpInterface.setActive(newValue);
1860 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1863 @SuppressWarnings("synthetic-access")
1864 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1865 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1869 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1870 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1871 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1873 /* read options from configuration. */
1874 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1875 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1876 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1877 options.getBooleanOption("ClearOnNextRestart").set(null);
1878 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1879 if (clearConfiguration) {
1880 /* stop loading the configuration. */
1884 loadConfigurationValue("InsertionDelay");
1885 loadConfigurationValue("PostsPerPage");
1886 loadConfigurationValue("CharactersPerPost");
1887 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1888 loadConfigurationValue("PositiveTrust");
1889 loadConfigurationValue("NegativeTrust");
1890 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1891 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1892 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1893 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1895 /* load known Sones. */
1896 int soneCounter = 0;
1898 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1899 if (knownSoneId == null) {
1902 synchronized (newSones) {
1903 knownSones.add(knownSoneId);
1907 /* load known posts. */
1908 int postCounter = 0;
1910 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1911 if (knownPostId == null) {
1914 synchronized (newPosts) {
1915 knownPosts.add(knownPostId);
1919 /* load known replies. */
1920 int replyCounter = 0;
1922 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1923 if (knownReplyId == null) {
1926 synchronized (newReplies) {
1927 knownReplies.add(knownReplyId);
1931 /* load bookmarked posts. */
1932 int bookmarkedPostCounter = 0;
1934 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1935 if (bookmarkedPostId == null) {
1938 synchronized (bookmarkedPosts) {
1939 bookmarkedPosts.add(bookmarkedPostId);
1946 * Loads an {@link Integer} configuration value for the option with the
1947 * given name, logging validation failures.
1950 * The name of the option to load
1952 private void loadConfigurationValue(String optionName) {
1954 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1955 } catch (IllegalArgumentException iae1) {
1956 logger.log(Level.WARNING, "Invalid value for " + optionName + " in configuration, using default.");
1961 * Generate a Sone URI from the given URI and latest edition.
1964 * The URI to derive the Sone URI from
1965 * @return The derived URI
1967 private FreenetURI getSoneUri(String uriString) {
1969 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1971 } catch (MalformedURLException mue1) {
1972 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1978 // INTERFACE IdentityListener
1985 public void ownIdentityAdded(OwnIdentity ownIdentity) {
1986 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1987 if (ownIdentity.hasContext("Sone")) {
1988 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
1989 addLocalSone(ownIdentity);
1997 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1998 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1999 trustedIdentities.remove(ownIdentity);
2006 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2007 logger.log(Level.FINEST, "Adding Identity: " + identity);
2008 trustedIdentities.get(ownIdentity).add(identity);
2009 addRemoteSone(identity);
2016 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2017 new Thread(new Runnable() {
2020 @SuppressWarnings("synthetic-access")
2022 Sone sone = getRemoteSone(identity.getId());
2023 sone.setIdentity(identity);
2024 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2025 soneDownloader.addSone(sone);
2026 soneDownloader.fetchSone(sone);
2035 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2036 trustedIdentities.get(ownIdentity).remove(identity);
2037 boolean foundIdentity = false;
2038 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2039 if (trustedIdentity.getKey().equals(ownIdentity)) {
2042 if (trustedIdentity.getValue().contains(identity)) {
2043 foundIdentity = true;
2046 if (foundIdentity) {
2047 /* some local identity still trusts this identity, don’t remove. */
2050 Sone sone = getSone(identity.getId(), false);
2052 /* TODO - we don’t have the Sone anymore. should this happen? */
2055 synchronized (posts) {
2056 synchronized (newPosts) {
2057 for (Post post : sone.getPosts()) {
2058 posts.remove(post.getId());
2059 newPosts.remove(post.getId());
2060 coreListenerManager.firePostRemoved(post);
2064 synchronized (replies) {
2065 synchronized (newReplies) {
2066 for (Reply reply : sone.getReplies()) {
2067 replies.remove(reply.getId());
2068 newReplies.remove(reply.getId());
2069 coreListenerManager.fireReplyRemoved(reply);
2073 synchronized (remoteSones) {
2074 remoteSones.remove(identity.getId());
2076 synchronized (newSones) {
2077 newSones.remove(identity.getId());
2078 coreListenerManager.fireSoneRemoved(sone);
2083 // INTERFACE UpdateListener
2090 public void updateFound(Version version, long releaseTime, long latestEdition) {
2091 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2095 // SONEINSERTLISTENER METHODS
2101 public void insertStarted(Sone sone) {
2102 coreListenerManager.fireSoneInserting(sone);
2109 public void insertFinished(Sone sone, long insertDuration) {
2110 coreListenerManager.fireSoneInserted(sone, insertDuration);
2117 public void insertAborted(Sone sone, Throwable cause) {
2118 coreListenerManager.fireSoneInsertAborted(sone, cause);
2122 * Convenience interface for external classes that want to access the core’s
2125 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2127 public static class Preferences {
2129 /** The wrapped options. */
2130 private final Options options;
2133 * Creates a new preferences object wrapped around the given options.
2136 * The options to wrap
2138 public Preferences(Options options) {
2139 this.options = options;
2143 * Returns the insertion delay.
2145 * @return The insertion delay
2147 public int getInsertionDelay() {
2148 return options.getIntegerOption("InsertionDelay").get();
2152 * Validates the given insertion delay.
2154 * @param insertionDelay
2155 * The insertion delay to validate
2156 * @return {@code true} if the given insertion delay was valid, {@code
2159 public boolean validateInsertionDelay(Integer insertionDelay) {
2160 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2164 * Sets the insertion delay
2166 * @param insertionDelay
2167 * The new insertion delay, or {@code null} to restore it to
2169 * @return This preferences
2171 public Preferences setInsertionDelay(Integer insertionDelay) {
2172 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2177 * Returns the number of posts to show per page.
2179 * @return The number of posts to show per page
2181 public int getPostsPerPage() {
2182 return options.getIntegerOption("PostsPerPage").get();
2186 * Validates the number of posts per page.
2188 * @param postsPerPage
2189 * The number of posts per page
2190 * @return {@code true} if the number of posts per page was valid,
2191 * {@code false} otherwise
2193 public boolean validatePostsPerPage(Integer postsPerPage) {
2194 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2198 * Sets the number of posts to show per page.
2200 * @param postsPerPage
2201 * The number of posts to show per page
2202 * @return This preferences object
2204 public Preferences setPostsPerPage(Integer postsPerPage) {
2205 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2210 * Returns the number of characters per post, or <code>-1</code> if the
2211 * posts should not be cut off.
2213 * @return The numbers of characters per post
2215 public int getCharactersPerPost() {
2216 return options.getIntegerOption("CharactersPerPost").get();
2220 * Validates the number of characters per post.
2222 * @param charactersPerPost
2223 * The number of characters per post
2224 * @return {@code true} if the number of characters per post was valid,
2225 * {@code false} otherwise
2227 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2228 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2232 * Sets the number of characters per post.
2234 * @param charactersPerPost
2235 * The number of characters per post, or <code>-1</code> to
2236 * not cut off the posts
2237 * @return This preferences objects
2239 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2240 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2245 * Returns whether Sone requires full access to be even visible.
2247 * @return {@code true} if Sone requires full access, {@code false}
2250 public boolean isRequireFullAccess() {
2251 return options.getBooleanOption("RequireFullAccess").get();
2255 * Sets whether Sone requires full access to be even visible.
2257 * @param requireFullAccess
2258 * {@code true} if Sone requires full access, {@code false}
2261 public void setRequireFullAccess(Boolean requireFullAccess) {
2262 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2266 * Returns the positive trust.
2268 * @return The positive trust
2270 public int getPositiveTrust() {
2271 return options.getIntegerOption("PositiveTrust").get();
2275 * Validates the positive trust.
2277 * @param positiveTrust
2278 * The positive trust to validate
2279 * @return {@code true} if the positive trust was valid, {@code false}
2282 public boolean validatePositiveTrust(Integer positiveTrust) {
2283 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2287 * Sets the positive trust.
2289 * @param positiveTrust
2290 * The new positive trust, or {@code null} to restore it to
2292 * @return This preferences
2294 public Preferences setPositiveTrust(Integer positiveTrust) {
2295 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2300 * Returns the negative trust.
2302 * @return The negative trust
2304 public int getNegativeTrust() {
2305 return options.getIntegerOption("NegativeTrust").get();
2309 * Validates the negative trust.
2311 * @param negativeTrust
2312 * The negative trust to validate
2313 * @return {@code true} if the negative trust was valid, {@code false}
2316 public boolean validateNegativeTrust(Integer negativeTrust) {
2317 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2321 * Sets the negative trust.
2323 * @param negativeTrust
2324 * The negative trust, or {@code null} to restore it to the
2326 * @return The preferences
2328 public Preferences setNegativeTrust(Integer negativeTrust) {
2329 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2334 * Returns the trust comment. This is the comment that is set in the web
2335 * of trust when a trust value is assigned to an identity.
2337 * @return The trust comment
2339 public String getTrustComment() {
2340 return options.getStringOption("TrustComment").get();
2344 * Sets the trust comment.
2346 * @param trustComment
2347 * The trust comment, or {@code null} to restore it to the
2349 * @return This preferences
2351 public Preferences setTrustComment(String trustComment) {
2352 options.getStringOption("TrustComment").set(trustComment);
2357 * Returns whether the {@link FcpInterface FCP interface} is currently
2360 * @see FcpInterface#setActive(boolean)
2361 * @return {@code true} if the FCP interface is currently active,
2362 * {@code false} otherwise
2364 public boolean isFcpInterfaceActive() {
2365 return options.getBooleanOption("ActivateFcpInterface").get();
2369 * Sets whether the {@link FcpInterface FCP interface} is currently
2372 * @see FcpInterface#setActive(boolean)
2373 * @param fcpInterfaceActive
2374 * {@code true} to activate the FCP interface, {@code false}
2375 * to deactivate the FCP interface
2376 * @return This preferences object
2378 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2379 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2384 * Returns the action level for which full access to the FCP interface
2387 * @return The action level for which full access to the FCP interface
2390 public FullAccessRequired getFcpFullAccessRequired() {
2391 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2395 * Sets the action level for which full access to the FCP interface is
2398 * @param fcpFullAccessRequired
2400 * @return This preferences
2402 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2403 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2408 * Returns whether Sone should clear its settings on the next restart.
2409 * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2410 * to return {@code true} as well!
2412 * @return {@code true} if Sone should clear its settings on the next
2413 * restart, {@code false} otherwise
2415 public boolean isClearOnNextRestart() {
2416 return options.getBooleanOption("ClearOnNextRestart").get();
2420 * Sets whether Sone will clear its settings on the next restart.
2422 * @param clearOnNextRestart
2423 * {@code true} if Sone should clear its settings on the next
2424 * restart, {@code false} otherwise
2425 * @return This preferences
2427 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2428 options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2433 * Returns whether Sone should really clear its settings on next
2434 * restart. This is a confirmation option that needs to be set in
2435 * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2436 * settings on the next restart.
2438 * @return {@code true} if Sone should really clear its settings on the
2439 * next restart, {@code false} otherwise
2441 public boolean isReallyClearOnNextRestart() {
2442 return options.getBooleanOption("ReallyClearOnNextRestart").get();
2446 * Sets whether Sone should really clear its settings on the next
2449 * @param reallyClearOnNextRestart
2450 * {@code true} if Sone should really clear its settings on
2451 * the next restart, {@code false} otherwise
2452 * @return This preferences
2454 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2455 options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);