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