Always return a Post.
[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                         return replies.get(replyId);
314                 }
315         }
316
317         /**
318          * Returns all replies for the given post, order ascending by time.
319          *
320          * @param post
321          *            The post to get all replies for
322          * @return All replies for the given post
323          */
324         public List<Reply> getReplies(Post post) {
325                 Set<Sone> sones = getSones();
326                 List<Reply> replies = new ArrayList<Reply>();
327                 for (Sone sone : sones) {
328                         for (Reply reply : sone.getReplies()) {
329                                 if (reply.getPost().equals(post)) {
330                                         replies.add(reply);
331                                 }
332                         }
333                 }
334                 Collections.sort(replies, Reply.TIME_COMPARATOR);
335                 return replies;
336         }
337
338         /**
339          * Returns all Sones that have liked the given post.
340          *
341          * @param post
342          *            The post to get the liking Sones for
343          * @return The Sones that like the given post
344          */
345         public Set<Sone> getLikes(Post post) {
346                 Set<Sone> sones = new HashSet<Sone>();
347                 for (Sone sone : getSones()) {
348                         if (sone.getLikedPostIds().contains(post.getId())) {
349                                 sones.add(sone);
350                         }
351                 }
352                 return sones;
353         }
354
355         /**
356          * Returns all Sones that have liked the given reply.
357          *
358          * @param reply
359          *            The reply to get the liking Sones for
360          * @return The Sones that like the given reply
361          */
362         public Set<Sone> getLikes(Reply reply) {
363                 Set<Sone> sones = new HashSet<Sone>();
364                 for (Sone sone : getSones()) {
365                         if (sone.getLikedPostIds().contains(reply.getId())) {
366                                 sones.add(sone);
367                         }
368                 }
369                 return sones;
370         }
371
372         //
373         // ACTIONS
374         //
375
376         /**
377          * Adds a local Sone from the given ID which has to be the ID of an own
378          * identity.
379          *
380          * @param id
381          *            The ID of an own identity to add a Sone for
382          * @return The added (or already existing) Sone
383          */
384         public Sone addLocalSone(String id) {
385                 synchronized (localSones) {
386                         if (localSones.containsKey(id)) {
387                                 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
388                                 return localSones.get(id);
389                         }
390                         OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
391                         if (ownIdentity == null) {
392                                 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
393                                 return null;
394                         }
395                         return addLocalSone(ownIdentity);
396                 }
397         }
398
399         /**
400          * Adds a local Sone from the given own identity.
401          *
402          * @param ownIdentity
403          *            The own identity to create a Sone from
404          * @return The added (or already existing) Sone
405          */
406         public Sone addLocalSone(OwnIdentity ownIdentity) {
407                 if (ownIdentity == null) {
408                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
409                         return null;
410                 }
411                 synchronized (localSones) {
412                         if (localSones.containsKey(ownIdentity.getId())) {
413                                 logger.log(Level.FINE, "Tried to add known local Sone: %s", ownIdentity);
414                                 return localSones.get(ownIdentity.getId());
415                         }
416                         final Sone sone;
417                         try {
418                                 sone = new Sone(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
419                                 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
420                         } catch (MalformedURLException mue1) {
421                                 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
422                                 return null;
423                         }
424                         /* TODO - load posts ’n stuff */
425                         localSones.put(ownIdentity.getId(), sone);
426                         SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
427                         soneInserters.put(sone, soneInserter);
428                         soneInserter.start();
429                         setSoneStatus(sone, SoneStatus.idle);
430                         new Thread(new Runnable() {
431
432                                 @Override
433                                 @SuppressWarnings("synthetic-access")
434                                 public void run() {
435                                         soneDownloader.fetchSone(sone);
436                                 }
437
438                         }, "Sone Downloader").start();
439                         return sone;
440                 }
441         }
442
443         /**
444          * Creates a new Sone for the given own identity.
445          *
446          * @param ownIdentity
447          *            The own identity to create a Sone for
448          * @return The created Sone
449          */
450         public Sone createSone(OwnIdentity ownIdentity) {
451                 identityManager.addContext(ownIdentity, "Sone");
452                 Sone sone = addLocalSone(ownIdentity);
453                 synchronized (sone) {
454                         /* mark as modified so that it gets inserted immediately. */
455                         sone.setModificationCounter(sone.getModificationCounter() + 1);
456                 }
457                 return sone;
458         }
459
460         /**
461          * Adds the Sone of the given identity.
462          *
463          * @param identity
464          *            The identity whose Sone to add
465          * @return The added or already existing Sone
466          */
467         public Sone addRemoteSone(Identity identity) {
468                 if (identity == null) {
469                         logger.log(Level.WARNING, "Given Identity is null!");
470                         return null;
471                 }
472                 synchronized (remoteSones) {
473                         if (remoteSones.containsKey(identity.getId())) {
474                                 logger.log(Level.FINE, "Identity already exists: %s", identity);
475                                 return remoteSones.get(identity.getId());
476                         }
477                         Sone sone = new Sone(identity);
478                         sone.setRequestUri(getSoneUri(identity.getRequestUri(), identity.getProperty("Sone.LatestEdition")));
479                         remoteSones.put(identity.getId(), sone);
480                         soneDownloader.addSone(sone);
481                         setSoneStatus(sone, SoneStatus.idle);
482                         return sone;
483                 }
484         }
485
486         /**
487          * Updates the stores Sone with the given Sone.
488          *
489          * @param sone
490          *            The updated Sone
491          */
492         public void updateSone(Sone sone) {
493                 if (isRemoteSone(sone)) {
494                         Sone storedSone = getRemoteSone(sone.getId());
495                         if (!(sone.getTime() > storedSone.getTime())) {
496                                 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
497                                 return;
498                         }
499                         synchronized (posts) {
500                                 for (Post post : storedSone.getPosts()) {
501                                         posts.remove(post.getId());
502                                 }
503                                 for (Post post : sone.getPosts()) {
504                                         posts.put(post.getId(), post);
505                                 }
506                         }
507                         synchronized (replies) {
508                                 for (Reply reply : storedSone.getReplies()) {
509                                         replies.remove(reply.getId());
510                                 }
511                                 for (Reply reply : sone.getReplies()) {
512                                         replies.put(reply.getId(), reply);
513                                 }
514                         }
515                         synchronized (storedSone) {
516                                 storedSone.setTime(sone.getTime());
517                                 storedSone.setProfile(sone.getProfile());
518                                 storedSone.setPosts(sone.getPosts());
519                                 storedSone.setReplies(sone.getReplies());
520                                 storedSone.setLikePostIds(sone.getLikedPostIds());
521                                 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
522                                 storedSone.setLatestEdition(sone.getRequestUri().getEdition());
523                         }
524                         saveSone(storedSone);
525                 }
526         }
527
528         /**
529          * Deletes the given Sone. This will remove the Sone from the
530          * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
531          * and remove the context from its identity.
532          *
533          * @param sone
534          *            The Sone to delete
535          */
536         public void deleteSone(Sone sone) {
537                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
538                         logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
539                         return;
540                 }
541                 synchronized (localSones) {
542                         if (!localSones.containsKey(sone.getId())) {
543                                 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
544                                 return;
545                         }
546                         localSones.remove(sone.getId());
547                         soneInserters.remove(sone.getId()).stop();
548                 }
549                 identityManager.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
550         }
551
552         /**
553          * Saves the given Sone. This will persist all local settings for the given
554          * Sone, such as the friends list and similar, private options.
555          *
556          * @param sone
557          *            The Sone to save
558          */
559         public void saveSone(Sone sone) {
560                 if (!isLocalSone(sone)) {
561                         logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
562                         return;
563                 }
564                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
565                         logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
566                         return;
567                 }
568
569                 logger.log(Level.INFO, "Saving Sone: %s", sone);
570                 identityManager.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
571                 try {
572                         /* save Sone into configuration. */
573                         String sonePrefix = "Sone/" + sone.getId();
574                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
575
576                         /* save profile. */
577                         Profile profile = sone.getProfile();
578                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
579                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
580                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
581                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
582                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
583                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
584
585                         /* save posts. */
586                         int postCounter = 0;
587                         for (Post post : sone.getPosts()) {
588                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
589                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
590                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
591                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
592                         }
593                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
594
595                         /* save replies. */
596                         int replyCounter = 0;
597                         for (Reply reply : sone.getReplies()) {
598                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
599                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
600                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
601                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
602                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
603                         }
604                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
605
606                         /* save post likes. */
607                         int postLikeCounter = 0;
608                         for (String postId : sone.getLikedPostIds()) {
609                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
610                         }
611                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
612
613                         /* save reply likes. */
614                         int replyLikeCounter = 0;
615                         for (String replyId : sone.getLikedReplyIds()) {
616                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
617                         }
618                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
619
620                         logger.log(Level.INFO, "Sone %s saved.", sone);
621                 } catch (ConfigurationException ce1) {
622                         logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
623                 }
624         }
625
626         /**
627          * Creates a new post.
628          *
629          * @param sone
630          *            The Sone that creates the post
631          * @param text
632          *            The text of the post
633          */
634         public void createPost(Sone sone, String text) {
635                 createPost(sone, System.currentTimeMillis(), text);
636         }
637
638         /**
639          * Creates a new post.
640          *
641          * @param sone
642          *            The Sone that creates the post
643          * @param time
644          *            The time of the post
645          * @param text
646          *            The text of the post
647          */
648         public void createPost(Sone sone, long time, String text) {
649                 if (!isLocalSone(sone)) {
650                         logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
651                         return;
652                 }
653                 Post post = new Post(sone, time, text);
654                 synchronized (posts) {
655                         posts.put(post.getId(), post);
656                 }
657                 sone.addPost(post);
658                 saveSone(sone);
659         }
660
661         /**
662          * Deletes the given post.
663          *
664          * @param post
665          *            The post to delete
666          */
667         public void deletePost(Post post) {
668                 if (!isLocalSone(post.getSone())) {
669                         logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
670                         return;
671                 }
672                 post.getSone().removePost(post);
673                 synchronized (posts) {
674                         posts.remove(post.getId());
675                 }
676                 saveSone(post.getSone());
677         }
678
679         /**
680          * Creates a new reply.
681          *
682          * @param sone
683          *            The Sone that creates the reply
684          * @param post
685          *            The post that this reply refers to
686          * @param text
687          *            The text of the reply
688          */
689         public void createReply(Sone sone, Post post, String text) {
690                 createReply(sone, post, System.currentTimeMillis(), text);
691         }
692
693         /**
694          * Creates a new reply.
695          *
696          * @param sone
697          *            The Sone that creates the reply
698          * @param post
699          *            The post that this reply refers to
700          * @param time
701          *            The time of the reply
702          * @param text
703          *            The text of the reply
704          */
705         public void createReply(Sone sone, Post post, long time, String text) {
706                 if (!isLocalSone(sone)) {
707                         logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
708                         return;
709                 }
710                 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
711                 synchronized (replies) {
712                         replies.put(reply.getId(), reply);
713                 }
714                 sone.addReply(reply);
715                 saveSone(sone);
716         }
717
718         /**
719          * Deletes the given reply.
720          *
721          * @param reply
722          *            The reply to delete
723          */
724         public void deleteReply(Reply reply) {
725                 Sone sone = reply.getSone();
726                 if (!isLocalSone(sone)) {
727                         logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
728                         return;
729                 }
730                 synchronized (replies) {
731                         replies.remove(reply.getId());
732                 }
733                 sone.removeReply(reply);
734                 saveSone(sone);
735         }
736
737         /**
738          * Starts the core.
739          */
740         public void start() {
741                 loadConfiguration();
742         }
743
744         /**
745          * Stops the core.
746          */
747         public void stop() {
748                 synchronized (localSones) {
749                         for (SoneInserter soneInserter : soneInserters.values()) {
750                                 soneInserter.stop();
751                         }
752                 }
753                 saveConfiguration();
754         }
755
756         //
757         // PRIVATE METHODS
758         //
759
760         /**
761          * Loads the configuration.
762          */
763         @SuppressWarnings("unchecked")
764         private void loadConfiguration() {
765                 /* create options. */
766                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
767
768                         @Override
769                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
770                                 SoneInserter.setInsertionDelay(newValue);
771                         }
772
773                 }));
774                 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
775                 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
776
777                 /* read options from configuration. */
778                 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
779                 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
780                 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
781                 options.getBooleanOption("ClearOnNextRestart").set(null);
782                 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
783                 if (clearConfiguration) {
784                         /* stop loading the configuration. */
785                         return;
786                 }
787
788                 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
789
790         }
791
792         /**
793          * Saves the current options.
794          */
795         private void saveConfiguration() {
796                 /* store the options first. */
797                 try {
798                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
799                         configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
800                         configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
801                 } catch (ConfigurationException ce1) {
802                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
803                 }
804         }
805
806         /**
807          * Generate a Sone URI from the given URI and latest edition.
808          *
809          * @param uriString
810          *            The URI to derive the Sone URI from
811          * @param latestEditionString
812          *            The latest edition as a {@link String}, or {@code null}
813          * @return The derived URI
814          */
815         private FreenetURI getSoneUri(String uriString, String latestEditionString) {
816                 try {
817                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]).setSuggestedEdition(Numbers.safeParseLong(latestEditionString, (long) 0));
818                         return uri;
819                 } catch (MalformedURLException mue1) {
820                         logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
821                         return null;
822                 }
823         }
824
825         //
826         // INTERFACE IdentityListener
827         //
828
829         /**
830          * {@inheritDoc}
831          */
832         @Override
833         public void ownIdentityAdded(OwnIdentity ownIdentity) {
834                 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
835                 if (ownIdentity.hasContext("Sone")) {
836                         addLocalSone(ownIdentity);
837                 }
838         }
839
840         /**
841          * {@inheritDoc}
842          */
843         @Override
844         public void ownIdentityRemoved(OwnIdentity ownIdentity) {
845                 /* TODO */
846         }
847
848         /**
849          * {@inheritDoc}
850          */
851         @Override
852         public void identityAdded(Identity identity) {
853                 logger.log(Level.FINEST, "Adding Identity: " + identity);
854                 addRemoteSone(identity);
855         }
856
857         /**
858          * {@inheritDoc}
859          */
860         @Override
861         public void identityUpdated(Identity identity) {
862                 /* TODO */
863         }
864
865         /**
866          * {@inheritDoc}
867          */
868         @Override
869         public void identityRemoved(Identity identity) {
870                 /* TODO */
871         }
872
873 }