Add options to clear the configuration on next restart.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / Core.java
1 /*
2  * FreenetSone - 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.Collection;
23 import java.util.Collections;
24 import java.util.Comparator;
25 import java.util.HashMap;
26 import java.util.HashSet;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Set;
30 import java.util.UUID;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
33
34 import net.pterodactylus.sone.core.Options.DefaultOption;
35 import net.pterodactylus.sone.core.Options.Option;
36 import net.pterodactylus.sone.core.Options.OptionWatcher;
37 import net.pterodactylus.sone.core.SoneException.Type;
38 import net.pterodactylus.sone.data.Post;
39 import net.pterodactylus.sone.data.Profile;
40 import net.pterodactylus.sone.data.Reply;
41 import net.pterodactylus.sone.data.Sone;
42 import net.pterodactylus.util.config.Configuration;
43 import net.pterodactylus.util.config.ConfigurationException;
44 import net.pterodactylus.util.filter.Filter;
45 import net.pterodactylus.util.filter.Filters;
46 import net.pterodactylus.util.logging.Logging;
47 import net.pterodactylus.util.service.AbstractService;
48 import freenet.client.FetchResult;
49 import freenet.keys.FreenetURI;
50
51 /**
52  * The Sone core.
53  *
54  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
55  */
56 public class Core extends AbstractService {
57
58         /**
59          * Enumeration for the possible states of a {@link Sone}.
60          *
61          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
62          */
63         public enum SoneStatus {
64
65                 /** The Sone is unknown, i.e. not yet downloaded. */
66                 unknown,
67
68                 /** The Sone is idle, i.e. not being downloaded or inserted. */
69                 idle,
70
71                 /** The Sone is currently being inserted. */
72                 inserting,
73
74                 /** The Sone is currently being downloaded. */
75                 downloading,
76         }
77
78         /** The logger. */
79         private static final Logger logger = Logging.getLogger(Core.class);
80
81         /** The options. */
82         private final Options options = new Options();
83
84         /** The configuration. */
85         private Configuration configuration;
86
87         /** Interface to freenet. */
88         private FreenetInterface freenetInterface;
89
90         /** The Sone downloader. */
91         private SoneDownloader soneDownloader;
92
93         /** The local Sones. */
94         private final Set<Sone> localSones = new HashSet<Sone>();
95
96         /** Sone inserters. */
97         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
98
99         /** The Sones’ statuses. */
100         private final Map<Sone, SoneStatus> soneStatuses = Collections.synchronizedMap(new HashMap<Sone, SoneStatus>());
101
102         /* various caches follow here. */
103
104         /** Cache for all known Sones. */
105         private final Map<String, Sone> soneCache = new HashMap<String, Sone>();
106
107         /** Cache for all known posts. */
108         private final Map<String, Post> postCache = new HashMap<String, Post>();
109
110         /** Cache for all known replies. */
111         private final Map<String, Reply> replyCache = new HashMap<String, Reply>();
112
113         /**
114          * Creates a new core.
115          */
116         public Core() {
117                 super("Sone Core", false);
118         }
119
120         //
121         // ACCESSORS
122         //
123
124         /**
125          * Returns the options of the Sone plugin.
126          *
127          * @return The options of the Sone plugin
128          */
129         public Options getOptions() {
130                 return options;
131         }
132
133         /**
134          * Sets the configuration of the core.
135          *
136          * @param configuration
137          *            The configuration of the core
138          * @return This core (for method chaining)
139          */
140         public Core configuration(Configuration configuration) {
141                 this.configuration = configuration;
142                 return this;
143         }
144
145         /**
146          * Sets the Freenet interface to use.
147          *
148          * @param freenetInterface
149          *            The Freenet interface to use
150          * @return This core (for method chaining)
151          */
152         public Core freenetInterface(FreenetInterface freenetInterface) {
153                 this.freenetInterface = freenetInterface;
154                 soneDownloader = new SoneDownloader(this, freenetInterface);
155                 soneDownloader.start();
156                 return this;
157         }
158
159         /**
160          * Returns the local Sones.
161          *
162          * @return The local Sones
163          */
164         public Set<Sone> getSones() {
165                 return Collections.unmodifiableSet(localSones);
166         }
167
168         /**
169          * Returns the Sone with the given ID, or an empty Sone that has been
170          * initialized with the given ID.
171          *
172          * @param soneId
173          *            The ID of the Sone
174          * @return The Sone
175          */
176         public Sone getSone(String soneId) {
177                 if (!soneCache.containsKey(soneId)) {
178                         Sone sone = new Sone(soneId);
179                         soneCache.put(soneId, sone);
180                         setSoneStatus(sone, SoneStatus.unknown);
181                 }
182                 return soneCache.get(soneId);
183         }
184
185         /**
186          * Returns all known sones.
187          *
188          * @return All known sones
189          */
190         public Collection<Sone> getKnownSones() {
191                 return soneCache.values();
192         }
193
194         /**
195          * Gets all known Sones that are not local Sones.
196          *
197          * @return All remote Sones
198          */
199         public Collection<Sone> getRemoteSones() {
200                 return Filters.filteredCollection(getKnownSones(), new Filter<Sone>() {
201
202                         @Override
203                         @SuppressWarnings("synthetic-access")
204                         public boolean filterObject(Sone object) {
205                                 return !localSones.contains(object);
206                         }
207                 });
208         }
209
210         /**
211          * Returns the status of the given Sone.
212          *
213          * @param sone
214          *            The Sone to get the status for
215          * @return The status of the Sone
216          */
217         public SoneStatus getSoneStatus(Sone sone) {
218                 return soneStatuses.get(sone);
219         }
220
221         /**
222          * Sets the status of the Sone.
223          *
224          * @param sone
225          *            The Sone to set the status for
226          * @param soneStatus
227          *            The status of the Sone
228          */
229         public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
230                 soneStatuses.put(sone, soneStatus);
231         }
232
233         /**
234          * Creates a new post and adds it to the given Sone.
235          *
236          * @param sone
237          *            The sone that creates the post
238          * @param text
239          *            The text of the post
240          * @return The created post
241          */
242         public Post createPost(Sone sone, String text) {
243                 return createPost(sone, System.currentTimeMillis(), text);
244         }
245
246         /**
247          * Creates a new post and adds it to the given Sone.
248          *
249          * @param sone
250          *            The Sone that creates the post
251          * @param time
252          *            The time of the post
253          * @param text
254          *            The text of the post
255          * @return The created post
256          */
257         public Post createPost(Sone sone, long time, String text) {
258                 Post post = getPost(UUID.randomUUID().toString()).setSone(sone).setTime(time).setText(text);
259                 sone.addPost(post);
260                 return post;
261         }
262
263         /**
264          * Creates a reply.
265          *
266          * @param sone
267          *            The Sone that posts the reply
268          * @param post
269          *            The post the reply refers to
270          * @param text
271          *            The text of the reply
272          * @return The created reply
273          */
274         public Reply createReply(Sone sone, Post post, String text) {
275                 return createReply(sone, post, System.currentTimeMillis(), text);
276         }
277
278         /**
279          * Creates a reply.
280          *
281          * @param sone
282          *            The Sone that posts the reply
283          * @param post
284          *            The post the reply refers to
285          * @param time
286          *            The time of the post
287          * @param text
288          *            The text of the reply
289          * @return The created reply
290          */
291         public Reply createReply(Sone sone, Post post, long time, String text) {
292                 Reply reply = getReply(UUID.randomUUID().toString()).setSone(sone).setPost(post).setTime(time).setText(text);
293                 sone.addReply(reply);
294                 return reply;
295         }
296
297         //
298         // ACTIONS
299         //
300
301         /**
302          * Adds a Sone to watch for updates. The Sone needs to be completely
303          * initialized.
304          *
305          * @param sone
306          *            The Sone to watch for updates
307          */
308         public void addSone(Sone sone) {
309                 soneCache.put(sone.getId(), sone);
310                 if (!localSones.contains(sone)) {
311                         soneDownloader.addSone(sone);
312                 }
313         }
314
315         /**
316          * Adds the given Sone.
317          *
318          * @param sone
319          *            The Sone to add
320          */
321         public void addLocalSone(Sone sone) {
322                 if (localSones.add(sone)) {
323                         setSoneStatus(sone, SoneStatus.idle);
324                         SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
325                         soneInserter.start();
326                         soneInserters.put(sone, soneInserter);
327                 }
328         }
329
330         /**
331          * Creates a new Sone at a random location.
332          *
333          * @param name
334          *            The name of the Sone
335          * @return The created Sone
336          * @throws SoneException
337          *             if a Sone error occurs
338          */
339         public Sone createSone(String name) throws SoneException {
340                 return createSone(name, "Sone", null, null);
341         }
342
343         /**
344          * Creates a new Sone at the given location. If one of {@code requestUri} or
345          * {@code insertUrI} is {@code null}, the Sone is created at a random
346          * location.
347          *
348          * @param name
349          *            The name of the Sone
350          * @param documentName
351          *            The document name in the SSK
352          * @param requestUri
353          *            The request URI of the Sone, or {@link NullPointerException}
354          *            to create a Sone at a random location
355          * @param insertUri
356          *            The insert URI of the Sone, or {@code null} to create a Sone
357          *            at a random location
358          * @return The created Sone
359          * @throws SoneException
360          *             if a Sone error occurs
361          */
362         public Sone createSone(String name, String documentName, String requestUri, String insertUri) throws SoneException {
363                 if ((name == null) || (name.trim().length() == 0)) {
364                         throw new SoneException(Type.INVALID_SONE_NAME);
365                 }
366                 String finalRequestUri;
367                 String finalInsertUri;
368                 if ((requestUri == null) || (insertUri == null)) {
369                         String[] keyPair = freenetInterface.generateKeyPair();
370                         finalRequestUri = keyPair[0];
371                         finalInsertUri = keyPair[1];
372                 } else {
373                         finalRequestUri = requestUri;
374                         finalInsertUri = insertUri;
375                 }
376                 Sone sone;
377                 try {
378                         logger.log(Level.FINEST, "Creating new Sone “%s” at %s (%s)…", new Object[] { name, finalRequestUri, finalInsertUri });
379                         sone = getSone(UUID.randomUUID().toString()).setName(name).setRequestUri(new FreenetURI(finalRequestUri).setKeyType("USK").setDocName(documentName)).setInsertUri(new FreenetURI(finalInsertUri).setKeyType("USK").setDocName(documentName));
380                         sone.setProfile(new Profile());
381                         /* set modification counter to 1 so it is inserted immediately. */
382                         sone.setModificationCounter(1);
383                         addLocalSone(sone);
384                 } catch (MalformedURLException mue1) {
385                         throw new SoneException(Type.INVALID_URI);
386                 }
387                 return sone;
388         }
389
390         /**
391          * Loads the Sone from the given request URI. The fetching of the data is
392          * performed in a new thread so this method returns immediately.
393          *
394          * @param requestUri
395          *            The request URI to load the Sone from
396          */
397         public void loadSone(final String requestUri) {
398                 loadSone(requestUri, null);
399         }
400
401         /**
402          * Loads the Sone from the given request URI. The fetching of the data is
403          * performed in a new thread so this method returns immediately. If
404          * {@code insertUri} is not {@code null} the loaded Sone is converted into a
405          * local Sone and available using as any other local Sone.
406          *
407          * @param requestUri
408          *            The request URI to load the Sone from
409          * @param insertUri
410          *            The insert URI of the Sone
411          */
412         public void loadSone(final String requestUri, final String insertUri) {
413                 new Thread(new Runnable() {
414
415                         @Override
416                         @SuppressWarnings("synthetic-access")
417                         public void run() {
418                                 try {
419                                         FreenetURI realRequestUri = new FreenetURI(requestUri).setMetaString(new String[] { "sone.xml" });
420                                         FetchResult fetchResult = freenetInterface.fetchUri(realRequestUri);
421                                         if (fetchResult == null) {
422                                                 return;
423                                         }
424                                         Sone parsedSone = soneDownloader.parseSone(null, fetchResult, realRequestUri);
425                                         if (parsedSone != null) {
426                                                 if (insertUri != null) {
427                                                         parsedSone.setInsertUri(new FreenetURI(insertUri));
428                                                         addLocalSone(parsedSone);
429                                                 } else {
430                                                         addSone(parsedSone);
431                                                 }
432                                         }
433                                 } catch (MalformedURLException mue1) {
434                                         logger.log(Level.INFO, "Could not create URI from “" + requestUri + "”.", mue1);
435                                 }
436                         }
437                 }, "Sone Downloader").start();
438         }
439
440         /**
441          * Loads and updates the given Sone.
442          *
443          * @param sone
444          *            The Sone to load
445          */
446         public void loadSone(final Sone sone) {
447                 new Thread(new Runnable() {
448
449                         @Override
450                         @SuppressWarnings("synthetic-access")
451                         public void run() {
452                                 FreenetURI realRequestUri = sone.getRequestUri().setMetaString(new String[] { "sone.xml" });
453                                 setSoneStatus(sone, SoneStatus.downloading);
454                                 try {
455                                         FetchResult fetchResult = freenetInterface.fetchUri(realRequestUri);
456                                         if (fetchResult == null) {
457                                                 /* TODO - mark Sone as bad. */
458                                                 return;
459                                         }
460                                         Sone parsedSone = soneDownloader.parseSone(sone, fetchResult, realRequestUri);
461                                         if (parsedSone != null) {
462                                                 addSone(parsedSone);
463                                         }
464                                 } finally {
465                                         setSoneStatus(sone, (sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
466                                 }
467                         }
468                 }, "Sone Downloader").start();
469         }
470
471         /**
472          * Deletes the given Sone from this plugin instance.
473          *
474          * @param sone
475          *            The sone to delete
476          */
477         public void deleteSone(Sone sone) {
478                 SoneInserter soneInserter = soneInserters.remove(sone);
479                 soneInserter.stop();
480                 localSones.remove(sone);
481         }
482
483         /**
484          * Returns the post with the given ID. If no post exists yet with the given
485          * ID, a new post is returned.
486          *
487          * @param postId
488          *            The ID of the post
489          * @return The post
490          */
491         public Post getPost(String postId) {
492                 if (!postCache.containsKey(postId)) {
493                         postCache.put(postId, new Post(postId));
494                 }
495                 return postCache.get(postId);
496         }
497
498         /**
499          * Returns the reply with the given ID. If no reply exists yet with the
500          * given ID, a new reply is returned.
501          *
502          * @param replyId
503          *            The ID of the reply
504          * @return The reply
505          */
506         public Reply getReply(String replyId) {
507                 if (!replyCache.containsKey(replyId)) {
508                         replyCache.put(replyId, new Reply(replyId));
509                 }
510                 return replyCache.get(replyId);
511         }
512
513         /**
514          * Gets all replies to the given post, sorted by date, oldest first.
515          *
516          * @param post
517          *            The post the replies refer to
518          * @return The sorted list of replies for the post
519          */
520         public List<Reply> getReplies(Post post) {
521                 List<Reply> replies = new ArrayList<Reply>();
522                 for (Reply reply : replyCache.values()) {
523                         if (reply.getPost().equals(post)) {
524                                 replies.add(reply);
525                         }
526                 }
527                 Collections.sort(replies, new Comparator<Reply>() {
528
529                         /**
530                          * {@inheritDoc}
531                          */
532                         @Override
533                         public int compare(Reply leftReply, Reply rightReply) {
534                                 return (int) Math.max(Integer.MIN_VALUE, Math.min(Integer.MAX_VALUE, leftReply.getTime() - rightReply.getTime()));
535                         }
536                 });
537                 return replies;
538         }
539
540         /**
541          * Gets all Sones that like the given post.
542          *
543          * @param post
544          *            The post to check for
545          * @return All Sones that like the post
546          */
547         public Set<Sone> getLikes(final Post post) {
548                 return Filters.filteredSet(getSones(), new Filter<Sone>() {
549
550                         @Override
551                         public boolean filterObject(Sone sone) {
552                                 return sone.isLikedPostId(post.getId());
553                         }
554                 });
555         }
556
557         /**
558          * Gets all Sones that like the given reply.
559          *
560          * @param reply
561          *            The reply to check for
562          * @return All Sones that like the reply
563          */
564         public Set<Sone> getLikes(final Reply reply) {
565                 return Filters.filteredSet(getSones(), new Filter<Sone>() {
566
567                         @Override
568                         public boolean filterObject(Sone sone) {
569                                 return sone.isLikedReplyId(reply.getId());
570                         }
571                 });
572         }
573
574         /**
575          * Deletes the given reply. It is removed from its Sone and from the reply
576          * cache.
577          *
578          * @param reply
579          *            The reply to remove
580          */
581         public void deleteReply(Reply reply) {
582                 reply.getSone().removeReply(reply);
583                 replyCache.remove(reply.getId());
584         }
585
586         //
587         // SERVICE METHODS
588         //
589
590         /**
591          * {@inheritDoc}
592          */
593         @Override
594         protected void serviceStart() {
595                 loadConfiguration();
596         }
597
598         /**
599          * {@inheritDoc}
600          */
601         @Override
602         protected void serviceStop() {
603                 soneDownloader.stop();
604                 /* stop all Sone inserters. */
605                 for (SoneInserter soneInserter : soneInserters.values()) {
606                         soneInserter.stop();
607                 }
608                 saveConfiguration();
609         }
610
611         //
612         // PRIVATE METHODS
613         //
614
615         /**
616          * Loads the configuration.
617          */
618         @SuppressWarnings("unchecked")
619         private void loadConfiguration() {
620                 logger.entering(Core.class.getName(), "loadConfiguration()");
621
622                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
623
624                         @Override
625                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
626                                 SoneInserter.setInsertionDelay(newValue);
627                         }
628
629                 })).set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
630
631                 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false)).set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
632                 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false)).set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
633
634                 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
635                 options.getBooleanOption("ClearOnNextRestart").set(null);
636                 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
637                 if (clearConfiguration) {
638                         /* stop loading the configuration. */
639                         return;
640                 }
641
642                 /* parse local Sones. */
643                 logger.log(Level.INFO, "Loading Sones…");
644                 int soneId = 0;
645                 do {
646                         String sonePrefix = "Sone/Sone." + soneId++;
647                         String id = configuration.getStringValue(sonePrefix + "/ID").getValue(null);
648                         if (id == null) {
649                                 break;
650                         }
651                         String name = configuration.getStringValue(sonePrefix + "/Name").getValue(null);
652                         long time = configuration.getLongValue(sonePrefix + "/Time").getValue((long) 0);
653                         String insertUri = configuration.getStringValue(sonePrefix + "/InsertURI").getValue(null);
654                         String requestUri = configuration.getStringValue(sonePrefix + "/RequestURI").getValue(null);
655                         long modificationCounter = configuration.getLongValue(sonePrefix + "/ModificationCounter").getValue((long) 0);
656                         String firstName = configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null);
657                         String middleName = configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null);
658                         String lastName = configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null);
659                         Integer birthDay = configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null);
660                         Integer birthMonth = configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null);
661                         Integer birthYear = configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null);
662                         try {
663                                 Profile profile = new Profile();
664                                 profile.setFirstName(firstName);
665                                 profile.setMiddleName(middleName);
666                                 profile.setLastName(lastName);
667                                 profile.setBirthDay(birthDay).setBirthMonth(birthMonth).setBirthYear(birthYear);
668                                 Sone sone = getSone(id).setName(name).setTime(time).setRequestUri(new FreenetURI(requestUri)).setInsertUri(new FreenetURI(insertUri));
669                                 sone.setProfile(profile);
670                                 int postId = 0;
671                                 do {
672                                         String postPrefix = sonePrefix + "/Post." + postId++;
673                                         id = configuration.getStringValue(postPrefix + "/ID").getValue(null);
674                                         if (id == null) {
675                                                 break;
676                                         }
677                                         time = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
678                                         String text = configuration.getStringValue(postPrefix + "/Text").getValue(null);
679                                         Post post = getPost(id).setSone(sone).setTime(time).setText(text);
680                                         sone.addPost(post);
681                                 } while (true);
682                                 int replyCounter = 0;
683                                 do {
684                                         String replyPrefix = sonePrefix + "/Reply." + replyCounter++;
685                                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
686                                         if (replyId == null) {
687                                                 break;
688                                         }
689                                         Post replyPost = getPost(configuration.getStringValue(replyPrefix + "/Post").getValue(null));
690                                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue(null);
691                                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
692                                         Reply reply = getReply(replyId).setSone(sone).setPost(replyPost).setTime(replyTime).setText(replyText);
693                                         sone.addReply(reply);
694                                 } while (true);
695
696                                 /* load friends. */
697                                 int friendCounter = 0;
698                                 while (true) {
699                                         String friendPrefix = sonePrefix + "/Friend." + friendCounter++;
700                                         String friendId = configuration.getStringValue(friendPrefix + "/ID").getValue(null);
701                                         if (friendId == null) {
702                                                 break;
703                                         }
704                                         Sone friendSone = getSone(friendId);
705                                         String friendKey = configuration.getStringValue(friendPrefix + "/Key").getValue(null);
706                                         String friendName = configuration.getStringValue(friendPrefix + "/Name").getValue(null);
707                                         friendSone.setRequestUri(new FreenetURI(friendKey)).setName(friendName);
708                                         sone.addFriend(friendSone);
709                                 }
710
711                                 /* load blocked Sone IDs. */
712                                 int blockedSoneCounter = 0;
713                                 while (true) {
714                                         String blockedSonePrefix = sonePrefix + "/BlockedSone." + blockedSoneCounter++;
715                                         String blockedSoneId = configuration.getStringValue(blockedSonePrefix + "/ID").getValue(null);
716                                         if (blockedSoneId == null) {
717                                                 break;
718                                         }
719                                         sone.addBlockedSoneId(blockedSoneId);
720                                 }
721
722                                 /* load liked post IDs. */
723                                 int likedPostIdCounter = 0;
724                                 while (true) {
725                                         String likedPostIdPrefix = sonePrefix + "/LikedPostId." + likedPostIdCounter++;
726                                         String likedPostId = configuration.getStringValue(likedPostIdPrefix + "/ID").getValue(null);
727                                         if (likedPostId == null) {
728                                                 break;
729                                         }
730                                         sone.addLikedPostId(likedPostId);
731                                 }
732
733                                 /* load liked reply IDs. */
734                                 int likedReplyIdCounter = 0;
735                                 while (true) {
736                                         String likedReplyIdPrefix = sonePrefix + "/LikedReplyId." + likedReplyIdCounter++;
737                                         String likedReplyId = configuration.getStringValue(likedReplyIdPrefix + "/ID").getValue(null);
738                                         if (likedReplyId == null) {
739                                                 break;
740                                         }
741                                         sone.addLikedReplyId(likedReplyId);
742                                 }
743
744                                 sone.setModificationCounter(modificationCounter);
745                                 addLocalSone(sone);
746                         } catch (MalformedURLException mue1) {
747                                 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + requestUri + "”) and insertUri (“" + insertUri + "”)!", mue1);
748                         }
749                 } while (true);
750                 logger.log(Level.INFO, "Loaded %d Sones.", getSones().size());
751
752                 /* load all known Sones. */
753                 int knownSonesCounter = 0;
754                 while (true) {
755                         String knownSonePrefix = "KnownSone." + knownSonesCounter++;
756                         String knownSoneId = configuration.getStringValue(knownSonePrefix + "/ID").getValue(null);
757                         if (knownSoneId == null) {
758                                 break;
759                         }
760                         String knownSoneName = configuration.getStringValue(knownSonePrefix + "/Name").getValue(null);
761                         String knownSoneKey = configuration.getStringValue(knownSonePrefix + "/Key").getValue(null);
762                         try {
763                                 getSone(knownSoneId).setName(knownSoneName).setRequestUri(new FreenetURI(knownSoneKey));
764                         } catch (MalformedURLException mue1) {
765                                 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + knownSoneKey + "”)!", mue1);
766                         }
767                 }
768
769                 /* load all remote Sones. */
770                 for (Sone remoteSone : getRemoteSones()) {
771                         loadSone(remoteSone);
772                 }
773
774                 logger.exiting(Core.class.getName(), "loadConfiguration()");
775         }
776
777         /**
778          * Saves the configuraiton.
779          */
780         private void saveConfiguration() {
781                 Set<Sone> sones = getSones();
782                 logger.log(Level.INFO, "Storing %d Sones…", sones.size());
783
784                 try {
785                         /* store the options first. */
786                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
787                         configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
788                         configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
789
790                         /* store all Sones. */
791                         int soneId = 0;
792                         for (Sone sone : localSones) {
793                                 String sonePrefix = "Sone/Sone." + soneId++;
794                                 configuration.getStringValue(sonePrefix + "/ID").setValue(sone.getId());
795                                 configuration.getStringValue(sonePrefix + "/Name").setValue(sone.getName());
796                                 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
797                                 configuration.getStringValue(sonePrefix + "/RequestURI").setValue(sone.getRequestUri().toString());
798                                 configuration.getStringValue(sonePrefix + "/InsertURI").setValue(sone.getInsertUri().toString());
799                                 configuration.getLongValue(sonePrefix + "/ModificationCounter").setValue(sone.getModificationCounter());
800                                 Profile profile = sone.getProfile();
801                                 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
802                                 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
803                                 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
804                                 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
805                                 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
806                                 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
807                                 int postId = 0;
808                                 for (Post post : sone.getPosts()) {
809                                         String postPrefix = sonePrefix + "/Post." + postId++;
810                                         configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
811                                         configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
812                                         configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
813                                 }
814                                 /* write null ID as terminator. */
815                                 configuration.getStringValue(sonePrefix + "/Post." + postId + "/ID").setValue(null);
816
817                                 int replyId = 0;
818                                 for (Reply reply : sone.getReplies()) {
819                                         String replyPrefix = sonePrefix + "/Reply." + replyId++;
820                                         configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
821                                         configuration.getStringValue(replyPrefix + "/Post").setValue(reply.getPost().getId());
822                                         configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
823                                         configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
824                                 }
825                                 /* write null ID as terminator. */
826                                 configuration.getStringValue(sonePrefix + "/Reply." + replyId + "/ID").setValue(null);
827
828                                 int friendId = 0;
829                                 for (Sone friend : sone.getFriends()) {
830                                         String friendPrefix = sonePrefix + "/Friend." + friendId++;
831                                         configuration.getStringValue(friendPrefix + "/ID").setValue(friend.getId());
832                                         configuration.getStringValue(friendPrefix + "/Key").setValue(friend.getRequestUri().toString());
833                                         configuration.getStringValue(friendPrefix + "/Name").setValue(friend.getName());
834                                 }
835                                 /* write null ID as terminator. */
836                                 configuration.getStringValue(sonePrefix + "/Friend." + friendId + "/ID").setValue(null);
837
838                                 /* write all blocked Sones. */
839                                 int blockedSoneCounter = 0;
840                                 for (String blockedSoneId : sone.getBlockedSoneIds()) {
841                                         String blockedSonePrefix = sonePrefix + "/BlockedSone." + blockedSoneCounter++;
842                                         configuration.getStringValue(blockedSonePrefix + "/ID").setValue(blockedSoneId);
843                                 }
844                                 configuration.getStringValue(sonePrefix + "/BlockedSone." + blockedSoneCounter + "/ID").setValue(null);
845
846                                 /* write all liked posts. */
847                                 int likedPostIdCounter = 0;
848                                 for (String soneLikedPostId : sone.getLikedPostIds()) {
849                                         String likedPostIdPrefix = sonePrefix + "/LikedPostId." + likedPostIdCounter++;
850                                         configuration.getStringValue(likedPostIdPrefix + "/ID").setValue(soneLikedPostId);
851                                 }
852                                 configuration.getStringValue(sonePrefix + "/LikedPostId." + likedPostIdCounter + "/ID").setValue(null);
853
854                                 /* write all liked replies. */
855                                 int likedReplyIdCounter = 0;
856                                 for (String soneLikedReplyId : sone.getLikedReplyIds()) {
857                                         String likedReplyIdPrefix = sonePrefix + "/LikedReplyId." + likedReplyIdCounter++;
858                                         configuration.getStringValue(likedReplyIdPrefix + "/ID").setValue(soneLikedReplyId);
859                                 }
860                                 configuration.getStringValue(sonePrefix + "/LikedReplyId." + likedReplyIdCounter + "/ID").setValue(null);
861
862                         }
863                         /* write null ID as terminator. */
864                         configuration.getStringValue("Sone/Sone." + soneId + "/ID").setValue(null);
865
866                         /* write all known Sones. */
867                         int knownSonesCounter = 0;
868                         for (Sone knownSone : getRemoteSones()) {
869                                 String knownSonePrefix = "KnownSone." + knownSonesCounter++;
870                                 configuration.getStringValue(knownSonePrefix + "/ID").setValue(knownSone.getId());
871                                 configuration.getStringValue(knownSonePrefix + "/Name").setValue(knownSone.getName());
872                                 configuration.getStringValue(knownSonePrefix + "/Key").setValue(knownSone.getRequestUri().toString());
873                                 /* TODO - store all known stuff? */
874                         }
875                         configuration.getStringValue("KnownSone." + knownSonesCounter + "/ID").setValue(null);
876
877                 } catch (ConfigurationException ce1) {
878                         logger.log(Level.WARNING, "Could not store configuration!", ce1);
879                 }
880         }
881
882 }