Add method to mark a Sone as known.
[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.logging.Level;
29 import java.util.logging.Logger;
30
31 import net.pterodactylus.sone.core.Options.DefaultOption;
32 import net.pterodactylus.sone.core.Options.Option;
33 import net.pterodactylus.sone.core.Options.OptionWatcher;
34 import net.pterodactylus.sone.data.Client;
35 import net.pterodactylus.sone.data.Post;
36 import net.pterodactylus.sone.data.Profile;
37 import net.pterodactylus.sone.data.Profile.Field;
38 import net.pterodactylus.sone.data.Reply;
39 import net.pterodactylus.sone.data.Sone;
40 import net.pterodactylus.sone.freenet.wot.Identity;
41 import net.pterodactylus.sone.freenet.wot.IdentityListener;
42 import net.pterodactylus.sone.freenet.wot.IdentityManager;
43 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
44 import net.pterodactylus.sone.freenet.wot.Trust;
45 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
46 import net.pterodactylus.sone.main.SonePlugin;
47 import net.pterodactylus.util.config.Configuration;
48 import net.pterodactylus.util.config.ConfigurationException;
49 import net.pterodactylus.util.logging.Logging;
50 import net.pterodactylus.util.number.Numbers;
51 import net.pterodactylus.util.validation.Validation;
52 import net.pterodactylus.util.version.Version;
53 import freenet.keys.FreenetURI;
54
55 /**
56  * The Sone core.
57  *
58  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
59  */
60 public class Core implements IdentityListener, UpdateListener {
61
62         /**
63          * Enumeration for the possible states of a {@link Sone}.
64          *
65          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
66          */
67         public enum SoneStatus {
68
69                 /** The Sone is unknown, i.e. not yet downloaded. */
70                 unknown,
71
72                 /** The Sone is idle, i.e. not being downloaded or inserted. */
73                 idle,
74
75                 /** The Sone is currently being inserted. */
76                 inserting,
77
78                 /** The Sone is currently being downloaded. */
79                 downloading,
80         }
81
82         /** The logger. */
83         private static final Logger logger = Logging.getLogger(Core.class);
84
85         /** The options. */
86         private final Options options = new Options();
87
88         /** The core listener manager. */
89         private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
90
91         /** The configuration. */
92         private Configuration configuration;
93
94         /** Whether we’re currently saving the configuration. */
95         private boolean storingConfiguration = false;
96
97         /** The identity manager. */
98         private final IdentityManager identityManager;
99
100         /** Interface to freenet. */
101         private final FreenetInterface freenetInterface;
102
103         /** The Sone downloader. */
104         private final SoneDownloader soneDownloader;
105
106         /** The update checker. */
107         private final UpdateChecker updateChecker;
108
109         /** Whether the core has been stopped. */
110         private volatile boolean stopped;
111
112         /** The Sones’ statuses. */
113         /* synchronize access on itself. */
114         private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
115
116         /** Locked local Sones. */
117         /* synchronize on itself. */
118         private final Set<Sone> lockedSones = new HashSet<Sone>();
119
120         /** Sone inserters. */
121         /* synchronize access on this on localSones. */
122         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
123
124         /** All local Sones. */
125         /* synchronize access on this on itself. */
126         private Map<String, Sone> localSones = new HashMap<String, Sone>();
127
128         /** All remote Sones. */
129         /* synchronize access on this on itself. */
130         private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
131
132         /** All new Sones. */
133         private Set<String> newSones = new HashSet<String>();
134
135         /** All known Sones. */
136         /* synchronize access on {@link #newSones}. */
137         private Set<String> knownSones = new HashSet<String>();
138
139         /** All posts. */
140         private Map<String, Post> posts = new HashMap<String, Post>();
141
142         /** All new posts. */
143         private Set<String> newPosts = new HashSet<String>();
144
145         /** All known posts. */
146         /* synchronize access on {@link #newPosts}. */
147         private Set<String> knownPosts = new HashSet<String>();
148
149         /** All replies. */
150         private Map<String, Reply> replies = new HashMap<String, Reply>();
151
152         /** All new replies. */
153         private Set<String> newReplies = new HashSet<String>();
154
155         /** All known replies. */
156         private Set<String> knownReplies = new HashSet<String>();
157
158         /** Trusted identities, sorted by own identities. */
159         private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
160
161         /**
162          * Creates a new core.
163          *
164          * @param configuration
165          *            The configuration of the core
166          * @param freenetInterface
167          *            The freenet interface
168          * @param identityManager
169          *            The identity manager
170          */
171         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
172                 this.configuration = configuration;
173                 this.freenetInterface = freenetInterface;
174                 this.identityManager = identityManager;
175                 this.soneDownloader = new SoneDownloader(this, freenetInterface);
176                 this.updateChecker = new UpdateChecker(freenetInterface);
177         }
178
179         //
180         // LISTENER MANAGEMENT
181         //
182
183         /**
184          * Adds a new core listener.
185          *
186          * @param coreListener
187          *            The listener to add
188          */
189         public void addCoreListener(CoreListener coreListener) {
190                 coreListenerManager.addListener(coreListener);
191         }
192
193         /**
194          * Removes a core listener.
195          *
196          * @param coreListener
197          *            The listener to remove
198          */
199         public void removeCoreListener(CoreListener coreListener) {
200                 coreListenerManager.removeListener(coreListener);
201         }
202
203         //
204         // ACCESSORS
205         //
206
207         /**
208          * Sets the configuration to use. This will automatically save the current
209          * configuration to the given configuration.
210          *
211          * @param configuration
212          *            The new configuration to use
213          */
214         public void setConfiguration(Configuration configuration) {
215                 this.configuration = configuration;
216                 saveConfiguration();
217         }
218
219         /**
220          * Returns the options used by the core.
221          *
222          * @return The options of the core
223          */
224         public Options getOptions() {
225                 return options;
226         }
227
228         /**
229          * Returns whether the “Sone rescue mode” is currently activated.
230          *
231          * @return {@code true} if the “Sone rescue mode” is currently activated,
232          *         {@code false} if it is not
233          */
234         public boolean isSoneRescueMode() {
235                 return options.getBooleanOption("SoneRescueMode").get();
236         }
237
238         /**
239          * Returns the identity manager used by the core.
240          *
241          * @return The identity manager
242          */
243         public IdentityManager getIdentityManager() {
244                 return identityManager;
245         }
246
247         /**
248          * Returns the update checker.
249          *
250          * @return The update checker
251          */
252         public UpdateChecker getUpdateChecker() {
253                 return updateChecker;
254         }
255
256         /**
257          * Returns the status of the given Sone.
258          *
259          * @param sone
260          *            The Sone to get the status for
261          * @return The status of the Sone
262          */
263         public SoneStatus getSoneStatus(Sone sone) {
264                 synchronized (soneStatuses) {
265                         return soneStatuses.get(sone);
266                 }
267         }
268
269         /**
270          * Sets the status of the given Sone.
271          *
272          * @param sone
273          *            The Sone to set the status of
274          * @param soneStatus
275          *            The status to set
276          */
277         public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
278                 synchronized (soneStatuses) {
279                         soneStatuses.put(sone, soneStatus);
280                 }
281         }
282
283         /**
284          * Returns whether the given Sone is currently locked.
285          *
286          * @param sone
287          *            The sone to check
288          * @return {@code true} if the Sone is locked, {@code false} if it is not
289          */
290         public boolean isLocked(Sone sone) {
291                 synchronized (lockedSones) {
292                         return lockedSones.contains(sone);
293                 }
294         }
295
296         /**
297          * Returns all Sones, remote and local.
298          *
299          * @return All Sones
300          */
301         public Set<Sone> getSones() {
302                 Set<Sone> allSones = new HashSet<Sone>();
303                 allSones.addAll(getLocalSones());
304                 allSones.addAll(getRemoteSones());
305                 return allSones;
306         }
307
308         /**
309          * Returns the Sone with the given ID, regardless whether it’s local or
310          * remote.
311          *
312          * @param id
313          *            The ID of the Sone to get
314          * @return The Sone with the given ID, or {@code null} if there is no such
315          *         Sone
316          */
317         public Sone getSone(String id) {
318                 return getSone(id, true);
319         }
320
321         /**
322          * Returns the Sone with the given ID, regardless whether it’s local or
323          * remote.
324          *
325          * @param id
326          *            The ID of the Sone to get
327          * @param create
328          *            {@code true} to create a new Sone if none exists,
329          *            {@code false} to return {@code null} if a Sone with the given
330          *            ID does not exist
331          * @return The Sone with the given ID, or {@code null} if there is no such
332          *         Sone
333          */
334         public Sone getSone(String id, boolean create) {
335                 if (isLocalSone(id)) {
336                         return getLocalSone(id);
337                 }
338                 return getRemoteSone(id, create);
339         }
340
341         /**
342          * Checks whether the core knows a Sone with the given ID.
343          *
344          * @param id
345          *            The ID of the Sone
346          * @return {@code true} if there is a Sone with the given ID, {@code false}
347          *         otherwise
348          */
349         public boolean hasSone(String id) {
350                 return isLocalSone(id) || isRemoteSone(id);
351         }
352
353         /**
354          * Returns whether the given Sone is a local Sone.
355          *
356          * @param sone
357          *            The Sone to check for its locality
358          * @return {@code true} if the given Sone is local, {@code false} otherwise
359          */
360         public boolean isLocalSone(Sone sone) {
361                 synchronized (localSones) {
362                         return localSones.containsKey(sone.getId());
363                 }
364         }
365
366         /**
367          * Returns whether the given ID is the ID of a local Sone.
368          *
369          * @param id
370          *            The Sone ID to check for its locality
371          * @return {@code true} if the given ID is a local Sone, {@code false}
372          *         otherwise
373          */
374         public boolean isLocalSone(String id) {
375                 synchronized (localSones) {
376                         return localSones.containsKey(id);
377                 }
378         }
379
380         /**
381          * Returns all local Sones.
382          *
383          * @return All local Sones
384          */
385         public Set<Sone> getLocalSones() {
386                 synchronized (localSones) {
387                         return new HashSet<Sone>(localSones.values());
388                 }
389         }
390
391         /**
392          * Returns the local Sone with the given ID.
393          *
394          * @param id
395          *            The ID of the Sone to get
396          * @return The Sone with the given ID
397          */
398         public Sone getLocalSone(String id) {
399                 return getLocalSone(id, true);
400         }
401
402         /**
403          * Returns the local Sone with the given ID, optionally creating a new Sone.
404          *
405          * @param id
406          *            The ID of the Sone
407          * @param create
408          *            {@code true} to create a new Sone if none exists,
409          *            {@code false} to return null if none exists
410          * @return The Sone with the given ID, or {@code null}
411          */
412         public Sone getLocalSone(String id, boolean create) {
413                 synchronized (localSones) {
414                         Sone sone = localSones.get(id);
415                         if ((sone == null) && create) {
416                                 sone = new Sone(id);
417                                 localSones.put(id, sone);
418                                 setSoneStatus(sone, SoneStatus.unknown);
419                         }
420                         return sone;
421                 }
422         }
423
424         /**
425          * Returns all remote Sones.
426          *
427          * @return All remote Sones
428          */
429         public Set<Sone> getRemoteSones() {
430                 synchronized (remoteSones) {
431                         return new HashSet<Sone>(remoteSones.values());
432                 }
433         }
434
435         /**
436          * Returns the remote Sone with the given ID.
437          *
438          * @param id
439          *            The ID of the remote Sone to get
440          * @return The Sone with the given ID
441          */
442         public Sone getRemoteSone(String id) {
443                 return getRemoteSone(id, true);
444         }
445
446         /**
447          * Returns the remote Sone with the given ID.
448          *
449          * @param id
450          *            The ID of the remote Sone to get
451          * @param create
452          *            {@code true} to always create a Sone, {@code false} to return
453          *            {@code null} if no Sone with the given ID exists
454          * @return The Sone with the given ID
455          */
456         public Sone getRemoteSone(String id, boolean create) {
457                 synchronized (remoteSones) {
458                         Sone sone = remoteSones.get(id);
459                         if ((sone == null) && create) {
460                                 sone = new Sone(id);
461                                 remoteSones.put(id, sone);
462                                 setSoneStatus(sone, SoneStatus.unknown);
463                         }
464                         return sone;
465                 }
466         }
467
468         /**
469          * Returns whether the given Sone is a remote Sone.
470          *
471          * @param sone
472          *            The Sone to check
473          * @return {@code true} if the given Sone is a remote Sone, {@code false}
474          *         otherwise
475          */
476         public boolean isRemoteSone(Sone sone) {
477                 synchronized (remoteSones) {
478                         return remoteSones.containsKey(sone.getId());
479                 }
480         }
481
482         /**
483          * Returns whether the Sone with the given ID is a remote Sone.
484          *
485          * @param id
486          *            The ID of the Sone to check
487          * @return {@code true} if the Sone with the given ID is a remote Sone,
488          *         {@code false} otherwise
489          */
490         public boolean isRemoteSone(String id) {
491                 synchronized (remoteSones) {
492                         return remoteSones.containsKey(id);
493                 }
494         }
495
496         /**
497          * Returns whether the given Sone is a new Sone. After this check, the Sone
498          * is marked as known, i.e. a second call with the same parameters will
499          * always yield {@code false}.
500          *
501          * @param sone
502          *            The sone to check for
503          * @return {@code true} if the given Sone is new, false otherwise
504          */
505         public boolean isNewSone(Sone sone) {
506                 synchronized (newSones) {
507                         boolean isNew = !knownSones.contains(sone.getId()) && newSones.remove(sone.getId());
508                         knownSones.add(sone.getId());
509                         if (isNew) {
510                                 coreListenerManager.fireMarkSoneKnown(sone);
511                         }
512                         return isNew;
513                 }
514         }
515
516         /**
517          * Returns whether the given Sone has been modified.
518          *
519          * @param sone
520          *            The Sone to check for modifications
521          * @return {@code true} if a modification has been detected in the Sone,
522          *         {@code false} otherwise
523          */
524         public boolean isModifiedSone(Sone sone) {
525                 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
526         }
527
528         /**
529          * Returns whether the target Sone is trusted by the origin Sone.
530          *
531          * @param origin
532          *            The origin Sone
533          * @param target
534          *            The target Sone
535          * @return {@code true} if the target Sone is trusted by the origin Sone
536          */
537         public boolean isSoneTrusted(Sone origin, Sone target) {
538                 return trustedIdentities.containsKey(origin) && trustedIdentities.get(origin.getIdentity()).contains(target);
539         }
540
541         /**
542          * Returns the post with the given ID.
543          *
544          * @param postId
545          *            The ID of the post to get
546          * @return The post, or {@code null} if there is no such post
547          */
548         public Post getPost(String postId) {
549                 return getPost(postId, true);
550         }
551
552         /**
553          * Returns the post with the given ID, optionally creating a new post.
554          *
555          * @param postId
556          *            The ID of the post to get
557          * @param create
558          *            {@code true} it create a new post if no post with the given ID
559          *            exists, {@code false} to return {@code null}
560          * @return The post, or {@code null} if there is no such post
561          */
562         public Post getPost(String postId, boolean create) {
563                 synchronized (posts) {
564                         Post post = posts.get(postId);
565                         if ((post == null) && create) {
566                                 post = new Post(postId);
567                                 posts.put(postId, post);
568                         }
569                         return post;
570                 }
571         }
572
573         /**
574          * Returns whether the given post ID is new. After this method returns it is
575          * marked a known post ID.
576          *
577          * @param postId
578          *            The post ID
579          * @return {@code true} if the post is considered to be new, {@code false}
580          *         otherwise
581          */
582         public boolean isNewPost(String postId) {
583                 return isNewPost(postId, true);
584         }
585
586         /**
587          * Returns whether the given post ID is new. If {@code markAsKnown} is
588          * {@code true} then after this method returns the post ID is marked a known
589          * post ID.
590          *
591          * @param postId
592          *            The post ID
593          * @param markAsKnown
594          *            {@code true} to mark the post ID as known, {@code false} to
595          *            not to mark it as known
596          * @return {@code true} if the post is considered to be new, {@code false}
597          *         otherwise
598          */
599         public boolean isNewPost(String postId, boolean markAsKnown) {
600                 synchronized (newPosts) {
601                         boolean isNew = !knownPosts.contains(postId) && newPosts.contains(postId);
602                         if (markAsKnown) {
603                                 Post post = getPost(postId, false);
604                                 if (post != null) {
605                                         markPostKnown(post);
606                                 }
607                         }
608                         return isNew;
609                 }
610         }
611
612         /**
613          * Returns the reply with the given ID. If there is no reply with the given
614          * ID yet, a new one is created.
615          *
616          * @param replyId
617          *            The ID of the reply to get
618          * @return The reply
619          */
620         public Reply getReply(String replyId) {
621                 return getReply(replyId, true);
622         }
623
624         /**
625          * Returns the reply with the given ID. If there is no reply with the given
626          * ID yet, a new one is created, unless {@code create} is false in which
627          * case {@code null} is returned.
628          *
629          * @param replyId
630          *            The ID of the reply to get
631          * @param create
632          *            {@code true} to always return a {@link Reply}, {@code false}
633          *            to return {@code null} if no reply can be found
634          * @return The reply, or {@code null} if there is no such reply
635          */
636         public Reply getReply(String replyId, boolean create) {
637                 synchronized (replies) {
638                         Reply reply = replies.get(replyId);
639                         if (create && (reply == null)) {
640                                 reply = new Reply(replyId);
641                                 replies.put(replyId, reply);
642                         }
643                         return reply;
644                 }
645         }
646
647         /**
648          * Returns all replies for the given post, order ascending by time.
649          *
650          * @param post
651          *            The post to get all replies for
652          * @return All replies for the given post
653          */
654         public List<Reply> getReplies(Post post) {
655                 Set<Sone> sones = getSones();
656                 List<Reply> replies = new ArrayList<Reply>();
657                 for (Sone sone : sones) {
658                         for (Reply reply : sone.getReplies()) {
659                                 if (reply.getPost().equals(post)) {
660                                         replies.add(reply);
661                                 }
662                         }
663                 }
664                 Collections.sort(replies, Reply.TIME_COMPARATOR);
665                 return replies;
666         }
667
668         /**
669          * Returns whether the reply with the given ID is new.
670          *
671          * @param replyId
672          *            The ID of the reply to check
673          * @return {@code true} if the reply is considered to be new, {@code false}
674          *         otherwise
675          */
676         public boolean isNewReply(String replyId) {
677                 return isNewReply(replyId, true);
678         }
679
680         /**
681          * Returns whether the reply with the given ID is new.
682          *
683          * @param replyId
684          *            The ID of the reply to check
685          * @param markAsKnown
686          *            {@code true} to mark the reply as known, {@code false} to not
687          *            to mark it as known
688          * @return {@code true} if the reply is considered to be new, {@code false}
689          *         otherwise
690          */
691         public boolean isNewReply(String replyId, boolean markAsKnown) {
692                 synchronized (newReplies) {
693                         boolean isNew = !knownReplies.contains(replyId) && newReplies.contains(replyId);
694                         if (markAsKnown) {
695                                 Reply reply = getReply(replyId, false);
696                                 if (reply != null) {
697                                         markReplyKnown(reply);
698                                 }
699                         }
700                         return isNew;
701                 }
702         }
703
704         /**
705          * Returns all Sones that have liked the given post.
706          *
707          * @param post
708          *            The post to get the liking Sones for
709          * @return The Sones that like the given post
710          */
711         public Set<Sone> getLikes(Post post) {
712                 Set<Sone> sones = new HashSet<Sone>();
713                 for (Sone sone : getSones()) {
714                         if (sone.getLikedPostIds().contains(post.getId())) {
715                                 sones.add(sone);
716                         }
717                 }
718                 return sones;
719         }
720
721         /**
722          * Returns all Sones that have liked the given reply.
723          *
724          * @param reply
725          *            The reply to get the liking Sones for
726          * @return The Sones that like the given reply
727          */
728         public Set<Sone> getLikes(Reply reply) {
729                 Set<Sone> sones = new HashSet<Sone>();
730                 for (Sone sone : getSones()) {
731                         if (sone.getLikedReplyIds().contains(reply.getId())) {
732                                 sones.add(sone);
733                         }
734                 }
735                 return sones;
736         }
737
738         //
739         // ACTIONS
740         //
741
742         /**
743          * Locks the given Sone. A locked Sone will not be inserted by
744          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
745          * again.
746          *
747          * @param sone
748          *            The sone to lock
749          */
750         public void lockSone(Sone sone) {
751                 synchronized (lockedSones) {
752                         if (lockedSones.add(sone)) {
753                                 coreListenerManager.fireSoneLocked(sone);
754                         }
755                 }
756         }
757
758         /**
759          * Unlocks the given Sone.
760          *
761          * @see #lockSone(Sone)
762          * @param sone
763          *            The sone to unlock
764          */
765         public void unlockSone(Sone sone) {
766                 synchronized (lockedSones) {
767                         if (lockedSones.remove(sone)) {
768                                 coreListenerManager.fireSoneUnlocked(sone);
769                         }
770                 }
771         }
772
773         /**
774          * Adds a local Sone from the given ID which has to be the ID of an own
775          * identity.
776          *
777          * @param id
778          *            The ID of an own identity to add a Sone for
779          * @return The added (or already existing) Sone
780          */
781         public Sone addLocalSone(String id) {
782                 synchronized (localSones) {
783                         if (localSones.containsKey(id)) {
784                                 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
785                                 return localSones.get(id);
786                         }
787                         OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
788                         if (ownIdentity == null) {
789                                 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
790                                 return null;
791                         }
792                         return addLocalSone(ownIdentity);
793                 }
794         }
795
796         /**
797          * Adds a local Sone from the given own identity.
798          *
799          * @param ownIdentity
800          *            The own identity to create a Sone from
801          * @return The added (or already existing) Sone
802          */
803         public Sone addLocalSone(OwnIdentity ownIdentity) {
804                 if (ownIdentity == null) {
805                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
806                         return null;
807                 }
808                 synchronized (localSones) {
809                         final Sone sone;
810                         try {
811                                 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
812                         } catch (MalformedURLException mue1) {
813                                 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
814                                 return null;
815                         }
816                         sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
817                         sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
818                         /* TODO - load posts ’n stuff */
819                         localSones.put(ownIdentity.getId(), sone);
820                         final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
821                         soneInserters.put(sone, soneInserter);
822                         setSoneStatus(sone, SoneStatus.idle);
823                         loadSone(sone);
824                         if (!isSoneRescueMode()) {
825                                 soneInserter.start();
826                         }
827                         new Thread(new Runnable() {
828
829                                 @Override
830                                 @SuppressWarnings("synthetic-access")
831                                 public void run() {
832                                         if (!isSoneRescueMode()) {
833                                                 soneDownloader.fetchSone(sone);
834                                                 return;
835                                         }
836                                         logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
837                                         coreListenerManager.fireRescuingSone(sone);
838                                         lockSone(sone);
839                                         long edition = sone.getLatestEdition();
840                                         while (!stopped && (edition >= 0) && isSoneRescueMode()) {
841                                                 logger.log(Level.FINE, "Downloading edition " + edition + "…");
842                                                 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
843                                                 --edition;
844                                         }
845                                         logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
846                                         saveSone(sone);
847                                         coreListenerManager.fireRescuedSone(sone);
848                                         soneInserter.start();
849                                 }
850
851                         }, "Sone Downloader").start();
852                         return sone;
853                 }
854         }
855
856         /**
857          * Creates a new Sone for the given own identity.
858          *
859          * @param ownIdentity
860          *            The own identity to create a Sone for
861          * @return The created Sone
862          */
863         public Sone createSone(OwnIdentity ownIdentity) {
864                 try {
865                         ownIdentity.addContext("Sone");
866                 } catch (WebOfTrustException wote1) {
867                         logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
868                         return null;
869                 }
870                 Sone sone = addLocalSone(ownIdentity);
871                 return sone;
872         }
873
874         /**
875          * Adds the Sone of the given identity.
876          *
877          * @param identity
878          *            The identity whose Sone to add
879          * @return The added or already existing Sone
880          */
881         public Sone addRemoteSone(Identity identity) {
882                 if (identity == null) {
883                         logger.log(Level.WARNING, "Given Identity is null!");
884                         return null;
885                 }
886                 synchronized (remoteSones) {
887                         final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
888                         boolean newSone = sone.getRequestUri() == null;
889                         sone.setRequestUri(getSoneUri(identity.getRequestUri()));
890                         sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
891                         if (newSone) {
892                                 synchronized (newSones) {
893                                         newSone = !knownSones.contains(sone.getId());
894                                         if (newSone) {
895                                                 newSones.add(sone.getId());
896                                         }
897                                 }
898                                 if (newSone) {
899                                         coreListenerManager.fireNewSoneFound(sone);
900                                 }
901                         }
902                         remoteSones.put(identity.getId(), sone);
903                         soneDownloader.addSone(sone);
904                         setSoneStatus(sone, SoneStatus.unknown);
905                         new Thread(new Runnable() {
906
907                                 @Override
908                                 @SuppressWarnings("synthetic-access")
909                                 public void run() {
910                                         soneDownloader.fetchSone(sone);
911                                 }
912
913                         }, "Sone Downloader").start();
914                         return sone;
915                 }
916         }
917
918         /**
919          * Retrieves the trust relationship from the origin to the target. If the
920          * trust relationship can not be retrieved, {@code null} is returned.
921          *
922          * @see Identity#getTrust(OwnIdentity)
923          * @param origin
924          *            The origin of the trust tree
925          * @param target
926          *            The target of the trust
927          * @return The trust relationship
928          */
929         public Trust getTrust(Sone origin, Sone target) {
930                 if (!isLocalSone(origin)) {
931                         logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
932                         return null;
933                 }
934                 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
935         }
936
937         /**
938          * Sets the trust value of the given origin Sone for the target Sone.
939          *
940          * @param origin
941          *            The origin Sone
942          * @param target
943          *            The target Sone
944          * @param trustValue
945          *            The trust value (from {@code -100} to {@code 100})
946          */
947         public void setTrust(Sone origin, Sone target, int trustValue) {
948                 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();
949                 try {
950                         ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, options.getStringOption("TrustComment").get());
951                 } catch (WebOfTrustException wote1) {
952                         logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
953                 }
954         }
955
956         /**
957          * Removes any trust assignment for the given target Sone.
958          *
959          * @param origin
960          *            The trust origin
961          * @param target
962          *            The trust target
963          */
964         public void removeTrust(Sone origin, Sone target) {
965                 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
966                 try {
967                         ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
968                 } catch (WebOfTrustException wote1) {
969                         logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
970                 }
971         }
972
973         /**
974          * Assigns the configured positive trust value for the given target.
975          *
976          * @param origin
977          *            The trust origin
978          * @param target
979          *            The trust target
980          */
981         public void trustSone(Sone origin, Sone target) {
982                 setTrust(origin, target, options.getIntegerOption("PositiveTrust").get());
983         }
984
985         /**
986          * Assigns the configured negative trust value for the given target.
987          *
988          * @param origin
989          *            The trust origin
990          * @param target
991          *            The trust target
992          */
993         public void distrustSone(Sone origin, Sone target) {
994                 setTrust(origin, target, options.getIntegerOption("NegativeTrust").get());
995         }
996
997         /**
998          * Removes the trust assignment for the given target.
999          *
1000          * @param origin
1001          *            The trust origin
1002          * @param target
1003          *            The trust target
1004          */
1005         public void untrustSone(Sone origin, Sone target) {
1006                 removeTrust(origin, target);
1007         }
1008
1009         /**
1010          * Updates the stores Sone with the given Sone.
1011          *
1012          * @param sone
1013          *            The updated Sone
1014          */
1015         public void updateSone(Sone sone) {
1016                 if (hasSone(sone.getId())) {
1017                         boolean soneRescueMode = isLocalSone(sone) && isSoneRescueMode();
1018                         Sone storedSone = getSone(sone.getId());
1019                         if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1020                                 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1021                                 return;
1022                         }
1023                         synchronized (posts) {
1024                                 if (!soneRescueMode) {
1025                                         for (Post post : storedSone.getPosts()) {
1026                                                 posts.remove(post.getId());
1027                                                 if (!sone.getPosts().contains(post)) {
1028                                                         coreListenerManager.firePostRemoved(post);
1029                                                 }
1030                                         }
1031                                 }
1032                                 synchronized (newPosts) {
1033                                         for (Post post : sone.getPosts()) {
1034                                                 post.setSone(getSone(post.getSone().getId()));
1035                                                 if (!storedSone.getPosts().contains(post) && !knownPosts.contains(post.getId())) {
1036                                                         newPosts.add(post.getId());
1037                                                         coreListenerManager.fireNewPostFound(post);
1038                                                 }
1039                                                 posts.put(post.getId(), post);
1040                                         }
1041                                 }
1042                         }
1043                         synchronized (replies) {
1044                                 if (!soneRescueMode) {
1045                                         for (Reply reply : storedSone.getReplies()) {
1046                                                 replies.remove(reply.getId());
1047                                                 if (!sone.getReplies().contains(reply)) {
1048                                                         coreListenerManager.fireReplyRemoved(reply);
1049                                                 }
1050                                         }
1051                                 }
1052                                 synchronized (newReplies) {
1053                                         for (Reply reply : sone.getReplies()) {
1054                                                 reply.setSone(getSone(reply.getSone().getId()));
1055                                                 if (!storedSone.getReplies().contains(reply) && !knownReplies.contains(reply.getId())) {
1056                                                         newReplies.add(reply.getId());
1057                                                         coreListenerManager.fireNewReplyFound(reply);
1058                                                 }
1059                                                 replies.put(reply.getId(), reply);
1060                                         }
1061                                 }
1062                         }
1063                         synchronized (storedSone) {
1064                                 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1065                                         storedSone.setTime(sone.getTime());
1066                                 }
1067                                 storedSone.setClient(sone.getClient());
1068                                 storedSone.setProfile(sone.getProfile());
1069                                 if (soneRescueMode) {
1070                                         for (Post post : sone.getPosts()) {
1071                                                 storedSone.addPost(post);
1072                                         }
1073                                         for (Reply reply : sone.getReplies()) {
1074                                                 storedSone.addReply(reply);
1075                                         }
1076                                         for (String likedPostId : sone.getLikedPostIds()) {
1077                                                 storedSone.addLikedPostId(likedPostId);
1078                                         }
1079                                         for (String likedReplyId : sone.getLikedReplyIds()) {
1080                                                 storedSone.addLikedReplyId(likedReplyId);
1081                                         }
1082                                 } else {
1083                                         storedSone.setPosts(sone.getPosts());
1084                                         storedSone.setReplies(sone.getReplies());
1085                                         storedSone.setLikePostIds(sone.getLikedPostIds());
1086                                         storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1087                                 }
1088                                 storedSone.setLatestEdition(sone.getLatestEdition());
1089                         }
1090                 }
1091         }
1092
1093         /**
1094          * Deletes the given Sone. This will remove the Sone from the
1095          * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1096          * and remove the context from its identity.
1097          *
1098          * @param sone
1099          *            The Sone to delete
1100          */
1101         public void deleteSone(Sone sone) {
1102                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1103                         logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1104                         return;
1105                 }
1106                 synchronized (localSones) {
1107                         if (!localSones.containsKey(sone.getId())) {
1108                                 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1109                                 return;
1110                         }
1111                         localSones.remove(sone.getId());
1112                         soneInserters.remove(sone).stop();
1113                 }
1114                 try {
1115                         ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1116                         ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1117                 } catch (WebOfTrustException wote1) {
1118                         logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1119                 }
1120                 try {
1121                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1122                 } catch (ConfigurationException ce1) {
1123                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1124                 }
1125         }
1126
1127         /**
1128          * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1129          * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1130          *
1131          * @param sone
1132          *            The Sone to mark as known
1133          */
1134         public void markSoneKnown(Sone sone) {
1135                 synchronized (newSones) {
1136                         if (newSones.remove(sone.getId())) {
1137                                 knownPosts.add(sone.getId());
1138                                 coreListenerManager.fireMarkSoneKnown(sone);
1139                                 saveConfiguration();
1140                         }
1141                 }
1142         }
1143
1144         /**
1145          * Loads and updates the given Sone from the configuration. If any error is
1146          * encountered, loading is aborted and the given Sone is not changed.
1147          *
1148          * @param sone
1149          *            The Sone to load and update
1150          */
1151         public void loadSone(Sone sone) {
1152                 if (!isLocalSone(sone)) {
1153                         logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1154                         return;
1155                 }
1156
1157                 /* load Sone. */
1158                 String sonePrefix = "Sone/" + sone.getId();
1159                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1160                 if (soneTime == null) {
1161                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1162                         return;
1163                 }
1164                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1165
1166                 /* load profile. */
1167                 Profile profile = new Profile();
1168                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1169                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1170                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1171                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1172                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1173                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1174
1175                 /* load profile fields. */
1176                 while (true) {
1177                         String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1178                         String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1179                         if (fieldName == null) {
1180                                 break;
1181                         }
1182                         String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1183                         profile.addField(fieldName).setValue(fieldValue);
1184                 }
1185
1186                 /* load posts. */
1187                 Set<Post> posts = new HashSet<Post>();
1188                 while (true) {
1189                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1190                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1191                         if (postId == null) {
1192                                 break;
1193                         }
1194                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1195                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1196                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1197                         if ((postTime == 0) || (postText == null)) {
1198                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1199                                 return;
1200                         }
1201                         Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1202                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1203                                 post.setRecipient(getSone(postRecipientId));
1204                         }
1205                         posts.add(post);
1206                 }
1207
1208                 /* load replies. */
1209                 Set<Reply> replies = new HashSet<Reply>();
1210                 while (true) {
1211                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1212                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1213                         if (replyId == null) {
1214                                 break;
1215                         }
1216                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1217                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1218                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1219                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1220                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1221                                 return;
1222                         }
1223                         replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1224                 }
1225
1226                 /* load post likes. */
1227                 Set<String> likedPostIds = new HashSet<String>();
1228                 while (true) {
1229                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1230                         if (likedPostId == null) {
1231                                 break;
1232                         }
1233                         likedPostIds.add(likedPostId);
1234                 }
1235
1236                 /* load reply likes. */
1237                 Set<String> likedReplyIds = new HashSet<String>();
1238                 while (true) {
1239                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1240                         if (likedReplyId == null) {
1241                                 break;
1242                         }
1243                         likedReplyIds.add(likedReplyId);
1244                 }
1245
1246                 /* load friends. */
1247                 Set<String> friends = new HashSet<String>();
1248                 while (true) {
1249                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1250                         if (friendId == null) {
1251                                 break;
1252                         }
1253                         friends.add(friendId);
1254                 }
1255
1256                 /* if we’re still here, Sone was loaded successfully. */
1257                 synchronized (sone) {
1258                         sone.setTime(soneTime);
1259                         sone.setProfile(profile);
1260                         sone.setPosts(posts);
1261                         sone.setReplies(replies);
1262                         sone.setLikePostIds(likedPostIds);
1263                         sone.setLikeReplyIds(likedReplyIds);
1264                         sone.setFriends(friends);
1265                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1266                 }
1267                 synchronized (newSones) {
1268                         for (String friend : friends) {
1269                                 knownSones.add(friend);
1270                         }
1271                 }
1272                 synchronized (newPosts) {
1273                         for (Post post : posts) {
1274                                 knownPosts.add(post.getId());
1275                         }
1276                 }
1277                 synchronized (newReplies) {
1278                         for (Reply reply : replies) {
1279                                 knownReplies.add(reply.getId());
1280                         }
1281                 }
1282         }
1283
1284         /**
1285          * Saves the given Sone. This will persist all local settings for the given
1286          * Sone, such as the friends list and similar, private options.
1287          *
1288          * @param sone
1289          *            The Sone to save
1290          */
1291         public synchronized void saveSone(Sone sone) {
1292                 if (!isLocalSone(sone)) {
1293                         logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1294                         return;
1295                 }
1296                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1297                         logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1298                         return;
1299                 }
1300
1301                 logger.log(Level.INFO, "Saving Sone: %s", sone);
1302                 try {
1303                         ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1304
1305                         /* save Sone into configuration. */
1306                         String sonePrefix = "Sone/" + sone.getId();
1307                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1308                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1309
1310                         /* save profile. */
1311                         Profile profile = sone.getProfile();
1312                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1313                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1314                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1315                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1316                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1317                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1318
1319                         /* save profile fields. */
1320                         int fieldCounter = 0;
1321                         for (Field profileField : profile.getFields()) {
1322                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1323                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1324                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1325                         }
1326                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1327
1328                         /* save posts. */
1329                         int postCounter = 0;
1330                         for (Post post : sone.getPosts()) {
1331                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1332                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1333                                 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1334                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1335                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1336                         }
1337                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1338
1339                         /* save replies. */
1340                         int replyCounter = 0;
1341                         for (Reply reply : sone.getReplies()) {
1342                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1343                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1344                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1345                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1346                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1347                         }
1348                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1349
1350                         /* save post likes. */
1351                         int postLikeCounter = 0;
1352                         for (String postId : sone.getLikedPostIds()) {
1353                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1354                         }
1355                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1356
1357                         /* save reply likes. */
1358                         int replyLikeCounter = 0;
1359                         for (String replyId : sone.getLikedReplyIds()) {
1360                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1361                         }
1362                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1363
1364                         /* save friends. */
1365                         int friendCounter = 0;
1366                         for (String friendId : sone.getFriends()) {
1367                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1368                         }
1369                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1370
1371                         configuration.save();
1372                         logger.log(Level.INFO, "Sone %s saved.", sone);
1373                 } catch (ConfigurationException ce1) {
1374                         logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1375                 } catch (WebOfTrustException wote1) {
1376                         logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1377                 }
1378         }
1379
1380         /**
1381          * Creates a new post.
1382          *
1383          * @param sone
1384          *            The Sone that creates the post
1385          * @param text
1386          *            The text of the post
1387          * @return The created post
1388          */
1389         public Post createPost(Sone sone, String text) {
1390                 return createPost(sone, System.currentTimeMillis(), text);
1391         }
1392
1393         /**
1394          * Creates a new post.
1395          *
1396          * @param sone
1397          *            The Sone that creates the post
1398          * @param time
1399          *            The time of the post
1400          * @param text
1401          *            The text of the post
1402          * @return The created post
1403          */
1404         public Post createPost(Sone sone, long time, String text) {
1405                 return createPost(sone, null, time, text);
1406         }
1407
1408         /**
1409          * Creates a new post.
1410          *
1411          * @param sone
1412          *            The Sone that creates the post
1413          * @param recipient
1414          *            The recipient Sone, or {@code null} if this post does not have
1415          *            a recipient
1416          * @param text
1417          *            The text of the post
1418          * @return The created post
1419          */
1420         public Post createPost(Sone sone, Sone recipient, String text) {
1421                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1422         }
1423
1424         /**
1425          * Creates a new post.
1426          *
1427          * @param sone
1428          *            The Sone that creates the post
1429          * @param recipient
1430          *            The recipient Sone, or {@code null} if this post does not have
1431          *            a recipient
1432          * @param time
1433          *            The time of the post
1434          * @param text
1435          *            The text of the post
1436          * @return The created post
1437          */
1438         public Post createPost(Sone sone, Sone recipient, long time, String text) {
1439                 if (!isLocalSone(sone)) {
1440                         logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1441                         return null;
1442                 }
1443                 Post post = new Post(sone, time, text);
1444                 if (recipient != null) {
1445                         post.setRecipient(recipient);
1446                 }
1447                 synchronized (posts) {
1448                         posts.put(post.getId(), post);
1449                 }
1450                 synchronized (newPosts) {
1451                         knownPosts.add(post.getId());
1452                 }
1453                 sone.addPost(post);
1454                 saveSone(sone);
1455                 return post;
1456         }
1457
1458         /**
1459          * Deletes the given post.
1460          *
1461          * @param post
1462          *            The post to delete
1463          */
1464         public void deletePost(Post post) {
1465                 if (!isLocalSone(post.getSone())) {
1466                         logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1467                         return;
1468                 }
1469                 post.getSone().removePost(post);
1470                 synchronized (posts) {
1471                         posts.remove(post.getId());
1472                 }
1473                 saveSone(post.getSone());
1474         }
1475
1476         /**
1477          * Marks the given post as known, if it is currently a new post (according
1478          * to {@link #isNewPost(String)}).
1479          *
1480          * @param post
1481          *            The post to mark as known
1482          */
1483         public void markPostKnown(Post post) {
1484                 synchronized (newPosts) {
1485                         if (newPosts.remove(post.getId())) {
1486                                 knownPosts.add(post.getId());
1487                                 coreListenerManager.fireMarkPostKnown(post);
1488                                 saveConfiguration();
1489                         }
1490                 }
1491         }
1492
1493         /**
1494          * Creates a new reply.
1495          *
1496          * @param sone
1497          *            The Sone that creates the reply
1498          * @param post
1499          *            The post that this reply refers to
1500          * @param text
1501          *            The text of the reply
1502          * @return The created reply
1503          */
1504         public Reply createReply(Sone sone, Post post, String text) {
1505                 return createReply(sone, post, System.currentTimeMillis(), text);
1506         }
1507
1508         /**
1509          * Creates a new reply.
1510          *
1511          * @param sone
1512          *            The Sone that creates the reply
1513          * @param post
1514          *            The post that this reply refers to
1515          * @param time
1516          *            The time of the reply
1517          * @param text
1518          *            The text of the reply
1519          * @return The created reply
1520          */
1521         public Reply createReply(Sone sone, Post post, long time, String text) {
1522                 if (!isLocalSone(sone)) {
1523                         logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1524                         return null;
1525                 }
1526                 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1527                 synchronized (replies) {
1528                         replies.put(reply.getId(), reply);
1529                 }
1530                 synchronized (newReplies) {
1531                         knownReplies.add(reply.getId());
1532                 }
1533                 sone.addReply(reply);
1534                 saveSone(sone);
1535                 return reply;
1536         }
1537
1538         /**
1539          * Deletes the given reply.
1540          *
1541          * @param reply
1542          *            The reply to delete
1543          */
1544         public void deleteReply(Reply reply) {
1545                 Sone sone = reply.getSone();
1546                 if (!isLocalSone(sone)) {
1547                         logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1548                         return;
1549                 }
1550                 synchronized (replies) {
1551                         replies.remove(reply.getId());
1552                 }
1553                 sone.removeReply(reply);
1554                 saveSone(sone);
1555         }
1556
1557         /**
1558          * Marks the given reply as known, if it is currently a new reply (according
1559          * to {@link #isNewReply(String)}).
1560          *
1561          * @param reply
1562          *            The reply to mark as known
1563          */
1564         public void markReplyKnown(Reply reply) {
1565                 synchronized (newReplies) {
1566                         if (newReplies.remove(reply.getId())) {
1567                                 knownReplies.add(reply.getId());
1568                                 coreListenerManager.fireMarkReplyKnown(reply);
1569                                 saveConfiguration();
1570                         }
1571                 }
1572         }
1573
1574         /**
1575          * Starts the core.
1576          */
1577         public void start() {
1578                 loadConfiguration();
1579                 updateChecker.addUpdateListener(this);
1580                 updateChecker.start();
1581         }
1582
1583         /**
1584          * Stops the core.
1585          */
1586         public void stop() {
1587                 synchronized (localSones) {
1588                         for (SoneInserter soneInserter : soneInserters.values()) {
1589                                 soneInserter.stop();
1590                         }
1591                 }
1592                 updateChecker.stop();
1593                 updateChecker.removeUpdateListener(this);
1594                 soneDownloader.stop();
1595                 saveConfiguration();
1596                 stopped = true;
1597         }
1598
1599         /**
1600          * Saves the current options.
1601          */
1602         public void saveConfiguration() {
1603                 synchronized (configuration) {
1604                         if (storingConfiguration) {
1605                                 logger.log(Level.FINE, "Already storing configuration…");
1606                                 return;
1607                         }
1608                         storingConfiguration = true;
1609                 }
1610
1611                 /* store the options first. */
1612                 try {
1613                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1614                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1615                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1616                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1617                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1618                         configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1619                         configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1620                         configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1621
1622                         /* save known Sones. */
1623                         int soneCounter = 0;
1624                         synchronized (newSones) {
1625                                 for (String knownSoneId : knownSones) {
1626                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1627                                 }
1628                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1629                         }
1630
1631                         /* save known posts. */
1632                         int postCounter = 0;
1633                         synchronized (newPosts) {
1634                                 for (String knownPostId : knownPosts) {
1635                                         configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1636                                 }
1637                                 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1638                         }
1639
1640                         /* save known replies. */
1641                         int replyCounter = 0;
1642                         synchronized (newReplies) {
1643                                 for (String knownReplyId : knownReplies) {
1644                                         configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1645                                 }
1646                                 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1647                         }
1648
1649                         /* now save it. */
1650                         configuration.save();
1651
1652                 } catch (ConfigurationException ce1) {
1653                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1654                 } finally {
1655                         synchronized (configuration) {
1656                                 storingConfiguration = false;
1657                         }
1658                 }
1659         }
1660
1661         //
1662         // PRIVATE METHODS
1663         //
1664
1665         /**
1666          * Loads the configuration.
1667          */
1668         @SuppressWarnings("unchecked")
1669         private void loadConfiguration() {
1670                 /* create options. */
1671                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
1672
1673                         @Override
1674                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1675                                 SoneInserter.setInsertionDelay(newValue);
1676                         }
1677
1678                 }));
1679                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75));
1680                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-100));
1681                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1682                 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1683                 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1684                 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1685
1686                 /* read options from configuration. */
1687                 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1688                 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1689                 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1690                 options.getBooleanOption("ClearOnNextRestart").set(null);
1691                 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1692                 if (clearConfiguration) {
1693                         /* stop loading the configuration. */
1694                         return;
1695                 }
1696
1697                 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
1698                 options.getIntegerOption("PositiveTrust").set(configuration.getIntValue("Option/PositiveTrust").getValue(null));
1699                 options.getIntegerOption("NegativeTrust").set(configuration.getIntValue("Option/NegativeTrust").getValue(null));
1700                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1701                 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1702
1703                 /* load known Sones. */
1704                 int soneCounter = 0;
1705                 while (true) {
1706                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1707                         if (knownSoneId == null) {
1708                                 break;
1709                         }
1710                         synchronized (newSones) {
1711                                 knownSones.add(knownSoneId);
1712                         }
1713                 }
1714
1715                 /* load known posts. */
1716                 int postCounter = 0;
1717                 while (true) {
1718                         String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1719                         if (knownPostId == null) {
1720                                 break;
1721                         }
1722                         synchronized (newPosts) {
1723                                 knownPosts.add(knownPostId);
1724                         }
1725                 }
1726
1727                 /* load known replies. */
1728                 int replyCounter = 0;
1729                 while (true) {
1730                         String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1731                         if (knownReplyId == null) {
1732                                 break;
1733                         }
1734                         synchronized (newReplies) {
1735                                 knownReplies.add(knownReplyId);
1736                         }
1737                 }
1738
1739         }
1740
1741         /**
1742          * Generate a Sone URI from the given URI and latest edition.
1743          *
1744          * @param uriString
1745          *            The URI to derive the Sone URI from
1746          * @return The derived URI
1747          */
1748         private FreenetURI getSoneUri(String uriString) {
1749                 try {
1750                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1751                         return uri;
1752                 } catch (MalformedURLException mue1) {
1753                         logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1754                         return null;
1755                 }
1756         }
1757
1758         //
1759         // INTERFACE IdentityListener
1760         //
1761
1762         /**
1763          * {@inheritDoc}
1764          */
1765         @Override
1766         public void ownIdentityAdded(OwnIdentity ownIdentity) {
1767                 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1768                 if (ownIdentity.hasContext("Sone")) {
1769                         trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
1770                         addLocalSone(ownIdentity);
1771                 }
1772         }
1773
1774         /**
1775          * {@inheritDoc}
1776          */
1777         @Override
1778         public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1779                 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1780                 trustedIdentities.remove(ownIdentity);
1781         }
1782
1783         /**
1784          * {@inheritDoc}
1785          */
1786         @Override
1787         public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
1788                 logger.log(Level.FINEST, "Adding Identity: " + identity);
1789                 trustedIdentities.get(ownIdentity).add(identity);
1790                 addRemoteSone(identity);
1791         }
1792
1793         /**
1794          * {@inheritDoc}
1795          */
1796         @Override
1797         public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
1798                 new Thread(new Runnable() {
1799
1800                         @Override
1801                         @SuppressWarnings("synthetic-access")
1802                         public void run() {
1803                                 Sone sone = getRemoteSone(identity.getId());
1804                                 sone.setIdentity(identity);
1805                                 soneDownloader.fetchSone(sone);
1806                         }
1807                 }).start();
1808         }
1809
1810         /**
1811          * {@inheritDoc}
1812          */
1813         @Override
1814         public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
1815                 trustedIdentities.get(ownIdentity).remove(identity);
1816         }
1817
1818         //
1819         // INTERFACE UpdateListener
1820         //
1821
1822         /**
1823          * {@inheritDoc}
1824          */
1825         @Override
1826         public void updateFound(Version version, long releaseTime) {
1827                 coreListenerManager.fireUpdateFound(version, releaseTime);
1828         }
1829
1830 }