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