adf580b458f5e144b5b653a1955e594585f949d2
[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.Post;
35 import net.pterodactylus.sone.data.Profile;
36 import net.pterodactylus.sone.data.Reply;
37 import net.pterodactylus.sone.data.Sone;
38 import net.pterodactylus.sone.freenet.wot.Identity;
39 import net.pterodactylus.sone.freenet.wot.IdentityListener;
40 import net.pterodactylus.sone.freenet.wot.IdentityManager;
41 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
42 import net.pterodactylus.util.config.Configuration;
43 import net.pterodactylus.util.config.ConfigurationException;
44 import net.pterodactylus.util.logging.Logging;
45 import net.pterodactylus.util.number.Numbers;
46 import freenet.keys.FreenetURI;
47
48 /**
49  * The Sone core.
50  *
51  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
52  */
53 public class Core implements IdentityListener {
54
55         /**
56          * Enumeration for the possible states of a {@link Sone}.
57          *
58          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
59          */
60         public enum SoneStatus {
61
62                 /** The Sone is unknown, i.e. not yet downloaded. */
63                 unknown,
64
65                 /** The Sone is idle, i.e. not being downloaded or inserted. */
66                 idle,
67
68                 /** The Sone is currently being inserted. */
69                 inserting,
70
71                 /** The Sone is currently being downloaded. */
72                 downloading,
73         }
74
75         /** The logger. */
76         private static final Logger logger = Logging.getLogger(Core.class);
77
78         /** The options. */
79         private final Options options = new Options();
80
81         /** The configuration. */
82         private final Configuration configuration;
83
84         /** The identity manager. */
85         private final IdentityManager identityManager;
86
87         /** Interface to freenet. */
88         private final FreenetInterface freenetInterface;
89
90         /** The Sone downloader. */
91         private final SoneDownloader soneDownloader;
92
93         /** The Sones’ statuses. */
94         /* synchronize access on itself. */
95         private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
96
97         /** Sone inserters. */
98         /* synchronize access on this on localSones. */
99         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
100
101         /** All local Sones. */
102         /* synchronize access on this on itself. */
103         private Map<String, Sone> localSones = new HashMap<String, Sone>();
104
105         /** All remote Sones. */
106         /* synchronize access on this on itself. */
107         private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
108
109         /** All posts. */
110         private Map<String, Post> posts = new HashMap<String, Post>();
111
112         /** All replies. */
113         private Map<String, Reply> replies = new HashMap<String, Reply>();
114
115         /**
116          * Creates a new core.
117          *
118          * @param configuration
119          *            The configuration of the core
120          * @param freenetInterface
121          *            The freenet interface
122          * @param identityManager
123          *            The identity manager
124          */
125         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
126                 this.configuration = configuration;
127                 this.freenetInterface = freenetInterface;
128                 this.identityManager = identityManager;
129                 this.soneDownloader = new SoneDownloader(this, freenetInterface);
130         }
131
132         //
133         // ACCESSORS
134         //
135
136         /**
137          * Returns the options used by the core.
138          *
139          * @return The options of the core
140          */
141         public Options getOptions() {
142                 return options;
143         }
144
145         /**
146          * Returns the identity manager used by the core.
147          *
148          * @return The identity manager
149          */
150         public IdentityManager getIdentityManager() {
151                 return identityManager;
152         }
153
154         /**
155          * Returns the status of the given Sone.
156          *
157          * @param sone
158          *            The Sone to get the status for
159          * @return The status of the Sone
160          */
161         public SoneStatus getSoneStatus(Sone sone) {
162                 synchronized (soneStatuses) {
163                         return soneStatuses.get(sone);
164                 }
165         }
166
167         /**
168          * Sets the status of the given Sone.
169          *
170          * @param sone
171          *            The Sone to set the status of
172          * @param soneStatus
173          *            The status to set
174          */
175         public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
176                 synchronized (soneStatuses) {
177                         soneStatuses.put(sone, soneStatus);
178                 }
179         }
180
181         /**
182          * Returns all Sones, remote and local.
183          *
184          * @return All Sones
185          */
186         public Set<Sone> getSones() {
187                 Set<Sone> allSones = new HashSet<Sone>();
188                 allSones.addAll(getLocalSones());
189                 allSones.addAll(getRemoteSones());
190                 return allSones;
191         }
192
193         /**
194          * Returns the Sone with the given ID, regardless whether it’s local or
195          * remote.
196          *
197          * @param id
198          *            The ID of the Sone to get
199          * @return The Sone with the given ID, or {@code null} if there is no such
200          *         Sone
201          */
202         public Sone getSone(String id) {
203                 Sone sone = getRemoteSone(id);
204                 if (sone != null) {
205                         return sone;
206                 }
207                 sone = getLocalSone(id);
208                 return sone;
209         }
210
211         /**
212          * Returns whether the given Sone is a local Sone.
213          *
214          * @param sone
215          *            The Sone to check for its locality
216          * @return {@code true} if the given Sone is local, {@code false} otherwise
217          */
218         public boolean isLocalSone(Sone sone) {
219                 synchronized (localSones) {
220                         return localSones.containsKey(sone.getId());
221                 }
222         }
223
224         /**
225          * Returns all local Sones.
226          *
227          * @return All local Sones
228          */
229         public Set<Sone> getLocalSones() {
230                 synchronized (localSones) {
231                         return new HashSet<Sone>(localSones.values());
232                 }
233         }
234
235         /**
236          * Returns the local Sone with the given ID.
237          *
238          * @param id
239          *            The ID of the Sone to get
240          * @return The Sone, or {@code null} if there is no Sone with the given ID
241          */
242         public Sone getLocalSone(String id) {
243                 synchronized (localSones) {
244                         return localSones.get(id);
245                 }
246         }
247
248         /**
249          * Returns all remote Sones.
250          *
251          * @return All remote Sones
252          */
253         public Set<Sone> getRemoteSones() {
254                 synchronized (remoteSones) {
255                         return new HashSet<Sone>(remoteSones.values());
256                 }
257         }
258
259         /**
260          * Returns the remote Sone with the given ID.
261          *
262          * @param id
263          *            The ID of the remote Sone to get
264          * @return The Sone, or {@code null} if there is no such Sone
265          */
266         public Sone getRemoteSone(String id) {
267                 synchronized (remoteSones) {
268                         return remoteSones.get(id);
269                 }
270         }
271
272         /**
273          * Returns whether the given Sone is a remote Sone.
274          *
275          * @param sone
276          *            The Sone to check
277          * @return {@code true} if the given Sone is a remote Sone, {@code false}
278          *         otherwise
279          */
280         public boolean isRemoteSone(Sone sone) {
281                 synchronized (remoteSones) {
282                         return remoteSones.containsKey(sone.getId());
283                 }
284         }
285
286         /**
287          * Returns the post with the given ID.
288          *
289          * @param postId
290          *            The ID of the post to get
291          * @return The post, or {@code null} if there is no such post
292          */
293         public Post getPost(String postId) {
294                 synchronized (posts) {
295                         Post post = posts.get(postId);
296                         if (post == null) {
297                                 post = new Post(postId);
298                                 posts.put(postId, post);
299                         }
300                         return post;
301                 }
302         }
303
304         /**
305          * Returns the reply with the given ID.
306          *
307          * @param replyId
308          *            The ID of the reply to get
309          * @return The reply, or {@code null} if there is no such reply
310          */
311         public Reply getReply(String replyId) {
312                 synchronized (replies) {
313                         Reply reply = replies.get(replyId);
314                         if (reply == null) {
315                                 reply = new Reply(replyId);
316                                 replies.put(replyId, reply);
317                         }
318                         return reply;
319                 }
320         }
321
322         /**
323          * Returns all replies for the given post, order ascending by time.
324          *
325          * @param post
326          *            The post to get all replies for
327          * @return All replies for the given post
328          */
329         public List<Reply> getReplies(Post post) {
330                 Set<Sone> sones = getSones();
331                 List<Reply> replies = new ArrayList<Reply>();
332                 for (Sone sone : sones) {
333                         for (Reply reply : sone.getReplies()) {
334                                 if (reply.getPost().equals(post)) {
335                                         replies.add(reply);
336                                 }
337                         }
338                 }
339                 Collections.sort(replies, Reply.TIME_COMPARATOR);
340                 return replies;
341         }
342
343         /**
344          * Returns all Sones that have liked the given post.
345          *
346          * @param post
347          *            The post to get the liking Sones for
348          * @return The Sones that like the given post
349          */
350         public Set<Sone> getLikes(Post post) {
351                 Set<Sone> sones = new HashSet<Sone>();
352                 for (Sone sone : getSones()) {
353                         if (sone.getLikedPostIds().contains(post.getId())) {
354                                 sones.add(sone);
355                         }
356                 }
357                 return sones;
358         }
359
360         /**
361          * Returns all Sones that have liked the given reply.
362          *
363          * @param reply
364          *            The reply to get the liking Sones for
365          * @return The Sones that like the given reply
366          */
367         public Set<Sone> getLikes(Reply reply) {
368                 Set<Sone> sones = new HashSet<Sone>();
369                 for (Sone sone : getSones()) {
370                         if (sone.getLikedPostIds().contains(reply.getId())) {
371                                 sones.add(sone);
372                         }
373                 }
374                 return sones;
375         }
376
377         //
378         // ACTIONS
379         //
380
381         /**
382          * Adds a local Sone from the given ID which has to be the ID of an own
383          * identity.
384          *
385          * @param id
386          *            The ID of an own identity to add a Sone for
387          * @return The added (or already existing) Sone
388          */
389         public Sone addLocalSone(String id) {
390                 synchronized (localSones) {
391                         if (localSones.containsKey(id)) {
392                                 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
393                                 return localSones.get(id);
394                         }
395                         OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
396                         if (ownIdentity == null) {
397                                 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
398                                 return null;
399                         }
400                         return addLocalSone(ownIdentity);
401                 }
402         }
403
404         /**
405          * Adds a local Sone from the given own identity.
406          *
407          * @param ownIdentity
408          *            The own identity to create a Sone from
409          * @return The added (or already existing) Sone
410          */
411         public Sone addLocalSone(OwnIdentity ownIdentity) {
412                 if (ownIdentity == null) {
413                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
414                         return null;
415                 }
416                 synchronized (localSones) {
417                         if (localSones.containsKey(ownIdentity.getId())) {
418                                 logger.log(Level.FINE, "Tried to add known local Sone: %s", ownIdentity);
419                                 return localSones.get(ownIdentity.getId());
420                         }
421                         final Sone sone;
422                         try {
423                                 sone = new Sone(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
424                                 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
425                         } catch (MalformedURLException mue1) {
426                                 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
427                                 return null;
428                         }
429                         /* TODO - load posts ’n stuff */
430                         localSones.put(ownIdentity.getId(), sone);
431                         SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
432                         soneInserters.put(sone, soneInserter);
433                         soneInserter.start();
434                         setSoneStatus(sone, SoneStatus.idle);
435                         new Thread(new Runnable() {
436
437                                 @Override
438                                 @SuppressWarnings("synthetic-access")
439                                 public void run() {
440                                         soneDownloader.fetchSone(sone);
441                                 }
442
443                         }, "Sone Downloader").start();
444                         return sone;
445                 }
446         }
447
448         /**
449          * Creates a new Sone for the given own identity.
450          *
451          * @param ownIdentity
452          *            The own identity to create a Sone for
453          * @return The created Sone
454          */
455         public Sone createSone(OwnIdentity ownIdentity) {
456                 identityManager.addContext(ownIdentity, "Sone");
457                 Sone sone = addLocalSone(ownIdentity);
458                 synchronized (sone) {
459                         /* mark as modified so that it gets inserted immediately. */
460                         sone.setModificationCounter(sone.getModificationCounter() + 1);
461                 }
462                 return sone;
463         }
464
465         /**
466          * Adds the Sone of the given identity.
467          *
468          * @param identity
469          *            The identity whose Sone to add
470          * @return The added or already existing Sone
471          */
472         public Sone addRemoteSone(Identity identity) {
473                 if (identity == null) {
474                         logger.log(Level.WARNING, "Given Identity is null!");
475                         return null;
476                 }
477                 synchronized (remoteSones) {
478                         if (remoteSones.containsKey(identity.getId())) {
479                                 logger.log(Level.FINE, "Identity already exists: %s", identity);
480                                 return remoteSones.get(identity.getId());
481                         }
482                         Sone sone = new Sone(identity);
483                         sone.setRequestUri(getSoneUri(identity.getRequestUri(), identity.getProperty("Sone.LatestEdition")));
484                         remoteSones.put(identity.getId(), sone);
485                         soneDownloader.addSone(sone);
486                         setSoneStatus(sone, SoneStatus.idle);
487                         return sone;
488                 }
489         }
490
491         /**
492          * Updates the stores Sone with the given Sone.
493          *
494          * @param sone
495          *            The updated Sone
496          */
497         public void updateSone(Sone sone) {
498                 if (isRemoteSone(sone)) {
499                         Sone storedSone = getRemoteSone(sone.getId());
500                         if (!(sone.getTime() > storedSone.getTime())) {
501                                 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
502                                 return;
503                         }
504                         synchronized (posts) {
505                                 for (Post post : storedSone.getPosts()) {
506                                         posts.remove(post.getId());
507                                 }
508                                 for (Post post : sone.getPosts()) {
509                                         posts.put(post.getId(), post);
510                                 }
511                         }
512                         synchronized (replies) {
513                                 for (Reply reply : storedSone.getReplies()) {
514                                         replies.remove(reply.getId());
515                                 }
516                                 for (Reply reply : sone.getReplies()) {
517                                         replies.put(reply.getId(), reply);
518                                 }
519                         }
520                         synchronized (storedSone) {
521                                 storedSone.setTime(sone.getTime());
522                                 storedSone.setProfile(sone.getProfile());
523                                 storedSone.setPosts(sone.getPosts());
524                                 storedSone.setReplies(sone.getReplies());
525                                 storedSone.setLikePostIds(sone.getLikedPostIds());
526                                 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
527                                 storedSone.setLatestEdition(sone.getRequestUri().getEdition());
528                         }
529                         saveSone(storedSone);
530                 }
531         }
532
533         /**
534          * Deletes the given Sone. This will remove the Sone from the
535          * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
536          * and remove the context from its identity.
537          *
538          * @param sone
539          *            The Sone to delete
540          */
541         public void deleteSone(Sone sone) {
542                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
543                         logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
544                         return;
545                 }
546                 synchronized (localSones) {
547                         if (!localSones.containsKey(sone.getId())) {
548                                 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
549                                 return;
550                         }
551                         localSones.remove(sone.getId());
552                         soneInserters.remove(sone.getId()).stop();
553                 }
554                 identityManager.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
555         }
556
557         /**
558          * Saves the given Sone. This will persist all local settings for the given
559          * Sone, such as the friends list and similar, private options.
560          *
561          * @param sone
562          *            The Sone to save
563          */
564         public void saveSone(Sone sone) {
565                 if (!isLocalSone(sone)) {
566                         logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
567                         return;
568                 }
569                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
570                         logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
571                         return;
572                 }
573
574                 logger.log(Level.INFO, "Saving Sone: %s", sone);
575                 identityManager.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
576                 try {
577                         /* save Sone into configuration. */
578                         String sonePrefix = "Sone/" + sone.getId();
579                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
580
581                         /* save profile. */
582                         Profile profile = sone.getProfile();
583                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
584                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
585                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
586                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
587                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
588                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
589
590                         /* save posts. */
591                         int postCounter = 0;
592                         for (Post post : sone.getPosts()) {
593                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
594                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
595                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
596                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
597                         }
598                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
599
600                         /* save replies. */
601                         int replyCounter = 0;
602                         for (Reply reply : sone.getReplies()) {
603                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
604                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
605                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
606                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
607                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
608                         }
609                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
610
611                         /* save post likes. */
612                         int postLikeCounter = 0;
613                         for (String postId : sone.getLikedPostIds()) {
614                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
615                         }
616                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
617
618                         /* save reply likes. */
619                         int replyLikeCounter = 0;
620                         for (String replyId : sone.getLikedReplyIds()) {
621                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
622                         }
623                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
624
625                         logger.log(Level.INFO, "Sone %s saved.", sone);
626                 } catch (ConfigurationException ce1) {
627                         logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
628                 }
629         }
630
631         /**
632          * Creates a new post.
633          *
634          * @param sone
635          *            The Sone that creates the post
636          * @param text
637          *            The text of the post
638          */
639         public void createPost(Sone sone, String text) {
640                 createPost(sone, System.currentTimeMillis(), text);
641         }
642
643         /**
644          * Creates a new post.
645          *
646          * @param sone
647          *            The Sone that creates the post
648          * @param time
649          *            The time of the post
650          * @param text
651          *            The text of the post
652          */
653         public void createPost(Sone sone, long time, String text) {
654                 if (!isLocalSone(sone)) {
655                         logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
656                         return;
657                 }
658                 Post post = new Post(sone, time, text);
659                 synchronized (posts) {
660                         posts.put(post.getId(), post);
661                 }
662                 sone.addPost(post);
663                 saveSone(sone);
664         }
665
666         /**
667          * Deletes the given post.
668          *
669          * @param post
670          *            The post to delete
671          */
672         public void deletePost(Post post) {
673                 if (!isLocalSone(post.getSone())) {
674                         logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
675                         return;
676                 }
677                 post.getSone().removePost(post);
678                 synchronized (posts) {
679                         posts.remove(post.getId());
680                 }
681                 saveSone(post.getSone());
682         }
683
684         /**
685          * Creates a new reply.
686          *
687          * @param sone
688          *            The Sone that creates the reply
689          * @param post
690          *            The post that this reply refers to
691          * @param text
692          *            The text of the reply
693          */
694         public void createReply(Sone sone, Post post, String text) {
695                 createReply(sone, post, System.currentTimeMillis(), text);
696         }
697
698         /**
699          * Creates a new reply.
700          *
701          * @param sone
702          *            The Sone that creates the reply
703          * @param post
704          *            The post that this reply refers to
705          * @param time
706          *            The time of the reply
707          * @param text
708          *            The text of the reply
709          */
710         public void createReply(Sone sone, Post post, long time, String text) {
711                 if (!isLocalSone(sone)) {
712                         logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
713                         return;
714                 }
715                 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
716                 synchronized (replies) {
717                         replies.put(reply.getId(), reply);
718                 }
719                 sone.addReply(reply);
720                 saveSone(sone);
721         }
722
723         /**
724          * Deletes the given reply.
725          *
726          * @param reply
727          *            The reply to delete
728          */
729         public void deleteReply(Reply reply) {
730                 Sone sone = reply.getSone();
731                 if (!isLocalSone(sone)) {
732                         logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
733                         return;
734                 }
735                 synchronized (replies) {
736                         replies.remove(reply.getId());
737                 }
738                 sone.removeReply(reply);
739                 saveSone(sone);
740         }
741
742         /**
743          * Starts the core.
744          */
745         public void start() {
746                 loadConfiguration();
747         }
748
749         /**
750          * Stops the core.
751          */
752         public void stop() {
753                 synchronized (localSones) {
754                         for (SoneInserter soneInserter : soneInserters.values()) {
755                                 soneInserter.stop();
756                         }
757                 }
758                 saveConfiguration();
759         }
760
761         //
762         // PRIVATE METHODS
763         //
764
765         /**
766          * Loads the configuration.
767          */
768         @SuppressWarnings("unchecked")
769         private void loadConfiguration() {
770                 /* create options. */
771                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
772
773                         @Override
774                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
775                                 SoneInserter.setInsertionDelay(newValue);
776                         }
777
778                 }));
779                 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
780                 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
781
782                 /* read options from configuration. */
783                 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
784                 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
785                 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
786                 options.getBooleanOption("ClearOnNextRestart").set(null);
787                 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
788                 if (clearConfiguration) {
789                         /* stop loading the configuration. */
790                         return;
791                 }
792
793                 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
794
795         }
796
797         /**
798          * Saves the current options.
799          */
800         private void saveConfiguration() {
801                 /* store the options first. */
802                 try {
803                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
804                         configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
805                         configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
806                 } catch (ConfigurationException ce1) {
807                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
808                 }
809         }
810
811         /**
812          * Generate a Sone URI from the given URI and latest edition.
813          *
814          * @param uriString
815          *            The URI to derive the Sone URI from
816          * @param latestEditionString
817          *            The latest edition as a {@link String}, or {@code null}
818          * @return The derived URI
819          */
820         private FreenetURI getSoneUri(String uriString, String latestEditionString) {
821                 try {
822                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]).setSuggestedEdition(Numbers.safeParseLong(latestEditionString, (long) 0));
823                         return uri;
824                 } catch (MalformedURLException mue1) {
825                         logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
826                         return null;
827                 }
828         }
829
830         //
831         // INTERFACE IdentityListener
832         //
833
834         /**
835          * {@inheritDoc}
836          */
837         @Override
838         public void ownIdentityAdded(OwnIdentity ownIdentity) {
839                 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
840                 if (ownIdentity.hasContext("Sone")) {
841                         addLocalSone(ownIdentity);
842                 }
843         }
844
845         /**
846          * {@inheritDoc}
847          */
848         @Override
849         public void ownIdentityRemoved(OwnIdentity ownIdentity) {
850                 /* TODO */
851         }
852
853         /**
854          * {@inheritDoc}
855          */
856         @Override
857         public void identityAdded(Identity identity) {
858                 logger.log(Level.FINEST, "Adding Identity: " + identity);
859                 addRemoteSone(identity);
860         }
861
862         /**
863          * {@inheritDoc}
864          */
865         @Override
866         public void identityUpdated(Identity identity) {
867                 /* TODO */
868         }
869
870         /**
871          * {@inheritDoc}
872          */
873         @Override
874         public void identityRemoved(Identity identity) {
875                 /* TODO */
876         }
877
878 }