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