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