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