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 {
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 soneInserters.put(sone, soneInserter);
886 setSoneStatus(sone, SoneStatus.idle);
888 soneInserter.start();
894 * Creates a new Sone for the given own identity.
897 * The own identity to create a Sone for
898 * @return The created Sone
900 public Sone createSone(OwnIdentity ownIdentity) {
902 ownIdentity.addContext("Sone");
903 } catch (WebOfTrustException wote1) {
904 logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
907 Sone sone = addLocalSone(ownIdentity);
908 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
909 sone.addFriend("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
915 * Adds the Sone of the given identity.
918 * The identity whose Sone to add
919 * @return The added or already existing Sone
921 public Sone addRemoteSone(Identity identity) {
922 if (identity == null) {
923 logger.log(Level.WARNING, "Given Identity is null!");
926 synchronized (remoteSones) {
927 final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
928 boolean newSone = sone.getRequestUri() == null;
929 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
930 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
932 synchronized (newSones) {
933 newSone = !knownSones.contains(sone.getId());
935 newSones.add(sone.getId());
939 coreListenerManager.fireNewSoneFound(sone);
940 for (Sone localSone : getLocalSones()) {
941 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
942 localSone.addFriend(sone.getId());
948 remoteSones.put(identity.getId(), sone);
949 soneDownloader.addSone(sone);
950 setSoneStatus(sone, SoneStatus.unknown);
951 soneDownloaders.execute(new Runnable() {
954 @SuppressWarnings("synthetic-access")
956 soneDownloader.fetchSone(sone, sone.getRequestUri());
965 * Retrieves the trust relationship from the origin to the target. If the
966 * trust relationship can not be retrieved, {@code null} is returned.
968 * @see Identity#getTrust(OwnIdentity)
970 * The origin of the trust tree
972 * The target of the trust
973 * @return The trust relationship
975 public Trust getTrust(Sone origin, Sone target) {
976 if (!isLocalSone(origin)) {
977 logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
980 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
984 * Sets the trust value of the given origin Sone for the target Sone.
991 * The trust value (from {@code -100} to {@code 100})
993 public void setTrust(Sone origin, Sone target, int trustValue) {
994 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();
996 ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
997 } catch (WebOfTrustException wote1) {
998 logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
1003 * Removes any trust assignment for the given target Sone.
1010 public void removeTrust(Sone origin, Sone target) {
1011 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1013 ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1014 } catch (WebOfTrustException wote1) {
1015 logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
1020 * Assigns the configured positive trust value for the given target.
1027 public void trustSone(Sone origin, Sone target) {
1028 setTrust(origin, target, preferences.getPositiveTrust());
1032 * Assigns the configured negative trust value for the given target.
1039 public void distrustSone(Sone origin, Sone target) {
1040 setTrust(origin, target, preferences.getNegativeTrust());
1044 * Removes the trust assignment for the given target.
1051 public void untrustSone(Sone origin, Sone target) {
1052 removeTrust(origin, target);
1056 * Updates the stored Sone with the given Sone.
1061 public void updateSone(Sone sone) {
1062 updateSone(sone, false);
1066 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1067 * {@code true}, an older Sone than the current Sone can be given to restore
1071 * The Sone to update
1072 * @param soneRescueMode
1073 * {@code true} if the stored Sone should be updated regardless
1074 * of the age of the given Sone
1076 public void updateSone(Sone sone, boolean soneRescueMode) {
1077 if (hasSone(sone.getId())) {
1078 Sone storedSone = getSone(sone.getId());
1079 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1080 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1083 synchronized (posts) {
1084 if (!soneRescueMode) {
1085 for (Post post : storedSone.getPosts()) {
1086 posts.remove(post.getId());
1087 if (!sone.getPosts().contains(post)) {
1088 coreListenerManager.firePostRemoved(post);
1092 List<Post> storedPosts = storedSone.getPosts();
1093 synchronized (newPosts) {
1094 for (Post post : sone.getPosts()) {
1095 post.setSone(storedSone);
1096 if (!storedPosts.contains(post) && !knownPosts.contains(post.getId())) {
1097 newPosts.add(post.getId());
1098 coreListenerManager.fireNewPostFound(post);
1100 posts.put(post.getId(), post);
1104 synchronized (replies) {
1105 if (!soneRescueMode) {
1106 for (Reply reply : storedSone.getReplies()) {
1107 replies.remove(reply.getId());
1108 if (!sone.getReplies().contains(reply)) {
1109 coreListenerManager.fireReplyRemoved(reply);
1113 Set<Reply> storedReplies = storedSone.getReplies();
1114 synchronized (newReplies) {
1115 for (Reply reply : sone.getReplies()) {
1116 reply.setSone(storedSone);
1117 if (!storedReplies.contains(reply) && !knownReplies.contains(reply.getId())) {
1118 newReplies.add(reply.getId());
1119 coreListenerManager.fireNewReplyFound(reply);
1121 replies.put(reply.getId(), reply);
1125 synchronized (storedSone) {
1126 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1127 storedSone.setTime(sone.getTime());
1129 storedSone.setClient(sone.getClient());
1130 storedSone.setProfile(sone.getProfile());
1131 if (soneRescueMode) {
1132 for (Post post : sone.getPosts()) {
1133 storedSone.addPost(post);
1135 for (Reply reply : sone.getReplies()) {
1136 storedSone.addReply(reply);
1138 for (String likedPostId : sone.getLikedPostIds()) {
1139 storedSone.addLikedPostId(likedPostId);
1141 for (String likedReplyId : sone.getLikedReplyIds()) {
1142 storedSone.addLikedReplyId(likedReplyId);
1145 storedSone.setPosts(sone.getPosts());
1146 storedSone.setReplies(sone.getReplies());
1147 storedSone.setLikePostIds(sone.getLikedPostIds());
1148 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1150 storedSone.setLatestEdition(sone.getLatestEdition());
1156 * Deletes the given Sone. This will remove the Sone from the
1157 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1158 * and remove the context from its identity.
1161 * The Sone to delete
1163 public void deleteSone(Sone sone) {
1164 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1165 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1168 synchronized (localSones) {
1169 if (!localSones.containsKey(sone.getId())) {
1170 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1173 localSones.remove(sone.getId());
1174 soneInserters.remove(sone).stop();
1177 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1178 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1179 } catch (WebOfTrustException wote1) {
1180 logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1183 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1184 } catch (ConfigurationException ce1) {
1185 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1190 * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1191 * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1194 * The Sone to mark as known
1196 public void markSoneKnown(Sone sone) {
1197 synchronized (newSones) {
1198 if (newSones.remove(sone.getId())) {
1199 knownSones.add(sone.getId());
1200 coreListenerManager.fireMarkSoneKnown(sone);
1201 saveConfiguration();
1207 * Loads and updates the given Sone from the configuration. If any error is
1208 * encountered, loading is aborted and the given Sone is not changed.
1211 * The Sone to load and update
1213 public void loadSone(Sone sone) {
1214 if (!isLocalSone(sone)) {
1215 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1219 /* initialize options. */
1220 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1223 String sonePrefix = "Sone/" + sone.getId();
1224 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1225 if (soneTime == null) {
1226 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1229 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1232 Profile profile = new Profile();
1233 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1234 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1235 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1236 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1237 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1238 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1240 /* load profile fields. */
1242 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1243 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1244 if (fieldName == null) {
1247 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1248 profile.addField(fieldName).setValue(fieldValue);
1252 Set<Post> posts = new HashSet<Post>();
1254 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1255 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1256 if (postId == null) {
1259 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1260 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1261 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1262 if ((postTime == 0) || (postText == null)) {
1263 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1266 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1267 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1268 post.setRecipient(getSone(postRecipientId));
1274 Set<Reply> replies = new HashSet<Reply>();
1276 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1277 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1278 if (replyId == null) {
1281 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1282 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1283 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1284 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1285 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1288 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1291 /* load post likes. */
1292 Set<String> likedPostIds = new HashSet<String>();
1294 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1295 if (likedPostId == null) {
1298 likedPostIds.add(likedPostId);
1301 /* load reply likes. */
1302 Set<String> likedReplyIds = new HashSet<String>();
1304 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1305 if (likedReplyId == null) {
1308 likedReplyIds.add(likedReplyId);
1312 Set<String> friends = new HashSet<String>();
1314 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1315 if (friendId == null) {
1318 friends.add(friendId);
1322 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1324 /* if we’re still here, Sone was loaded successfully. */
1325 synchronized (sone) {
1326 sone.setTime(soneTime);
1327 sone.setProfile(profile);
1328 sone.setPosts(posts);
1329 sone.setReplies(replies);
1330 sone.setLikePostIds(likedPostIds);
1331 sone.setLikeReplyIds(likedReplyIds);
1332 sone.setFriends(friends);
1333 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1335 synchronized (newSones) {
1336 for (String friend : friends) {
1337 knownSones.add(friend);
1340 synchronized (newPosts) {
1341 for (Post post : posts) {
1342 knownPosts.add(post.getId());
1345 synchronized (newReplies) {
1346 for (Reply reply : replies) {
1347 knownReplies.add(reply.getId());
1353 * Saves the given Sone. This will persist all local settings for the given
1354 * Sone, such as the friends list and similar, private options.
1359 public synchronized void saveSone(Sone sone) {
1360 if (!isLocalSone(sone)) {
1361 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1364 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1365 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1369 logger.log(Level.INFO, "Saving Sone: %s", sone);
1371 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1373 /* save Sone into configuration. */
1374 String sonePrefix = "Sone/" + sone.getId();
1375 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1376 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1379 Profile profile = sone.getProfile();
1380 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1381 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1382 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1383 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1384 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1385 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1387 /* save profile fields. */
1388 int fieldCounter = 0;
1389 for (Field profileField : profile.getFields()) {
1390 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1391 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1392 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1394 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1397 int postCounter = 0;
1398 for (Post post : sone.getPosts()) {
1399 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1400 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1401 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1402 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1403 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1405 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1408 int replyCounter = 0;
1409 for (Reply reply : sone.getReplies()) {
1410 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1411 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1412 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1413 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1414 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1416 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1418 /* save post likes. */
1419 int postLikeCounter = 0;
1420 for (String postId : sone.getLikedPostIds()) {
1421 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1423 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1425 /* save reply likes. */
1426 int replyLikeCounter = 0;
1427 for (String replyId : sone.getLikedReplyIds()) {
1428 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1430 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1433 int friendCounter = 0;
1434 for (String friendId : sone.getFriends()) {
1435 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1437 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1440 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1442 configuration.save();
1443 logger.log(Level.INFO, "Sone %s saved.", sone);
1444 } catch (ConfigurationException ce1) {
1445 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1446 } catch (WebOfTrustException wote1) {
1447 logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1452 * Creates a new post.
1455 * The Sone that creates the post
1457 * The text of the post
1458 * @return The created post
1460 public Post createPost(Sone sone, String text) {
1461 return createPost(sone, System.currentTimeMillis(), text);
1465 * Creates a new post.
1468 * The Sone that creates the post
1470 * The time of the post
1472 * The text of the post
1473 * @return The created post
1475 public Post createPost(Sone sone, long time, String text) {
1476 return createPost(sone, null, time, text);
1480 * Creates a new post.
1483 * The Sone that creates the post
1485 * The recipient Sone, or {@code null} if this post does not have
1488 * The text of the post
1489 * @return The created post
1491 public Post createPost(Sone sone, Sone recipient, String text) {
1492 return createPost(sone, recipient, System.currentTimeMillis(), text);
1496 * Creates a new post.
1499 * The Sone that creates the post
1501 * The recipient Sone, or {@code null} if this post does not have
1504 * The time of the post
1506 * The text of the post
1507 * @return The created post
1509 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1510 if (!isLocalSone(sone)) {
1511 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1514 final Post post = new Post(sone, time, text);
1515 if (recipient != null) {
1516 post.setRecipient(recipient);
1518 synchronized (posts) {
1519 posts.put(post.getId(), post);
1521 synchronized (newPosts) {
1522 newPosts.add(post.getId());
1523 coreListenerManager.fireNewPostFound(post);
1527 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1534 markPostKnown(post);
1536 }, "Mark " + post + " read.");
1541 * Deletes the given post.
1544 * The post to delete
1546 public void deletePost(Post post) {
1547 if (!isLocalSone(post.getSone())) {
1548 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1551 post.getSone().removePost(post);
1552 synchronized (posts) {
1553 posts.remove(post.getId());
1555 coreListenerManager.firePostRemoved(post);
1556 synchronized (newPosts) {
1557 markPostKnown(post);
1558 knownPosts.remove(post.getId());
1560 saveSone(post.getSone());
1564 * Marks the given post as known, if it is currently a new post (according
1565 * to {@link #isNewPost(String)}).
1568 * The post to mark as known
1570 public void markPostKnown(Post post) {
1571 synchronized (newPosts) {
1572 if (newPosts.remove(post.getId())) {
1573 knownPosts.add(post.getId());
1574 coreListenerManager.fireMarkPostKnown(post);
1575 saveConfiguration();
1581 * Bookmarks the given post.
1584 * The post to bookmark
1586 public void bookmark(Post post) {
1587 bookmarkPost(post.getId());
1591 * Bookmarks the post with the given ID.
1594 * The ID of the post to bookmark
1596 public void bookmarkPost(String id) {
1597 synchronized (bookmarkedPosts) {
1598 bookmarkedPosts.add(id);
1603 * Removes the given post from the bookmarks.
1606 * The post to unbookmark
1608 public void unbookmark(Post post) {
1609 unbookmarkPost(post.getId());
1613 * Removes the post with the given ID from the bookmarks.
1616 * The ID of the post to unbookmark
1618 public void unbookmarkPost(String id) {
1619 synchronized (bookmarkedPosts) {
1620 bookmarkedPosts.remove(id);
1625 * Creates a new reply.
1628 * The Sone that creates the reply
1630 * The post that this reply refers to
1632 * The text of the reply
1633 * @return The created reply
1635 public Reply createReply(Sone sone, Post post, String text) {
1636 return createReply(sone, post, System.currentTimeMillis(), text);
1640 * Creates a new reply.
1643 * The Sone that creates the reply
1645 * The post that this reply refers to
1647 * The time of the reply
1649 * The text of the reply
1650 * @return The created reply
1652 public Reply createReply(Sone sone, Post post, long time, String text) {
1653 if (!isLocalSone(sone)) {
1654 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1657 final Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1658 synchronized (replies) {
1659 replies.put(reply.getId(), reply);
1661 synchronized (newReplies) {
1662 newReplies.add(reply.getId());
1663 coreListenerManager.fireNewReplyFound(reply);
1665 sone.addReply(reply);
1667 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1674 markReplyKnown(reply);
1676 }, "Mark " + reply + " read.");
1681 * Deletes the given reply.
1684 * The reply to delete
1686 public void deleteReply(Reply reply) {
1687 Sone sone = reply.getSone();
1688 if (!isLocalSone(sone)) {
1689 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1692 synchronized (replies) {
1693 replies.remove(reply.getId());
1695 synchronized (newReplies) {
1696 markReplyKnown(reply);
1697 knownReplies.remove(reply.getId());
1699 sone.removeReply(reply);
1704 * Marks the given reply as known, if it is currently a new reply (according
1705 * to {@link #isNewReply(String)}).
1708 * The reply to mark as known
1710 public void markReplyKnown(Reply reply) {
1711 synchronized (newReplies) {
1712 if (newReplies.remove(reply.getId())) {
1713 knownReplies.add(reply.getId());
1714 coreListenerManager.fireMarkReplyKnown(reply);
1715 saveConfiguration();
1723 public void start() {
1724 loadConfiguration();
1725 updateChecker.addUpdateListener(this);
1726 updateChecker.start();
1732 public void stop() {
1733 synchronized (localSones) {
1734 for (SoneInserter soneInserter : soneInserters.values()) {
1735 soneInserter.stop();
1737 for (Sone localSone : localSones.values()) {
1738 saveSone(localSone);
1741 updateChecker.stop();
1742 updateChecker.removeUpdateListener(this);
1743 soneDownloader.stop();
1744 saveConfiguration();
1749 * Saves the current options.
1751 public void saveConfiguration() {
1752 synchronized (configuration) {
1753 if (storingConfiguration) {
1754 logger.log(Level.FINE, "Already storing configuration…");
1757 storingConfiguration = true;
1760 /* store the options first. */
1762 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1763 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1764 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1765 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1766 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1767 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1768 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1769 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1770 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1771 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1772 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1773 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1774 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1776 /* save known Sones. */
1777 int soneCounter = 0;
1778 synchronized (newSones) {
1779 for (String knownSoneId : knownSones) {
1780 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1782 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1785 /* save known posts. */
1786 int postCounter = 0;
1787 synchronized (newPosts) {
1788 for (String knownPostId : knownPosts) {
1789 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1791 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1794 /* save known replies. */
1795 int replyCounter = 0;
1796 synchronized (newReplies) {
1797 for (String knownReplyId : knownReplies) {
1798 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1800 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1803 /* save bookmarked posts. */
1804 int bookmarkedPostCounter = 0;
1805 synchronized (bookmarkedPosts) {
1806 for (String bookmarkedPostId : bookmarkedPosts) {
1807 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1810 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1813 configuration.save();
1815 } catch (ConfigurationException ce1) {
1816 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1818 synchronized (configuration) {
1819 storingConfiguration = false;
1829 * Loads the configuration.
1831 @SuppressWarnings("unchecked")
1832 private void loadConfiguration() {
1833 /* create options. */
1834 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1837 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1838 SoneInserter.setInsertionDelay(newValue);
1842 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
1843 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
1844 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1845 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
1846 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
1847 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1848 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1851 @SuppressWarnings("synthetic-access")
1852 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1853 fcpInterface.setActive(newValue);
1856 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1859 @SuppressWarnings("synthetic-access")
1860 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1861 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1865 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1866 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1867 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1869 /* read options from configuration. */
1870 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1871 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1872 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1873 options.getBooleanOption("ClearOnNextRestart").set(null);
1874 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1875 if (clearConfiguration) {
1876 /* stop loading the configuration. */
1880 loadConfigurationValue("InsertionDelay");
1881 loadConfigurationValue("PostsPerPage");
1882 loadConfigurationValue("CharactersPerPost");
1883 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1884 loadConfigurationValue("PositiveTrust");
1885 loadConfigurationValue("NegativeTrust");
1886 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1887 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1888 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1889 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1891 /* load known Sones. */
1892 int soneCounter = 0;
1894 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1895 if (knownSoneId == null) {
1898 synchronized (newSones) {
1899 knownSones.add(knownSoneId);
1903 /* load known posts. */
1904 int postCounter = 0;
1906 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1907 if (knownPostId == null) {
1910 synchronized (newPosts) {
1911 knownPosts.add(knownPostId);
1915 /* load known replies. */
1916 int replyCounter = 0;
1918 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1919 if (knownReplyId == null) {
1922 synchronized (newReplies) {
1923 knownReplies.add(knownReplyId);
1927 /* load bookmarked posts. */
1928 int bookmarkedPostCounter = 0;
1930 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1931 if (bookmarkedPostId == null) {
1934 synchronized (bookmarkedPosts) {
1935 bookmarkedPosts.add(bookmarkedPostId);
1942 * Loads an {@link Integer} configuration value for the option with the
1943 * given name, logging validation failures.
1946 * The name of the option to load
1948 private void loadConfigurationValue(String optionName) {
1950 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1951 } catch (IllegalArgumentException iae1) {
1952 logger.log(Level.WARNING, "Invalid value for " + optionName + " in configuration, using default.");
1957 * Generate a Sone URI from the given URI and latest edition.
1960 * The URI to derive the Sone URI from
1961 * @return The derived URI
1963 private FreenetURI getSoneUri(String uriString) {
1965 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1967 } catch (MalformedURLException mue1) {
1968 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1974 // INTERFACE IdentityListener
1981 public void ownIdentityAdded(OwnIdentity ownIdentity) {
1982 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1983 if (ownIdentity.hasContext("Sone")) {
1984 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
1985 addLocalSone(ownIdentity);
1993 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1994 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1995 trustedIdentities.remove(ownIdentity);
2002 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2003 logger.log(Level.FINEST, "Adding Identity: " + identity);
2004 trustedIdentities.get(ownIdentity).add(identity);
2005 addRemoteSone(identity);
2012 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2013 new Thread(new Runnable() {
2016 @SuppressWarnings("synthetic-access")
2018 Sone sone = getRemoteSone(identity.getId());
2019 sone.setIdentity(identity);
2020 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2021 soneDownloader.addSone(sone);
2022 soneDownloader.fetchSone(sone);
2031 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2032 trustedIdentities.get(ownIdentity).remove(identity);
2033 boolean foundIdentity = false;
2034 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2035 if (trustedIdentity.getKey().equals(ownIdentity)) {
2038 if (trustedIdentity.getValue().contains(identity)) {
2039 foundIdentity = true;
2042 if (foundIdentity) {
2043 /* some local identity still trusts this identity, don’t remove. */
2046 Sone sone = getSone(identity.getId(), false);
2048 /* TODO - we don’t have the Sone anymore. should this happen? */
2051 synchronized (posts) {
2052 synchronized (newPosts) {
2053 for (Post post : sone.getPosts()) {
2054 posts.remove(post.getId());
2055 newPosts.remove(post.getId());
2056 coreListenerManager.firePostRemoved(post);
2060 synchronized (replies) {
2061 synchronized (newReplies) {
2062 for (Reply reply : sone.getReplies()) {
2063 replies.remove(reply.getId());
2064 newReplies.remove(reply.getId());
2065 coreListenerManager.fireReplyRemoved(reply);
2069 synchronized (remoteSones) {
2070 remoteSones.remove(identity.getId());
2072 synchronized (newSones) {
2073 newSones.remove(identity.getId());
2074 coreListenerManager.fireSoneRemoved(sone);
2079 // INTERFACE UpdateListener
2086 public void updateFound(Version version, long releaseTime, long latestEdition) {
2087 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2091 * Convenience interface for external classes that want to access the core’s
2094 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2096 public static class Preferences {
2098 /** The wrapped options. */
2099 private final Options options;
2102 * Creates a new preferences object wrapped around the given options.
2105 * The options to wrap
2107 public Preferences(Options options) {
2108 this.options = options;
2112 * Returns the insertion delay.
2114 * @return The insertion delay
2116 public int getInsertionDelay() {
2117 return options.getIntegerOption("InsertionDelay").get();
2121 * Validates the given insertion delay.
2123 * @param insertionDelay
2124 * The insertion delay to validate
2125 * @return {@code true} if the given insertion delay was valid, {@code
2128 public boolean validateInsertionDelay(Integer insertionDelay) {
2129 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2133 * Sets the insertion delay
2135 * @param insertionDelay
2136 * The new insertion delay, or {@code null} to restore it to
2138 * @return This preferences
2140 public Preferences setInsertionDelay(Integer insertionDelay) {
2141 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2146 * Returns the number of posts to show per page.
2148 * @return The number of posts to show per page
2150 public int getPostsPerPage() {
2151 return options.getIntegerOption("PostsPerPage").get();
2155 * Validates the number of posts per page.
2157 * @param postsPerPage
2158 * The number of posts per page
2159 * @return {@code true} if the number of posts per page was valid,
2160 * {@code false} otherwise
2162 public boolean validatePostsPerPage(Integer postsPerPage) {
2163 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2167 * Sets the number of posts to show per page.
2169 * @param postsPerPage
2170 * The number of posts to show per page
2171 * @return This preferences object
2173 public Preferences setPostsPerPage(Integer postsPerPage) {
2174 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2179 * Returns the number of characters per post, or <code>-1</code> if the
2180 * posts should not be cut off.
2182 * @return The numbers of characters per post
2184 public int getCharactersPerPost() {
2185 return options.getIntegerOption("CharactersPerPost").get();
2189 * Validates the number of characters per post.
2191 * @param charactersPerPost
2192 * The number of characters per post
2193 * @return {@code true} if the number of characters per post was valid,
2194 * {@code false} otherwise
2196 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2197 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2201 * Sets the number of characters per post.
2203 * @param charactersPerPost
2204 * The number of characters per post, or <code>-1</code> to
2205 * not cut off the posts
2206 * @return This preferences objects
2208 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2209 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2214 * Returns whether Sone requires full access to be even visible.
2216 * @return {@code true} if Sone requires full access, {@code false}
2219 public boolean isRequireFullAccess() {
2220 return options.getBooleanOption("RequireFullAccess").get();
2224 * Sets whether Sone requires full access to be even visible.
2226 * @param requireFullAccess
2227 * {@code true} if Sone requires full access, {@code false}
2230 public void setRequireFullAccess(Boolean requireFullAccess) {
2231 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2235 * Returns the positive trust.
2237 * @return The positive trust
2239 public int getPositiveTrust() {
2240 return options.getIntegerOption("PositiveTrust").get();
2244 * Validates the positive trust.
2246 * @param positiveTrust
2247 * The positive trust to validate
2248 * @return {@code true} if the positive trust was valid, {@code false}
2251 public boolean validatePositiveTrust(Integer positiveTrust) {
2252 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2256 * Sets the positive trust.
2258 * @param positiveTrust
2259 * The new positive trust, or {@code null} to restore it to
2261 * @return This preferences
2263 public Preferences setPositiveTrust(Integer positiveTrust) {
2264 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2269 * Returns the negative trust.
2271 * @return The negative trust
2273 public int getNegativeTrust() {
2274 return options.getIntegerOption("NegativeTrust").get();
2278 * Validates the negative trust.
2280 * @param negativeTrust
2281 * The negative trust to validate
2282 * @return {@code true} if the negative trust was valid, {@code false}
2285 public boolean validateNegativeTrust(Integer negativeTrust) {
2286 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2290 * Sets the negative trust.
2292 * @param negativeTrust
2293 * The negative trust, or {@code null} to restore it to the
2295 * @return The preferences
2297 public Preferences setNegativeTrust(Integer negativeTrust) {
2298 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2303 * Returns the trust comment. This is the comment that is set in the web
2304 * of trust when a trust value is assigned to an identity.
2306 * @return The trust comment
2308 public String getTrustComment() {
2309 return options.getStringOption("TrustComment").get();
2313 * Sets the trust comment.
2315 * @param trustComment
2316 * The trust comment, or {@code null} to restore it to the
2318 * @return This preferences
2320 public Preferences setTrustComment(String trustComment) {
2321 options.getStringOption("TrustComment").set(trustComment);
2326 * Returns whether the {@link FcpInterface FCP interface} is currently
2329 * @see FcpInterface#setActive(boolean)
2330 * @return {@code true} if the FCP interface is currently active,
2331 * {@code false} otherwise
2333 public boolean isFcpInterfaceActive() {
2334 return options.getBooleanOption("ActivateFcpInterface").get();
2338 * Sets whether the {@link FcpInterface FCP interface} is currently
2341 * @see FcpInterface#setActive(boolean)
2342 * @param fcpInterfaceActive
2343 * {@code true} to activate the FCP interface, {@code false}
2344 * to deactivate the FCP interface
2345 * @return This preferences object
2347 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2348 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2353 * Returns the action level for which full access to the FCP interface
2356 * @return The action level for which full access to the FCP interface
2359 public FullAccessRequired getFcpFullAccessRequired() {
2360 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2364 * Sets the action level for which full access to the FCP interface is
2367 * @param fcpFullAccessRequired
2369 * @return This preferences
2371 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2372 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2377 * Returns whether Sone should clear its settings on the next restart.
2378 * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2379 * to return {@code true} as well!
2381 * @return {@code true} if Sone should clear its settings on the next
2382 * restart, {@code false} otherwise
2384 public boolean isClearOnNextRestart() {
2385 return options.getBooleanOption("ClearOnNextRestart").get();
2389 * Sets whether Sone will clear its settings on the next restart.
2391 * @param clearOnNextRestart
2392 * {@code true} if Sone should clear its settings on the next
2393 * restart, {@code false} otherwise
2394 * @return This preferences
2396 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2397 options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2402 * Returns whether Sone should really clear its settings on next
2403 * restart. This is a confirmation option that needs to be set in
2404 * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2405 * settings on the next restart.
2407 * @return {@code true} if Sone should really clear its settings on the
2408 * next restart, {@code false} otherwise
2410 public boolean isReallyClearOnNextRestart() {
2411 return options.getBooleanOption("ReallyClearOnNextRestart").get();
2415 * Sets whether Sone should really clear its settings on the next
2418 * @param reallyClearOnNextRestart
2419 * {@code true} if Sone should really clear its settings on
2420 * the next restart, {@code false} otherwise
2421 * @return This preferences
2423 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2424 options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);