Add an option for the insertion delay.
[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         private void loadConfiguration() {
619                 logger.entering(Core.class.getName(), "loadConfiguration()");
620
621                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
622
623                         @Override
624                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
625                                 SoneInserter.setInsertionDelay(newValue);
626                         }
627
628                 })).set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
629
630                 /* parse local Sones. */
631                 logger.log(Level.INFO, "Loading Sones…");
632                 int soneId = 0;
633                 do {
634                         String sonePrefix = "Sone/Sone." + soneId++;
635                         String id = configuration.getStringValue(sonePrefix + "/ID").getValue(null);
636                         if (id == null) {
637                                 break;
638                         }
639                         String name = configuration.getStringValue(sonePrefix + "/Name").getValue(null);
640                         long time = configuration.getLongValue(sonePrefix + "/Time").getValue((long) 0);
641                         String insertUri = configuration.getStringValue(sonePrefix + "/InsertURI").getValue(null);
642                         String requestUri = configuration.getStringValue(sonePrefix + "/RequestURI").getValue(null);
643                         long modificationCounter = configuration.getLongValue(sonePrefix + "/ModificationCounter").getValue((long) 0);
644                         String firstName = configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null);
645                         String middleName = configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null);
646                         String lastName = configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null);
647                         Integer birthDay = configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null);
648                         Integer birthMonth = configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null);
649                         Integer birthYear = configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null);
650                         try {
651                                 Profile profile = new Profile();
652                                 profile.setFirstName(firstName);
653                                 profile.setMiddleName(middleName);
654                                 profile.setLastName(lastName);
655                                 profile.setBirthDay(birthDay).setBirthMonth(birthMonth).setBirthYear(birthYear);
656                                 Sone sone = getSone(id).setName(name).setTime(time).setRequestUri(new FreenetURI(requestUri)).setInsertUri(new FreenetURI(insertUri));
657                                 sone.setProfile(profile);
658                                 int postId = 0;
659                                 do {
660                                         String postPrefix = sonePrefix + "/Post." + postId++;
661                                         id = configuration.getStringValue(postPrefix + "/ID").getValue(null);
662                                         if (id == null) {
663                                                 break;
664                                         }
665                                         time = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
666                                         String text = configuration.getStringValue(postPrefix + "/Text").getValue(null);
667                                         Post post = getPost(id).setSone(sone).setTime(time).setText(text);
668                                         sone.addPost(post);
669                                 } while (true);
670                                 int replyCounter = 0;
671                                 do {
672                                         String replyPrefix = sonePrefix + "/Reply." + replyCounter++;
673                                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
674                                         if (replyId == null) {
675                                                 break;
676                                         }
677                                         Post replyPost = getPost(configuration.getStringValue(replyPrefix + "/Post").getValue(null));
678                                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue(null);
679                                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
680                                         Reply reply = getReply(replyId).setSone(sone).setPost(replyPost).setTime(replyTime).setText(replyText);
681                                         sone.addReply(reply);
682                                 } while (true);
683
684                                 /* load friends. */
685                                 int friendCounter = 0;
686                                 while (true) {
687                                         String friendPrefix = sonePrefix + "/Friend." + friendCounter++;
688                                         String friendId = configuration.getStringValue(friendPrefix + "/ID").getValue(null);
689                                         if (friendId == null) {
690                                                 break;
691                                         }
692                                         Sone friendSone = getSone(friendId);
693                                         String friendKey = configuration.getStringValue(friendPrefix + "/Key").getValue(null);
694                                         String friendName = configuration.getStringValue(friendPrefix + "/Name").getValue(null);
695                                         friendSone.setRequestUri(new FreenetURI(friendKey)).setName(friendName);
696                                         sone.addFriend(friendSone);
697                                 }
698
699                                 /* load blocked Sone IDs. */
700                                 int blockedSoneCounter = 0;
701                                 while (true) {
702                                         String blockedSonePrefix = sonePrefix + "/BlockedSone." + blockedSoneCounter++;
703                                         String blockedSoneId = configuration.getStringValue(blockedSonePrefix + "/ID").getValue(null);
704                                         if (blockedSoneId == null) {
705                                                 break;
706                                         }
707                                         sone.addBlockedSoneId(blockedSoneId);
708                                 }
709
710                                 /* load liked post IDs. */
711                                 int likedPostIdCounter = 0;
712                                 while (true) {
713                                         String likedPostIdPrefix = sonePrefix + "/LikedPostId." + likedPostIdCounter++;
714                                         String likedPostId = configuration.getStringValue(likedPostIdPrefix + "/ID").getValue(null);
715                                         if (likedPostId == null) {
716                                                 break;
717                                         }
718                                         sone.addLikedPostId(likedPostId);
719                                 }
720
721                                 /* load liked reply IDs. */
722                                 int likedReplyIdCounter = 0;
723                                 while (true) {
724                                         String likedReplyIdPrefix = sonePrefix + "/LikedReplyId." + likedReplyIdCounter++;
725                                         String likedReplyId = configuration.getStringValue(likedReplyIdPrefix + "/ID").getValue(null);
726                                         if (likedReplyId == null) {
727                                                 break;
728                                         }
729                                         sone.addLikedReplyId(likedReplyId);
730                                 }
731
732                                 sone.setModificationCounter(modificationCounter);
733                                 addLocalSone(sone);
734                         } catch (MalformedURLException mue1) {
735                                 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + requestUri + "”) and insertUri (“" + insertUri + "”)!", mue1);
736                         }
737                 } while (true);
738                 logger.log(Level.INFO, "Loaded %d Sones.", getSones().size());
739
740                 /* load all known Sones. */
741                 int knownSonesCounter = 0;
742                 while (true) {
743                         String knownSonePrefix = "KnownSone." + knownSonesCounter++;
744                         String knownSoneId = configuration.getStringValue(knownSonePrefix + "/ID").getValue(null);
745                         if (knownSoneId == null) {
746                                 break;
747                         }
748                         String knownSoneName = configuration.getStringValue(knownSonePrefix + "/Name").getValue(null);
749                         String knownSoneKey = configuration.getStringValue(knownSonePrefix + "/Key").getValue(null);
750                         try {
751                                 getSone(knownSoneId).setName(knownSoneName).setRequestUri(new FreenetURI(knownSoneKey));
752                         } catch (MalformedURLException mue1) {
753                                 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + knownSoneKey + "”)!", mue1);
754                         }
755                 }
756
757                 /* load all remote Sones. */
758                 for (Sone remoteSone : getRemoteSones()) {
759                         loadSone(remoteSone);
760                 }
761
762                 logger.exiting(Core.class.getName(), "loadConfiguration()");
763         }
764
765         /**
766          * Saves the configuraiton.
767          */
768         private void saveConfiguration() {
769                 Set<Sone> sones = getSones();
770                 logger.log(Level.INFO, "Storing %d Sones…", sones.size());
771
772                 try {
773                         /* store the options first. */
774                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
775
776                         /* store all Sones. */
777                         int soneId = 0;
778                         for (Sone sone : localSones) {
779                                 String sonePrefix = "Sone/Sone." + soneId++;
780                                 configuration.getStringValue(sonePrefix + "/ID").setValue(sone.getId());
781                                 configuration.getStringValue(sonePrefix + "/Name").setValue(sone.getName());
782                                 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
783                                 configuration.getStringValue(sonePrefix + "/RequestURI").setValue(sone.getRequestUri().toString());
784                                 configuration.getStringValue(sonePrefix + "/InsertURI").setValue(sone.getInsertUri().toString());
785                                 configuration.getLongValue(sonePrefix + "/ModificationCounter").setValue(sone.getModificationCounter());
786                                 Profile profile = sone.getProfile();
787                                 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
788                                 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
789                                 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
790                                 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
791                                 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
792                                 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
793                                 int postId = 0;
794                                 for (Post post : sone.getPosts()) {
795                                         String postPrefix = sonePrefix + "/Post." + postId++;
796                                         configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
797                                         configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
798                                         configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
799                                 }
800                                 /* write null ID as terminator. */
801                                 configuration.getStringValue(sonePrefix + "/Post." + postId + "/ID").setValue(null);
802
803                                 int replyId = 0;
804                                 for (Reply reply : sone.getReplies()) {
805                                         String replyPrefix = sonePrefix + "/Reply." + replyId++;
806                                         configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
807                                         configuration.getStringValue(replyPrefix + "/Post").setValue(reply.getPost().getId());
808                                         configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
809                                         configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
810                                 }
811                                 /* write null ID as terminator. */
812                                 configuration.getStringValue(sonePrefix + "/Reply." + replyId + "/ID").setValue(null);
813
814                                 int friendId = 0;
815                                 for (Sone friend : sone.getFriends()) {
816                                         String friendPrefix = sonePrefix + "/Friend." + friendId++;
817                                         configuration.getStringValue(friendPrefix + "/ID").setValue(friend.getId());
818                                         configuration.getStringValue(friendPrefix + "/Key").setValue(friend.getRequestUri().toString());
819                                         configuration.getStringValue(friendPrefix + "/Name").setValue(friend.getName());
820                                 }
821                                 /* write null ID as terminator. */
822                                 configuration.getStringValue(sonePrefix + "/Friend." + friendId + "/ID").setValue(null);
823
824                                 /* write all blocked Sones. */
825                                 int blockedSoneCounter = 0;
826                                 for (String blockedSoneId : sone.getBlockedSoneIds()) {
827                                         String blockedSonePrefix = sonePrefix + "/BlockedSone." + blockedSoneCounter++;
828                                         configuration.getStringValue(blockedSonePrefix + "/ID").setValue(blockedSoneId);
829                                 }
830                                 configuration.getStringValue(sonePrefix + "/BlockedSone." + blockedSoneCounter + "/ID").setValue(null);
831
832                                 /* write all liked posts. */
833                                 int likedPostIdCounter = 0;
834                                 for (String soneLikedPostId : sone.getLikedPostIds()) {
835                                         String likedPostIdPrefix = sonePrefix + "/LikedPostId." + likedPostIdCounter++;
836                                         configuration.getStringValue(likedPostIdPrefix + "/ID").setValue(soneLikedPostId);
837                                 }
838                                 configuration.getStringValue(sonePrefix + "/LikedPostId." + likedPostIdCounter + "/ID").setValue(null);
839
840                                 /* write all liked replies. */
841                                 int likedReplyIdCounter = 0;
842                                 for (String soneLikedReplyId : sone.getLikedReplyIds()) {
843                                         String likedReplyIdPrefix = sonePrefix + "/LikedReplyId." + likedReplyIdCounter++;
844                                         configuration.getStringValue(likedReplyIdPrefix + "/ID").setValue(soneLikedReplyId);
845                                 }
846                                 configuration.getStringValue(sonePrefix + "/LikedReplyId." + likedReplyIdCounter + "/ID").setValue(null);
847
848                         }
849                         /* write null ID as terminator. */
850                         configuration.getStringValue("Sone/Sone." + soneId + "/ID").setValue(null);
851
852                         /* write all known Sones. */
853                         int knownSonesCounter = 0;
854                         for (Sone knownSone : getRemoteSones()) {
855                                 String knownSonePrefix = "KnownSone." + knownSonesCounter++;
856                                 configuration.getStringValue(knownSonePrefix + "/ID").setValue(knownSone.getId());
857                                 configuration.getStringValue(knownSonePrefix + "/Name").setValue(knownSone.getName());
858                                 configuration.getStringValue(knownSonePrefix + "/Key").setValue(knownSone.getRequestUri().toString());
859                                 /* TODO - store all known stuff? */
860                         }
861                         configuration.getStringValue("KnownSone." + knownSonesCounter + "/ID").setValue(null);
862
863                 } catch (ConfigurationException ce1) {
864                         logger.log(Level.WARNING, "Could not store configuration!", ce1);
865                 }
866         }
867
868 }