Fire appropriate Sone insert events from core.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / Core.java
1 /*
2  * Sone - Core.java - Copyright © 2010 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sone.core;
19
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;
26 import java.util.Map;
27 import java.util.Set;
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;
33
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;
63
64 /**
65  * The Sone core.
66  *
67  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
68  */
69 public class Core implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener {
70
71         /**
72          * Enumeration for the possible states of a {@link Sone}.
73          *
74          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
75          */
76         public enum SoneStatus {
77
78                 /** The Sone is unknown, i.e. not yet downloaded. */
79                 unknown,
80
81                 /** The Sone is idle, i.e. not being downloaded or inserted. */
82                 idle,
83
84                 /** The Sone is currently being inserted. */
85                 inserting,
86
87                 /** The Sone is currently being downloaded. */
88                 downloading,
89         }
90
91         /** The logger. */
92         private static final Logger logger = Logging.getLogger(Core.class);
93
94         /** The options. */
95         private final Options options = new Options();
96
97         /** The preferences. */
98         private final Preferences preferences = new Preferences(options);
99
100         /** The core listener manager. */
101         private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
102
103         /** The configuration. */
104         private Configuration configuration;
105
106         /** Whether we’re currently saving the configuration. */
107         private boolean storingConfiguration = false;
108
109         /** The identity manager. */
110         private final IdentityManager identityManager;
111
112         /** Interface to freenet. */
113         private final FreenetInterface freenetInterface;
114
115         /** The Sone downloader. */
116         private final SoneDownloader soneDownloader;
117
118         /** Sone downloader thread-pool. */
119         private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
120
121         /** The update checker. */
122         private final UpdateChecker updateChecker;
123
124         /** The FCP interface. */
125         private volatile FcpInterface fcpInterface;
126
127         /** Whether the core has been stopped. */
128         @SuppressWarnings("unused")
129         private volatile boolean stopped;
130
131         /** The Sones’ statuses. */
132         /* synchronize access on itself. */
133         private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
134
135         /** Locked local Sones. */
136         /* synchronize on itself. */
137         private final Set<Sone> lockedSones = new HashSet<Sone>();
138
139         /** Sone inserters. */
140         /* synchronize access on this on localSones. */
141         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
142
143         /** Sone rescuers. */
144         /* synchronize access on this on localSones. */
145         private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
146
147         /** All local Sones. */
148         /* synchronize access on this on itself. */
149         private Map<String, Sone> localSones = new HashMap<String, Sone>();
150
151         /** All remote Sones. */
152         /* synchronize access on this on itself. */
153         private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
154
155         /** All new Sones. */
156         private Set<String> newSones = new HashSet<String>();
157
158         /** All known Sones. */
159         /* synchronize access on {@link #newSones}. */
160         private Set<String> knownSones = new HashSet<String>();
161
162         /** All posts. */
163         private Map<String, Post> posts = new HashMap<String, Post>();
164
165         /** All new posts. */
166         private Set<String> newPosts = new HashSet<String>();
167
168         /** All known posts. */
169         /* synchronize access on {@link #newPosts}. */
170         private Set<String> knownPosts = new HashSet<String>();
171
172         /** All replies. */
173         private Map<String, Reply> replies = new HashMap<String, Reply>();
174
175         /** All new replies. */
176         private Set<String> newReplies = new HashSet<String>();
177
178         /** All known replies. */
179         private Set<String> knownReplies = new HashSet<String>();
180
181         /** All bookmarked posts. */
182         /* synchronize access on itself. */
183         private Set<String> bookmarkedPosts = new HashSet<String>();
184
185         /** Trusted identities, sorted by own identities. */
186         private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
187
188         /** Ticker for threads that mark own elements as known. */
189         private Ticker localElementTicker = new Ticker();
190
191         /**
192          * Creates a new core.
193          *
194          * @param configuration
195          *            The configuration of the core
196          * @param freenetInterface
197          *            The freenet interface
198          * @param identityManager
199          *            The identity manager
200          */
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);
207         }
208
209         //
210         // LISTENER MANAGEMENT
211         //
212
213         /**
214          * Adds a new core listener.
215          *
216          * @param coreListener
217          *            The listener to add
218          */
219         public void addCoreListener(CoreListener coreListener) {
220                 coreListenerManager.addListener(coreListener);
221         }
222
223         /**
224          * Removes a core listener.
225          *
226          * @param coreListener
227          *            The listener to remove
228          */
229         public void removeCoreListener(CoreListener coreListener) {
230                 coreListenerManager.removeListener(coreListener);
231         }
232
233         //
234         // ACCESSORS
235         //
236
237         /**
238          * Sets the configuration to use. This will automatically save the current
239          * configuration to the given configuration.
240          *
241          * @param configuration
242          *            The new configuration to use
243          */
244         public void setConfiguration(Configuration configuration) {
245                 this.configuration = configuration;
246                 saveConfiguration();
247         }
248
249         /**
250          * Returns the options used by the core.
251          *
252          * @return The options of the core
253          */
254         public Preferences getPreferences() {
255                 return preferences;
256         }
257
258         /**
259          * Returns the identity manager used by the core.
260          *
261          * @return The identity manager
262          */
263         public IdentityManager getIdentityManager() {
264                 return identityManager;
265         }
266
267         /**
268          * Returns the update checker.
269          *
270          * @return The update checker
271          */
272         public UpdateChecker getUpdateChecker() {
273                 return updateChecker;
274         }
275
276         /**
277          * Sets the FCP interface to use.
278          *
279          * @param fcpInterface
280          *            The FCP interface to use
281          */
282         public void setFcpInterface(FcpInterface fcpInterface) {
283                 this.fcpInterface = fcpInterface;
284         }
285
286         /**
287          * Returns the status of the given Sone.
288          *
289          * @param sone
290          *            The Sone to get the status for
291          * @return The status of the Sone
292          */
293         public SoneStatus getSoneStatus(Sone sone) {
294                 synchronized (soneStatuses) {
295                         return soneStatuses.get(sone);
296                 }
297         }
298
299         /**
300          * Sets the status of the given Sone.
301          *
302          * @param sone
303          *            The Sone to set the status of
304          * @param soneStatus
305          *            The status to set
306          */
307         public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
308                 synchronized (soneStatuses) {
309                         soneStatuses.put(sone, soneStatus);
310                 }
311         }
312
313         /**
314          * Returns the Sone rescuer for the given local Sone.
315          *
316          * @param sone
317          *            The local Sone to get the rescuer for
318          * @return The Sone rescuer for the given Sone
319          */
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);
327                                 soneRescuer.start();
328                         }
329                         return soneRescuer;
330                 }
331         }
332
333         /**
334          * Returns whether the given Sone is currently locked.
335          *
336          * @param sone
337          *            The sone to check
338          * @return {@code true} if the Sone is locked, {@code false} if it is not
339          */
340         public boolean isLocked(Sone sone) {
341                 synchronized (lockedSones) {
342                         return lockedSones.contains(sone);
343                 }
344         }
345
346         /**
347          * Returns all Sones, remote and local.
348          *
349          * @return All Sones
350          */
351         public Set<Sone> getSones() {
352                 Set<Sone> allSones = new HashSet<Sone>();
353                 allSones.addAll(getLocalSones());
354                 allSones.addAll(getRemoteSones());
355                 return allSones;
356         }
357
358         /**
359          * Returns the Sone with the given ID, regardless whether it’s local or
360          * remote.
361          *
362          * @param id
363          *            The ID of the Sone to get
364          * @return The Sone with the given ID, or {@code null} if there is no such
365          *         Sone
366          */
367         public Sone getSone(String id) {
368                 return getSone(id, true);
369         }
370
371         /**
372          * Returns the Sone with the given ID, regardless whether it’s local or
373          * remote.
374          *
375          * @param id
376          *            The ID of the Sone to get
377          * @param create
378          *            {@code true} to create a new Sone if none exists,
379          *            {@code false} to return {@code null} if a Sone with the given
380          *            ID does not exist
381          * @return The Sone with the given ID, or {@code null} if there is no such
382          *         Sone
383          */
384         @Override
385         public Sone getSone(String id, boolean create) {
386                 if (isLocalSone(id)) {
387                         return getLocalSone(id);
388                 }
389                 return getRemoteSone(id, create);
390         }
391
392         /**
393          * Checks whether the core knows a Sone with the given ID.
394          *
395          * @param id
396          *            The ID of the Sone
397          * @return {@code true} if there is a Sone with the given ID, {@code false}
398          *         otherwise
399          */
400         public boolean hasSone(String id) {
401                 return isLocalSone(id) || isRemoteSone(id);
402         }
403
404         /**
405          * Returns whether the given Sone is a local Sone.
406          *
407          * @param sone
408          *            The Sone to check for its locality
409          * @return {@code true} if the given Sone is local, {@code false} otherwise
410          */
411         public boolean isLocalSone(Sone sone) {
412                 synchronized (localSones) {
413                         return localSones.containsKey(sone.getId());
414                 }
415         }
416
417         /**
418          * Returns whether the given ID is the ID of a local Sone.
419          *
420          * @param id
421          *            The Sone ID to check for its locality
422          * @return {@code true} if the given ID is a local Sone, {@code false}
423          *         otherwise
424          */
425         public boolean isLocalSone(String id) {
426                 synchronized (localSones) {
427                         return localSones.containsKey(id);
428                 }
429         }
430
431         /**
432          * Returns all local Sones.
433          *
434          * @return All local Sones
435          */
436         public Set<Sone> getLocalSones() {
437                 synchronized (localSones) {
438                         return new HashSet<Sone>(localSones.values());
439                 }
440         }
441
442         /**
443          * Returns the local Sone with the given ID.
444          *
445          * @param id
446          *            The ID of the Sone to get
447          * @return The Sone with the given ID
448          */
449         public Sone getLocalSone(String id) {
450                 return getLocalSone(id, true);
451         }
452
453         /**
454          * Returns the local Sone with the given ID, optionally creating a new Sone.
455          *
456          * @param id
457          *            The ID of the Sone
458          * @param create
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}
462          */
463         public Sone getLocalSone(String id, boolean create) {
464                 synchronized (localSones) {
465                         Sone sone = localSones.get(id);
466                         if ((sone == null) && create) {
467                                 sone = new Sone(id);
468                                 localSones.put(id, sone);
469                                 setSoneStatus(sone, SoneStatus.unknown);
470                         }
471                         return sone;
472                 }
473         }
474
475         /**
476          * Returns all remote Sones.
477          *
478          * @return All remote Sones
479          */
480         public Set<Sone> getRemoteSones() {
481                 synchronized (remoteSones) {
482                         return new HashSet<Sone>(remoteSones.values());
483                 }
484         }
485
486         /**
487          * Returns the remote Sone with the given ID.
488          *
489          * @param id
490          *            The ID of the remote Sone to get
491          * @return The Sone with the given ID
492          */
493         public Sone getRemoteSone(String id) {
494                 return getRemoteSone(id, true);
495         }
496
497         /**
498          * Returns the remote Sone with the given ID.
499          *
500          * @param id
501          *            The ID of the remote Sone to get
502          * @param create
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
506          */
507         public Sone getRemoteSone(String id, boolean create) {
508                 synchronized (remoteSones) {
509                         Sone sone = remoteSones.get(id);
510                         if ((sone == null) && create) {
511                                 sone = new Sone(id);
512                                 remoteSones.put(id, sone);
513                                 setSoneStatus(sone, SoneStatus.unknown);
514                         }
515                         return sone;
516                 }
517         }
518
519         /**
520          * Returns whether the given Sone is a remote Sone.
521          *
522          * @param sone
523          *            The Sone to check
524          * @return {@code true} if the given Sone is a remote Sone, {@code false}
525          *         otherwise
526          */
527         public boolean isRemoteSone(Sone sone) {
528                 synchronized (remoteSones) {
529                         return remoteSones.containsKey(sone.getId());
530                 }
531         }
532
533         /**
534          * Returns whether the Sone with the given ID is a remote Sone.
535          *
536          * @param id
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
540          */
541         public boolean isRemoteSone(String id) {
542                 synchronized (remoteSones) {
543                         return remoteSones.containsKey(id);
544                 }
545         }
546
547         /**
548          * Returns whether the Sone with the given ID is a new Sone.
549          *
550          * @param soneId
551          *            The ID of the sone to check for
552          * @return {@code true} if the given Sone is new, false otherwise
553          */
554         public boolean isNewSone(String soneId) {
555                 synchronized (newSones) {
556                         return !knownSones.contains(soneId) && newSones.contains(soneId);
557                 }
558         }
559
560         /**
561          * Returns whether the given Sone has been modified.
562          *
563          * @param sone
564          *            The Sone to check for modifications
565          * @return {@code true} if a modification has been detected in the Sone,
566          *         {@code false} otherwise
567          */
568         public boolean isModifiedSone(Sone sone) {
569                 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
570         }
571
572         /**
573          * Returns whether the target Sone is trusted by the origin Sone.
574          *
575          * @param origin
576          *            The origin Sone
577          * @param target
578          *            The target Sone
579          * @return {@code true} if the target Sone is trusted by the origin Sone
580          */
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());
584         }
585
586         /**
587          * Returns the post with the given ID.
588          *
589          * @param postId
590          *            The ID of the post to get
591          * @return The post with the given ID, or a new post with the given ID
592          */
593         public Post getPost(String postId) {
594                 return getPost(postId, true);
595         }
596
597         /**
598          * Returns the post with the given ID, optionally creating a new post.
599          *
600          * @param postId
601          *            The ID of the post to get
602          * @param create
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
606          */
607         @Override
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);
614                         }
615                         return post;
616                 }
617         }
618
619         /**
620          * Returns whether the given post ID is new.
621          *
622          * @param postId
623          *            The post ID
624          * @return {@code true} if the post is considered to be new, {@code false}
625          *         otherwise
626          */
627         public boolean isNewPost(String postId) {
628                 synchronized (newPosts) {
629                         return !knownPosts.contains(postId) && newPosts.contains(postId);
630                 }
631         }
632
633         /**
634          * Returns all posts that have the given Sone as recipient.
635          *
636          * @see Post#getRecipient()
637          * @param recipient
638          *            The recipient of the posts
639          * @return All posts that have the given Sone as recipient
640          */
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);
648                                 }
649                         }
650                 }
651                 return directedPosts;
652         }
653
654         /**
655          * Returns the reply with the given ID. If there is no reply with the given
656          * ID yet, a new one is created.
657          *
658          * @param replyId
659          *            The ID of the reply to get
660          * @return The reply
661          */
662         public Reply getReply(String replyId) {
663                 return getReply(replyId, true);
664         }
665
666         /**
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.
670          *
671          * @param replyId
672          *            The ID of the reply to get
673          * @param create
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
677          */
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);
684                         }
685                         return reply;
686                 }
687         }
688
689         /**
690          * Returns all replies for the given post, order ascending by time.
691          *
692          * @param post
693          *            The post to get all replies for
694          * @return All replies for the given post
695          */
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)) {
702                                         replies.add(reply);
703                                 }
704                         }
705                 }
706                 Collections.sort(replies, Reply.TIME_COMPARATOR);
707                 return replies;
708         }
709
710         /**
711          * Returns whether the reply with the given ID is new.
712          *
713          * @param replyId
714          *            The ID of the reply to check
715          * @return {@code true} if the reply is considered to be new, {@code false}
716          *         otherwise
717          */
718         public boolean isNewReply(String replyId) {
719                 synchronized (newReplies) {
720                         return !knownReplies.contains(replyId) && newReplies.contains(replyId);
721                 }
722         }
723
724         /**
725          * Returns all Sones that have liked the given post.
726          *
727          * @param post
728          *            The post to get the liking Sones for
729          * @return The Sones that like the given post
730          */
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())) {
735                                 sones.add(sone);
736                         }
737                 }
738                 return sones;
739         }
740
741         /**
742          * Returns all Sones that have liked the given reply.
743          *
744          * @param reply
745          *            The reply to get the liking Sones for
746          * @return The Sones that like the given reply
747          */
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())) {
752                                 sones.add(sone);
753                         }
754                 }
755                 return sones;
756         }
757
758         /**
759          * Returns whether the given post is bookmarked.
760          *
761          * @param post
762          *            The post to check
763          * @return {@code true} if the given post is bookmarked, {@code false}
764          *         otherwise
765          */
766         public boolean isBookmarked(Post post) {
767                 return isPostBookmarked(post.getId());
768         }
769
770         /**
771          * Returns whether the post with the given ID is bookmarked.
772          *
773          * @param id
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
777          */
778         public boolean isPostBookmarked(String id) {
779                 synchronized (bookmarkedPosts) {
780                         return bookmarkedPosts.contains(id);
781                 }
782         }
783
784         /**
785          * Returns all currently known bookmarked posts.
786          *
787          * @return All bookmarked posts
788          */
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);
794                                 if (post != null) {
795                                         posts.add(post);
796                                 }
797                         }
798                 }
799                 return posts;
800         }
801
802         //
803         // ACTIONS
804         //
805
806         /**
807          * Locks the given Sone. A locked Sone will not be inserted by
808          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
809          * again.
810          *
811          * @param sone
812          *            The sone to lock
813          */
814         public void lockSone(Sone sone) {
815                 synchronized (lockedSones) {
816                         if (lockedSones.add(sone)) {
817                                 coreListenerManager.fireSoneLocked(sone);
818                         }
819                 }
820         }
821
822         /**
823          * Unlocks the given Sone.
824          *
825          * @see #lockSone(Sone)
826          * @param sone
827          *            The sone to unlock
828          */
829         public void unlockSone(Sone sone) {
830                 synchronized (lockedSones) {
831                         if (lockedSones.remove(sone)) {
832                                 coreListenerManager.fireSoneUnlocked(sone);
833                         }
834                 }
835         }
836
837         /**
838          * Adds a local Sone from the given ID which has to be the ID of an own
839          * identity.
840          *
841          * @param id
842          *            The ID of an own identity to add a Sone for
843          * @return The added (or already existing) Sone
844          */
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);
850                         }
851                         OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
852                         if (ownIdentity == null) {
853                                 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
854                                 return null;
855                         }
856                         return addLocalSone(ownIdentity);
857                 }
858         }
859
860         /**
861          * Adds a local Sone from the given own identity.
862          *
863          * @param ownIdentity
864          *            The own identity to create a Sone from
865          * @return The added (or already existing) Sone
866          */
867         public Sone addLocalSone(OwnIdentity ownIdentity) {
868                 if (ownIdentity == null) {
869                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
870                         return null;
871                 }
872                 synchronized (localSones) {
873                         final Sone sone;
874                         try {
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);
878                                 return null;
879                         }
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);
888                         loadSone(sone);
889                         soneInserter.start();
890                         return sone;
891                 }
892         }
893
894         /**
895          * Creates a new Sone for the given own identity.
896          *
897          * @param ownIdentity
898          *            The own identity to create a Sone for
899          * @return The created Sone
900          */
901         public Sone createSone(OwnIdentity ownIdentity) {
902                 try {
903                         ownIdentity.addContext("Sone");
904                 } catch (WebOfTrustException wote1) {
905                         logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
906                         return null;
907                 }
908                 Sone sone = addLocalSone(ownIdentity);
909                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
910                 sone.addFriend("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
911                 saveSone(sone);
912                 return sone;
913         }
914
915         /**
916          * Adds the Sone of the given identity.
917          *
918          * @param identity
919          *            The identity whose Sone to add
920          * @return The added or already existing Sone
921          */
922         public Sone addRemoteSone(Identity identity) {
923                 if (identity == null) {
924                         logger.log(Level.WARNING, "Given Identity is null!");
925                         return null;
926                 }
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));
932                         if (newSone) {
933                                 synchronized (newSones) {
934                                         newSone = !knownSones.contains(sone.getId());
935                                         if (newSone) {
936                                                 newSones.add(sone.getId());
937                                         }
938                                 }
939                                 if (newSone) {
940                                         coreListenerManager.fireNewSoneFound(sone);
941                                         for (Sone localSone : getLocalSones()) {
942                                                 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
943                                                         localSone.addFriend(sone.getId());
944                                                         saveSone(localSone);
945                                                 }
946                                         }
947                                 }
948                         }
949                         remoteSones.put(identity.getId(), sone);
950                         soneDownloader.addSone(sone);
951                         setSoneStatus(sone, SoneStatus.unknown);
952                         soneDownloaders.execute(new Runnable() {
953
954                                 @Override
955                                 @SuppressWarnings("synthetic-access")
956                                 public void run() {
957                                         soneDownloader.fetchSone(sone, sone.getRequestUri());
958                                 }
959
960                         });
961                         return sone;
962                 }
963         }
964
965         /**
966          * Retrieves the trust relationship from the origin to the target. If the
967          * trust relationship can not be retrieved, {@code null} is returned.
968          *
969          * @see Identity#getTrust(OwnIdentity)
970          * @param origin
971          *            The origin of the trust tree
972          * @param target
973          *            The target of the trust
974          * @return The trust relationship
975          */
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);
979                         return null;
980                 }
981                 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
982         }
983
984         /**
985          * Sets the trust value of the given origin Sone for the target Sone.
986          *
987          * @param origin
988          *            The origin Sone
989          * @param target
990          *            The target Sone
991          * @param trustValue
992          *            The trust value (from {@code -100} to {@code 100})
993          */
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();
996                 try {
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);
1000                 }
1001         }
1002
1003         /**
1004          * Removes any trust assignment for the given target Sone.
1005          *
1006          * @param origin
1007          *            The trust origin
1008          * @param target
1009          *            The trust target
1010          */
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();
1013                 try {
1014                         ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1015                 } catch (WebOfTrustException wote1) {
1016                         logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
1017                 }
1018         }
1019
1020         /**
1021          * Assigns the configured positive trust value for the given target.
1022          *
1023          * @param origin
1024          *            The trust origin
1025          * @param target
1026          *            The trust target
1027          */
1028         public void trustSone(Sone origin, Sone target) {
1029                 setTrust(origin, target, preferences.getPositiveTrust());
1030         }
1031
1032         /**
1033          * Assigns the configured negative trust value for the given target.
1034          *
1035          * @param origin
1036          *            The trust origin
1037          * @param target
1038          *            The trust target
1039          */
1040         public void distrustSone(Sone origin, Sone target) {
1041                 setTrust(origin, target, preferences.getNegativeTrust());
1042         }
1043
1044         /**
1045          * Removes the trust assignment for the given target.
1046          *
1047          * @param origin
1048          *            The trust origin
1049          * @param target
1050          *            The trust target
1051          */
1052         public void untrustSone(Sone origin, Sone target) {
1053                 removeTrust(origin, target);
1054         }
1055
1056         /**
1057          * Updates the stored Sone with the given Sone.
1058          *
1059          * @param sone
1060          *            The updated Sone
1061          */
1062         public void updateSone(Sone sone) {
1063                 updateSone(sone, false);
1064         }
1065
1066         /**
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
1069          * an old state.
1070          *
1071          * @param sone
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
1076          */
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 });
1082                                 return;
1083                         }
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);
1090                                                 }
1091                                         }
1092                                 }
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);
1100                                                 }
1101                                                 posts.put(post.getId(), post);
1102                                         }
1103                                 }
1104                         }
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);
1111                                                 }
1112                                         }
1113                                 }
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);
1121                                                 }
1122                                                 replies.put(reply.getId(), reply);
1123                                         }
1124                                 }
1125                         }
1126                         synchronized (storedSone) {
1127                                 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1128                                         storedSone.setTime(sone.getTime());
1129                                 }
1130                                 storedSone.setClient(sone.getClient());
1131                                 storedSone.setProfile(sone.getProfile());
1132                                 if (soneRescueMode) {
1133                                         for (Post post : sone.getPosts()) {
1134                                                 storedSone.addPost(post);
1135                                         }
1136                                         for (Reply reply : sone.getReplies()) {
1137                                                 storedSone.addReply(reply);
1138                                         }
1139                                         for (String likedPostId : sone.getLikedPostIds()) {
1140                                                 storedSone.addLikedPostId(likedPostId);
1141                                         }
1142                                         for (String likedReplyId : sone.getLikedReplyIds()) {
1143                                                 storedSone.addLikedReplyId(likedReplyId);
1144                                         }
1145                                 } else {
1146                                         storedSone.setPosts(sone.getPosts());
1147                                         storedSone.setReplies(sone.getReplies());
1148                                         storedSone.setLikePostIds(sone.getLikedPostIds());
1149                                         storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1150                                 }
1151                                 storedSone.setLatestEdition(sone.getLatestEdition());
1152                         }
1153                 }
1154         }
1155
1156         /**
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.
1160          *
1161          * @param sone
1162          *            The Sone to delete
1163          */
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);
1167                         return;
1168                 }
1169                 synchronized (localSones) {
1170                         if (!localSones.containsKey(sone.getId())) {
1171                                 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1172                                 return;
1173                         }
1174                         localSones.remove(sone.getId());
1175                         SoneInserter soneInserter = soneInserters.remove(sone);
1176                         soneInserter.removeSoneInsertListener(this);
1177                         soneInserter.stop();
1178                 }
1179                 try {
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);
1184                 }
1185                 try {
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);
1189                 }
1190         }
1191
1192         /**
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.
1195          *
1196          * @param sone
1197          *            The Sone to mark as known
1198          */
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();
1205                         }
1206                 }
1207         }
1208
1209         /**
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.
1212          *
1213          * @param sone
1214          *            The Sone to load and update
1215          */
1216         public void loadSone(Sone sone) {
1217                 if (!isLocalSone(sone)) {
1218                         logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1219                         return;
1220                 }
1221
1222                 /* initialize options. */
1223                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1224
1225                 /* load Sone. */
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.");
1230                         return;
1231                 }
1232                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1233
1234                 /* load profile. */
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));
1242
1243                 /* load profile fields. */
1244                 while (true) {
1245                         String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1246                         String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1247                         if (fieldName == null) {
1248                                 break;
1249                         }
1250                         String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1251                         profile.addField(fieldName).setValue(fieldValue);
1252                 }
1253
1254                 /* load posts. */
1255                 Set<Post> posts = new HashSet<Post>();
1256                 while (true) {
1257                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1258                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1259                         if (postId == null) {
1260                                 break;
1261                         }
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!");
1267                                 return;
1268                         }
1269                         Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1270                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1271                                 post.setRecipient(getSone(postRecipientId));
1272                         }
1273                         posts.add(post);
1274                 }
1275
1276                 /* load replies. */
1277                 Set<Reply> replies = new HashSet<Reply>();
1278                 while (true) {
1279                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1280                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1281                         if (replyId == null) {
1282                                 break;
1283                         }
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!");
1289                                 return;
1290                         }
1291                         replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1292                 }
1293
1294                 /* load post likes. */
1295                 Set<String> likedPostIds = new HashSet<String>();
1296                 while (true) {
1297                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1298                         if (likedPostId == null) {
1299                                 break;
1300                         }
1301                         likedPostIds.add(likedPostId);
1302                 }
1303
1304                 /* load reply likes. */
1305                 Set<String> likedReplyIds = new HashSet<String>();
1306                 while (true) {
1307                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1308                         if (likedReplyId == null) {
1309                                 break;
1310                         }
1311                         likedReplyIds.add(likedReplyId);
1312                 }
1313
1314                 /* load friends. */
1315                 Set<String> friends = new HashSet<String>();
1316                 while (true) {
1317                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1318                         if (friendId == null) {
1319                                 break;
1320                         }
1321                         friends.add(friendId);
1322                 }
1323
1324                 /* load options. */
1325                 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1326
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);
1337                 }
1338                 synchronized (newSones) {
1339                         for (String friend : friends) {
1340                                 knownSones.add(friend);
1341                         }
1342                 }
1343                 synchronized (newPosts) {
1344                         for (Post post : posts) {
1345                                 knownPosts.add(post.getId());
1346                         }
1347                 }
1348                 synchronized (newReplies) {
1349                         for (Reply reply : replies) {
1350                                 knownReplies.add(reply.getId());
1351                         }
1352                 }
1353         }
1354
1355         /**
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.
1358          *
1359          * @param sone
1360          *            The Sone to save
1361          */
1362         public synchronized void saveSone(Sone sone) {
1363                 if (!isLocalSone(sone)) {
1364                         logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1365                         return;
1366                 }
1367                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1368                         logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1369                         return;
1370                 }
1371
1372                 logger.log(Level.INFO, "Saving Sone: %s", sone);
1373                 try {
1374                         ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1375
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());
1380
1381                         /* save profile. */
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());
1389
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());
1396                         }
1397                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1398
1399                         /* save posts. */
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());
1407                         }
1408                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1409
1410                         /* save replies. */
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());
1418                         }
1419                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1420
1421                         /* save post likes. */
1422                         int postLikeCounter = 0;
1423                         for (String postId : sone.getLikedPostIds()) {
1424                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1425                         }
1426                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1427
1428                         /* save reply likes. */
1429                         int replyLikeCounter = 0;
1430                         for (String replyId : sone.getLikedReplyIds()) {
1431                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1432                         }
1433                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1434
1435                         /* save friends. */
1436                         int friendCounter = 0;
1437                         for (String friendId : sone.getFriends()) {
1438                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1439                         }
1440                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1441
1442                         /* save options. */
1443                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1444
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);
1451                 }
1452         }
1453
1454         /**
1455          * Creates a new post.
1456          *
1457          * @param sone
1458          *            The Sone that creates the post
1459          * @param text
1460          *            The text of the post
1461          * @return The created post
1462          */
1463         public Post createPost(Sone sone, String text) {
1464                 return createPost(sone, System.currentTimeMillis(), text);
1465         }
1466
1467         /**
1468          * Creates a new post.
1469          *
1470          * @param sone
1471          *            The Sone that creates the post
1472          * @param time
1473          *            The time of the post
1474          * @param text
1475          *            The text of the post
1476          * @return The created post
1477          */
1478         public Post createPost(Sone sone, long time, String text) {
1479                 return createPost(sone, null, time, text);
1480         }
1481
1482         /**
1483          * Creates a new post.
1484          *
1485          * @param sone
1486          *            The Sone that creates the post
1487          * @param recipient
1488          *            The recipient Sone, or {@code null} if this post does not have
1489          *            a recipient
1490          * @param text
1491          *            The text of the post
1492          * @return The created post
1493          */
1494         public Post createPost(Sone sone, Sone recipient, String text) {
1495                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1496         }
1497
1498         /**
1499          * Creates a new post.
1500          *
1501          * @param sone
1502          *            The Sone that creates the post
1503          * @param recipient
1504          *            The recipient Sone, or {@code null} if this post does not have
1505          *            a recipient
1506          * @param time
1507          *            The time of the post
1508          * @param text
1509          *            The text of the post
1510          * @return The created post
1511          */
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);
1515                         return null;
1516                 }
1517                 final Post post = new Post(sone, time, text);
1518                 if (recipient != null) {
1519                         post.setRecipient(recipient);
1520                 }
1521                 synchronized (posts) {
1522                         posts.put(post.getId(), post);
1523                 }
1524                 synchronized (newPosts) {
1525                         newPosts.add(post.getId());
1526                         coreListenerManager.fireNewPostFound(post);
1527                 }
1528                 sone.addPost(post);
1529                 saveSone(sone);
1530                 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1531
1532                         /**
1533                          * {@inheritDoc}
1534                          */
1535                         @Override
1536                         public void run() {
1537                                 markPostKnown(post);
1538                         }
1539                 }, "Mark " + post + " read.");
1540                 return post;
1541         }
1542
1543         /**
1544          * Deletes the given post.
1545          *
1546          * @param post
1547          *            The post to delete
1548          */
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());
1552                         return;
1553                 }
1554                 post.getSone().removePost(post);
1555                 synchronized (posts) {
1556                         posts.remove(post.getId());
1557                 }
1558                 coreListenerManager.firePostRemoved(post);
1559                 synchronized (newPosts) {
1560                         markPostKnown(post);
1561                         knownPosts.remove(post.getId());
1562                 }
1563                 saveSone(post.getSone());
1564         }
1565
1566         /**
1567          * Marks the given post as known, if it is currently a new post (according
1568          * to {@link #isNewPost(String)}).
1569          *
1570          * @param post
1571          *            The post to mark as known
1572          */
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();
1579                         }
1580                 }
1581         }
1582
1583         /**
1584          * Bookmarks the given post.
1585          *
1586          * @param post
1587          *            The post to bookmark
1588          */
1589         public void bookmark(Post post) {
1590                 bookmarkPost(post.getId());
1591         }
1592
1593         /**
1594          * Bookmarks the post with the given ID.
1595          *
1596          * @param id
1597          *            The ID of the post to bookmark
1598          */
1599         public void bookmarkPost(String id) {
1600                 synchronized (bookmarkedPosts) {
1601                         bookmarkedPosts.add(id);
1602                 }
1603         }
1604
1605         /**
1606          * Removes the given post from the bookmarks.
1607          *
1608          * @param post
1609          *            The post to unbookmark
1610          */
1611         public void unbookmark(Post post) {
1612                 unbookmarkPost(post.getId());
1613         }
1614
1615         /**
1616          * Removes the post with the given ID from the bookmarks.
1617          *
1618          * @param id
1619          *            The ID of the post to unbookmark
1620          */
1621         public void unbookmarkPost(String id) {
1622                 synchronized (bookmarkedPosts) {
1623                         bookmarkedPosts.remove(id);
1624                 }
1625         }
1626
1627         /**
1628          * Creates a new reply.
1629          *
1630          * @param sone
1631          *            The Sone that creates the reply
1632          * @param post
1633          *            The post that this reply refers to
1634          * @param text
1635          *            The text of the reply
1636          * @return The created reply
1637          */
1638         public Reply createReply(Sone sone, Post post, String text) {
1639                 return createReply(sone, post, System.currentTimeMillis(), text);
1640         }
1641
1642         /**
1643          * Creates a new reply.
1644          *
1645          * @param sone
1646          *            The Sone that creates the reply
1647          * @param post
1648          *            The post that this reply refers to
1649          * @param time
1650          *            The time of the reply
1651          * @param text
1652          *            The text of the reply
1653          * @return The created reply
1654          */
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);
1658                         return null;
1659                 }
1660                 final Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1661                 synchronized (replies) {
1662                         replies.put(reply.getId(), reply);
1663                 }
1664                 synchronized (newReplies) {
1665                         newReplies.add(reply.getId());
1666                         coreListenerManager.fireNewReplyFound(reply);
1667                 }
1668                 sone.addReply(reply);
1669                 saveSone(sone);
1670                 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1671
1672                         /**
1673                          * {@inheritDoc}
1674                          */
1675                         @Override
1676                         public void run() {
1677                                 markReplyKnown(reply);
1678                         }
1679                 }, "Mark " + reply + " read.");
1680                 return reply;
1681         }
1682
1683         /**
1684          * Deletes the given reply.
1685          *
1686          * @param reply
1687          *            The reply to delete
1688          */
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);
1693                         return;
1694                 }
1695                 synchronized (replies) {
1696                         replies.remove(reply.getId());
1697                 }
1698                 synchronized (newReplies) {
1699                         markReplyKnown(reply);
1700                         knownReplies.remove(reply.getId());
1701                 }
1702                 sone.removeReply(reply);
1703                 saveSone(sone);
1704         }
1705
1706         /**
1707          * Marks the given reply as known, if it is currently a new reply (according
1708          * to {@link #isNewReply(String)}).
1709          *
1710          * @param reply
1711          *            The reply to mark as known
1712          */
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();
1719                         }
1720                 }
1721         }
1722
1723         /**
1724          * Starts the core.
1725          */
1726         public void start() {
1727                 loadConfiguration();
1728                 updateChecker.addUpdateListener(this);
1729                 updateChecker.start();
1730         }
1731
1732         /**
1733          * Stops the core.
1734          */
1735         public void stop() {
1736                 synchronized (localSones) {
1737                         for (SoneInserter soneInserter : soneInserters.values()) {
1738                                 soneInserter.removeSoneInsertListener(this);
1739                                 soneInserter.stop();
1740                         }
1741                         for (Sone localSone : localSones.values()) {
1742                                 saveSone(localSone);
1743                         }
1744                 }
1745                 updateChecker.stop();
1746                 updateChecker.removeUpdateListener(this);
1747                 soneDownloader.stop();
1748                 saveConfiguration();
1749                 stopped = true;
1750         }
1751
1752         /**
1753          * Saves the current options.
1754          */
1755         public void saveConfiguration() {
1756                 synchronized (configuration) {
1757                         if (storingConfiguration) {
1758                                 logger.log(Level.FINE, "Already storing configuration…");
1759                                 return;
1760                         }
1761                         storingConfiguration = true;
1762                 }
1763
1764                 /* store the options first. */
1765                 try {
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());
1779
1780                         /* save known Sones. */
1781                         int soneCounter = 0;
1782                         synchronized (newSones) {
1783                                 for (String knownSoneId : knownSones) {
1784                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1785                                 }
1786                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1787                         }
1788
1789                         /* save known posts. */
1790                         int postCounter = 0;
1791                         synchronized (newPosts) {
1792                                 for (String knownPostId : knownPosts) {
1793                                         configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1794                                 }
1795                                 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1796                         }
1797
1798                         /* save known replies. */
1799                         int replyCounter = 0;
1800                         synchronized (newReplies) {
1801                                 for (String knownReplyId : knownReplies) {
1802                                         configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1803                                 }
1804                                 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1805                         }
1806
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);
1812                                 }
1813                         }
1814                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1815
1816                         /* now save it. */
1817                         configuration.save();
1818
1819                 } catch (ConfigurationException ce1) {
1820                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1821                 } finally {
1822                         synchronized (configuration) {
1823                                 storingConfiguration = false;
1824                         }
1825                 }
1826         }
1827
1828         //
1829         // PRIVATE METHODS
1830         //
1831
1832         /**
1833          * Loads the configuration.
1834          */
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>() {
1839
1840                         @Override
1841                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1842                                 SoneInserter.setInsertionDelay(newValue);
1843                         }
1844
1845                 }));
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>() {
1853
1854                         @Override
1855                         @SuppressWarnings("synthetic-access")
1856                         public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1857                                 fcpInterface.setActive(newValue);
1858                         }
1859                 }));
1860                 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1861
1862                         @Override
1863                         @SuppressWarnings("synthetic-access")
1864                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1865                                 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1866                         }
1867
1868                 }));
1869                 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1870                 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1871                 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1872
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. */
1881                         return;
1882                 }
1883
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));
1894
1895                 /* load known Sones. */
1896                 int soneCounter = 0;
1897                 while (true) {
1898                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1899                         if (knownSoneId == null) {
1900                                 break;
1901                         }
1902                         synchronized (newSones) {
1903                                 knownSones.add(knownSoneId);
1904                         }
1905                 }
1906
1907                 /* load known posts. */
1908                 int postCounter = 0;
1909                 while (true) {
1910                         String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1911                         if (knownPostId == null) {
1912                                 break;
1913                         }
1914                         synchronized (newPosts) {
1915                                 knownPosts.add(knownPostId);
1916                         }
1917                 }
1918
1919                 /* load known replies. */
1920                 int replyCounter = 0;
1921                 while (true) {
1922                         String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1923                         if (knownReplyId == null) {
1924                                 break;
1925                         }
1926                         synchronized (newReplies) {
1927                                 knownReplies.add(knownReplyId);
1928                         }
1929                 }
1930
1931                 /* load bookmarked posts. */
1932                 int bookmarkedPostCounter = 0;
1933                 while (true) {
1934                         String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1935                         if (bookmarkedPostId == null) {
1936                                 break;
1937                         }
1938                         synchronized (bookmarkedPosts) {
1939                                 bookmarkedPosts.add(bookmarkedPostId);
1940                         }
1941                 }
1942
1943         }
1944
1945         /**
1946          * Loads an {@link Integer} configuration value for the option with the
1947          * given name, logging validation failures.
1948          *
1949          * @param optionName
1950          *            The name of the option to load
1951          */
1952         private void loadConfigurationValue(String optionName) {
1953                 try {
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.");
1957                 }
1958         }
1959
1960         /**
1961          * Generate a Sone URI from the given URI and latest edition.
1962          *
1963          * @param uriString
1964          *            The URI to derive the Sone URI from
1965          * @return The derived URI
1966          */
1967         private FreenetURI getSoneUri(String uriString) {
1968                 try {
1969                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1970                         return uri;
1971                 } catch (MalformedURLException mue1) {
1972                         logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1973                         return null;
1974                 }
1975         }
1976
1977         //
1978         // INTERFACE IdentityListener
1979         //
1980
1981         /**
1982          * {@inheritDoc}
1983          */
1984         @Override
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);
1990                 }
1991         }
1992
1993         /**
1994          * {@inheritDoc}
1995          */
1996         @Override
1997         public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1998                 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1999                 trustedIdentities.remove(ownIdentity);
2000         }
2001
2002         /**
2003          * {@inheritDoc}
2004          */
2005         @Override
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);
2010         }
2011
2012         /**
2013          * {@inheritDoc}
2014          */
2015         @Override
2016         public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2017                 new Thread(new Runnable() {
2018
2019                         @Override
2020                         @SuppressWarnings("synthetic-access")
2021                         public void run() {
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);
2027                         }
2028                 }).start();
2029         }
2030
2031         /**
2032          * {@inheritDoc}
2033          */
2034         @Override
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)) {
2040                                 continue;
2041                         }
2042                         if (trustedIdentity.getValue().contains(identity)) {
2043                                 foundIdentity = true;
2044                         }
2045                 }
2046                 if (foundIdentity) {
2047                         /* some local identity still trusts this identity, don’t remove. */
2048                         return;
2049                 }
2050                 Sone sone = getSone(identity.getId(), false);
2051                 if (sone == null) {
2052                         /* TODO - we don’t have the Sone anymore. should this happen? */
2053                         return;
2054                 }
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);
2061                                 }
2062                         }
2063                 }
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);
2070                                 }
2071                         }
2072                 }
2073                 synchronized (remoteSones) {
2074                         remoteSones.remove(identity.getId());
2075                 }
2076                 synchronized (newSones) {
2077                         newSones.remove(identity.getId());
2078                         coreListenerManager.fireSoneRemoved(sone);
2079                 }
2080         }
2081
2082         //
2083         // INTERFACE UpdateListener
2084         //
2085
2086         /**
2087          * {@inheritDoc}
2088          */
2089         @Override
2090         public void updateFound(Version version, long releaseTime, long latestEdition) {
2091                 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2092         }
2093
2094         //
2095         // SONEINSERTLISTENER METHODS
2096         //
2097
2098         /**
2099          * {@inheritDoc}
2100          */
2101         public void insertStarted(Sone sone) {
2102                 coreListenerManager.fireSoneInserting(sone);
2103         }
2104
2105         /**
2106          * {@inheritDoc}
2107          */
2108         @Override
2109         public void insertFinished(Sone sone, long insertDuration) {
2110                 coreListenerManager.fireSoneInserted(sone, insertDuration);
2111         }
2112
2113         /**
2114          * {@inheritDoc}
2115          */
2116         @Override
2117         public void insertAborted(Sone sone, Throwable cause) {
2118                 coreListenerManager.fireSoneInsertAborted(sone, cause);
2119         }
2120
2121         /**
2122          * Convenience interface for external classes that want to access the core’s
2123          * configuration.
2124          *
2125          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2126          */
2127         public static class Preferences {
2128
2129                 /** The wrapped options. */
2130                 private final Options options;
2131
2132                 /**
2133                  * Creates a new preferences object wrapped around the given options.
2134                  *
2135                  * @param options
2136                  *            The options to wrap
2137                  */
2138                 public Preferences(Options options) {
2139                         this.options = options;
2140                 }
2141
2142                 /**
2143                  * Returns the insertion delay.
2144                  *
2145                  * @return The insertion delay
2146                  */
2147                 public int getInsertionDelay() {
2148                         return options.getIntegerOption("InsertionDelay").get();
2149                 }
2150
2151                 /**
2152                  * Validates the given insertion delay.
2153                  *
2154                  * @param insertionDelay
2155                  *            The insertion delay to validate
2156                  * @return {@code true} if the given insertion delay was valid, {@code
2157                  *         false} otherwise
2158                  */
2159                 public boolean validateInsertionDelay(Integer insertionDelay) {
2160                         return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2161                 }
2162
2163                 /**
2164                  * Sets the insertion delay
2165                  *
2166                  * @param insertionDelay
2167                  *            The new insertion delay, or {@code null} to restore it to
2168                  *            the default value
2169                  * @return This preferences
2170                  */
2171                 public Preferences setInsertionDelay(Integer insertionDelay) {
2172                         options.getIntegerOption("InsertionDelay").set(insertionDelay);
2173                         return this;
2174                 }
2175
2176                 /**
2177                  * Returns the number of posts to show per page.
2178                  *
2179                  * @return The number of posts to show per page
2180                  */
2181                 public int getPostsPerPage() {
2182                         return options.getIntegerOption("PostsPerPage").get();
2183                 }
2184
2185                 /**
2186                  * Validates the number of posts per page.
2187                  *
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
2192                  */
2193                 public boolean validatePostsPerPage(Integer postsPerPage) {
2194                         return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2195                 }
2196
2197                 /**
2198                  * Sets the number of posts to show per page.
2199                  *
2200                  * @param postsPerPage
2201                  *            The number of posts to show per page
2202                  * @return This preferences object
2203                  */
2204                 public Preferences setPostsPerPage(Integer postsPerPage) {
2205                         options.getIntegerOption("PostsPerPage").set(postsPerPage);
2206                         return this;
2207                 }
2208
2209                 /**
2210                  * Returns the number of characters per post, or <code>-1</code> if the
2211                  * posts should not be cut off.
2212                  *
2213                  * @return The numbers of characters per post
2214                  */
2215                 public int getCharactersPerPost() {
2216                         return options.getIntegerOption("CharactersPerPost").get();
2217                 }
2218
2219                 /**
2220                  * Validates the number of characters per post.
2221                  *
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
2226                  */
2227                 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2228                         return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2229                 }
2230
2231                 /**
2232                  * Sets the number of characters per post.
2233                  *
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
2238                  */
2239                 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2240                         options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2241                         return this;
2242                 }
2243
2244                 /**
2245                  * Returns whether Sone requires full access to be even visible.
2246                  *
2247                  * @return {@code true} if Sone requires full access, {@code false}
2248                  *         otherwise
2249                  */
2250                 public boolean isRequireFullAccess() {
2251                         return options.getBooleanOption("RequireFullAccess").get();
2252                 }
2253
2254                 /**
2255                  * Sets whether Sone requires full access to be even visible.
2256                  *
2257                  * @param requireFullAccess
2258                  *            {@code true} if Sone requires full access, {@code false}
2259                  *            otherwise
2260                  */
2261                 public void setRequireFullAccess(Boolean requireFullAccess) {
2262                         options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2263                 }
2264
2265                 /**
2266                  * Returns the positive trust.
2267                  *
2268                  * @return The positive trust
2269                  */
2270                 public int getPositiveTrust() {
2271                         return options.getIntegerOption("PositiveTrust").get();
2272                 }
2273
2274                 /**
2275                  * Validates the positive trust.
2276                  *
2277                  * @param positiveTrust
2278                  *            The positive trust to validate
2279                  * @return {@code true} if the positive trust was valid, {@code false}
2280                  *         otherwise
2281                  */
2282                 public boolean validatePositiveTrust(Integer positiveTrust) {
2283                         return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2284                 }
2285
2286                 /**
2287                  * Sets the positive trust.
2288                  *
2289                  * @param positiveTrust
2290                  *            The new positive trust, or {@code null} to restore it to
2291                  *            the default vlaue
2292                  * @return This preferences
2293                  */
2294                 public Preferences setPositiveTrust(Integer positiveTrust) {
2295                         options.getIntegerOption("PositiveTrust").set(positiveTrust);
2296                         return this;
2297                 }
2298
2299                 /**
2300                  * Returns the negative trust.
2301                  *
2302                  * @return The negative trust
2303                  */
2304                 public int getNegativeTrust() {
2305                         return options.getIntegerOption("NegativeTrust").get();
2306                 }
2307
2308                 /**
2309                  * Validates the negative trust.
2310                  *
2311                  * @param negativeTrust
2312                  *            The negative trust to validate
2313                  * @return {@code true} if the negative trust was valid, {@code false}
2314                  *         otherwise
2315                  */
2316                 public boolean validateNegativeTrust(Integer negativeTrust) {
2317                         return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2318                 }
2319
2320                 /**
2321                  * Sets the negative trust.
2322                  *
2323                  * @param negativeTrust
2324                  *            The negative trust, or {@code null} to restore it to the
2325                  *            default value
2326                  * @return The preferences
2327                  */
2328                 public Preferences setNegativeTrust(Integer negativeTrust) {
2329                         options.getIntegerOption("NegativeTrust").set(negativeTrust);
2330                         return this;
2331                 }
2332
2333                 /**
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.
2336                  *
2337                  * @return The trust comment
2338                  */
2339                 public String getTrustComment() {
2340                         return options.getStringOption("TrustComment").get();
2341                 }
2342
2343                 /**
2344                  * Sets the trust comment.
2345                  *
2346                  * @param trustComment
2347                  *            The trust comment, or {@code null} to restore it to the
2348                  *            default value
2349                  * @return This preferences
2350                  */
2351                 public Preferences setTrustComment(String trustComment) {
2352                         options.getStringOption("TrustComment").set(trustComment);
2353                         return this;
2354                 }
2355
2356                 /**
2357                  * Returns whether the {@link FcpInterface FCP interface} is currently
2358                  * active.
2359                  *
2360                  * @see FcpInterface#setActive(boolean)
2361                  * @return {@code true} if the FCP interface is currently active,
2362                  *         {@code false} otherwise
2363                  */
2364                 public boolean isFcpInterfaceActive() {
2365                         return options.getBooleanOption("ActivateFcpInterface").get();
2366                 }
2367
2368                 /**
2369                  * Sets whether the {@link FcpInterface FCP interface} is currently
2370                  * active.
2371                  *
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
2377                  */
2378                 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2379                         options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2380                         return this;
2381                 }
2382
2383                 /**
2384                  * Returns the action level for which full access to the FCP interface
2385                  * is required.
2386                  *
2387                  * @return The action level for which full access to the FCP interface
2388                  *         is required
2389                  */
2390                 public FullAccessRequired getFcpFullAccessRequired() {
2391                         return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2392                 }
2393
2394                 /**
2395                  * Sets the action level for which full access to the FCP interface is
2396                  * required
2397                  *
2398                  * @param fcpFullAccessRequired
2399                  *            The action level
2400                  * @return This preferences
2401                  */
2402                 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2403                         options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2404                         return this;
2405                 }
2406
2407                 /**
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!
2411                  *
2412                  * @return {@code true} if Sone should clear its settings on the next
2413                  *         restart, {@code false} otherwise
2414                  */
2415                 public boolean isClearOnNextRestart() {
2416                         return options.getBooleanOption("ClearOnNextRestart").get();
2417                 }
2418
2419                 /**
2420                  * Sets whether Sone will clear its settings on the next restart.
2421                  *
2422                  * @param clearOnNextRestart
2423                  *            {@code true} if Sone should clear its settings on the next
2424                  *            restart, {@code false} otherwise
2425                  * @return This preferences
2426                  */
2427                 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2428                         options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2429                         return this;
2430                 }
2431
2432                 /**
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.
2437                  *
2438                  * @return {@code true} if Sone should really clear its settings on the
2439                  *         next restart, {@code false} otherwise
2440                  */
2441                 public boolean isReallyClearOnNextRestart() {
2442                         return options.getBooleanOption("ReallyClearOnNextRestart").get();
2443                 }
2444
2445                 /**
2446                  * Sets whether Sone should really clear its settings on the next
2447                  * restart.
2448                  *
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
2453                  */
2454                 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2455                         options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);
2456                         return this;
2457                 }
2458
2459         }
2460
2461 }